4224 lines
1.1 MiB
4224 lines
1.1 MiB
|
|
/*
|
|
Face-API
|
|
homepage: <https://github.com/vladmandic/face-api>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var Y_=Object.create,dd=Object.defineProperty,Z_=Object.getPrototypeOf,J_=Object.prototype.hasOwnProperty,Q_=Object.getOwnPropertyNames,eE=Object.getOwnPropertyDescriptor;var Kw=e=>dd(e,"__esModule",{value:!0});var tE=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),hd=(e,t)=>{for(var n in t)dd(e,n,{get:t[n],enumerable:!0})},nE=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Q_(t))!J_.call(e,a)&&a!=="default"&&dd(e,a,{get:()=>t[a],enumerable:!(n=eE(t,a))||n.enumerable});return e},aE=e=>e&&e.__esModule?e:nE(Kw(dd(e!=null?Y_(Z_(e)):{},"default",{value:e,enumerable:!0})),e);var K2=tE((dre,q2)=>{Kw(dre);hd(dre,{isNodejs:()=>hre});function hre(){return typeof global=="object"&&!0&&typeof q2!="undefined"&&typeof process!="undefined"&&!!process.version}});var Ug={};hd(Ug,{Abs:()=>Eo,Acos:()=>Ao,Acosh:()=>Fo,AdadeltaOptimizer:()=>Wh,AdagradOptimizer:()=>Vh,AdamOptimizer:()=>Uh,AdamaxOptimizer:()=>Gh,Add:()=>zr,AddN:()=>Ss,All:()=>vd,Any:()=>wd,ArgMax:()=>Cs,ArgMin:()=>oc,Asin:()=>$o,Asinh:()=>Do,Atan:()=>Ro,Atan2:()=>Po,Atanh:()=>Mo,AvgPool:()=>_s,AvgPool3D:()=>lc,AvgPool3DGrad:()=>Id,AvgPoolGrad:()=>kd,BackendWasm:()=>U2,BatchMatMul:()=>Es,BatchToSpaceND:()=>uc,Bincount:()=>Nd,BroadcastTo:()=>l0,Callback:()=>VI,CallbackList:()=>Bk,Cast:()=>As,Ceil:()=>Fs,ClipByValue:()=>Br,Complex:()=>Td,ComplexAbs:()=>cc,Concat:()=>Oo,Conv2D:()=>$s,Conv2DBackpropFilter:()=>Sd,Conv2DBackpropInput:()=>Ds,Conv3D:()=>pc,Conv3DBackpropFilterV2:()=>Cd,Conv3DBackpropInputV2:()=>_d,Cos:()=>Rs,Cosh:()=>Lo,CropAndResize:()=>zo,Cumsum:()=>Ms,CustomCallback:()=>Vk,DataStorage:()=>gd,DenseBincount:()=>Ed,DepthToSpace:()=>Bo,DepthwiseConv2dNative:()=>Ps,DepthwiseConv2dNativeBackpropFilter:()=>Ad,DepthwiseConv2dNativeBackpropInput:()=>Fd,Diag:()=>$d,Dilation2D:()=>dc,Dilation2DBackpropFilter:()=>Rd,Dilation2DBackpropInput:()=>Dd,ENV:()=>Kg,EarlyStopping:()=>GI,Elu:()=>Wo,EluGrad:()=>Md,Environment:()=>i0,Equal:()=>Uo,Erf:()=>Vo,Exp:()=>Ls,ExpandDims:()=>Go,Expm1:()=>Ho,FFT:()=>Pd,Fill:()=>hc,FlipLeftRight:()=>jo,Floor:()=>zs,FloorDiv:()=>Bs,FromPixels:()=>Yd,FusedBatchNorm:()=>Ws,FusedConv2D:()=>xi,FusedDepthwiseConv2D:()=>vi,GatherNd:()=>Ko,GatherV2:()=>qo,GraphModel:()=>vN,Greater:()=>Xo,GreaterEqual:()=>Vs,History:()=>Wk,IFFT:()=>Od,Identity:()=>Us,Imag:()=>Ld,InputSpec:()=>Xt,IsFinite:()=>Yo,IsInf:()=>Zo,IsNan:()=>Jo,KernelBackend:()=>rc,LRN:()=>gc,LRNGrad:()=>Bd,LayerVariable:()=>Mk,LayersModel:()=>kr,LeakyRelu:()=>Gs,Less:()=>Qo,LessEqual:()=>el,LinSpace:()=>zd,Log:()=>Hs,Log1p:()=>tl,LogSoftmax:()=>u0,LogicalAnd:()=>nl,LogicalNot:()=>mc,LogicalOr:()=>fc,Max:()=>js,MaxPool:()=>Ks,MaxPool3D:()=>yc,MaxPool3DGrad:()=>Vd,MaxPoolGrad:()=>Wd,MaxPoolWithArgmax:()=>Ud,Maximum:()=>qs,Mean:()=>Xs,Min:()=>Ys,Minimum:()=>Zs,MirrorPad:()=>bc,Mod:()=>al,MomentumOptimizer:()=>Hh,Multinomial:()=>Gd,Multiply:()=>Js,Neg:()=>rl,NonMaxSuppressionV3:()=>il,NonMaxSuppressionV4:()=>ol,NonMaxSuppressionV5:()=>ll,NotEqual:()=>sl,OP_SCOPE_SUFFIX:()=>v0,OneHot:()=>Qs,OnesLike:()=>ul,Optimizer:()=>xr,Pack:()=>cl,PadV2:()=>ei,Pool:()=>qE,Pow:()=>ti,Prelu:()=>ni,Prod:()=>pl,RMSPropOptimizer:()=>jh,RNN:()=>nr,Range:()=>xc,Rank:()=>ty,Real:()=>Hd,RealDiv:()=>Os,Reciprocal:()=>dl,Reduction:()=>dn,Relu:()=>ai,Relu6:()=>si,Reshape:()=>hl,ResizeBilinear:()=>ri,ResizeBilinearGrad:()=>qd,ResizeNearestNeighbor:()=>vc,ResizeNearestNeighborGrad:()=>jd,Reverse:()=>ii,RotateWithOffset:()=>Cl,Round:()=>oi,Rsqrt:()=>li,SGDOptimizer:()=>Kc,ScatterNd:()=>ml,Select:()=>fl,Selu:()=>gl,Sequential:()=>Jl,Sigmoid:()=>ci,Sign:()=>xl,Sin:()=>ui,Sinh:()=>bl,Slice:()=>yl,Softmax:()=>hi,Softplus:()=>vl,SpaceToBatchND:()=>wc,SparseToDense:()=>Kd,SplitV:()=>wl,Sqrt:()=>pi,Square:()=>kc,SquaredDifference:()=>mi,Step:()=>Vr,StridedSlice:()=>kl,Sub:()=>fi,Sum:()=>di,SymbolicTensor:()=>Fa,Tan:()=>Il,Tanh:()=>gi,Tensor:()=>Ae,TensorBuffer:()=>Ot,Tile:()=>Wr,TopK:()=>Nl,Transpose:()=>yi,Unique:()=>Xd,Unpack:()=>Tl,UnsortedSegmentSum:()=>Ic,Variable:()=>Ur,ZerosLike:()=>Sl,_FusedMatMul:()=>bi,abs:()=>Lt,acos:()=>Sy,acosh:()=>Cy,add:()=>Z,addN:()=>n1,all:()=>ph,any:()=>Rc,argMax:()=>Mc,argMin:()=>_y,asin:()=>Ey,asinh:()=>Ay,atan:()=>Fy,atan2:()=>$y,atanh:()=>Dy,avgPool:()=>Xn,avgPool3d:()=>Py,backend:()=>t1,backend_util:()=>_,basicLSTMCell:()=>k$,batchNorm:()=>gr,batchNorm2d:()=>i1,batchNorm3d:()=>o1,batchNorm4d:()=>l1,batchToSpaceND:()=>Oc,bincount:()=>u1,booleanMaskAsync:()=>SM,broadcastTo:()=>Lc,browser:()=>Ni,buffer:()=>Le,callbacks:()=>h4,cast:()=>ce,ceil:()=>Oy,clipByValue:()=>qt,clone:()=>qr,complex:()=>Gr,concat:()=>Qe,concat1d:()=>c1,concat2d:()=>p1,concat3d:()=>d1,concat4d:()=>h1,constraints:()=>lk,conv1d:()=>hh,conv2d:()=>At,conv2dTranspose:()=>mh,conv3d:()=>zy,conv3dTranspose:()=>G$,copyRegisteredKernels:()=>YE,cos:()=>zc,cosh:()=>fh,cosineWindow:()=>pb,cumsum:()=>gh,customGrad:()=>Ka,data:()=>kN,denseBincount:()=>f1,deprecationWarn:()=>Ty,depthToSpace:()=>By,depthwiseConv2d:()=>Yr,deregisterOp:()=>f4,device_util:()=>ah,diag:()=>J$,dilation2d:()=>Wy,disableDeprecationWarnings:()=>RF,dispose:()=>Fe,disposeVariables:()=>MF,div:()=>ve,divNoNan:()=>Vy,dot:()=>g1,dropout:()=>O1,elu:()=>Ol,enableDebugMode:()=>DF,enableProdMode:()=>$F,enclosingPowerOfTwo:()=>L1,engine:()=>Ha,env:()=>ee,equal:()=>Zr,erf:()=>Uy,exp:()=>pn,expandDims:()=>$n,expm1:()=>Gy,eye:()=>Hy,fft:()=>jc,fill:()=>wn,findBackend:()=>VF,findBackendFactory:()=>UF,floor:()=>Ll,floorDiv:()=>ch,fused:()=>es,gather:()=>Ci,gatherND:()=>P1,gather_util:()=>by,getBackend:()=>BF,getGradient:()=>Jg,getKernel:()=>Zd,getKernelsForBackend:()=>Jd,grad:()=>CD,grads:()=>_D,greater:()=>pa,greaterEqual:()=>Jr,ifft:()=>Gl,imag:()=>yh,image:()=>Za,inTopKAsync:()=>OM,initializers:()=>fk,input:()=>_k,io:()=>Ht,irfft:()=>$h,isFinite:()=>y1,isInf:()=>b1,isNaN:()=>x1,keep:()=>jt,kernel_impls:()=>Ja,layers:()=>Ck,leakyRelu:()=>Bc,less:()=>bh,lessEqual:()=>_i,linalg:()=>Y1,linspace:()=>v1,loadGraphModel:()=>mV,loadLayersModel:()=>DW,localResponseNormalization:()=>jy,log:()=>Dn,log1p:()=>xh,logSigmoid:()=>k1,logSoftmax:()=>wh,logSumExp:()=>Xy,logicalAnd:()=>da,logicalNot:()=>Wc,logicalOr:()=>kh,logicalXor:()=>S1,losses:()=>JP,matMul:()=>ze,math:()=>P0,max:()=>Yn,maxPool:()=>Ft,maxPool3d:()=>Yy,maxPoolWithArgmax:()=>C1,maximum:()=>Xa,mean:()=>St,memory:()=>lh,metrics:()=>zI,min:()=>Bl,minimum:()=>Wl,mirrorPad:()=>Zy,mod:()=>Jy,model:()=>FW,models:()=>BI,moments:()=>Ih,movingAverage:()=>EM,mul:()=>L,multiRNNCell:()=>aR,multinomial:()=>_1,neg:()=>Tt,nextFrame:()=>qh,norm:()=>Ph,notEqual:()=>Ai,oneHot:()=>Dl,ones:()=>Ya,onesLike:()=>Rn,op:()=>O,outerProduct:()=>lR,pad:()=>Zn,pad1d:()=>pR,pad2d:()=>hR,pad3d:()=>fR,pad4d:()=>yR,pool:()=>E1,pow:()=>yr,prelu:()=>Uc,print:()=>A0,prod:()=>Nh,profile:()=>PF,rand:()=>SR,randomGamma:()=>AR,randomNormal:()=>A1,randomUniform:()=>Vl,range:()=>Th,ready:()=>zF,real:()=>Gc,reciprocal:()=>tb,registerBackend:()=>uh,registerCallbackConstructor:()=>RW,registerGradient:()=>c0,registerKernel:()=>Tc,registerOp:()=>m4,regularizers:()=>WI,relu:()=>Ye,relu6:()=>Sh,removeBackend:()=>WF,reshape:()=>H,reverse:()=>Mn,reverse1d:()=>zR,reverse2d:()=>WR,reverse3d:()=>UR,reverse4d:()=>HR,rfft:()=>qc,round:()=>nb,rsqrt:()=>Ch,scalar:()=>de,scatterND:()=>M1,scatter_util:()=>xy,selu:()=>_h,separableConv2d:()=>Fi,sequential:()=>$W,serialization:()=>re,setBackend:()=>LF,setPlatform:()=>GF,setWasmPath:()=>nre,setWasmPaths:()=>are,setdiff1dAsync:()=>F1,sigmoid:()=>ca,sign:()=>ab,signal:()=>ZP,sin:()=>Eh,sinh:()=>Ah,slice:()=>We,slice1d:()=>Fh,slice2d:()=>rb,slice3d:()=>Ul,slice4d:()=>Hc,slice_util:()=>cn,softmax:()=>Ta,softplus:()=>zl,spaceToBatchND:()=>Vc,sparseToDense:()=>cb,spectral:()=>YP,split:()=>Pn,sqrt:()=>en,square:()=>lt,squaredDifference:()=>Dh,squeeze:()=>Qr,stack:()=>$t,step:()=>Hl,stridedSlice:()=>sb,sub:()=>fe,sum:()=>Te,sumOutType:()=>nh,tan:()=>ib,tanh:()=>Pl,tensor:()=>qn,tensor1d:()=>tt,tensor2d:()=>Sa,tensor3d:()=>ih,tensor4d:()=>Ca,tensor5d:()=>yM,tensor6d:()=>bM,tensor_util:()=>Na,test_util:()=>Z0,tidy:()=>D,tile:()=>qa,time:()=>OF,topk:()=>ob,train:()=>Di,transpose:()=>Ue,truncatedNormal:()=>Rh,unique:()=>Mh,unregisterGradient:()=>XE,unregisterKernel:()=>KE,unsortedSegmentSum:()=>lb,unstack:()=>dt,upcastType:()=>ua,util:()=>k,valueAndGrad:()=>ED,valueAndGrads:()=>AD,variable:()=>$1,variableGrads:()=>w1,version:()=>cee,version_converter:()=>wN,version_core:()=>e1,version_layers:()=>ym,version_wasm:()=>rre,where:()=>vn,whereAsync:()=>ub,zeros:()=>vt,zerosLike:()=>Ge});var rE=Object.create,md=Object.defineProperty,sE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty,oE=Object.getOwnPropertyNames,lE=Object.getOwnPropertyDescriptor,uE=e=>md(e,"__esModule",{value:!0}),un=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Oe=(e,t)=>{for(var n in t)md(e,n,{get:t[n],enumerable:!0})},cE=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of oE(t))!iE.call(e,a)&&a!=="default"&&md(e,a,{get:()=>t[a],enumerable:!(n=lE(t,a))||n.enumerable});return e},So=e=>e&&e.__esModule?e:cE(uE(md(e!=null?rE(sE(e)):{},"default",{value:e,enumerable:!0})),e),pE=un(()=>{}),dE=un((e,t)=>{(function(n,a,r){function s(c){var u=this,p=l();u.next=function(){var d=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=d-(u.c=d|0)},u.c=1,u.s0=p(" "),u.s1=p(" "),u.s2=p(" "),u.s0-=p(c),u.s0<0&&(u.s0+=1),u.s1-=p(c),u.s1<0&&(u.s1+=1),u.s2-=p(c),u.s2<0&&(u.s2+=1),p=null}function i(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function o(c,u){var p=new s(c),d=u&&u.state,h=p.next;return h.int32=function(){return p.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&i(d,p),h.state=function(){return i(p,{})}),h}function l(){var c=4022871197,u=function(p){p=p.toString();for(var d=0;d<p.length;d++){c+=p.charCodeAt(d);var h=.02519603282416938*c;c=h>>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}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)}),hE=un((e,t)=>{(function(n,a,r){function s(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var d=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^d^d>>>8},l===(l|0)?c.x=l:u+=l;for(var p=0;p<u.length+64;p++)c.x^=u.charCodeAt(p)|0,c.next()}function i(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c}function o(l,c){var u=new s(l),p=c&&c.state,d=function(){return(u.next()>>>0)/4294967296};return d.double=function(){do var h=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},d.int32=u.next,d.quick=d,p&&(typeof p=="object"&&i(p,u),d.state=function(){return i(u,{})}),d}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)}),mE=un((e,t)=>{(function(n,a,r){function s(l){var c=this,u="";c.next=function(){var d=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(d^d<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var p=0;p<u.length+64;p++)c.x^=u.charCodeAt(p)|0,p==u.length&&(c.d=c.x<<10^c.x>>>4),c.next()}function i(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function o(l,c){var u=new s(l),p=c&&c.state,d=function(){return(u.next()>>>0)/4294967296};return d.double=function(){do var h=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},d.int32=u.next,d.quick=d,p&&(typeof p=="object"&&i(p,u),d.state=function(){return i(u,{})}),d}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)}),fE=un((e,t)=>{(function(n,a,r){function s(l){var c=this;c.next=function(){var p=c.x,d=c.i,h,m,f;return h=p[d],h^=h>>>7,m=h^h<<24,h=p[d+1&7],m^=h^h>>>10,h=p[d+3&7],m^=h^h>>>3,h=p[d+4&7],m^=h^h<<7,h=p[d+7&7],h=h^h<<13,m^=h^h<<9,p[d]=m,c.i=d+1&7,m};function u(p,d){var h,m,f=[];if(d===(d|0))m=f[0]=d;else for(d=""+d,h=0;h<d.length;++h)f[h&7]=f[h&7]<<15^d.charCodeAt(h)+f[h+1&7]<<13;for(;f.length<8;)f.push(0);for(h=0;h<8&&f[h]===0;++h);for(h==8?m=f[7]=-1:m=f[h],p.x=f,p.i=0,h=256;h>0;--h)p.next()}u(c,l)}function i(l,c){return c.x=l.x.slice(),c.i=l.i,c}function o(l,c){l==null&&(l=+new Date);var u=new s(l),p=c&&c.state,d=function(){return(u.next()>>>0)/4294967296};return d.double=function(){do var h=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},d.int32=u.next,d.quick=d,p&&(p.x&&i(p,u),d.state=function(){return i(u,{})}),d}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)}),gE=un((e,t)=>{(function(n,a,r){function s(l){var c=this;c.next=function(){var p=c.w,d=c.X,h=c.i,m,f;return c.w=p=p+1640531527|0,f=d[h+34&127],m=d[h=h+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=d[h]=f^m,c.i=h,f+(p^p>>>16)|0};function u(p,d){var h,m,f,g,y,b=[],v=128;for(d===(d|0)?(m=d,d=null):(d=d+"\0",m=0,v=Math.max(v,d.length)),f=0,g=-32;g<v;++g)d&&(m^=d.charCodeAt((g+32)%d.length)),g===0&&(y=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,h=b[g&127]^=m+y,f=h==0?f+1:0);for(f>=128&&(b[(d&&d.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=b[f+34&127],h=b[f=f+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,b[f]=m^h;p.w=y,p.X=b,p.i=f}u(c,l)}function i(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function o(l,c){l==null&&(l=+new Date);var u=new s(l),p=c&&c.state,d=function(){return(u.next()>>>0)/4294967296};return d.double=function(){do var h=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},d.int32=u.next,d.quick=d,p&&(p.X&&i(p,u),d.state=function(){return i(u,{})}),d}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)}),yE=un((e,t)=>{(function(n,a,r){function s(l){var c=this,u="";c.next=function(){var d=c.b,h=c.c,m=c.d,f=c.a;return d=d<<25^d>>>7^h,h=h-m|0,m=m<<24^m>>>8^f,f=f-d|0,c.b=d=d<<20^d>>>12^h,c.c=h=h-m|0,c.d=m<<16^h>>>16^f,c.a=f-d|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var p=0;p<u.length+20;p++)c.b^=u.charCodeAt(p)|0,c.next()}function i(l,c){return c.a=l.a,c.b=l.b,c.c=l.c,c.d=l.d,c}function o(l,c){var u=new s(l),p=c&&c.state,d=function(){return(u.next()>>>0)/4294967296};return d.double=function(){do var h=u.next()>>>11,m=(u.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},d.int32=u.next,d.quick=d,p&&(typeof p=="object"&&i(p,u),d.state=function(){return i(u,{})}),d}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)}),bE=un(()=>{}),xE=un((e,t)=>{(function(n,a){var r=this,s=256,i=6,o=52,l="random",c=a.pow(s,i),u=a.pow(2,o),p=u*2,d=s-1,h;function m(N,T,C){var F=[];T=T==!0?{entropy:!0}:T||{};var $=b(y(T.entropy?[N,x(n)]:N==null?v():N,3),F),P=new f(F),B=function(){for(var W=P.g(i),G=c,q=0;W<u;)W=(W+q)*s,G*=s,q=P.g(1);for(;W>=p;)W/=2,G/=2,q>>>=1;return(W+q)/G};return B.int32=function(){return P.g(4)|0},B.quick=function(){return P.g(4)/4294967296},B.double=B,b(x(P.S),n),(T.pass||C||function(W,G,q,j){return j&&(j.S&&g(j,P),W.state=function(){return g(P,{})}),q?(a[l]=W,G):W})(B,$,"global"in T?T.global:this==a,T.state)}a["seed"+l]=m;function f(N){var T,C=N.length,F=this,$=0,P=F.i=F.j=0,B=F.S=[];for(C||(N=[C++]);$<s;)B[$]=$++;for($=0;$<s;$++)B[$]=B[P=d&P+N[$%C]+(T=B[$])],B[P]=T;(F.g=function(W){for(var G,q=0,j=F.i,X=F.j,K=F.S;W--;)G=K[j=d&j+1],q=q*s+K[d&(K[j]=K[X=d&X+G])+(K[X]=G)];return F.i=j,F.j=X,q})(s)}function g(N,T){return T.i=N.i,T.j=N.j,T.S=N.S.slice(),T}function y(N,T){var C=[],F=typeof N,$;if(T&&F=="object")for($ in N)try{C.push(y(N[$],T-1))}catch(P){}return C.length?C:F=="string"?N:N+"\0"}function b(N,T){for(var C=N+"",F,$=0;$<C.length;)T[d&$]=d&(F^=T[d&$]*19)+C.charCodeAt($++);return x(T)}function v(){try{var N;return h&&(N=h.randomBytes)?N=N(s):(N=new Uint8Array(s),(r.crypto||r.msCrypto).getRandomValues(N)),x(N)}catch(F){var T=r.navigator,C=T&&T.plugins;return[+new Date,r,C,r.screen,x(n)]}}function x(N){return String.fromCharCode.apply(0,N)}if(b(a.random(),n),typeof t=="object"&&t.exports){t.exports=m;try{h=bE()}catch(N){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)}),fd=un((e,t)=>{var n=dE(),a=hE(),r=mE(),s=fE(),i=gE(),o=yE(),l=xE();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),vE=un(()=>{}),ac=un(()=>{}),wE=un(()=>{}),kE=un(()=>{}),IE=un((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 Q.buffer!=Je&&Fn(Q.buffer),En}function i(){return Q.buffer!=Je&&Fn(Q.buffer),Qt}function o(){return Q.buffer!=Je&&Fn(Q.buffer),xn}function l(){return Q.buffer!=Je&&Fn(Q.buffer),ln}function c(){return Q.buffer!=Je&&Fn(Q.buffer),Ba}var u=typeof r!="undefined"?r:{},p={},d;for(d in u)u.hasOwnProperty(d)&&(p[d]=u[d]);var h=[],m="./this.program",f=function(w,S){throw S},g=!1,y=!1,b=!1,v=!1;g=typeof window=="object",y=typeof importScripts=="function",b=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v=!g&&!b&&!y;var x=u.ENVIRONMENT_IS_PTHREAD||!1;x&&(Je=u.buffer,ra=u.DYNAMIC_BASE,Ia=u.DYNAMICTOP_PTR);var N="";function T(w){return u.locateFile?u.locateFile(w,N):N+w}var C,F,$,P,B,W;if(b){y?N=ac().dirname(N)+"/":N=__dirname+"/",C=function(w,S){return B||(B=require("fs")),W||(W=ac()),w=W.normalize(w),B.readFileSync(w,S?null:"utf8")},$=function(w){var S=C(w,!0);return S.buffer||(S=new Uint8Array(S)),ke(S.buffer),S},process.argv.length>1&&(m=process.argv[1].replace(/\\/g,"/")),h=process.argv.slice(2),process.on("uncaughtException",function(w){if(!(w instanceof jw))throw w}),process.on("unhandledRejection",pr),f=function(w){process.exit(w)},u.inspect=function(){return"[Emscripten Module object]"};var G;try{G=wE()}catch(w){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),w}Worker=G.Worker}else v?(typeof read!="undefined"&&(C=function(w){return read(w)}),$=function(w){var S;return typeof readbuffer=="function"?new Uint8Array(readbuffer(w)):(S=read(w,"binary"),ke(typeof S=="object"),S)},typeof scriptArgs!="undefined"?h=scriptArgs:typeof arguments!="undefined"&&(h=arguments),typeof quit=="function"&&(f=function(w){quit(w)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(g||y)&&(y?N=self.location.href:document.currentScript&&(N=document.currentScript.src),typeof a!="undefined"&&a&&(N=a),N.indexOf("blob:")!==0?N=N.substr(0,N.lastIndexOf("/")+1):N="",b?(C=function(w,S){return B||(B=require("fs")),W||(W=ac()),w=W.normalize(w),B.readFileSync(w,S?null:"utf8")},$=function(w){var S=C(w,!0);return S.buffer||(S=new Uint8Array(S)),ke(S.buffer),S}):(C=function(w){var S=new XMLHttpRequest;return S.open("GET",w,!1),S.send(null),S.responseText},y&&($=function(w){var S=new XMLHttpRequest;return S.open("GET",w,!1),S.responseType="arraybuffer",S.send(null),new Uint8Array(S.response)}),F=function(w,S,R){var U=new XMLHttpRequest;U.open("GET",w,!0),U.responseType="arraybuffer",U.onload=function(){if(U.status==200||U.status==0&&U.response){S(U.response);return}R()},U.onerror=R,U.send(null)}),P=function(w){document.title=w});b&&typeof performance=="undefined"&&(performance=kE().performance);var q=u.print||console.log.bind(console),j=u.printErr||console.warn.bind(console);for(d in p)p.hasOwnProperty(d)&&(u[d]=p[d]);p=null,u.arguments&&(h=u.arguments),u.thisProgram&&(m=u.thisProgram),u.quit&&(f=u.quit);var X=Atomics.load,K=Atomics.store,ne=Atomics.compareExchange,J;u.wasmBinary&&(J=u.wasmBinary);var se;u.noExitRuntime&&(se=u.noExitRuntime),typeof WebAssembly!="object"&&j("no native wasm support detected");var Q,oe=new WebAssembly.Table({initial:171,maximum:171+0,element:"anyfunc"}),ae,pe=0,ue=0,ge=!1,ye=0;function ke(w,S){w||pr("Assertion failed: "+S)}function Se(w){var S=u["_"+w];return ke(S,"Cannot call unknown function "+w+", make sure it is exported"),S}function Ce(w,S,R,U,he){var le={string:function(jn){var Pr=0;if(jn!=null&&jn!==0){var nc=(jn.length<<2)+1;Pr=ko(nc),ot(jn,Pr,nc)}return Pr},array:function(jn){var Pr=ko(jn.length);return ct(jn,Pr),Pr}};function ie(jn){return S==="string"?Ve(jn):S==="boolean"?Boolean(jn):jn}var xe=Se(w),et=[],Mt=0;if(U)for(var rn=0;rn<U.length;rn++){var No=le[R[rn]];No?(Mt===0&&(Mt=Qu()),et[rn]=No(U[rn])):et[rn]=U[rn]}var tc=xe.apply(null,et);return tc=ie(tc),Mt!==0&&Io(Mt),tc}function Re(w,S,R,U){R=R||[];var he=R.every(function(ie){return ie==="number"}),le=S!=="string";return le&&he&&!U?Se(w):function(){return Ce(w,S,R,arguments,U)}}function Ke(w,S,R){for(var U=S+R,he="";!(S>=U);){var le=w[S++];if(!le)return he;if(!(le&128)){he+=String.fromCharCode(le);continue}var ie=w[S++]&63;if((le&224)==192){he+=String.fromCharCode((le&31)<<6|ie);continue}var xe=w[S++]&63;if((le&240)==224?le=(le&15)<<12|ie<<6|xe:le=(le&7)<<18|ie<<12|xe<<6|w[S++]&63,le<65536)he+=String.fromCharCode(le);else{var et=le-65536;he+=String.fromCharCode(55296|et>>10,56320|et&1023)}}return he}function Ve(w,S){return w?Ke(i(),w,S):""}function rt(w,S,R,U){if(!(U>0))return 0;for(var he=R,le=R+U-1,ie=0;ie<w.length;++ie){var xe=w.charCodeAt(ie);if(xe>=55296&&xe<=57343){var et=w.charCodeAt(++ie);xe=65536+((xe&1023)<<10)|et&1023}if(xe<=127){if(R>=le)break;S[R++]=xe}else if(xe<=2047){if(R+1>=le)break;S[R++]=192|xe>>6,S[R++]=128|xe&63}else if(xe<=65535){if(R+2>=le)break;S[R++]=224|xe>>12,S[R++]=128|xe>>6&63,S[R++]=128|xe&63}else{if(R+3>=le)break;S[R++]=240|xe>>18,S[R++]=128|xe>>12&63,S[R++]=128|xe>>6&63,S[R++]=128|xe&63}}return S[R]=0,R-he}function ot(w,S,R){return rt(w,i(),S,R)}function He(w){for(var S=0,R=0;R<w.length;++R){var U=w.charCodeAt(R);U>=55296&&U<=57343&&(U=65536+((U&1023)<<10)|w.charCodeAt(++R)&1023),U<=127?++S:U<=2047?S+=2:U<=65535?S+=3:S+=4}return S}function ct(w,S){s().set(w,S)}var pt=65536;function Gn(w,S){return w%S>0&&(w+=S-w%S),w}var Je,En,Qt,An,na,xn,ln,aa,Ba;function Fn(w){Je=w,u.HEAP8=En=new Int8Array(w),u.HEAP16=An=new Int16Array(w),u.HEAP32=xn=new Int32Array(w),u.HEAPU8=Qt=new Uint8Array(w),u.HEAPU16=na=new Uint16Array(w),u.HEAPU32=ln=new Uint32Array(w),u.HEAPF32=aa=new Float32Array(w),u.HEAPF64=Ba=new Float64Array(w)}var ho=5256464,zu=ho,ka=13584,ra=5256464,Ia=12656,mo=u.INITIAL_MEMORY||16777216;if(x)Q=u.wasmMemory,Je=u.buffer;else if(u.wasmMemory)Q=u.wasmMemory;else if(Q=new WebAssembly.Memory({initial:mo/pt,maximum:2147483648/pt,shared:!0}),!(Q.buffer instanceof SharedArrayBuffer))throw j("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Q&&(Je=Q.buffer),mo=Je.byteLength,Fn(Je),x||(o()[Ia>>2]=ra);function fo(w){for(;w.length>0;){var S=w.shift();if(typeof S=="function"){S(u);continue}var R=S.func;typeof R=="number"?S.arg===void 0?u.dynCall_v(R):u.dynCall_vi(R,S.arg):R(S.arg===void 0?null:S.arg)}}var ys=[],Bu=[],Rf=[],Wu=[],Up=[],Vu=!1;x&&(Vu=!0);function sa(){if(!x){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)Of(u.preRun.shift());fo(ys)}}function Gp(){Vu=!0,fo(Bu)}function Mf(){x||fo(Rf)}function Pf(){if(!x){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)bs(u.postRun.shift());fo(Up)}}function Of(w){ys.unshift(w)}function bs(w){Up.unshift(w)}var go=Math.ceil,Lf=Math.floor,cr=0,Uu=null,xs=null;function zf(w){ke(!x,"addRunDependency cannot be used in a pthread worker"),cr++,u.monitorRunDependencies&&u.monitorRunDependencies(cr)}function Bf(w){if(cr--,u.monitorRunDependencies&&u.monitorRunDependencies(cr),cr==0&&(Uu!==null&&(clearInterval(Uu),Uu=null),xs)){var S=xs;xs=null,S()}}u.preloadedImages={},u.preloadedAudios={};function pr(w){throw u.onAbort&&u.onAbort(w),x&&console.error("Pthread aborting at "+new Error().stack),w+="",q(w),j(w),ge=!0,ye=1,w="abort("+w+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(w)}function Gu(w,S){return String.prototype.startsWith?w.startsWith(S):w.indexOf(S)===0}var Wf="data:application/octet-stream;base64,";function Hp(w){return Gu(w,Wf)}var Vf="file://";function jp(w){return Gu(w,Vf)}var ia="tfjs-backend-wasm-threaded-simd.wasm";Hp(ia)||(ia=T(ia));function qp(){try{if(J)return new Uint8Array(J);if($)return $(ia);throw"both async and sync fetching of the wasm failed"}catch(w){pr(w)}}function Uf(){return!J&&(g||y)&&typeof fetch=="function"&&!jp(ia)?fetch(ia,{credentials:"same-origin"}).then(function(w){if(!w.ok)throw"failed to load wasm binary file at '"+ia+"'";return w.arrayBuffer()}).catch(function(){return qp()}):new Promise(function(w,S){w(qp())})}function Gf(){var w={a:Mg};function S(ie,xe){var et=ie.exports;if(u.asm=et,ae=xe,!x){var Mt=me.unusedWorkers.length;me.unusedWorkers.forEach(function(rn){me.loadWasmModuleToWorker(rn,function(){--Mt||Bf("wasm-instantiate")})})}}x||zf("wasm-instantiate");function R(ie){S(ie.instance,ie.module)}function U(ie){return Uf().then(function(xe){return WebAssembly.instantiate(xe,w)}).then(ie,function(xe){j("failed to asynchronously prepare wasm: "+xe),pr(xe)})}function he(){if(!J&&typeof WebAssembly.instantiateStreaming=="function"&&!Hp(ia)&&!jp(ia)&&typeof fetch=="function")fetch(ia,{credentials:"same-origin"}).then(function(ie){var xe=WebAssembly.instantiateStreaming(ie,w);return xe.then(R,function(et){j("wasm streaming compile failed: "+et),j("falling back to ArrayBuffer instantiation"),U(R)})});else return U(R)}if(u.instantiateWasm)try{var le=u.instantiateWasm(w,S);return le}catch(ie){return j("Module.instantiateWasm callback failed with error: "+ie),!1}return he(),{}}var Hf={};function jf(){me.initRuntime()}x||Bu.push({func:function(){sd()}});var Kp=0,Xp=0,Yp=0;function yo(w,S,R){w=w|0,S=S|0,R=R|0,Kp=w,Yp=S,Xp=R}u.__register_pthread_ptr=yo;var Hu={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},bo=13568;function xo(w,S){if(w<=0||w>s().length||w&!0||S<0)return-28;if(S==0)return 0;S>=2147483647&&(S=Infinity);var R=Atomics.load(o(),bo>>2),U=0;if(R==w){var he=Atomics.compareExchange(o(),bo>>2,R,0);if(he==R&&(--S,U=1,S<=0))return 1}var le=Atomics.notify(o(),w>>2,S);if(le>=0)return le+U;throw"Atomics.notify returned an unexpected value "+le}u._emscripten_futex_wake=xo;function qf(w){if(x)throw"Internal Error! _kill_thread() can only ever be called from main application thread!";if(!w)throw"Internal Error! Null pthread_ptr in _kill_thread!";o()[w+12>>2]=0;var S=me.pthreads[w];S.worker.terminate(),me.freeThreadData(S),me.runningWorkers.splice(me.runningWorkers.indexOf(S.worker),1),S.worker.pthread=void 0}function Kf(w){if(x)throw"Internal Error! _cancel_thread() can only ever be called from main application thread!";if(!w)throw"Internal Error! Null pthread_ptr in _cancel_thread!";var S=me.pthreads[w];S.worker.postMessage({cmd:"cancel"})}function Xf(w){if(x)throw"Internal Error! _cleanup_thread() can only ever be called from main application thread!";if(!w)throw"Internal Error! Null pthread_ptr in _cleanup_thread!";o()[w+12>>2]=0;var S=me.pthreads[w];if(S){var R=S.worker;me.returnWorkerToPool(R)}}var me={MAIN_THREAD_ID:1,mainThreadInfo:{schedPolicy:0,schedPrio:0},unusedWorkers:[],runningWorkers:[],initRuntime:function(){yo(me.mainThreadBlock,!y,1),Vw(me.mainThreadBlock)},initMainThreadBlock:function(){for(var w=8,S=0;S<w;++S)me.allocateUnusedWorker();me.mainThreadBlock=12816;for(var S=0;S<232/4;++S)l()[me.mainThreadBlock/4+S]=0;o()[me.mainThreadBlock+12>>2]=me.mainThreadBlock;var R=me.mainThreadBlock+156;o()[R>>2]=R;for(var U=13056,S=0;S<128;++S)l()[U/4+S]=0;Atomics.store(l(),me.mainThreadBlock+104>>2,U),Atomics.store(l(),me.mainThreadBlock+40>>2,me.mainThreadBlock),Atomics.store(l(),me.mainThreadBlock+44>>2,42)},initWorker:function(){},pthreads:{},exitHandlers:null,setThreadStatus:function(){},runExitHandlers:function(){if(me.exitHandlers!==null){for(;me.exitHandlers.length>0;)me.exitHandlers.pop()();me.exitHandlers=null}x&&pe&&Ww()},threadExit:function(w){var S=Wa();S&&(Atomics.store(l(),S+4>>2,w),Atomics.store(l(),S+0>>2,1),Atomics.store(l(),S+60>>2,1),Atomics.store(l(),S+64>>2,0),me.runExitHandlers(),xo(S+0,2147483647),yo(0,0,0),pe=0,x&&postMessage({cmd:"exit"}))},threadCancel:function(){me.runExitHandlers(),Atomics.store(l(),pe+4>>2,-1),Atomics.store(l(),pe+0>>2,1),xo(pe+0,2147483647),pe=ue=0,yo(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var w in me.pthreads){var S=me.pthreads[w];S&&S.worker&&me.returnWorkerToPool(S.worker)}me.pthreads={};for(var R=0;R<me.unusedWorkers.length;++R){var U=me.unusedWorkers[R];U.terminate()}me.unusedWorkers=[];for(var R=0;R<me.runningWorkers.length;++R){var U=me.runningWorkers[R],S=U.pthread;me.freeThreadData(S),U.terminate()}me.runningWorkers=[]},freeThreadData:function(w){if(w){if(w.threadInfoStruct){var S=o()[w.threadInfoStruct+104>>2];o()[w.threadInfoStruct+104>>2]=0,Ju(S),Ju(w.threadInfoStruct)}w.threadInfoStruct=0,w.allocatedOwnStack&&w.stackBase&&Ju(w.stackBase),w.stackBase=0,w.worker&&(w.worker.pthread=null)}},returnWorkerToPool:function(w){delete me.pthreads[w.pthread.thread],me.unusedWorkers.push(w),me.runningWorkers.splice(me.runningWorkers.indexOf(w),1),me.freeThreadData(w.pthread),w.pthread=void 0},receiveObjectTransfer:function(w){},loadWasmModuleToWorker:function(w,S){w.onmessage=function(R){var U=R.data,he=U.cmd;if(w.pthread&&(me.currentProxiedOperationCallerThread=w.pthread.threadInfoStruct),U.targetThread&&U.targetThread!=Wa()){var le=me.pthreads[U.targetThread];le?le.worker.postMessage(R.data,U.transferList):console.error('Internal error! Worker sent a message "'+he+'" to target pthread '+U.targetThread+", but that thread no longer exists!"),me.currentProxiedOperationCallerThread=void 0;return}if(he==="processQueuedMainThreadWork")Lg();else if(he==="spawnThread")nd(R.data);else if(he==="cleanupThread")Xf(U.thread);else if(he==="killThread")qf(U.thread);else if(he==="cancelThread")Kf(U.thread);else if(he==="loaded")w.loaded=!0,S&&S(w),w.runPthread&&(w.runPthread(),delete w.runPthread);else if(he==="print")q("Thread "+U.threadId+": "+U.text);else if(he==="printErr")j("Thread "+U.threadId+": "+U.text);else if(he==="alert")alert("Thread "+U.threadId+": "+U.text);else if(he==="exit"){var ie=w.pthread&&Atomics.load(l(),w.pthread.thread+68>>2);ie&&me.returnWorkerToPool(w)}else he==="cancelDone"?me.returnWorkerToPool(w):he==="objectTransfer"?me.receiveObjectTransfer(R.data):R.data.target==="setimmediate"?w.postMessage(R.data):j("worker sent an unknown command "+he);me.currentProxiedOperationCallerThread=void 0},w.onerror=function(R){j("pthread sent an error! "+R.filename+":"+R.lineno+": "+R.message)},b&&(w.on("message",function(R){w.onmessage({data:R})}),w.on("error",function(R){w.onerror(R)}),w.on("exit",function(R){console.log("worker exited - TODO: update the worker queue?")})),w.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||a,wasmMemory:Q,wasmModule:ae,DYNAMIC_BASE:ra,DYNAMICTOP_PTR:Ia})},allocateUnusedWorker:function(){var w=T("tfjs-backend-wasm-threaded-simd.worker.js");me.unusedWorkers.push(new Worker(w))},getNewWorker:function(){return me.unusedWorkers.length==0&&(me.allocateUnusedWorker(),me.loadWasmModuleToWorker(me.unusedWorkers[0])),me.unusedWorkers.length>0?me.unusedWorkers.pop():null},busySpinWait:function(w){for(var S=performance.now()+w;performance.now()<S;);}};function Yf(w,S){ho=zu=w,ka=S,Io(w)}u.establishStackSpace=Yf;function Zf(){return se}u.getNoExitRuntime=Zf;function Jf(w,S,R,U){pr("Assertion failed: "+Ve(w)+", at: "+[S?Ve(S):"unknown filename",R,U?Ve(U):"unknown function"])}function Qf(w,S){var R=_main(w,S)}var vs;b?vs=function(){var w=process.hrtime();return w[0]*1e3+w[1]/1e6}:x?vs=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?vs=dateNow:vs=function(){return performance.now()};function eg(w){return o()[Lw()>>2]=w,w}function tg(w,S){if(x)return Dr(1,1,w,S);Wu.unshift({func:w,arg:S})}function ng(w,S){if(w==S)postMessage({cmd:"processQueuedMainThreadWork"});else if(x)postMessage({targetThread:w,cmd:"processThreadQueue"});else{var R=me.pthreads[w],U=R&&R.worker;if(!U)return;U.postMessage({cmd:"processThreadQueue"})}return 1}function ag(){pr()}function rg(w,S){w=w|0,S=S|0}function sg(w,S,R){if(w<=0||w>s().length||w&!0)return-28;if(y){var U=Atomics.wait(o(),w>>2,S,R);if(U==="timed-out")return-73;if(U==="not-equal")return-6;if(U==="ok")return 0;throw"Atomics.wait returned an unexpected value "+U}else{var he=Atomics.load(o(),w>>2);if(S!=he)return-6;var le=performance.now(),ie=le+R;Atomics.store(o(),bo>>2,w);for(var xe=w;w==xe;){if(le=performance.now(),le>ie)return-73;Lg(),w=Atomics.load(o(),bo>>2)}return 0}}function ig(){return Yp|0}function og(){return Xp|0}function lg(w,S,R){i().copyWithin(w,S,S+R)}function ug(){return navigator.hardwareConcurrency}function Dr(w,S){for(var R=arguments.length-2,U=Qu(),he=ko(R*8),le=he>>3,ie=0;ie<R;ie++)c()[le+ie]=arguments[2+ie];var xe=Gw(w,R,he,S);return Io(U),xe}var ws=[];function vo(w,S){vo.array||(vo.array=[]);var R=vo.array;R.length=0;for(var U;U=i()[w++];)U===100||U===102?(S=S+7&~7,R.push(c()[S>>3]),S+=8):(S=S+3&~3,R.push(o()[S>>2]),S+=4);return R}function cg(w,S,R){ws.length=S;for(var U=R>>3,he=0;he<S;he++)ws[he]=c()[U+he];var le=w<0,ie=le?Hf[-w-1]:Rg[w];if(le){var xe=ws[1],et=ws[2],Mt=vo(xe,et);return ie.apply(null,Mt)}return ie.apply(null,ws)}function pg(){return i().length}function dg(w){try{return Q.grow(w-Je.byteLength+65535>>>16),Fn(Q.buffer),1}catch(S){}}function hg(w){w=w>>>0;var S=pg();if(w<=S)return!1;var R=65536,U=2147483648;if(w>U)return!1;for(var he=16777216,le=1;le<=4;le*=2){var ie=S*(1+.2/le);ie=Math.min(ie,w+100663296);var xe=Math.min(U,Gn(Math.max(he,w,ie),R)),et=dg(xe);if(et)return!0}return!1}var Pe={keyEvent:0,mouseEvent:0,wheelEvent:0,uiEvent:0,focusEvent:0,deviceOrientationEvent:0,deviceMotionEvent:0,fullscreenChangeEvent:0,pointerlockChangeEvent:0,visibilityChangeEvent:0,touchEvent:0,previousFullscreenElement:null,previousScreenX:null,previousScreenY:null,removeEventListenersRegistered:!1,removeAllEventListeners:function(){for(var w=Pe.eventHandlers.length-1;w>=0;--w)Pe._removeHandler(w);Pe.eventHandlers=[],Pe.deferredCalls=[]},registerRemoveEventListeners:function(){Pe.removeEventListenersRegistered||(Wu.push(Pe.removeAllEventListeners),Pe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(w,S,R){function U(ie,xe){if(ie.length!=xe.length)return!1;for(var et in ie)if(ie[et]!=xe[et])return!1;return!0}for(var he in Pe.deferredCalls){var le=Pe.deferredCalls[he];if(le.targetFunction==w&&U(le.argsList,R))return}Pe.deferredCalls.push({targetFunction:w,precedence:S,argsList:R}),Pe.deferredCalls.sort(function(ie,xe){return ie.precedence<xe.precedence})},removeDeferredCalls:function(w){for(var S=0;S<Pe.deferredCalls.length;++S)Pe.deferredCalls[S].targetFunction==w&&(Pe.deferredCalls.splice(S,1),--S)},canPerformEventHandlerRequests:function(){return Pe.inEventHandler&&Pe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(Pe.canPerformEventHandlerRequests())for(var w=0;w<Pe.deferredCalls.length;++w){var S=Pe.deferredCalls[w];Pe.deferredCalls.splice(w,1),--w,S.targetFunction.apply(null,S.argsList)}},inEventHandler:0,currentEventHandler:null,eventHandlers:[],removeAllHandlersOnTarget:function(w,S){for(var R=0;R<Pe.eventHandlers.length;++R)Pe.eventHandlers[R].target==w&&(!S||S==Pe.eventHandlers[R].eventTypeString)&&Pe._removeHandler(R--)},_removeHandler:function(w){var S=Pe.eventHandlers[w];S.target.removeEventListener(S.eventTypeString,S.eventListenerFunc,S.useCapture),Pe.eventHandlers.splice(w,1)},registerOrRemoveHandler:function(w){var S=function(U){++Pe.inEventHandler,Pe.currentEventHandler=w,Pe.runDeferredCalls(),w.handlerFunc(U),Pe.runDeferredCalls(),--Pe.inEventHandler};if(w.callbackfunc)w.eventListenerFunc=S,w.target.addEventListener(w.eventTypeString,S,w.useCapture),Pe.eventHandlers.push(w),Pe.registerRemoveEventListeners();else for(var R=0;R<Pe.eventHandlers.length;++R)Pe.eventHandlers[R].target==w.target&&Pe.eventHandlers[R].eventTypeString==w.eventTypeString&&Pe._removeHandler(R--)},queueEventHandlerOnThread_iiii:function(w,S,R,U,he){var le=Qu(),ie=ko(12);o()[ie>>2]=R,o()[ie+4>>2]=U,o()[ie+8>>2]=he,zg(w,637534208,S,U,ie),Io(le)},getTargetThreadForEventCallback:function(w){switch(w){case 1:return 0;case 2:return me.currentProxiedOperationCallerThread;default:return w}},getNodeNameForTarget:function(w){return w?w==window?"#window":w==screen?"#screen":w&&w.nodeName?w.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function mg(w){var S=He(w)+1,R=Zu(S);return ot(w,R,S),R}function fg(w,S,R,U){var he=Qu(),le=ko(12),ie=0;S&&(ie=mg(S)),o()[le>>2]=ie,o()[le+4>>2]=R,o()[le+8>>2]=U,zg(w,657457152,0,ie,le),Io(he)}function gg(w,S,R,U){S=S?Ve(S):"",fg(w,S,R,U)}function yg(w){return w>2?Ve(w):w}var bg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function xg(w){w=yg(w);var S=bg[w]||(typeof document!="undefined"?document.querySelector(w):void 0);return S}function ju(w){return xg(w)}function Zp(w,S,R){var U=ju(w);if(!U)return-4;if(U.canvasSharedPtr&&(o()[U.canvasSharedPtr>>2]=S,o()[U.canvasSharedPtr+4>>2]=R),U.offscreenCanvas||!U.controlTransferredOffscreen){U.offscreenCanvas&&(U=U.offscreenCanvas);var he=!1;if(U.GLctxObject&&U.GLctxObject.GLctx){var le=U.GLctxObject.GLctx.getParameter(2978);he=le[0]===0&&le[1]===0&&le[2]===U.width&&le[3]===U.height}U.width=S,U.height=R,he&&U.GLctxObject.GLctx.viewport(0,0,S,R)}else if(U.canvasSharedPtr){var ie=o()[U.canvasSharedPtr+8>>2];return gg(ie,w,S,R),1}else return-4;return 0}function Jp(w,S,R){return x?Dr(2,1,w,S,R):Zp(w,S,R)}function vg(w,S,R){var U=ju(w);return U?Zp(w,S,R):Jp(w,S,R)}function wg(w){w=w|0}function kg(w,S){w=w|0,S=S|0}function Ig(w){var S=w.getExtension("ANGLE_instanced_arrays");if(S)return w.vertexAttribDivisor=function(R,U){S.vertexAttribDivisorANGLE(R,U)},w.drawArraysInstanced=function(R,U,he,le){S.drawArraysInstancedANGLE(R,U,he,le)},w.drawElementsInstanced=function(R,U,he,le,ie){S.drawElementsInstancedANGLE(R,U,he,le,ie)},1}function Ng(w){var S=w.getExtension("OES_vertex_array_object");if(S)return w.createVertexArray=function(){return S.createVertexArrayOES()},w.deleteVertexArray=function(R){S.deleteVertexArrayOES(R)},w.bindVertexArray=function(R){S.bindVertexArrayOES(R)},w.isVertexArray=function(R){return S.isVertexArrayOES(R)},1}function Tg(w){var S=w.getExtension("WEBGL_draw_buffers");if(S)return w.drawBuffers=function(R,U){S.drawBuffersWEBGL(R,U)},1}var Be={counter:1,lastError:0,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},currentContext:null,offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,init:function(){for(var w=new Float32Array(Be.MINI_TEMP_BUFFER_SIZE),S=0;S<Be.MINI_TEMP_BUFFER_SIZE;S++)Be.miniTempBufferFloatViews[S]=w.subarray(0,S+1);for(var R=new Int32Array(Be.MINI_TEMP_BUFFER_SIZE),S=0;S<Be.MINI_TEMP_BUFFER_SIZE;S++)Be.miniTempBufferIntViews[S]=R.subarray(0,S+1)},recordError:function(w){Be.lastError||(Be.lastError=w)},getNewId:function(w){for(var S=Be.counter++,R=w.length;R<S;R++)w[R]=null;return S},MINI_TEMP_BUFFER_SIZE:256,miniTempBufferFloatViews:[0],miniTempBufferIntViews:[0],getSource:function(w,S,R,U){for(var he="",le=0;le<S;++le){var ie=U?o()[U+le*4>>2]:-1;he+=Ve(o()[R+le*4>>2],ie<0?void 0:ie)}return he},createContext:function(w,S){var R=w.getContext("webgl",S);if(!R)return 0;var U=Be.registerContext(R,S);return U},registerContext:function(w,S){var R=Zu(8);o()[R+4>>2]=Wa();var U={handle:R,attributes:S,version:S.majorVersion,GLctx:w};return w.canvas&&(w.canvas.GLctxObject=U),Be.contexts[R]=U,(typeof S.enableExtensionsByDefault=="undefined"||S.enableExtensionsByDefault)&&Be.initExtensions(U),R},makeContextCurrent:function(w){return Be.currentContext=Be.contexts[w],u.ctx=Rr=Be.currentContext&&Be.currentContext.GLctx,!(w&&!Rr)},getContext:function(w){return Be.contexts[w]},deleteContext:function(w){Be.currentContext===Be.contexts[w]&&(Be.currentContext=null),typeof Pe=="object"&&Pe.removeAllHandlersOnTarget(Be.contexts[w].GLctx.canvas),Be.contexts[w]&&Be.contexts[w].GLctx.canvas&&(Be.contexts[w].GLctx.canvas.GLctxObject=void 0),Ju(Be.contexts[w].handle),Be.contexts[w]=null},initExtensions:function(w){if(w||(w=Be.currentContext),!w.initExtensionsDone){w.initExtensionsDone=!0;var S=w.GLctx;Ig(S),Ng(S),Tg(S),S.disjointTimerQueryExt=S.getExtension("EXT_disjoint_timer_query");var R=["OES_texture_float","OES_texture_half_float","OES_standard_derivatives","OES_vertex_array_object","WEBGL_compressed_texture_s3tc","WEBGL_depth_texture","OES_element_index_uint","EXT_texture_filter_anisotropic","EXT_frag_depth","WEBGL_draw_buffers","ANGLE_instanced_arrays","OES_texture_float_linear","OES_texture_half_float_linear","EXT_blend_minmax","EXT_shader_texture_lod","EXT_texture_norm16","WEBGL_compressed_texture_pvrtc","EXT_color_buffer_half_float","WEBGL_color_buffer_float","EXT_sRGB","WEBGL_compressed_texture_etc1","EXT_disjoint_timer_query","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_astc","EXT_color_buffer_float","WEBGL_compressed_texture_s3tc_srgb","EXT_disjoint_timer_query_webgl2","WEBKIT_WEBGL_compressed_texture_pvrtc"],U=S.getSupportedExtensions()||[];U.forEach(function(he){R.indexOf(he)!=-1&&S.getExtension(he)})}},populateUniformTable:function(w){for(var S=Be.programs[w],R=Be.programInfos[w]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},U=R.uniforms,he=Rr.getProgramParameter(S,35718),le=0;le<he;++le){var ie=Rr.getActiveUniform(S,le),xe=ie.name;R.maxUniformLength=Math.max(R.maxUniformLength,xe.length+1),xe.slice(-1)=="]"&&(xe=xe.slice(0,xe.lastIndexOf("[")));var et=Rr.getUniformLocation(S,xe);if(et){var Mt=Be.getNewId(Be.uniforms);U[xe]=[ie.size,Mt],Be.uniforms[Mt]=et;for(var rn=1;rn<ie.size;++rn){var No=xe+"["+rn+"]";et=Rr.getUniformLocation(S,No),Mt=Be.getNewId(Be.uniforms),Be.uniforms[Mt]=et}}}}},Sg=["default","low-power","high-performance"];function Cg(w,S){var R={},U=S>>2;R.alpha=!!o()[U+(0>>2)],R.depth=!!o()[U+(4>>2)],R.stencil=!!o()[U+(8>>2)],R.antialias=!!o()[U+(12>>2)],R.premultipliedAlpha=!!o()[U+(16>>2)],R.preserveDrawingBuffer=!!o()[U+(20>>2)];var he=o()[U+(24>>2)];R.powerPreference=Sg[he],R.failIfMajorPerformanceCaveat=!!o()[U+(28>>2)],R.majorVersion=o()[U+(32>>2)],R.minorVersion=o()[U+(36>>2)],R.enableExtensionsByDefault=o()[U+(40>>2)],R.explicitSwapControl=o()[U+(44>>2)],R.proxyContextToMainThread=o()[U+(48>>2)],R.renderViaOffscreenBackBuffer=o()[U+(52>>2)];var le=ju(w);if(!le)return-4;if(R.explicitSwapControl)return-1;var ie=Be.createContext(le,R);return ie}function _g(w,S){return Cg(w,S)}var ks={splitPath:function(w){var S=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return S.exec(w).slice(1)},normalizeArray:function(w,S){for(var R=0,U=w.length-1;U>=0;U--){var he=w[U];he==="."?w.splice(U,1):he===".."?(w.splice(U,1),R++):R&&(w.splice(U,1),R--)}if(S)for(;R;R--)w.unshift("..");return w},normalize:function(w){var S=w.charAt(0)==="/",R=w.substr(-1)==="/";return w=ks.normalizeArray(w.split("/").filter(function(U){return!!U}),!S).join("/"),!w&&!S&&(w="."),w&&R&&(w+="/"),(S?"/":"")+w},dirname:function(w){var S=ks.splitPath(w),R=S[0],U=S[1];return!R&&!U?".":(U&&(U=U.substr(0,U.length-1)),R+U)},basename:function(w){if(w==="/")return"/";var S=w.lastIndexOf("/");return S===-1?w:w.substr(S+1)},extname:function(w){return ks.splitPath(w)[3]},join:function(){var w=Array.prototype.slice.call(arguments,0);return ks.normalize(w.join("/"))},join2:function(w,S){return ks.normalize(w+"/"+S)}},wo={mappings:{},buffers:[null,[],[]],printChar:function(w,S){var R=wo.buffers[w];S===0||S===10?((w===1?q:j)(Ke(R,0)),R.length=0):R.push(S)},varargs:void 0,get:function(){wo.varargs+=4;var w=o()[wo.varargs-4>>2];return w},getStr:function(w){var S=Ve(w);return S},get64:function(w,S){return w}};function Qp(w){return x?Dr(3,1,w):0}function ed(w,S,R,U,he){if(x)return Dr(4,1,w,S,R,U,he)}function td(w,S,R,U){if(x)return Dr(5,1,w,S,R,U);for(var he=0,le=0;le<R;le++){for(var ie=o()[S+le*8>>2],xe=o()[S+(le*8+4)>>2],et=0;et<xe;et++)wo.printChar(w,i()[ie+et]);he+=xe}return o()[U>>2]=he,0}function Eg(w){var S=me.exitHandlers.pop();w&&S()}function Ag(w,S){me.exitHandlers===null&&(me.exitHandlers=[]),me.exitHandlers.push(function(){Hw(w,S)})}function nd(w){if(x)throw"Internal Error! _spawn_thread() can only ever be called from main application thread!";var S=me.getNewWorker();if(S.pthread!==void 0)throw"Internal error!";if(!w.pthread_ptr)throw"Internal error, no pthread ptr!";me.runningWorkers.push(S);for(var R=Zu(128*4),U=0;U<128;++U)o()[R+U*4>>2]=0;var he=w.stackBase+w.stackSize,le=me.pthreads[w.pthread_ptr]={worker:S,stackBase:w.stackBase,stackSize:w.stackSize,allocatedOwnStack:w.allocatedOwnStack,thread:w.pthread_ptr,threadInfoStruct:w.pthread_ptr},ie=le.threadInfoStruct>>2;Atomics.store(l(),ie+(0>>2),0),Atomics.store(l(),ie+(4>>2),0),Atomics.store(l(),ie+(8>>2),0),Atomics.store(l(),ie+(68>>2),w.detached),Atomics.store(l(),ie+(104>>2),R),Atomics.store(l(),ie+(48>>2),0),Atomics.store(l(),ie+(40>>2),le.threadInfoStruct),Atomics.store(l(),ie+(44>>2),42),Atomics.store(l(),ie+(108>>2),w.stackSize),Atomics.store(l(),ie+(84>>2),w.stackSize),Atomics.store(l(),ie+(80>>2),he),Atomics.store(l(),ie+(108+8>>2),he),Atomics.store(l(),ie+(108+12>>2),w.detached),Atomics.store(l(),ie+(108+20>>2),w.schedPolicy),Atomics.store(l(),ie+(108+24>>2),w.schedPrio);var xe=zw(),et=xe+40;Atomics.store(l(),ie+(176>>2),et),S.pthread=le;var Mt={cmd:"run",start_routine:w.startRoutine,arg:w.arg,threadInfoStruct:w.pthread_ptr,selfThreadId:w.pthread_ptr,parentThreadId:w.parent_pthread_ptr,stackBase:w.stackBase,stackSize:w.stackSize};S.runPthread=function(){Mt.time=performance.now(),S.postMessage(Mt,w.transferList)},S.loaded&&(S.runPthread(),delete S.runPthread)}function Fg(w,S,R){if(!S&&!R)return Hu.EINVAL;if(!w)return j("pthread_getschedparam called with a null thread pointer!"),Hu.ESRCH;var U=o()[w+12>>2];if(U!==w)return j("pthread_getschedparam attempted on thread "+w+", which does not point to a valid thread, or does not exist anymore!"),Hu.ESRCH;var he=Atomics.load(l(),w+108+20>>2),le=Atomics.load(l(),w+108+24>>2);return S&&(o()[S>>2]=he),R&&(o()[R>>2]=le),0}function Wa(){return Kp|0}u._pthread_self=Wa;function $g(w,S,R,U){if(typeof SharedArrayBuffer=="undefined")return j("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!w)return j("pthread_create called with a null thread pointer!"),28;var he=[],le=0;if(x&&(he.length===0||le))return Uw(687865856,w,S,R,U);if(le)return le;var ie=0,xe=0,et=0,Mt=0,rn=0;if(S){ie=o()[S>>2],ie+=81920,xe=o()[S+8>>2],et=o()[S+12>>2]!==0;var No=o()[S+16>>2]===0;if(No){var tc=o()[S+20>>2],jn=o()[S+24>>2],Pr=me.currentProxiedOperationCallerThread?me.currentProxiedOperationCallerThread:Wa();Fg(Pr,S+20,S+24),Mt=o()[S+20>>2],rn=o()[S+24>>2],o()[S+20>>2]=tc,o()[S+24>>2]=jn}else Mt=o()[S+20>>2],rn=o()[S+24>>2]}else ie=2097152;var nc=xe==0;nc?xe=Bw(16,ie):(xe-=ie,ke(xe>0));for(var To=Zu(232),Wg=0;Wg<232>>2;++Wg)l()[(To>>2)+Wg]=0;o()[w>>2]=To,o()[To+12>>2]=To;var qw=To+156;o()[qw>>2]=qw;var Vg={stackBase:xe,stackSize:ie,allocatedOwnStack:nc,schedPolicy:Mt,schedPrio:rn,detached:et,startRoutine:R,pthread_ptr:To,parent_pthread_ptr:Wa(),arg:U,transferList:he};return x?(Vg.cmd="spawnThread",postMessage(Vg,he)):nd(Vg),0}function Dg(w){return w=+w,w>=0?+Lf(w+.5):+go(w-.5)}function ad(w){if(x)return Dr(6,1,w);switch(w){case 30:return 16384;case 85:var S=2147483648;return S/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 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:case 79: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: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 eg(28),-1}x?me.initWorker():me.initMainThreadBlock();var Rr;Be.init();var Rg=[null,tg,Jp,Qp,ed,td,ad],Mg={e:Jf,r:Qf,w:ng,a:ag,l:rg,d:sg,c:xo,h:vs,g:ig,x:og,q:lg,B:ug,t:cg,A:hg,u:vg,k:wg,s:kg,v:_g,m:Qp,o:ed,i:td,p:jf,memory:Q||u.wasmMemory,y:Eg,z:Ag,j:$g,b:Wa,f:Dg,n:ad,table:oe},rd=Gf();u.asm=rd;var sd=u.___wasm_call_ctors=function(){return(sd=u.___wasm_call_ctors=u.asm.C).apply(null,arguments)},id=u._init=function(){return(id=u._init=u.asm.D).apply(null,arguments)},qu=u._register_tensor=function(){return(qu=u._register_tensor=u.asm.E).apply(null,arguments)},od=u._dispose_data=function(){return(od=u._dispose_data=u.asm.F).apply(null,arguments)},Is=u._dispose=function(){return(Is=u._dispose=u.asm.G).apply(null,arguments)},Ku=u._Abs=function(){return(Ku=u._Abs=u.asm.H).apply(null,arguments)},Pg=u._Add=function(){return(Pg=u._Add=u.asm.I).apply(null,arguments)},Og=u._AddN=function(){return(Og=u._AddN=u.asm.J).apply(null,arguments)},Xu=u._ArgMax=function(){return(Xu=u._ArgMax=u.asm.K).apply(null,arguments)},ld=u._AvgPool=function(){return(ld=u._AvgPool=u.asm.L).apply(null,arguments)},ud=u._BatchMatMul=function(){return(ud=u._BatchMatMul=u.asm.M).apply(null,arguments)},V=u._Ceil=function(){return(V=u._Ceil=u.asm.N).apply(null,arguments)},te=u._ClipByValue=function(){return(te=u._ClipByValue=u.asm.O).apply(null,arguments)},Ie=u._Conv2D=function(){return(Ie=u._Conv2D=u.asm.P).apply(null,arguments)},_e=u._Conv2DBackpropInput=function(){return(_e=u._Conv2DBackpropInput=u.asm.Q).apply(null,arguments)},at=u._Cos=function(){return(at=u._Cos=u.asm.R).apply(null,arguments)},_t=u._CropAndResize=function(){return(_t=u._CropAndResize=u.asm.S).apply(null,arguments)},Xe=u._Cumsum=function(){return(Xe=u._Cumsum=u.asm.T).apply(null,arguments)},je=u._DepthToSpace=function(){return(je=u._DepthToSpace=u.asm.U).apply(null,arguments)},Ut=u._DepthwiseConv2dNative=function(){return(Ut=u._DepthwiseConv2dNative=u.asm.V).apply(null,arguments)},dr=u._Equal=function(){return(dr=u._Equal=u.asm.W).apply(null,arguments)},hr=u._Exp=function(){return(hr=u._Exp=u.asm.X).apply(null,arguments)},cd=u._FlipLeftRight=function(){return(cd=u._FlipLeftRight=u.asm.Y).apply(null,arguments)},Yu=u._Floor=function(){return(Yu=u._Floor=u.asm.Z).apply(null,arguments)},Hn=u._FloorDiv=function(){return(Hn=u._FloorDiv=u.asm._).apply(null,arguments)},Mr=u._FusedBatchNorm=function(){return(Mr=u._FusedBatchNorm=u.asm.$).apply(null,arguments)},pd=u._FusedConv2D=function(){return(pd=u._FusedConv2D=u.asm.aa).apply(null,arguments)},PC=u._FusedDepthwiseConv2D=function(){return(PC=u._FusedDepthwiseConv2D=u.asm.ba).apply(null,arguments)},OC=u._Gather=function(){return(OC=u._Gather=u.asm.ca).apply(null,arguments)},LC=u._GatherNd=function(){return(LC=u._GatherNd=u.asm.da).apply(null,arguments)},zC=u._Greater=function(){return(zC=u._Greater=u.asm.ea).apply(null,arguments)},BC=u._GreaterEqual=function(){return(BC=u._GreaterEqual=u.asm.fa).apply(null,arguments)},WC=u._LeakyRelu=function(){return(WC=u._LeakyRelu=u.asm.ga).apply(null,arguments)},VC=u._Less=function(){return(VC=u._Less=u.asm.ha).apply(null,arguments)},UC=u._LessEqual=function(){return(UC=u._LessEqual=u.asm.ia).apply(null,arguments)},GC=u._Log=function(){return(GC=u._Log=u.asm.ja).apply(null,arguments)},HC=u._LogicalAnd=function(){return(HC=u._LogicalAnd=u.asm.ka).apply(null,arguments)},jC=u._Max=function(){return(jC=u._Max=u.asm.la).apply(null,arguments)},qC=u._MaxPool=function(){return(qC=u._MaxPool=u.asm.ma).apply(null,arguments)},KC=u._Maximum=function(){return(KC=u._Maximum=u.asm.na).apply(null,arguments)},XC=u._Mean=function(){return(XC=u._Mean=u.asm.oa).apply(null,arguments)},YC=u._Min=function(){return(YC=u._Min=u.asm.pa).apply(null,arguments)},ZC=u._Minimum=function(){return(ZC=u._Minimum=u.asm.qa).apply(null,arguments)},JC=u._Multiply=function(){return(JC=u._Multiply=u.asm.ra).apply(null,arguments)},QC=u._Neg=function(){return(QC=u._Neg=u.asm.sa).apply(null,arguments)},e_=u._NonMaxSuppressionV3=function(){return(e_=u._NonMaxSuppressionV3=u.asm.ta).apply(null,arguments)},t_=u._NonMaxSuppressionV4=function(){return(t_=u._NonMaxSuppressionV4=u.asm.ua).apply(null,arguments)},n_=u._NonMaxSuppressionV5=function(){return(n_=u._NonMaxSuppressionV5=u.asm.va).apply(null,arguments)},a_=u._NotEqual=function(){return(a_=u._NotEqual=u.asm.wa).apply(null,arguments)},r_=u._OneHot=function(){return(r_=u._OneHot=u.asm.xa).apply(null,arguments)},s_=u._PadV2=function(){return(s_=u._PadV2=u.asm.ya).apply(null,arguments)},i_=u._Pow=function(){return(i_=u._Pow=u.asm.za).apply(null,arguments)},o_=u._Prelu=function(){return(o_=u._Prelu=u.asm.Aa).apply(null,arguments)},l_=u._Prod=function(){return(l_=u._Prod=u.asm.Ba).apply(null,arguments)},u_=u._RealDiv=function(){return(u_=u._RealDiv=u.asm.Ca).apply(null,arguments)},c_=u._Relu=function(){return(c_=u._Relu=u.asm.Da).apply(null,arguments)},p_=u._Relu6=function(){return(p_=u._Relu6=u.asm.Ea).apply(null,arguments)},d_=u._ResizeBilinear=function(){return(d_=u._ResizeBilinear=u.asm.Fa).apply(null,arguments)},h_=u._Reverse=function(){return(h_=u._Reverse=u.asm.Ga).apply(null,arguments)},m_=u._RotateWithOffset=function(){return(m_=u._RotateWithOffset=u.asm.Ha).apply(null,arguments)},f_=u._Round=function(){return(f_=u._Round=u.asm.Ia).apply(null,arguments)},g_=u._Rsqrt=function(){return(g_=u._Rsqrt=u.asm.Ja).apply(null,arguments)},y_=u._ScatterNd=function(){return(y_=u._ScatterNd=u.asm.Ka).apply(null,arguments)},b_=u._SelectV2=function(){return(b_=u._SelectV2=u.asm.La).apply(null,arguments)},x_=u._Sigmoid=function(){return(x_=u._Sigmoid=u.asm.Ma).apply(null,arguments)},v_=u._Sin=function(){return(v_=u._Sin=u.asm.Na).apply(null,arguments)},w_=u._Softmax=function(){return(w_=u._Softmax=u.asm.Oa).apply(null,arguments)},k_=u._Sqrt=function(){return(k_=u._Sqrt=u.asm.Pa).apply(null,arguments)},I_=u._Square=function(){return(I_=u._Square=u.asm.Qa).apply(null,arguments)},N_=u._SquaredDifference=function(){return(N_=u._SquaredDifference=u.asm.Ra).apply(null,arguments)},T_=u._Step=function(){return(T_=u._Step=u.asm.Sa).apply(null,arguments)},S_=u._StridedSlice=function(){return(S_=u._StridedSlice=u.asm.Ta).apply(null,arguments)},C_=u._Sub=function(){return(C_=u._Sub=u.asm.Ua).apply(null,arguments)},__=u._Sum=function(){return(__=u._Sum=u.asm.Va).apply(null,arguments)},E_=u._Tanh=function(){return(E_=u._Tanh=u.asm.Wa).apply(null,arguments)},A_=u._Tile=function(){return(A_=u._Tile=u.asm.Xa).apply(null,arguments)},F_=u._TopK=function(){return(F_=u._TopK=u.asm.Ya).apply(null,arguments)},$_=u._Transpose=function(){return($_=u._Transpose=u.asm.Za).apply(null,arguments)},D_=u.__FusedMatMul=function(){return(D_=u.__FusedMatMul=u.asm._a).apply(null,arguments)},Zu=u._malloc=function(){return(Zu=u._malloc=u.asm.$a).apply(null,arguments)},Ju=u._free=function(){return(Ju=u._free=u.asm.ab).apply(null,arguments)},Lw=u.___errno_location=function(){return(Lw=u.___errno_location=u.asm.bb).apply(null,arguments)},zw=u._emscripten_get_global_libc=function(){return(zw=u._emscripten_get_global_libc=u.asm.cb).apply(null,arguments)},R_=u.___em_js__initPthreadsJS=function(){return(R_=u.___em_js__initPthreadsJS=u.asm.db).apply(null,arguments)},Bw=u._memalign=function(){return(Bw=u._memalign=u.asm.eb).apply(null,arguments)},Ww=u.___pthread_tsd_run_dtors=function(){return(Ww=u.___pthread_tsd_run_dtors=u.asm.fb).apply(null,arguments)},Lg=u._emscripten_main_thread_process_queued_calls=function(){return(Lg=u._emscripten_main_thread_process_queued_calls=u.asm.gb).apply(null,arguments)},M_=u._emscripten_current_thread_process_queued_calls=function(){return(M_=u._emscripten_current_thread_process_queued_calls=u.asm.hb).apply(null,arguments)},Vw=u._emscripten_register_main_browser_thread_id=function(){return(Vw=u._emscripten_register_main_browser_thread_id=u.asm.ib).apply(null,arguments)},P_=u._emscripten_main_browser_thread_id=function(){return(P_=u._emscripten_main_browser_thread_id=u.asm.jb).apply(null,arguments)},O_=u._emscripten_async_run_in_main_thread=function(){return(O_=u._emscripten_async_run_in_main_thread=u.asm.kb).apply(null,arguments)},L_=u._emscripten_sync_run_in_main_thread=function(){return(L_=u._emscripten_sync_run_in_main_thread=u.asm.lb).apply(null,arguments)},z_=u._emscripten_sync_run_in_main_thread_0=function(){return(z_=u._emscripten_sync_run_in_main_thread_0=u.asm.mb).apply(null,arguments)},B_=u._emscripten_sync_run_in_main_thread_1=function(){return(B_=u._emscripten_sync_run_in_main_thread_1=u.asm.nb).apply(null,arguments)},W_=u._emscripten_sync_run_in_main_thread_2=function(){return(W_=u._emscripten_sync_run_in_main_thread_2=u.asm.ob).apply(null,arguments)},V_=u._emscripten_sync_run_in_main_thread_xprintf_varargs=function(){return(V_=u._emscripten_sync_run_in_main_thread_xprintf_varargs=u.asm.pb).apply(null,arguments)},U_=u._emscripten_sync_run_in_main_thread_3=function(){return(U_=u._emscripten_sync_run_in_main_thread_3=u.asm.qb).apply(null,arguments)},Uw=u._emscripten_sync_run_in_main_thread_4=function(){return(Uw=u._emscripten_sync_run_in_main_thread_4=u.asm.rb).apply(null,arguments)},G_=u._emscripten_sync_run_in_main_thread_5=function(){return(G_=u._emscripten_sync_run_in_main_thread_5=u.asm.sb).apply(null,arguments)},H_=u._emscripten_sync_run_in_main_thread_6=function(){return(H_=u._emscripten_sync_run_in_main_thread_6=u.asm.tb).apply(null,arguments)},j_=u._emscripten_sync_run_in_main_thread_7=function(){return(j_=u._emscripten_sync_run_in_main_thread_7=u.asm.ub).apply(null,arguments)},Gw=u._emscripten_run_in_main_runtime_thread_js=function(){return(Gw=u._emscripten_run_in_main_runtime_thread_js=u.asm.vb).apply(null,arguments)},zg=u._emscripten_async_queue_on_thread_=function(){return(zg=u._emscripten_async_queue_on_thread_=u.asm.wb).apply(null,arguments)},q_=u._emscripten_tls_init=function(){return(q_=u._emscripten_tls_init=u.asm.xb).apply(null,arguments)},Qu=u.stackSave=function(){return(Qu=u.stackSave=u.asm.yb).apply(null,arguments)},ko=u.stackAlloc=function(){return(ko=u.stackAlloc=u.asm.zb).apply(null,arguments)},Io=u.stackRestore=function(){return(Io=u.stackRestore=u.asm.Ab).apply(null,arguments)},Hw=u.dynCall_vi=function(){return(Hw=u.dynCall_vi=u.asm.Bb).apply(null,arguments)},K_=u.dynCall_v=function(){return(K_=u.dynCall_v=u.asm.Cb).apply(null,arguments)},X_=u.dynCall_ii=function(){return(X_=u.dynCall_ii=u.asm.Db).apply(null,arguments)};u.asm=rd,u.cwrap=Re,u.PThread=me,u.PThread=me,u._pthread_self=Wa,u.wasmMemory=Q,u.ExitStatus=jw;var ec;u.then=function(w){if(ec)w(u);else{var S=u.onRuntimeInitialized;u.onRuntimeInitialized=function(){S&&S(),w(u)}}return u};function jw(w){this.name="ExitStatus",this.message="Program terminated with exit("+w+")",this.status=w}xs=function w(){ec||Bg(),ec||(xs=w)};function Bg(w){if(w=w||h,cr>0||(sa(),cr>0))return;function S(){ec||(ec=!0,u.calledRun=!0,!ge&&(Gp(),Mf(),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Pf()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),S()},1)):S()}if(u.run=Bg,u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return x||(se=!0),x||Bg(),r}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}),NE=un((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;for(o in s)s.hasOwnProperty(o)&&(i[o]=s[o]);var l=[],c="./this.program",u=function(V,te){throw te},p=!1,d=!1,h=!1,m=!1;p=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",m=!p&&!h&&!d;var f="";function g(V){return s.locateFile?s.locateFile(V,f):f+V}var y,b,v,x,N,T;h?(d?f=ac().dirname(f)+"/":f=__dirname+"/",y=function(V,te){return N||(N=require("fs")),T||(T=ac()),V=T.normalize(V),N.readFileSync(V,te?null:"utf8")},v=function(V){var te=y(V,!0);return te.buffer||(te=new Uint8Array(te)),j(te.buffer),te},process.argv.length>1&&(c=process.argv[1].replace(/\\/g,"/")),l=process.argv.slice(2),process.on("uncaughtException",function(V){if(!(V instanceof Ku))throw V}),process.on("unhandledRejection",ys),u=function(V){process.exit(V)},s.inspect=function(){return"[Emscripten Module object]"}):m?(typeof read!="undefined"&&(y=function(V){return read(V)}),v=function(V){var te;return typeof readbuffer=="function"?new Uint8Array(readbuffer(V)):(te=read(V,"binary"),j(typeof te=="object"),te)},typeof scriptArgs!="undefined"?l=scriptArgs:typeof arguments!="undefined"&&(l=arguments),typeof quit=="function"&&(u=function(V){quit(V)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(p||d)&&(d?f=self.location.href:document.currentScript&&(f=document.currentScript.src),a&&(f=a),f.indexOf("blob:")!==0?f=f.substr(0,f.lastIndexOf("/")+1):f="",y=function(V){var te=new XMLHttpRequest;return te.open("GET",V,!1),te.send(null),te.responseText},d&&(v=function(V){var te=new XMLHttpRequest;return te.open("GET",V,!1),te.responseType="arraybuffer",te.send(null),new Uint8Array(te.response)}),b=function(V,te,Ie){var _e=new XMLHttpRequest;_e.open("GET",V,!0),_e.responseType="arraybuffer",_e.onload=function(){if(_e.status==200||_e.status==0&&_e.response){te(_e.response);return}Ie()},_e.onerror=Ie,_e.send(null)},x=function(V){document.title=V});var C=s.print||console.log.bind(console),F=s.printErr||console.warn.bind(console);for(o in i)i.hasOwnProperty(o)&&(s[o]=i[o]);i=null,s.arguments&&(l=s.arguments),s.thisProgram&&(c=s.thisProgram),s.quit&&(u=s.quit);var $;s.wasmBinary&&($=s.wasmBinary);var P;s.noExitRuntime&&(P=s.noExitRuntime),typeof WebAssembly!="object"&&F("no native wasm support detected");var B,W=new WebAssembly.Table({initial:153,maximum:153+0,element:"anyfunc"}),G=!1,q=0;function j(V,te){V||ys("Assertion failed: "+te)}function X(V){var te=s["_"+V];return j(te,"Cannot call unknown function "+V+", make sure it is exported"),te}function K(V,te,Ie,_e,at){var _t={string:function(Hn){var Mr=0;if(Hn!=null&&Hn!==0){var pd=(Hn.length<<2)+1;Mr=qu(pd),ae(Hn,Mr,pd)}return Mr},array:function(Hn){var Mr=qu(Hn.length);return pe(Hn,Mr),Mr}};function Xe(Hn){return te==="string"?Q(Hn):te==="boolean"?Boolean(Hn):Hn}var je=X(V),Ut=[],dr=0;if(_e)for(var hr=0;hr<_e.length;hr++){var cd=_t[Ie[hr]];cd?(dr===0&&(dr=id()),Ut[hr]=cd(_e[hr])):Ut[hr]=_e[hr]}var Yu=je.apply(null,Ut);return Yu=Xe(Yu),dr!==0&&od(dr),Yu}function ne(V,te,Ie,_e){Ie=Ie||[];var at=Ie.every(function(Xe){return Xe==="number"}),_t=te!=="string";return _t&&at&&!_e?X(V):function(){return K(V,te,Ie,arguments,_e)}}var J=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function se(V,te,Ie){for(var _e=te+Ie,at=te;V[at]&&!(at>=_e);)++at;if(at-te>16&&V.subarray&&J)return J.decode(V.subarray(te,at));for(var _t="";te<at;){var Xe=V[te++];if(!(Xe&128)){_t+=String.fromCharCode(Xe);continue}var je=V[te++]&63;if((Xe&224)==192){_t+=String.fromCharCode((Xe&31)<<6|je);continue}var Ut=V[te++]&63;if((Xe&240)==224?Xe=(Xe&15)<<12|je<<6|Ut:Xe=(Xe&7)<<18|je<<12|Ut<<6|V[te++]&63,Xe<65536)_t+=String.fromCharCode(Xe);else{var dr=Xe-65536;_t+=String.fromCharCode(55296|dr>>10,56320|dr&1023)}}return _t}function Q(V,te){return V?se(ye,V,te):""}function oe(V,te,Ie,_e){if(!(_e>0))return 0;for(var at=Ie,_t=Ie+_e-1,Xe=0;Xe<V.length;++Xe){var je=V.charCodeAt(Xe);if(je>=55296&&je<=57343){var Ut=V.charCodeAt(++Xe);je=65536+((je&1023)<<10)|Ut&1023}if(je<=127){if(Ie>=_t)break;te[Ie++]=je}else if(je<=2047){if(Ie+1>=_t)break;te[Ie++]=192|je>>6,te[Ie++]=128|je&63}else if(je<=65535){if(Ie+2>=_t)break;te[Ie++]=224|je>>12,te[Ie++]=128|je>>6&63,te[Ie++]=128|je&63}else{if(Ie+3>=_t)break;te[Ie++]=240|je>>18,te[Ie++]=128|je>>12&63,te[Ie++]=128|je>>6&63,te[Ie++]=128|je&63}}return te[Ie]=0,Ie-at}function ae(V,te,Ie){return oe(V,ye,te,Ie)}function pe(V,te){ge.set(V,te)}var ue,ge,ye,ke,Se,Ce,Re,Ke,Ve;function rt(V){ue=V,s.HEAP8=ge=new Int8Array(V),s.HEAP16=ke=new Int16Array(V),s.HEAP32=Ce=new Int32Array(V),s.HEAPU8=ye=new Uint8Array(V),s.HEAPU16=Se=new Uint16Array(V),s.HEAPU32=Re=new Uint32Array(V),s.HEAPF32=Ke=new Float32Array(V),s.HEAPF64=Ve=new Float64Array(V)}var ot=s.INITIAL_MEMORY||16777216;function He(V){for(;V.length>0;){var te=V.shift();if(typeof te=="function"){te(s);continue}var Ie=te.func;typeof Ie=="number"?te.arg===void 0?s.dynCall_v(Ie):s.dynCall_vi(Ie,te.arg):Ie(te.arg===void 0?null:te.arg)}}var ct=[],pt=[],Gn=[],Je=[],En=!1,Qt=!1;function An(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)Ba(s.preRun.shift());He(ct)}function na(){En=!0,He(pt)}function xn(){He(Gn)}function ln(){Qt=!0}function aa(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Fn(s.postRun.shift());He(Je)}function Ba(V){ct.unshift(V)}function Fn(V){Je.unshift(V)}var ho=Math.ceil,zu=Math.floor,ka=0,ra=null,Ia=null;function mo(V){ka++,s.monitorRunDependencies&&s.monitorRunDependencies(ka)}function fo(V){if(ka--,s.monitorRunDependencies&&s.monitorRunDependencies(ka),ka==0&&(ra!==null&&(clearInterval(ra),ra=null),Ia)){var te=Ia;Ia=null,te()}}s.preloadedImages={},s.preloadedAudios={};function ys(V){throw s.onAbort&&s.onAbort(V),V+="",C(V),F(V),G=!0,q=1,V="abort("+V+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(V)}function Bu(V,te){return String.prototype.startsWith?V.startsWith(te):V.indexOf(te)===0}var Rf="data:application/octet-stream;base64,";function Wu(V){return Bu(V,Rf)}var Up="file://";function Vu(V){return Bu(V,Up)}var sa="tfjs-backend-wasm.wasm";Wu(sa)||(sa=g(sa));function Gp(){try{if($)return new Uint8Array($);if(v)return v(sa);throw"both async and sync fetching of the wasm failed"}catch(V){ys(V)}}function Mf(){return!$&&(p||d)&&typeof fetch=="function"&&!Vu(sa)?fetch(sa,{credentials:"same-origin"}).then(function(V){if(!V.ok)throw"failed to load wasm binary file at '"+sa+"'";return V.arrayBuffer()}).catch(function(){return Gp()}):new Promise(function(V,te){V(Gp())})}function Pf(){var V={env:pr,wasi_snapshot_preview1:pr};function te(Xe,je){var Ut=Xe.exports;s.asm=Ut,B=Ut.memory,rt(B.buffer),fo("wasm-instantiate")}mo("wasm-instantiate");function Ie(Xe){te(Xe.instance)}function _e(Xe){return Mf().then(function(je){return WebAssembly.instantiate(je,V)}).then(Xe,function(je){F("failed to asynchronously prepare wasm: "+je),ys(je)})}function at(){if(!$&&typeof WebAssembly.instantiateStreaming=="function"&&!Wu(sa)&&!Vu(sa)&&typeof fetch=="function")fetch(sa,{credentials:"same-origin"}).then(function(Xe){var je=WebAssembly.instantiateStreaming(Xe,V);return je.then(Ie,function(Ut){F("wasm streaming compile failed: "+Ut),F("falling back to ArrayBuffer instantiation"),_e(Ie)})});else return _e(Ie)}if(s.instantiateWasm)try{var _t=s.instantiateWasm(V,te);return _t}catch(Xe){return F("Module.instantiateWasm callback failed with error: "+Xe),!1}return at(),{}}pt.push();function Of(V){rt(B.buffer)}var bs={splitPath:function(V){var te=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return te.exec(V).slice(1)},normalizeArray:function(V,te){for(var Ie=0,_e=V.length-1;_e>=0;_e--){var at=V[_e];at==="."?V.splice(_e,1):at===".."?(V.splice(_e,1),Ie++):Ie&&(V.splice(_e,1),Ie--)}if(te)for(;Ie;Ie--)V.unshift("..");return V},normalize:function(V){var te=V.charAt(0)==="/",Ie=V.substr(-1)==="/";return V=bs.normalizeArray(V.split("/").filter(function(_e){return!!_e}),!te).join("/"),!V&&!te&&(V="."),V&&Ie&&(V+="/"),(te?"/":"")+V},dirname:function(V){var te=bs.splitPath(V),Ie=te[0],_e=te[1];return!Ie&&!_e?".":(_e&&(_e=_e.substr(0,_e.length-1)),Ie+_e)},basename:function(V){if(V==="/")return"/";var te=V.lastIndexOf("/");return te===-1?V:V.substr(te+1)},extname:function(V){return bs.splitPath(V)[3]},join:function(){var V=Array.prototype.slice.call(arguments,0);return bs.normalize(V.join("/"))},join2:function(V,te){return bs.normalize(V+"/"+te)}},go={mappings:{},buffers:[null,[],[]],printChar:function(V,te){var Ie=go.buffers[V];te===0||te===10?((V===1?C:F)(se(Ie,0)),Ie.length=0):Ie.push(te)},varargs:void 0,get:function(){go.varargs+=4;var V=Ce[go.varargs-4>>2];return V},getStr:function(V){var te=Q(V);return te},get64:function(V,te){return V}};function Lf(V){return 0}function cr(V,te,Ie,_e,at){}function Uu(V,te,Ie,_e){for(var at=0,_t=0;_t<Ie;_t++){for(var Xe=Ce[te+_t*8>>2],je=Ce[te+(_t*8+4)>>2],Ut=0;Ut<je;Ut++)go.printChar(V,ye[Xe+Ut]);at+=je}return Ce[_e>>2]=at,0}function xs(V){ld(V)}function zf(V){xs(V)}function Bf(V){return V=+V,V>=0?+zu(V+.5):+ho(V-.5)}var pr={emscripten_notify_memory_growth:Of,fd_close:Lf,fd_seek:cr,fd_write:Uu,proc_exit:zf,roundf:Bf},Gu=Pf();s.asm=Gu;var Wf=s._init=function(){return(Wf=s._init=s.asm.init).apply(null,arguments)},Hp=s._register_tensor=function(){return(Hp=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},Vf=s._dispose_data=function(){return(Vf=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},jp=s._dispose=function(){return(jp=s._dispose=s.asm.dispose).apply(null,arguments)},ia=s._Abs=function(){return(ia=s._Abs=s.asm.Abs).apply(null,arguments)},qp=s._Add=function(){return(qp=s._Add=s.asm.Add).apply(null,arguments)},Uf=s._AddN=function(){return(Uf=s._AddN=s.asm.AddN).apply(null,arguments)},Gf=s._ArgMax=function(){return(Gf=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},Hf=s._AvgPool=function(){return(Hf=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},jf=s._BatchMatMul=function(){return(jf=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},Kp=s._Ceil=function(){return(Kp=s._Ceil=s.asm.Ceil).apply(null,arguments)},Xp=s._ClipByValue=function(){return(Xp=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Yp=s._Conv2D=function(){return(Yp=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},yo=s._Conv2DBackpropInput=function(){return(yo=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},Hu=s._Cos=function(){return(Hu=s._Cos=s.asm.Cos).apply(null,arguments)},bo=s._CropAndResize=function(){return(bo=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},xo=s._Cumsum=function(){return(xo=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},qf=s._DepthToSpace=function(){return(qf=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},Kf=s._DepthwiseConv2dNative=function(){return(Kf=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},Xf=s._Equal=function(){return(Xf=s._Equal=s.asm.Equal).apply(null,arguments)},me=s._Exp=function(){return(me=s._Exp=s.asm.Exp).apply(null,arguments)},Yf=s._FlipLeftRight=function(){return(Yf=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},Zf=s._Floor=function(){return(Zf=s._Floor=s.asm.Floor).apply(null,arguments)},Jf=s._FloorDiv=function(){return(Jf=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},Qf=s._FusedBatchNorm=function(){return(Qf=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},vs=s._FusedConv2D=function(){return(vs=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},eg=s._FusedDepthwiseConv2D=function(){return(eg=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},tg=s._Gather=function(){return(tg=s._Gather=s.asm.Gather).apply(null,arguments)},ng=s._GatherNd=function(){return(ng=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},ag=s._Greater=function(){return(ag=s._Greater=s.asm.Greater).apply(null,arguments)},rg=s._GreaterEqual=function(){return(rg=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},sg=s._LeakyRelu=function(){return(sg=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},ig=s._Less=function(){return(ig=s._Less=s.asm.Less).apply(null,arguments)},og=s._LessEqual=function(){return(og=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},lg=s._Log=function(){return(lg=s._Log=s.asm.Log).apply(null,arguments)},ug=s._LogicalAnd=function(){return(ug=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},Dr=s._Max=function(){return(Dr=s._Max=s.asm.Max).apply(null,arguments)},ws=s._MaxPool=function(){return(ws=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},vo=s._Maximum=function(){return(vo=s._Maximum=s.asm.Maximum).apply(null,arguments)},cg=s._Mean=function(){return(cg=s._Mean=s.asm.Mean).apply(null,arguments)},pg=s._Min=function(){return(pg=s._Min=s.asm.Min).apply(null,arguments)},dg=s._Minimum=function(){return(dg=s._Minimum=s.asm.Minimum).apply(null,arguments)},hg=s._Multiply=function(){return(hg=s._Multiply=s.asm.Multiply).apply(null,arguments)},Pe=s._Neg=function(){return(Pe=s._Neg=s.asm.Neg).apply(null,arguments)},mg=s._NonMaxSuppressionV3=function(){return(mg=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},fg=s._NonMaxSuppressionV4=function(){return(fg=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},gg=s._NonMaxSuppressionV5=function(){return(gg=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},yg=s._NotEqual=function(){return(yg=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},bg=s._OneHot=function(){return(bg=s._OneHot=s.asm.OneHot).apply(null,arguments)},xg=s._PadV2=function(){return(xg=s._PadV2=s.asm.PadV2).apply(null,arguments)},ju=s._Pow=function(){return(ju=s._Pow=s.asm.Pow).apply(null,arguments)},Zp=s._Prelu=function(){return(Zp=s._Prelu=s.asm.Prelu).apply(null,arguments)},Jp=s._Prod=function(){return(Jp=s._Prod=s.asm.Prod).apply(null,arguments)},vg=s._RealDiv=function(){return(vg=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},wg=s._Relu=function(){return(wg=s._Relu=s.asm.Relu).apply(null,arguments)},kg=s._Relu6=function(){return(kg=s._Relu6=s.asm.Relu6).apply(null,arguments)},Ig=s._ResizeBilinear=function(){return(Ig=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},Ng=s._Reverse=function(){return(Ng=s._Reverse=s.asm.Reverse).apply(null,arguments)},Tg=s._RotateWithOffset=function(){return(Tg=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},Be=s._Round=function(){return(Be=s._Round=s.asm.Round).apply(null,arguments)},Sg=s._Rsqrt=function(){return(Sg=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},Cg=s._ScatterNd=function(){return(Cg=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},_g=s._SelectV2=function(){return(_g=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},ks=s._Sigmoid=function(){return(ks=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},wo=s._Sin=function(){return(wo=s._Sin=s.asm.Sin).apply(null,arguments)},Qp=s._Softmax=function(){return(Qp=s._Softmax=s.asm.Softmax).apply(null,arguments)},ed=s._Sqrt=function(){return(ed=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},td=s._Square=function(){return(td=s._Square=s.asm.Square).apply(null,arguments)},Eg=s._SquaredDifference=function(){return(Eg=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},Ag=s._Step=function(){return(Ag=s._Step=s.asm.Step).apply(null,arguments)},nd=s._StridedSlice=function(){return(nd=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},Fg=s._Sub=function(){return(Fg=s._Sub=s.asm.Sub).apply(null,arguments)},Wa=s._Sum=function(){return(Wa=s._Sum=s.asm.Sum).apply(null,arguments)},$g=s._Tanh=function(){return($g=s._Tanh=s.asm.Tanh).apply(null,arguments)},Dg=s._Tile=function(){return(Dg=s._Tile=s.asm.Tile).apply(null,arguments)},ad=s._TopK=function(){return(ad=s._TopK=s.asm.TopK).apply(null,arguments)},Rr=s._Transpose=function(){return(Rr=s._Transpose=s.asm.Transpose).apply(null,arguments)},Rg=s.__FusedMatMul=function(){return(Rg=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},Mg=s._malloc=function(){return(Mg=s._malloc=s.asm.malloc).apply(null,arguments)},rd=s._free=function(){return(rd=s._free=s.asm.free).apply(null,arguments)},sd=s.__start=function(){return(sd=s.__start=s.asm._start).apply(null,arguments)},id=s.stackSave=function(){return(id=s.stackSave=s.asm.stackSave).apply(null,arguments)},qu=s.stackAlloc=function(){return(qu=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},od=s.stackRestore=function(){return(od=s.stackRestore=s.asm.stackRestore).apply(null,arguments)};s.asm=Gu,s.cwrap=ne;var Is;s.then=function(V){if(Is)V(s);else{var te=s.onRuntimeInitialized;s.onRuntimeInitialized=function(){te&&te(),V(s)}}return s};function Ku(V){this.name="ExitStatus",this.message="Program terminated with exit("+V+")",this.status=V}var Pg=!1;Ia=function V(){Is||Xu(),Is||(Ia=V)};function Og(V){var te=s.__start;try{te();var Ie=0;ld(Ie,!0)}catch(at){if(at instanceof Ku)return;if(at=="unwind"){P=!0;return}else{var _e=at;at&&typeof at=="object"&&at.stack&&(_e=[at,at.stack]),F("exception thrown: "+_e),u(1,at)}}finally{Pg=!0}}function Xu(V){if(V=V||l,ka>0||(An(),ka>0))return;function te(){Is||(Is=!0,s.calledRun=!0,!G&&(na(),xn(),s.onRuntimeInitialized&&s.onRuntimeInitialized(),ud&&Og(V),aa()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),te()},1)):te()}s.run=Xu;function ld(V,te){te&&P&&V===0||(P||(G=!0,q=V,ln(),s.onExit&&s.onExit(V)),u(V,new Ku(V)))}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();var ud=!0;return s.noInitialRun&&(ud=!1),P=!0,Xu(),r}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}),TE=1e-7,SE=1e-4,gd=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}},rc=class{refCount(e){return oa("refCount")}incRef(e){return oa("incRef")}timerAvailable(){return!0}time(e){return oa("time")}read(e){return oa("read")}readSync(e){return oa("readSync")}numDataIds(){return oa("numDataIds")}disposeData(e,t){return oa("disposeData")}write(e,t,n){return oa("write")}move(e,t,n,a,r){return oa("move")}memory(){return oa("memory")}floatPrecision(){return oa("floatPrecision")}epsilon(){return this.floatPrecision()===32?TE:SE}dispose(){return oa("dispose")}};function oa(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function Xw(e){let t=e.length,n=0,a=0;for(;t>0;)a=Math.random()*t|0,t--,n=e[t],e[t]=e[a],e[a]=n}function CE(e,t){if(e.length!==t.length)throw 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 sc(e,t,n){return Math.max(e,Math.min(t,n))}function _E(e){return e%2==0?e:e+1}function EE(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function AE(e,t){let n=Math.random();return t*n+(1-n)*e}function FE(e,t){let n=0;for(let a=0;a<e.length;a++){let r=Number(e[a])-Number(t[a]);n+=r*r}return n}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function sn(e,t,n=""){A(mr(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Ns(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ts(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||on(e)&&!n)for(let a=0;a<e.length;++a)Ts(e[a],t,n);else t.push(e);return t}function Pt(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function $E(e){return e.length===0}function mr(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gt(e){return e%1==0}function DE(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function RE(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ME(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Xw(t),t}function ic(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function PE(e,t=a=>0,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 OE(e,t){let n=1,a=-1;for(let s=0;s<e.length;++s)if(e[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 la(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),A(e.every(a=>a>=-n&&a<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(a=>Gt(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function Yw(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:la(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(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 Zw(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 Jw(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 Qw(e,t){for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))throw Error(`A tensor of type ${t} being uploaded contains ${a}.`)}}function e0(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function LE(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function on(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Gg(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function t0(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Or(e){return typeof e=="string"||e instanceof String}function n0(e){return typeof e=="boolean"}function a0(e){return typeof e=="number"}function yd(e){return Array.isArray(e)?yd(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":a0(e)?"float32":Or(e)?"string":n0(e)?"bool":"float32"}function Lr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function bd(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Co(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let a=t-3;a>=0;--a)n[a]=n[a+1]*e[a+1];return n}function r0(e,t,n){let a=new Array;if(t.length===1){let r=t[0];for(let s=0;s<r;s++)a[s]=n[e+s]}else{let r=t[0],s=t.slice(1),i=s.reduce((o,l)=>o*l);for(let o=0;o<r;o++)a[o]=r0(e+o*i,s,n)}return a}function _o(e,t){if(e.length===0)return t[0];let n=e.reduce((a,r)=>a*r);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return r0(0,e,t)}function Hg(e,t){let n=xd(e,t);for(let a=0;a<n.length;a++)n[a]=1;return n}function xd(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function zE(e,t){let n=e.reduce((a,r)=>a*r,1);if(t==null||t==="float32")return _o(e,new Float32Array(n));if(t==="int32")return _o(e,new Int32Array(n));if(t==="bool")return _o(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function jg(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function BE(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<e.length-1;++r)a+=n[r]*e[r];return a}function WE(e,t,n){if(t===0)return[];if(t===1)return[e];let a=new Array(t);for(let r=0;r<a.length-1;++r)a[r]=Math.floor(e/n[r]),e-=a[r]*n[r];return a[a.length-1]=e,a}function qg(e){return e&&e.then&&typeof e.then=="function"}var s0="tfjsflags",i0=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let a=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${a}.`),this.set(e,a)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(qg(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=VE(this.global.location.search);s0 in e&&e[s0].split(",").forEach(t=>{let[n,a]=t.split(":");this.urlFlags[n]=UE(n,a)})}};function VE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(GE(t,a[0],a[1]),a.join("="))),t}function GE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function UE(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 ee(){return Kg}var Kg=null;function HE(e){Kg=e}var Xg;function o0(){if(Xg==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");Xg=e}return Xg}function jE(){let e=o0();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Yg(e,t){let n=jE();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var Eo="Abs",Ao="Acos",Fo="Acosh",zr="Add",Ss="AddN",vd="All",wd="Any",Cs="ArgMax",oc="ArgMin",$o="Asin",Do="Asinh",Ro="Atan",Mo="Atanh",Po="Atan2",_s="AvgPool",kd="AvgPoolGrad",lc="AvgPool3D",Id="AvgPool3DGrad",Es="BatchMatMul",uc="BatchToSpaceND",Nd="Bincount",l0="BroadcastTo",As="Cast",Fs="Ceil",Br="ClipByValue",Td="Complex",cc="ComplexAbs",Oo="Concat",$s="Conv2D",Sd="Conv2DBackpropFilter",Ds="Conv2DBackpropInput",pc="Conv3D",Cd="Conv3DBackpropFilterV2",_d="Conv3DBackpropInputV2",Rs="Cos",Lo="Cosh",Ms="Cumsum",zo="CropAndResize",Ed="DenseBincount",Bo="DepthToSpace",Ps="DepthwiseConv2dNative",Ad="DepthwiseConv2dNativeBackpropFilter",Fd="DepthwiseConv2dNativeBackpropInput",$d="Diag",dc="Dilation2D",Dd="Dilation2DBackpropInput",Rd="Dilation2DBackpropFilter",Os="RealDiv",Wo="Elu",Md="EluGrad",Vo="Erf",Uo="Equal",Ls="Exp",Go="ExpandDims",Ho="Expm1",Pd="FFT",hc="Fill",jo="FlipLeftRight",zs="Floor",Bs="FloorDiv",Ws="FusedBatchNorm",qo="GatherV2",Ko="GatherNd",Xo="Greater",Vs="GreaterEqual",Us="Identity",Od="IFFT",Ld="Imag",Yo="IsFinite",Zo="IsInf",Jo="IsNan",Gs="LeakyRelu",Qo="Less",el="LessEqual",zd="LinSpace",Hs="Log",tl="Log1p",nl="LogicalAnd",mc="LogicalNot",fc="LogicalOr",u0="LogSoftmax",gc="LRN",Bd="LRNGrad",js="Max",qs="Maximum",Ks="MaxPool",Wd="MaxPoolGrad",yc="MaxPool3D",Vd="MaxPool3DGrad",Ud="MaxPoolWithArgmax",Xs="Mean",Ys="Min",Zs="Minimum",bc="MirrorPad",al="Mod",Gd="Multinomial",Js="Multiply",rl="Neg",sl="NotEqual",il="NonMaxSuppressionV3",ol="NonMaxSuppressionV4",ll="NonMaxSuppressionV5",ul="OnesLike",Qs="OneHot",cl="Pack",ei="PadV2",qE="Pool",ti="Pow",ni="Prelu",pl="Prod",xc="Range",Hd="Real",dl="Reciprocal",ai="Relu",hl="Reshape",vc="ResizeNearestNeighbor",jd="ResizeNearestNeighborGrad",ri="ResizeBilinear",qd="ResizeBilinearGrad",si="Relu6",ii="Reverse",oi="Round",li="Rsqrt",ml="ScatterNd",fl="Select",gl="Selu",yl="Slice",ui="Sin",bl="Sinh",xl="Sign",ci="Sigmoid",vl="Softplus",pi="Sqrt",di="Sum",wc="SpaceToBatchND",wl="SplitV",hi="Softmax",mi="SquaredDifference",kc="Square",fi="Sub",Kd="SparseToDense",kl="StridedSlice",Il="Tan",gi="Tanh",Wr="Tile",Nl="TopK",yi="Transpose",Xd="Unique",Tl="Unpack",Ic="UnsortedSegmentSum",Sl="ZerosLike",Vr="Step",Yd="FromPixels",Cl="RotateWithOffset",bi="_FusedMatMul",xi="FusedConv2D",vi="FusedDepthwiseConv2D",_l=Yg("kernelRegistry",()=>new Map),Nc=Yg("gradRegistry",()=>new Map);function Zd(e,t){let n=Zg(e,t);return _l.get(n)}function Jg(e){return Nc.get(e)}function Jd(e){let t=_l.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 Tc(e){let{kernelName:t,backendName:n}=e,a=Zg(t,n);_l.has(a)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),_l.set(a,e)}function c0(e){let{kernelName:t}=e;Nc.has(t)&&ee().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),Nc.set(t,e)}function KE(e,t){let n=Zg(e,t);if(!_l.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);_l.delete(n)}function XE(e){if(!Nc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Nc.delete(e)}function YE(e,t){Jd(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});Tc(a)})}function Zg(e,t){return`${t}_${e}`}var k={};Oe(k,{arraysEqual:()=>mr,assert:()=>A,assertNonNegativeIntegerDimensions:()=>jg,assertNonNull:()=>Ns,assertShapesMatch:()=>sn,bytesFromStringArray:()=>t0,bytesPerElement:()=>Gg,checkConversionForErrors:()=>Qw,clamp:()=>sc,computeStrides:()=>Co,createScalarValue:()=>ZE,createShuffledIndices:()=>ME,decodeString:()=>eh,distSquared:()=>FE,encodeString:()=>Cc,fetch:()=>JE,flatten:()=>Ts,getArrayFromDType:()=>Jw,getTypedArrayFromDType:()=>Zw,hasEncodingLoss:()=>LE,indexToLoc:()=>WE,inferDtype:()=>yd,inferFromImplicitShape:()=>OE,isBoolean:()=>n0,isFunction:()=>Lr,isInt:()=>Gt,isNumber:()=>a0,isPromise:()=>qg,isScalarShape:()=>$E,isString:()=>Or,isTypedArray:()=>on,isValidDtype:()=>e0,locToIndex:()=>BE,makeOnesTypedArray:()=>Hg,makeZerosNestedTypedArray:()=>zE,makeZerosTypedArray:()=>xd,nearestDivisor:()=>bd,nearestLargerEven:()=>_E,now:()=>Sc,parseAxisParam:()=>la,randUniform:()=>AE,repeatedTry:()=>PE,rightPad:()=>ic,shuffle:()=>Xw,shuffleCombo:()=>CE,sizeFromShape:()=>Pt,sizeToSquarishShape:()=>RE,squeezeShape:()=>Yw,sum:()=>EE,tanh:()=>DE,toNestedArray:()=>_o,toTypedArray:()=>Qd});function ZE(e,t){return t==="string"?Cc(e):Qd([e],t)}function QE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Qd(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ts(e)),ee().getBool("DEBUG")&&Qw(e,t),QE(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<n.length;++a)Math.round(e[a])!==0&&(n[a]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Sc(){return ee().platform.now()}function JE(e,t){return ee().platform.fetch(e,t)}function Cc(e,t="utf-8"){return t=t||"utf-8",ee().platform.encode(e,t)}function eh(e,t="utf-8"){return t=t||"utf-8",ee().platform.decode(e,t)}var nA=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new tA)}profileKernel(e,t,n){let a,r=()=>{a=n()},s,i=Sc();if(this.backendTimer.timerAvailable()?s=this.backendTimer.time(r):(r(),a.map(o=>o.dataSync()),s=Promise.resolve({kernelMs:Sc()-i})),ee().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<a.length;o++){let l=a[o];l.data().then(c=>{eA(c,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 eA(e,t,n){if(t!=="float32")return!1;for(let a=0;a<e.length;a++){let r=e[a];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}var tA=class{logKernelProfile(e,t,n,a,r,s){let i=typeof a=="number"?ic(`${a}ms`,9):a.error,o=ic(e,25),l=t.rank,c=t.size,u=ic(t.shape.toString(),14),p="";for(let d in r){let h=r[d];if(h!=null){let m=h.shape||t.shape,f=m.length;p+=`${d}: ${f}D ${f>0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${u} %c${c} %c${p} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function aA(e,t,n){let a={},r={};for(let l=0;l<t.length;l++)a[t[l].id]=!0;for(let l=0;l<e.length;l++){let c=e[l],u=c.inputs;for(let p in u){let d=u[p],h=!1;for(let m=0;m<t.length;m++)if(a[d.id]){c.outputs.forEach(f=>a[f.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let p=0;p<c.outputs.length;p++)if(s[c.outputs[p].id]){for(let d in u)s[u[d].id]=!0,i[c.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let c=e[l];if(r[c.id]&&i[c.id]){let u={};for(let d in c.inputs){let h=c.inputs[d];a[h.id]&&(u[d]=h)}let p=Object.assign({},c);p.inputs=u,p.outputs=c.outputs,o.push(p)}}return o}function rA(e,t,n,a){for(let r=t.length-1;r>=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let c=e[l.id];c!=null?i.push(c):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 c=n(()=>o[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=s.inputs[l];if(!mr(c.shape,u.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let p=e[u.id];e[u.id]=a(p,c),p.dispose()}}}}var p0=20,_c=3,Qg=7;function iA(e,t,n,a){let r=Co(t),s=sA(e,t,n,r),i=t.length,o=th(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(c=>" "+c).join(`
|
|
`)),l.join(`
|
|
`)}function sA(e,t,n,a){let r=Pt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Ac(e):e;if(o>1)for(let c=0;c<r/s;c++){let u=c*s;for(let p=0;p<s;p++)i[p]=Math.max(i[p],Ec(l[u+p],0,n).length)}return i}function Ec(e,t,n){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(Qg))} + ${parseFloat(e[1].toFixed(Qg))}j`:Or(e)?a=`'${e}'`:n==="bool"?a=d0(e):a=parseFloat(e.toFixed(Qg)).toString(),ic(a,t)}function d0(e){return e===0?"false":"true"}function th(e,t,n,a,r,s=!0){let i=n==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(n==="complex64"){let f=Ac(e);return[Ec(f[0],0,n)]}return n==="bool"?[d0(e[0])]:[e[0].toString()]}if(l===1){if(o>p0){let g=_c*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o-_c)*i,o*i));return n==="complex64"&&(y=Ac(y),b=Ac(b)),["["+y.map((v,x)=>Ec(v,r[x],n)).join(", ")+", ..., "+b.map((v,x)=>Ec(v,r[o-_c+x],n)).join(", ")+"]"]}let f=n==="complex64"?Ac(e):Array.from(e);return["["+f.map((g,y)=>Ec(g,r[y],n)).join(", ")+"]"]}let c=t.slice(1),u=a.slice(1),p=a[0]*i,d=[];if(o>p0){for(let f=0;f<_c;f++){let g=f*p,y=g+p;d.push(...th(e.slice(g,y),c,n,u,r,!1))}d.push("...");for(let f=o-_c;f<o;f++){let g=f*p,y=g+p;d.push(...th(e.slice(g,y),c,n,u,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*p,y=g+p;d.push(...th(e.slice(g,y),c,n,u,r,f===o-1))}let h=l===2?",":"";d[0]="["+d[0]+h;for(let f=1;f<d.length-1;f++)d[f]=" "+d[f]+h;let m=`,
|
|
`;for(let f=2;f<l;f++)m+=`
|
|
`;return d[d.length-1]=" "+d[d.length-1]+"]"+(s?"":m),d}function Ac(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ot=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Pt(e),n!=null){let a=n.length;A(a===this.size,()=>`Length of values '${a}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Jw(t,this.size),this.strides=Co(e)}set(e,...t){t.length===0&&(t=[0]),A(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;a<e.length-1;++a)n+=this.strides[a]*e[a];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Va().makeTensor(this.values,this.shape,this.dtype)}},Va=null,El=null,oA=null;function lA(e){Va=e}function uA(e){El=e}function cA(e){oA=e}var Ae=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Pt(e),this.strides=Co(e),this.dataId=n,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return El.buffer(this.shape,this.dtype,e)}bufferSync(){return El.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return _o(this.shape,e)}arraySync(){return _o(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Va().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>eh(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=Va().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>eh(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 Va().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Va().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return El.print(this,e)}clone(){return this.throwIfDisposed(),El.clone(this)}toString(e=!1){let t=this.dataSync();return iA(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),El.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Va().makeVariable(this,e,t,n)}};Object.defineProperty(Ae,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Y(){return Yg("Tensor",()=>Ae)}Y();var Ur=class extends Ae{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(!mr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Va().disposeTensor(this),this.dataId=e.dataId,Va().incRef(this,null)}dispose(){Va().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Ur,Symbol.hasInstance,{value:e=>e instanceof Ae&&e.assign!=null&&e.assign instanceof Function});var Na={};Oe(Na,{assertTypesMatch:()=>h0,getTensorsInContainer:()=>ey,isTensorInList:()=>pA,makeTypesMatch:()=>Nt});var ty;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(ty||(ty={}));var ny;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(ny||(ny={}));var ay;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(ay||(ay={}));var ry;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(ry||(ry={}));var sy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(sy||(sy={}));var dA={float32:ry,int32:ny,bool:ay,complex64:sy};function ua(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return dA[e][t]}function nh(e){return ua(e,"int32")}function Nt(e,t){if(e.dtype===t.dtype)return[e,t];let n=ua(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function h0(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function pA(e,t){return t.some(n=>n.id===e.id)}function ey(e){let t=[],n=new Set;return m0(e,t,n),t}function m0(e,t,n){if(e==null)return;if(e instanceof Ae){t.push(e);return}if(!hA(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),m0(s,t,n))}}function hA(e){return Array.isArray(e)||typeof e=="object"}function iy(e){return e.kernelName!=null}var f0=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()}},Fc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new f0}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new nA(this.backendInstance),!0}setupRegisteredKernels(){Jd(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Jd(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 rc)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(a<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(s.stack||s.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:a,asyncInit:r}=this.initializeBackend(n);if(r||a)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),a=n.backend,r=this.readSync(t),s=a.refCount(t);a.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let a;return this.scopedRun(()=>this.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 Fc.nextTensorId++}nextVariableId(){return Fc.nextVariableId++}clone(e){let t=M.runKernel(Us,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return M.runKernel(As,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(Zd(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=iy(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(iy(e)){let{kernelName:h,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=Zd(h,this.backendName);A(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let b=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,b);let v=b.map(x=>{if(x.rank!=null)return x;let{dataId:N,shape:T,dtype:C}=x;return this.makeTensorFromDataId(N,T,C)});if(a){let x=this.getTensorsForGradient(h,m,v);n=this.saveTensorsForBackwardMode(x)}return v}}else{let{forwardFunc:h}=e,m=f=>{!a||(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>h(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:c,attrs:u}=e,p=iy(e)?null:e.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(d=this.profiler.profileKernel(l,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs)}),a&&this.addTapeNode(l,c,t,p,n,u),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(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=Jg(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(A(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,c)=>s[c]);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"&&Or(e[0])&&(r=e.map(o=>Cc(o)));let s=a.write(r,t,n),i=new Ae(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=t0(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r=new Ae(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 Ur(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*Gg(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 Ur||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*Gg(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=Jg(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((c,u)=>{if(c==null){let p=n[u],d=xd(p.size,p.dtype);return this.makeTensor(d,p.shape,p.dtype)}return c}),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=ey(e),n=new Set(t.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){let s=this.state.activeScope.track[r];!s.kept&&!n.has(s.id)&&s.dispose()}let a=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(r=>{!r.kept&&r.scopeId===a.id&&this.track(r)})}gradients(e,t,n,a=!1){if(A(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));A(r instanceof Ae,()=>"The result y returned by f() must be a tensor.");let s=aA(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?mA(r.shape):n,rA(i,s,l=>this.tidy(l),fA);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return A(Lr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(i=>i instanceof Ae),()=>"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),A(n.value instanceof Ae,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(Lr(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),c=Array.isArray(l)?l:[l];A(c.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(...)."),A(c.every(p=>p instanceof Ae),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((p,d)=>{u[d]=()=>p}),u};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=Sc(),n=await this.backend.time(e);return n.wallMs=Sc()-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 f0;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}};Fc.nextTensorId=0;Fc.nextVariableId=0;function mA(e){let t=Hg(Pt(e),"float32");return M.makeTensor(t,e,"float32")}function g0(){let e=o0();if(e._tfengine==null){let t=new i0(e);e._tfengine=new Fc(t)}return HE(e._tfengine.ENV),lA(()=>e._tfengine),e._tfengine}var M=g0();function fA(e,t){let n={a:e,b:t};return M.runKernel(zr,n)}var ah={};Oe(ah,{isBrowser:()=>y0,isMobile:()=>gA});function yA(){return typeof navigator!="undefined"&&navigator!=null}function gA(){if(yA()){let e=navigator.userAgent||navigator.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(e)||/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(e.substr(0,4))}return!1}function y0(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Ua=ee();Ua.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.")});Ua.registerFlag("IS_BROWSER",()=>y0());Ua.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Ua.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Ua.registerFlag("PROD",()=>!1);Ua.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ua.getBool("DEBUG"));Ua.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Ua.registerFlag("IS_TEST",()=>!1);Ua.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);function Ga(e,t){let n=e;if(on(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||on(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&ee().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&b0(e,a,[]),a}function b0(e,t,n){if(n=n||[],!Array.isArray(e)&&!on(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(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<e.length;++r)b0(e[r],a,n.concat(r))}function x0(e,t,n,a){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${a}' must be ${e} tensor, but got ${t} tensor`)}}function E(e,t,n,a="numeric"){if(e instanceof Ae)return x0(a,e.dtype,t,n),e;let r=yd(e);if(r!=="string"&&["bool","int32","float32"].indexOf(a)>=0&&(r=a),x0(a,r,t,n),e==null||!on(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=Ga(e,r);!on(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Qd(e,r):Ts(e,[],!0);return M.makeTensor(i,s,r)}function $c(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)=>E(r,`${t}[${s}]`,n,a))}var v0="__op";function O(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+v0;let r=(...s)=>{M.startScope(n);try{let i=a(...s);return qg(i)&&console.error("Cannot return a Promise inside of tidy."),M.endScope(i),i}catch(i){throw M.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function bA(e,t){let n=E(e,"real","complex"),a=E(t,"imag","complex");sn(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 M.runKernel(Td,r)}var Gr=O({complex_:bA});function Hr(e,t,n,a){if(a==null&&(a=yd(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!on(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){jg(t);let r=Pt(t),s=Pt(n);A(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i<n.length;++i){let o=n[i],l=i===n.length-1?o!==Pt(t.slice(i)):!0;A(n[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!on(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?Qd(e,a):Ts(e,[],!0),M.makeTensor(e,t,a)}function qn(e,t,n){let a=Ga(e,n);return Hr(e,t,a,n)}var oy={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},rh=4;async function vA(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<r.length;++i){let o=r[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let c={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let u=new Promise(async p=>{let d=await l.bytes(),h=d.reduce((g,y)=>g+y.length,0)+rh*d.length,m=new Uint8Array(h),f=0;for(let g=0;g<d.length;g++){let y=d[g],b=new Uint8Array(new Uint32Array([y.length]).buffer);m.set(b,f),f+=rh,m.set(y,f),f+=y.length}p(m)});a.push(u)}else a.push(l.data());t!=null&&(c.group=t),n.push(c)}let s=await Promise.all(a);return{data:xA(s),specs:n}}function w0(e,t){let n={},a,r=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,c=Pt(l),u;if("quantization"in s){let p=s.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let d=oy[p.dtype],h=e.slice(r,r+c*d),m=p.dtype==="uint8"?new Uint8Array(h):new Uint16Array(h);if(o==="float32")if(p.dtype==="uint8"||p.dtype==="uint16"){u=new Float32Array(m.length);for(let f=0;f<m.length;f++){let g=m[f];u[f]=g*p.scale+p.min}}else if(p.dtype==="float16")a===void 0&&(a=wA()),u=a(m);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(o==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);u=new Int32Array(m.length);for(let f=0;f<m.length;f++){let g=m[f];u[f]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=c*d}else if(o==="string"){let p=Pt(s.shape);u=[];for(let d=0;d<p;d++){let h=new Uint32Array(e.slice(r,r+rh))[0];r+=rh;let m=new Uint8Array(e.slice(r,r+h));u.push(m),r+=h}}else{let p=oy[o],d=e.slice(r,r+c*p);if(o==="float32")u=new Float32Array(d);else if(o==="int32")u=new Int32Array(d);else if(o==="bool")u=new Uint8Array(d);else if(o==="complex64"){u=new Float32Array(d);let h=new Float32Array(u.length/2),m=new Float32Array(u.length/2);for(let y=0;y<h.length;y++)h[y]=u[y*2],m[y]=u[y*2+1];let f=qn(h,l,"float32"),g=qn(m,l,"float32");n[i]=Gr(f,g),f.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=c*p}o!=="complex64"&&(n[i]=qn(u,l,o))}return n}function xA(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(s=>{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 ly=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function k0(e){return ly?Buffer.byteLength(e):new Blob([e]).size}function kA(e){if(ly)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a<r;a++)n+=String.fromCharCode(t[a]);return btoa(n)}function IA(e){if(ly){let a=Buffer.from(e,"base64");return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;++a)n.set([t.charCodeAt(a)],a);return n.buffer}function uy(e){if(e.length===1)return e[0];let t=0;e.forEach(r=>{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 I0(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 Dc(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:k0(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:k0(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function NA(){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 TA(){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 SA(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function wA(){let e=NA(),t=TA(),n=SA();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i<a.length;i++){let o=a[i],l=e[n[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var Et=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Et.instance==null&&(Et.instance=new Et),Et.instance}static registerSaveRouter(e){Et.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Et.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Et.getHandlers(e,"save")}static getLoadHandlers(e,t){return Et.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?Et.getInstance().loadRouters:Et.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},CA=e=>Et.registerSaveRouter(e),_A=e=>Et.registerLoadRouter(e),EA=e=>Et.getSaveHandlers(e),AA=(e,t)=>Et.getLoadHandlers(e,t),cy="tensorflowjs",py=1,wi="models_store",jr="model_info_store";function N0(){if(!ee().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 dy(e){let t=e.result;t.createObjectStore(wi,{keyPath:"modelPath"}),t.createObjectStore(jr,{keyPath:"modelPath"})}var ki=class{constructor(e){if(this.indexedDB=N0(),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(cy,py);r.onupgradeneeded=()=>dy(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(wi,"readonly"),o=i.objectStore(wi).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=Dc(t),o=s.transaction(jr,"readwrite"),l=o.objectStore(jr),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),u;c.onsuccess=()=>{u=s.transaction(wi,"readwrite");let p=u.objectStore(wi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});p.onsuccess=()=>n({modelArtifactsInfo:i}),p.onerror=d=>{l=o.objectStore(jr);let h=l.delete(this.modelPath);h.onsuccess=()=>(s.close(),a(p.error)),h.onerror=m=>(s.close(),a(p.error))}},c.onerror=p=>(s.close(),a(c.error)),o.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};ki.URL_SCHEME="indexeddb://";var T0=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ki.URL_SCHEME)?FA(e.slice(ki.URL_SCHEME.length)):null;Et.registerSaveRouter(T0);Et.registerLoadRouter(T0);function FA(e){return new ki(e)}function $A(e){return e.startsWith(ki.URL_SCHEME)?e.slice(ki.URL_SCHEME.length):e}var DA=class{constructor(){this.indexedDB=N0()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(cy,py);n.onupgradeneeded=()=>dy(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(jr,"readonly"),s=r.objectStore(jr).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=$A(e),new Promise((t,n)=>{let a=this.indexedDB.open(cy,py);a.onupgradeneeded=()=>dy(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(jr,"readwrite"),i=s.objectStore(jr),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 c=i.delete(e),u=()=>{l=r.transaction(wi,"readwrite");let p=l.objectStore(wi).delete(e);p.onsuccess=()=>t(o.result.modelArtifactsInfo),p.onerror=d=>n(o.error)};c.onsuccess=u,c.onerror=p=>(u(),r.close(),n(o.error))}},o.onerror=c=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},fr="/",Al="tensorflowjs_models",S0="info",RA="model_topology",MA="weight_specs",PA="weight_data",OA="model_metadata";function C0(e){return{info:[Al,e,S0].join(fr),topology:[Al,e,RA].join(fr),weightSpecs:[Al,e,MA].join(fr),weightData:[Al,e,PA].join(fr),modelMetadata:[Al,e,OA].join(fr)}}function LA(e){let t=e.split(fr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(fr)}function zA(e){return e.startsWith(Ii.URL_SCHEME)?e.slice(Ii.URL_SCHEME.length):e}var Ii=class{constructor(e){if(!ee().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=C0(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=Dc(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,kA(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=IA(s),t}};Ii.URL_SCHEME="localstorage://";var _0=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ii.URL_SCHEME)?BA(e.slice(Ii.URL_SCHEME.length)):null;Et.registerSaveRouter(_0);Et.registerLoadRouter(_0);function BA(e){return new Ii(e)}var WA=class{constructor(){A(ee().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Al+fr,n=fr+S0;for(let a=0;a<this.LS.length;++a){let r=this.LS.key(a);if(r.startsWith(t)&&r.endsWith(n)){let s=LA(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=zA(e);let t=C0(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),n}},Fl="://",Kn=class{constructor(){this.managers={}}static getInstance(){return Kn.instance==null&&(Kn.instance=new Kn),Kn.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Fl)&&(e=e.slice(0,e.indexOf(Fl))),A(e.length>0,()=>"scheme must not be an empty string.");let n=Kn.getInstance();A(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 sh(e){if(e.indexOf(Fl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Kn.getSchemes().join(",")}`);return{scheme:e.split(Fl)[0],path:e.split(Fl)[1]}}async function E0(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=Et.getLoadHandlers(e);A(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=Et.getSaveHandlers(t);A(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=sh(e).scheme,l=sh(e).path,c=o===sh(e).scheme,u=await r.load();n&&c&&await Kn.getManager(o).removeModel(l);let p=await i.save(u);return n&&!c&&await Kn.getManager(o).removeModel(l),p.modelArtifactsInfo}async function VA(){let e=Kn.getSchemes(),t={};for(let n of e){let a=await Kn.getManager(n).listModels();for(let r in a){let s=n+Fl+r;t[s]=a[r]}}return t}async function UA(e){let t=sh(e);return Kn.getManager(t.scheme).removeModel(t.path)}async function GA(e,t){return E0(e,t,!1)}async function HA(e,t){return E0(e,t,!0)}var jA=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(ee().get("IS_BROWSER")){ee().setPlatform("browser",new jA);try{Kn.registerManager(Ii.URL_SCHEME,new WA)}catch(e){}try{Kn.registerManager(ki.URL_SCHEME,new DA)}catch(e){}}var qA={importFetch:()=>pE()},hy,KA=class{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return ee().global.fetch!=null?ee().global.fetch(e,t):(hy==null&&(hy=qA.importFetch()),hy(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)}};ee().get("IS_NODE")&&ee().setPlatform("node",new KA);function Le(e,t="float32",n){return t=t||"float32",jg(e),new Ot(e,t,n)}function XA(e,t){let n=E(e,"x","cast");if(!e0(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 M.runKernel(As,a,r)}var ce=O({cast_:XA});function YA(e){let t={x:E(e,"x","clone","string_or_numeric")};return M.runKernel(Us,t)}var qr=O({clone_:YA});function A0(e,t=!1){console.log(e.toString(t))}g0();var ZA={buffer:Le,cast:ce,clone:qr,print:A0};uA(ZA);var Ht={};Oe(Ht,{browserFiles:()=>JA,browserHTTPRequest:()=>eF,concatenateArrayBuffers:()=>uy,copyModel:()=>GA,decodeWeights:()=>w0,encodeWeights:()=>vA,fromMemory:()=>tF,getLoadHandlers:()=>AA,getModelArtifactsInfoForJSON:()=>Dc,getSaveHandlers:()=>EA,http:()=>fy,isHTTPScheme:()=>my,listModels:()=>VA,loadWeights:()=>QA,moveModel:()=>HA,registerLoadRouter:()=>_A,registerSaveRouter:()=>CA,removeModel:()=>UA,weightsLoaderFactory:()=>F0,withSaveHandler:()=>nF});var aF="model",rF=".json",sF=".weights.bin";function $0(e){return new Promise(t=>setTimeout(t)).then(e)}var $l=class{constructor(e){if(!ee().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith($l.URL_SCHEME)&&(e=e.slice($l.URL_SCHEME.length)),(e==null||e.length===0)&&(e=aF),this.modelTopologyFileName=e+rF,this.weightDataFileName=e+sF}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 $0(()=>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 $0(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Dc(e)}}}};$l.URL_SCHEME="downloads://";var iF=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 c;try{c=this.checkManifestAndWeightFiles(l,t)}catch(h){a(h);return}let u=[],p=[],d=[];l.forEach(h=>{h.paths.forEach(m=>{p.push(m),d.push(null)}),u.push(...h.weights)}),l.forEach(h=>{h.paths.forEach(m=>{let f=new FileReader;f.onload=g=>{let y=g.target.result,b=p.indexOf(m);if(d[b]=y,d.indexOf(null)===-1){let v={modelTopology:o,weightSpecs:u,weightData:uy(d),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(v.signature=i.signature),i.userDefinedMetadata!=null&&(v.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(v.modelInitializer=i.modelInitializer),n(v)}},f.onerror=g=>a(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(c[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=>I0(s.name)),r={};for(let s of e)s.paths.forEach(i=>{let o=I0(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}},lF=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($l.URL_SCHEME)?oF(e.slice($l.URL_SCHEME.length)):null;Et.registerSaveRouter(lF);function oF(e="model"){return new $l(e)}function JA(e){return new iF(e)}function D0(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(c=>{let u=n+ ++r/e.length*(a-n);return t(u),c}),l);function i(l){A(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,c){A(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),A(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),A(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(s))}async function R0(e,t){t==null&&(t={});let n=t.fetchFunc==null?ee().platform.fetch:t.fetchFunc,a=e.map(c=>n(c,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await D0(a,t.onProgress,r,s)).map(c=>c.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await D0(i,t.onProgress,o,l)}async function QA(e,t="",n,a){return F0(r=>R0(r,{requestInit:a}))(e,t,n)}function F0(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((h,m)=>{let f=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,b=oy[y]*Pt(g.shape),v=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:b})};a!=null?a.forEach((x,N)=>{x===g.name&&(v(),i[N]=!0)}):v(),o.push(g.name),f+=b})}),!i.every(h=>h)){let h=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
|
|
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;c.push(f)})});let u=await e(c),p={},d=0;return l.forEach(h=>{let m=t[h].paths.length,f=0;for(let v=0;v<m;v++)f+=u[d+v].byteLength;let g=new ArrayBuffer(f),y=new Uint8Array(g),b=0;for(let v=0;v<m;v++){let x=new Uint8Array(u[d+v]);y.set(x,b),b+=x.byteLength}s[h].forEach(v=>{let x=g.slice(v.groupOffset,v.groupOffset+v.sizeBytes),N=w0(x,[v.manifestEntry]);for(let T in N)p[T]=N[T]}),d+=m}),p}}var uF="application/octet-stream",cF="application/json",gy=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?(A(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=ee().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(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:cF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:uF}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Dc(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(h){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 c,u;a!=null&&([c,u]=await this.loadWeights(a));let p={modelTopology:n,weightSpecs:c,weightData:u,generatedBy:r,convertedBy:s,format:i};o!=null&&(p.signature=o),l!=null&&(p.userDefinedMetadata=l);let d=t.modelInitializer;return d&&(p.modelInitializer=d),p}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=pF(t),r=this.weightPathPrefix||n,s=[];for(let c of e)s.push(...c.weights);let i=[],o=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(u)):i.push(r+u+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await R0(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,uy(l)]}};gy.URL_SCHEME_REGEX=/^https?:\/\//;function pF(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function my(e){return e.match(gy.URL_SCHEME_REGEX)!=null}var M0=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>my(a)):n=my(e),n)return fy(e,t)}return null};Et.registerSaveRouter(M0);Et.registerLoadRouter(M0);function fy(e,t){return new gy(e,t)}function eF(e,t){return fy(e,t)}var yy=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},dF=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function tF(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new yy(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 yy({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 yy({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function nF(e){return new dF(e)}var P0={};Oe(P0,{confusionMatrix:()=>hF});function mF(e,t,n=!1,a=!1){let r=E(e,"a","matMul"),s=E(t,"b","matMul");[r,s]=Nt(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return M.runKernel(Es,i,o)}var ze=O({matMul_:mF});function fF(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:E(e,"indices","oneHot","int32")},s={depth:t,onValue:n,offValue:a};return M.runKernel(Qs,r,s)}var Dl=O({oneHot_:fF});function gF(e,t){let n=E(e,"x","transpose");if(t==null&&(t=n.shape.map((s,i)=>i).reverse()),A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(s=>{A(s>=0&&s<n.rank,()=>`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 M.runKernel(yi,a,r)}var Ue=O({transpose_:gF});function yF(e,t,n){let a=E(e,"labels","confusionMatrix"),r=E(t,"predictions","confusionMatrix");A(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),A(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),A(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),A(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.`),A(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=Dl(ce(a,"int32"),n),i=Dl(ce(r,"int32"),n),o=Ue(s),l=ze(o,i);return ce(l,"int32")}var hF=O({confusionMatrix_:yF}),Ni={};Oe(Ni,{fromPixels:()=>xF,toPixels:()=>bF});function ih(e,t,n){if(Ns(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=Ga(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 Hr(e,t,a,n)}var Rl;function vF(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 d=2;if(r&&e.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Zd(Yd,M.backendName)!=null){let d={pixels:e},h={numChannels:t};return M.runKernel(Yd,d,h)}let[l,c]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],u;i?u=e.getContext("2d").getImageData(0,0,l,c).data:a||n?u=e.data:(s||r||o)&&(Rl==null&&(Rl=document.createElement("canvas").getContext("2d")),Rl.canvas.width=l,Rl.canvas.height=c,Rl.drawImage(e,0,0,l,c),u=Rl.getImageData(0,0,l,c).data);let p;if(t===4)p=new Int32Array(u);else{let d=l*c;p=new Int32Array(d*t);for(let h=0;h<d;h++)for(let m=0;m<t;++m)p[h*t+m]=u[h*4+m]}return ih(p,[c,l,t],"int32")}async function bF(e,t){let n=E(e,"img","toPixels");if(!(e instanceof Ae)){let c=n;n=ce(c,"int32"),c.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);let[a,r]=n.shape.slice(0,2),s=n.rank===2?1:n.shape[2];if(s>4||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 c=0;c<a*r;++c){let u=[0,0,0,255];for(let d=0;d<s;d++){let h=i[c*s+d];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);s===1?(u[0]=h*o,u[1]=h*o,u[2]=h*o):u[d]=h*o}let p=c*4;l[p+0]=Math.round(u[0]),l[p+1]=Math.round(u[1]),l[p+2]=Math.round(u[2]),l[p+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=a;let c=t.getContext("2d"),u=new ImageData(l,r,a);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var xF=O({fromPixels_:vF}),by={};Oe(by,{prepareAndValidate:()=>O0});function O0(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(Pt(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 p=0;p<r.length-1;++p)i*=r[p];let o=e.shape,l=r.slice();l.pop();let c=1;for(let p=s;p<n;++p)c*=o[p],l.push(o[p]);let u=[...Co(e.shape).map(p=>p/c),1].slice(0,s);return[l,i,c,u]}var xy={};Oe(xy,{calculateShapes:()=>L0,validateInput:()=>wy,validateUpdateShape:()=>vy});function vy(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.rank<r)throw new Error(s+` update.rank < ${r}. `);if(e.length<a+(n.rank-r))throw new Error(s+` Output shape length < ${a+(n.rank-r)}`);if(n.rank!==r+e.length-a)throw new Error(s+` update.rank != ${r+e.length-a}`);for(let i=0;i<r;++i)if(n.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${n.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<n.rank-r;++i)if(n.shape[i+r]!==e[i+a])throw new Error(s+` updates.shape[${i+r}] (${n.shape[i+r]}) != shape[${i+r}] (${e[i+r]})`)}function wy(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}vy(n,t,e)}function L0(e,t,n){let a=t.shape.length,r=a>1?t.shape[a-1]:1,s=n.length,i=1;for(let p=r;p<s;++p)i*=n[p];let o=r<1?1:r,l=Pt(t.shape)/o,c=[...Co(n.slice(0,r)),1],u=Pt(n);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:c,outputSize:u}}var cn={};Oe(cn,{assertParamsValid:()=>wF,computeFlatOffset:()=>IF,computeOutShape:()=>z0,getNormalizedAxes:()=>W0,isSliceContinous:()=>kF,maskToAxes:()=>oh,parseSliceParams:()=>q0,sliceInfo:()=>NF,startForAxis:()=>H0,startIndicesWithElidedDims:()=>V0,stopForAxis:()=>j0,stopIndicesWithElidedDims:()=>U0,stridesForAxis:()=>G0,stridesWithElidedDims:()=>B0});function wF(e,t,n){let a=e.shape.length;A(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),A(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<a;++r)A(t[r]+n[r]<=e.shape[r],()=>`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function oh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function z0(e,t,n){let a=[];for(let r=0;r<e.length;r++)a[r]=Math.ceil((t[r]-e[r])/n[r]);return a}function B0(e,t,n,a){let r=[...e];for(let s=r.length;s<a.length;s++)r.push(1);for(let s=0;s<n;s++)s===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function K0(e,t,n){return n<=e?n:n-(t-1)}function X0(e,t){let n=[];for(let a=0;a<e;a++)n.push(t+a);return n}function W0(e,t,n,a,r,s,i,o,l){let c=e.length,u=new Array(c),p=new Array(c),d=new Array(c);if(t.length&&n>0){let h=t[0],m=n+1;u=V0(i,h,m,a,e),p=U0(o,h,m,r,e),d=B0(s,h,m,e)}else for(let h=0;h<c;h++)u[h]=H0(i,a,s,e,h,l),p[h]=j0(o,r,s,e,h,l),d[h]=G0(s,h,l);return{begin:u,end:p,strides:d}}function V0(e,t,n,a,r){let s=[...r],i=X0(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=K0(t,n,o),c=a[l];e&1<<l&&(c=0),s[o]=c}return s}function U0(e,t,n,a,r){let s=[...r],i=X0(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=K0(t,n,o),c=a[l];e&1<<l&&(c=Number.MAX_SAFE_INTEGER),s[o]=c}for(let o=0;o<s.length;o++){let l=r[o];s[o]<0&&(s[o]+=l),s[o]=sc(0,s[o],r[o])}return s}function G0(e,t,n){let a=e[t];return(n&1<<t||a==null)&&(a=1),a}function H0(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=sc(0,i,l-1),i}function j0(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=sc(0,i,l):i=sc(-1,i,l-1),i}function kF(e,t,n){let a=n.length;for(let r=0;r<n.length;r++)if(n[r]>1){a=r;break}for(let r=a+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function IF(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a<e.length-1;a++)n+=e[a]*t[a];return n}function q0(e,t,n){let a,r=e.shape.length;typeof t=="number"?a=[t,...new Array(r-1).fill(0)]:t.length<r?a=t.concat(new Array(r-t.length).fill(0)):a=t.slice(),a.forEach(i=>{A(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.length<r?s=n.concat(new Array(r-n.length).fill(-1)):s=n,s=s.map((i,o)=>i>=0?i:(A(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 NF(e,t,n,a,r,s,i,o,l){let c=t.slice(),u=n.slice(),p=a;a==null&&(p=new Array(c.length));let d=oh(i);if(d.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 h=e.length-c.length,m=oh(o),f=e.slice();m.forEach(T=>{c[T]=0,u[T]=1,f.splice(T,0,1)});let{begin:g,end:y,strides:b}=W0(f,d,h,c,u,p,r,s,i);c=g,u=y,p=b;let v=oh(l);v.forEach(T=>{u[T]=c[T]+1,p[T]=1});let x=z0(c,u,p),N=x.filter((T,C)=>v.indexOf(C)===-1);return{nonStrided:p.every(T=>T===1),$begin:c,$end:u,$strides:p,size:x,newShape:f,outShape:N}}var re={};Oe(re,{Serializable:()=>Y0,SerializationMap:()=>Ti,registerClass:()=>Kr});var Y0=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Ti=class{constructor(){this.classNameMap={}}static getMap(){return Ti.instance==null&&(Ti.instance=new Ti),Ti.instance}static register(e){Ti.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Kr(e){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Ti.register(e)}var Z0={};Oe(Z0,{TEST_EPSILON_FLOAT16:()=>J0,encodeStrings:()=>Q0,expectArrayBuffersEqual:()=>AF,expectArraysClose:()=>TF,expectArraysEqual:()=>CF,expectNumbersClose:()=>_F,expectPromiseToFail:()=>SF,expectValuesInRange:()=>EF,testEpsilon:()=>ky});var FF=.001,J0=.1;function TF(e,t,n){return n==null&&(n=ky()),Iy(e,t,(a,r)=>Ny(a,r,n))}function ky(){return M.backend.floatPrecision()===32?FF:J0}function Iy(e,t,n){let a=!0;if((on(e)||on(t))&&(a=!1),on(e)&&on(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=Ga(e),o=Ga(t);if(!mr(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=on(e)?e:Ts(e),s=on(t)?t:Ts(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}.
|
|
Actual: ${r}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!n(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
|
|
Actual: ${r}.
|
|
Expected: ${s}.`)}}function SF(e,t){e().then(()=>t.fail(),()=>t())}function CF(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Or(e)||Or(e[0])||Or(t)||Or(t[0])?Iy(e,n,(a,r)=>a==r):Iy(e,t,(a,r)=>Ny(a,r,0))}function _F(e,t,n){if(n==null&&(n=ky()),!Ny(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ny(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function EF(e,t,n){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>n)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${n}`)}function AF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function Q0(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?Q0(n):e[t]=Cc(n)}return e}var e1="3.1.0";function $F(){ee().set("PROD",!0)}function DF(){ee().set("DEBUG",!0)}function RF(){ee().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Ty(e){ee().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}cA(Ty);function MF(){M.disposeVariables()}function Ha(){return M}function lh(){return M.memory()}function PF(e){return M.profile(e)}function D(e,t){return M.tidy(e,t)}function Fe(e){ey(e).forEach(t=>t.dispose())}function jt(e){return M.keep(e)}function OF(e){return M.time(e)}function LF(e){return M.setBackend(e)}function zF(){return M.ready()}function BF(){return M.backendName}function WF(e){M.removeBackend(e)}function VF(e){return M.findBackend(e)}function UF(e){return M.findBackendFactory(e)}function uh(e,t,n=1){return M.registerBackend(e,t,n)}function t1(){return M.backend}function GF(e,t){ee().setPlatform(e,t)}function HF(e,t){let n=E(e,"a","add"),a=E(t,"b","add");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(zr,r)}var Z=O({add_:HF});function jF(e,t){let n=E(e,"a","floorDiv"),a=E(t,"b","floorDiv");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(Bs,r)}var ch=O({floorDiv_:jF});function qF(e,t){let n=E(e,"a","div"),a=E(t,"b","div");if([n,a]=Nt(n,a),n.dtype==="int32"&&a.dtype==="int32")return ch(n,a);let r={a:n,b:a},s={};return M.runKernel(Os,r,s)}var ve=O({div_:qF});function KF(e,t){let n=E(e,"a","mul"),a=E(t,"b","mul");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(Js,r)}var L=O({mul_:KF});function XF(e){let t=E(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return M.runKernel(cc,n)}else{let n={x:t};return M.runKernel(Eo,n)}}var Lt=O({abs_:XF});function YF(e){let t={x:E(e,"x","acos")};return M.runKernel(Ao,t)}var Sy=O({acos_:YF});function ZF(e){let t={x:E(e,"x","acosh")};return M.runKernel(Fo,t)}var Cy=O({acosh_:ZF});function JF(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>E(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(!mr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return M.runKernel(Ss,a)}var n1=O({addN_:JF});function QF(e,t=null,n=!1){let a={x:E(e,"x","all","bool")},r={axis:t,keepDims:n};return M.runKernel(vd,a,r)}var ph=O({all_:QF});function e$(e,t=null,n=!1){let a={x:E(e,"x","any","bool")},r={axis:t,keepDims:n};return M.runKernel(wd,a,r)}var Rc=O({any_:e$});function t$(e,t=0){let n={x:E(e,"x","argMax")},a={axis:t};return M.runKernel(Cs,n,a)}var Mc=O({argMax_:t$});function n$(e,t=0){let n={x:E(e,"x","argMin")},a={axis:t};return M.runKernel(oc,n,a)}var _y=O({argMin_:n$});function a$(e){let t={x:E(e,"x","asin")};return M.runKernel($o,t)}var Ey=O({asin_:a$});function r$(e){let t={x:E(e,"x","asinh")};return M.runKernel(Do,t)}var Ay=O({asinh_:r$});function s$(e){let t={x:E(e,"x","atan")};return M.runKernel(Ro,t)}var Fy=O({atan_:s$});function i$(e,t){let n=E(e,"a","atan2"),a=E(t,"b","atan2");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(Po,r)}var $y=O({atan2_:i$});function o$(e){let t={x:E(e,"x","atanh")};return M.runKernel(Mo,t)}var Dy=O({atanh_:o$});function l$(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=a1(r);return Pc(e,o,n,s,a,null,null,l)}function r1(e,t,n,a,r,s,i="channelsLast"){let[o,l]=dh(t),c;if(i==="channelsLast")c=[o,l,e[3],e[3]];else if(i==="channelsFirst")c=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Pc(e,c,n,a,r,s,!1,i)}function u$(e,t,n,a,r,s,i="NDHWC"){let[o,l,c]=Ry(t),u,p;if(i==="NDHWC")p="channelsLast",u=[o,l,c,e[4],e[4]];else if(i==="NCDHW")p="channelsFirst",u=[o,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return s1(e,u,n,a,r,!1,p,s)}function Pc(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,c,u,p]=[-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,p]=e;else if(o==="channelsFirst")[l,p,c,u]=e;else throw new Error(`Unknown dataFormat ${o}`);let[d,h,,m]=t,[f,g]=dh(n),[y,b]=dh(a),v=Ml(d,y),x=Ml(h,b),{padInfo:N,outHeight:T,outWidth:C}=c$(r,c,u,f,g,v,x,s,o),F=i?m*p:m,$;return o==="channelsFirst"?$=[l,F,T,C]:o==="channelsLast"&&($=[l,T,C,F]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:p,outHeight:T,outWidth:C,outChannels:F,padInfo:N,strideHeight:f,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:v,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:e,outShape:$,filterShape:t}}function s1(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,c,u,p,d]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,p,d]=e;else if(i==="channelsFirst")[l,d,c,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,m,f,,g]=t,[y,b,v]=Ry(n),[x,N,T]=Ry(a),C=Ml(h,x),F=Ml(m,N),$=Ml(f,T),{padInfo:P,outDepth:B,outHeight:W,outWidth:G}=p$(r,c,u,p,y,b,v,C,F,$,o),q=s?g*d:g,j;return i==="channelsFirst"?j=[l,q,B,W,G]:i==="channelsLast"&&(j=[l,B,W,G,q]),{batchSize:l,dataFormat:i,inDepth:c,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:W,outWidth:G,outChannels:q,padInfo:P,strideDepth:y,strideHeight:b,strideWidth:v,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:F,effectiveFilterWidth:$,dilationDepth:x,dilationHeight:N,dilationWidth:T,inShape:e,outShape:j,filterShape:t}}function d$(e,t,n,a,r){a==null&&(a=My(e,t,n));let s=e[0],i=e[1],o=Si((s-t+2*a)/n+1,r),l=Si((i-t+2*a)/n+1,r);return[o,l]}function h$(e,t,n,a,r,s){r==null&&(r=My(e,t,a));let i=e[0],o=e[1],l=e[2],c=Si((i-t+2*r)/a+1,s),u=Si((o-t+2*r)/a+1,s),p=Si((l-t+2*r)/a+1,s);return[c,u,p,n]}function My(e,t,n,a=1){let r=Ml(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function dh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Ry(e){return typeof e=="number"?[e,e,e]:e}function Ml(e,t){return t<=1?e:e+(e-1)*(t-1)}function c$(e,t,n,a,r,s,i,o,l){let c,u,p;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let d=d$([t,n],s,a,e,o);u=d[0],p=d[1]}else if(e==="same"){u=Math.ceil(t/a),p=Math.ceil(n/r);let d=Math.max(0,(u-1)*a+s-t),h=Math.max(0,(p-1)*r+i-n),m=Math.floor(d/2),f=d-m,g=Math.floor(h/2),y=h-g;c={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/a),p=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let d=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];c={top:d,bottom:h,left:m,right:f,type:d===0&&h===0&&m===0&&f===0?"VALID":"EXPLICIT"},u=Si((t-s+d+h)/a+1,o),p=Si((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:p}}function p$(e,t,n,a,r,s,i,o,l,c,u){let p,d,h,m;if(typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=h$([t,n,a,1],o,1,r,e,u);d=f[0],h=f[1],m=f[2]}else if(e==="same"){d=Math.ceil(t/r),h=Math.ceil(n/s),m=Math.ceil(a/i);let f=(d-1)*r+o-t,g=(h-1)*s+l-n,y=(m-1)*i+c-a,b=Math.floor(f/2),v=f-b,x=Math.floor(g/2),N=g-x,T=Math.floor(y/2),C=y-T;p={top:x,bottom:N,left:T,right:C,front:b,back:v,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-o+1)/r),h=Math.ceil((n-l+1)/s),m=Math.ceil((a-c+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:h,outWidth:m}}function Si(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 Xr(e){let[t,n,a]=dh(e);return t===1&&n===1&&a===1}function ja(e,t){return Xr(e)||Xr(t)}function a1(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function m$(e,t){let n={x:E(e,"x","reshape","string_or_numeric")},a={shape:t};return M.runKernel(hl,n,a)}var H=O({reshape_:m$});function f$(e,t,n,a,r){let s=E(e,"x","avgPool","float32"),i=1;A(ja(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=H(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),r!=null&&A(Gt(a),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r},p=M.runKernel(_s,c,u);return p=ce(p,s.dtype),l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Xn=O({avgPool_:f$});function g$(e,t,n,a,r,s="NDHWC"){let i=E(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&A(Gt(a),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},p=M.runKernel(lc,c,u);return p=ce(p,o.dtype),l?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Py=O({avgPool3d_:g$});function y$(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=$c(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 qr(n[0]);let a=n,r={axis:t};return M.runKernel(Oo,a,r)}var Qe=O({concat_:y$});function b$(e){let t={x:E(e,"x","sigmoid")};return M.runKernel(ci,t)}var ca=O({sigmoid_:b$});function x$(e,t,n){let a=E(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 M.runKernel(yl,r,s)}var We=O({slice_:x$});function v$(e){let t={x:E(e,"x","tanh")};return M.runKernel(gi,t)}var Pl=O({tanh_:v$});function w$(e,t,n,a,r,s){let i=E(e,"forgetBias","basicLSTMCell"),o=E(t,"lstmKernel","basicLSTMCell"),l=E(n,"lstmBias","basicLSTMCell"),c=E(a,"data","basicLSTMCell"),u=E(r,"c","basicLSTMCell"),p=E(s,"h","basicLSTMCell"),d=Qe([c,p],1),h=ze(d,o),m=Z(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],b=We(m,[0,0],y),v=We(m,[0,g],y),x=We(m,[0,g*2],y),N=We(m,[0,g*3],y),T=Z(L(ca(b),Pl(v)),L(u,ca(Z(i,x)))),C=L(Pl(T),ca(N));return[T,C]}var k$=O({basicLSTMCell_:w$});function I$(e,t,n){let a=E(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);A(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(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 M.runKernel(uc,s,i)}var Oc=O({batchToSpaceND_:I$});function N$(e){let t;return e.rank===0||e.rank===1?t=H(e,[1,1,1,e.size]):e.rank===2?t=H(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function T$(e,t,n,a,r,s){s==null&&(s=.001);let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;a!=null&&(u=E(a,"offset","batchNorm")),A(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(c==null||o.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:N$(i),scale:c,offset:u,mean:o,variance:l},d={varianceEpsilon:s},h=M.runKernel(Ws,p,d);return H(h,i.shape)}var gr=O({batchNorm_:T$});function S$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),gr(i,o,l,u,c,s)}var i1=O({batchNorm2d_:S$});function C$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),A(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&A(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),gr(i,o,l,u,c,s)}var o1=O({batchNorm3d_:C$});function _$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),A(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),A(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&A(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&A(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),gr(i,o,l,u,c,s)}var l1=O({batchNorm4d_:_$});function E$(e,t,n){let a=E(e,"x","bincount"),r=E(t,"weights","bincount");A(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(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 M.runKernel(Nd,s,i)}var u1=O({bincount_:E$});function A$(e,t){let n=E(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.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){let l=n.shape.slice();for(;l.length<t.length;)l.unshift(1);n=H(n,l)}let r=n.shape,s=Array.from(t);for(let l=t.length-1;l>=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,c)=>l>1?c:-1).filter(l=>l>=0).length===0)return qr(n);let i={x:n},o={reps:s};return M.runKernel(Wr,i,o)}var Lc=O({broadcastTo_:A$});function F$(e){let t={x:E(e,"x","ceil")};return M.runKernel(Fs,t)}var Oy=O({ceil_:F$});function $$(e,t,n){let a=E(e,"x","clipByValue");A(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 M.runKernel(Br,r,s)}var qt=O({clipByValue_:$$});function D$(e){return Qe(e,0)}var c1=O({concat1d_:D$});function R$(e,t){return Qe(e,t)}var p1=O({concat2d_:R$});function M$(e,t){return Qe(e,t)}var d1=O({concat3d_:M$});function P$(e,t){return Qe(e,t)}var h1=O({concat4d_:P$});function O$(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","conv2d"),l=E(t,"filter","conv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=H(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&A(Gt(a),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let p=r==="NHWC"?c.shape[3]:c.shape[1];A(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),A(ja(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let d={x:c,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=M.runKernel($s,d,h);return u?H(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var At=O({conv2d_:O$});function L$(e,t,n,a,r="NWC",s=1,i){let o=E(e,"x","conv1d"),l=E(t,"filter","conv1d"),c=o,u=!1;o.rank===2&&(u=!0,c=H(o,[1,o.shape[0],o.shape[1]])),A(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&A(Gt(a),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),A(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(ja(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),A(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let p=H(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=H(c,[c.shape[0],1,c.shape[1],c.shape[2]]),h=At(d,p,[1,n],a,"NHWC",[1,s],i);return u?H(h,[h.shape[2],h.shape[3]]):H(h,[h.shape[0],h.shape[2],h.shape[3]])}var hh=O({conv1d_:L$});function z$(e,t,n,a,r,s="NHWC",i){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,c=!1;t.rank===3&&(c=!0,l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),A(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=s==="NHWC"?o[3]:o[1],p=s==="NHWC"?l.shape[3]:l.shape[1];A(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),A(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),i!=null&&A(Gt(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let d={dy:l,filter:n},h={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=M.runKernel(Ds,d,h);return c?H(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ly=O({conv2DBackpropInput_:z$});function B$(e,t,n,a,r,s){let i=E(e,"x","conv2dTranspose"),o=E(t,"filter","conv2dTranspose");return Ly(n,i,o,a,r,"NHWC",s)}var mh=O({conv2dTranspose_:B$});function W$(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=E(e,"x","conv3d"),o=E(t,"filter","conv3d"),l=i,c=!1;i.rank===4&&(c=!0,l=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),A(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),A(ja(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:o},p={strides:n,pad:a,dataFormat:r,dilations:s},d=M.runKernel(pc,u,p);return c?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var zy=O({conv3d_:W$});function V$(e,t,n,a,r){A(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=H(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],c=i.shape[4];A(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),A(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),A(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),A(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),A(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:i,filter:n},p={pad:r,strides:a,inputShape:s},d=M.runKernel(_d,u,p);return o?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var m1=O({conv3DBackpropInput_:V$});function U$(e,t,n,a,r){let s=E(e,"x","conv3dTranspose"),i=E(t,"filter","conv3dTranspose");return m1(n,s,i,a,r)}var G$=O({conv3dTranspose_:U$});function H$(e){let t={x:E(e,"x","cos")};return M.runKernel(Rs,t)}var zc=O({cos_:H$});function j$(e){let t={x:E(e,"x","cosh")};return M.runKernel(Lo,t)}var fh=O({cosh_:j$});function q$(e,t=0,n=!1,a=!1){let r={x:E(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return M.runKernel(Ms,r,s)}var gh=O({cumsum_:q$});function K$(e,t,n,a=!1){let r=E(e,"x","denseBincount"),s=E(t,"weights","denseBincount");A(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),A(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(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 M.runKernel(Ed,i,o)}var f1=O({denseBincount_:K$});function X$(e,t,n="NHWC"){let a=E(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];A(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${r} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),A(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),A(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 M.runKernel(Bo,o,l)}var By=O({depthToSpace_:X$});function Y$(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","depthwiseConv2d"),l=E(t,"filter","depthwiseConv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=H(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),A(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),i!=null&&A(Gt(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let p={x:c,filter:l},d={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},h=M.runKernel(Ps,p,d);return u?H(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Yr=O({depthwiseConv2d_:Y$});function Z$(e){let t={x:E(e,"x","diag")};return M.runKernel($d,t)}var J$=O({diag_:Z$});function Q$(e,t,n,a,r=[1,1],s="NHWC"){let i=E(e,"x","dilation2d"),o=E(t,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,c=!1;i.rank===3&&(l=H(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=!0);let u={x:l,filter:o},p={strides:n,pad:a,dilations:r},d=M.runKernel(dc,u,p);return c?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Wy=O({dilation2d_:Q$});function eD(e,t){let n=e.length,a=[];for(let r=0;r<n;r++){let s=n-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&a.unshift(s)}return a}function zt(e,t){let n=[];for(let a=0;a<t.length;a++){let r=e[e.length-a-1],s=t.length-a-1,i=t[s];(r==null||r===1&&i>1)&&n.unshift(s)}return n}function xt(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;r<a;r++){let s=e[e.length-r-1];s==null&&(s=1);let i=t[t.length-r-1];if(i==null&&(i=1),s===1)n.unshift(i);else if(i===1)n.unshift(s);else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else n.unshift(s)}return n}function tD(e,t){let n=E(e,"a","equal"),a=E(t,"b","equal");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Uo,r)}var Zr=O({equal_:tD});function nD(e,t,n){let a=E(t,"a","where"),r=E(n,"b","where"),s=E(e,"condition","where","bool"),i=xt(a.shape,r.shape),o=Lc(a,i),l=Lc(r,i);s.rank===1&&A(s.shape[0]===a.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),s.rank!==1&&sn(s.shape,l.shape,"Error in where: ");let c={condition:s,t:o,e:l};return M.runKernel(fl,c)}var vn=O({where_:nD});function aD(e){let t={x:E(e,"x","zerosLike")};return M.runKernel(Sl,t)}var Ge=O({zerosLike_:aD});function rD(e,t){let n=E(e,"a","div"),a=E(t,"b","div");[n,a]=Nt(n,a);let r=ve(n,a),s=Ge(r),i=Zr(a,s);return vn(i,s,r)}var Vy=O({divNoNan_:rD});function sD(e,t){let n=E(e,"t1","dot"),a=E(t,"t2","dot");A((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=>`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(A(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=H(n,[1,-1]),o=H(a,[-1,1]),l=ze(i,o);return H(l,[])}else if(n.rank===1&&a.rank===2){let i=H(n,[1,-1]),o=H(a,[a.shape[0],a.shape[1]]),l=ze(i,o);return H(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=H(a,[-1,1]),o=ze(n,i);return H(o,[o.size])}else{let i=H(a,[a.shape[0],a.shape[1]]);return ze(n,i)}}var g1=O({dot_:sD});function iD(e){let t={x:E(e,"x","elu")};return M.runKernel(Wo,t)}var Ol=O({elu_:iD});function oD(e){let t=E(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return M.runKernel(Vo,n)}var Uy=O({erf_:oD});function lD(e){let t={x:E(e,"x","exp")};return M.runKernel(Ls,t)}var pn=O({exp_:lD});function uD(e,t=0){let n=E(e,"x","expandDims","string_or_numeric");A(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return M.runKernel(Go,a,r)}var $n=O({expandDims_:uD});function cD(e){let t={x:E(e,"x","expm1")};return M.runKernel(Ho,t)}var Gy=O({expm1_:cD});function pD(e,t){let n=E(e,"x","tile","string_or_numeric");A(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 M.runKernel(Wr,a,r)}var qa=O({tile_:pD});function dD(e,t,n,a="float32"){t==null&&(t=e);let r=Le([e,t],a),s=e<=t?e:t;for(let o=0;o<s;++o)r.set(1,o,o);let i=H(r.toTensor(),[e,t]);if(n==null)return i;if(n.length===1)return qa($n(i,0),[n[0],1,1]);if(n.length===2)return qa($n($n(i,0),0),[n[0],n[1],1,1]);if(n.length===3)return qa($n($n($n(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var Hy=O({eye_:dD});function wn(e,t,n){let a={shape:e,value:t,dtype:n};return M.runKernel(hc,{},a)}function hD(e){let t={x:E(e,"x","floor")};return M.runKernel(zs,t)}var Ll=O({floor_:hD});function mD(e,t,n=0,a=0){let r=E(e,"x","gather"),s=E(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:n,batchDims:a};return M.runKernel(qo,i,o)}var Ci=O({gather_:mD});function fD(e,t){let n=E(e,"a","greater"),a=E(t,"b","greater");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Xo,r)}var pa=O({greater_:fD});function gD(e,t){let n=E(e,"a","greaterEqual"),a=E(t,"b","greaterEqual");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Vs,r)}var Jr=O({greaterEqual_:gD});function yD(e){let t={input:E(e,"input","imag")};return M.runKernel(Ld,t)}var yh=O({imag_:yD});function bD(e){let t={x:E(e,"x","isFinite")};return M.runKernel(Yo,t)}var y1=O({isFinite_:bD});function xD(e){let t={x:E(e,"x","isInf")};return M.runKernel(Zo,t)}var b1=O({isInf_:xD});function vD(e){let t={x:E(e,"x","isNaN")};return M.runKernel(Jo,t)}var x1=O({isNaN_:vD});function wD(e,t=.2){let n={x:E(e,"x","leakyRelu")},a={alpha:t};return M.runKernel(Gs,n,a)}var Bc=O({leakyRelu_:wD});function kD(e,t){let n=E(e,"a","less"),a=E(t,"b","less");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Qo,r)}var bh=O({less_:kD});function ID(e,t){let n=E(e,"a","lessEqual"),a=E(t,"b","lessEqual");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(el,r)}var _i=O({lessEqual_:ID});function v1(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let a={start:e,stop:t,num:n};return M.runKernel(zd,{},a)}function ND(e,t=5,n=1,a=1,r=.5){let s=E(e,"x","localResponseNormalization");A(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),A(Gt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=H(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},c={depthRadius:t,bias:n,alpha:a,beta:r},u=M.runKernel(gc,l,c);return o?H(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var jy=O({localResponseNormalization_:ND});function TD(e){let t={x:E(e,"x","log")};return M.runKernel(Hs,t)}var Dn=O({log_:TD});function SD(e){let t={x:E(e,"x","log1p")};return M.runKernel(tl,t)}var xh=O({log1p_:SD});function CD(e){return A(Lr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=E(t,"x","tf.grad","string_or_numeric"),r=n!=null?E(n,"dy","tf.grad"):null;return M.tidy(()=>{let{value:s,grads:i}=M.gradients(()=>e(a),[a],r);return r!=null&&sn(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),vh(i),i[0]})}}function _D(e){return A(Lr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=$c(t,"args","tf.grads","string_or_numeric"),r=n!=null?E(n,"dy","tf.grads"):null;return M.tidy(()=>{let{value:s,grads:i}=M.gradients(()=>e(...a),a,r);return r!=null&&sn(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vh(i),i})}}function ED(e){return A(Lr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof Ae,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof Ae,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=M.gradients(()=>e(t),[t],n);return vh(a),{grad:a[0],value:r}}}function AD(e){return A(Lr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(r=>r instanceof Ae),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof Ae,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=M.gradients(()=>e(...t),t,n);return n!=null&&sn(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),vh(a.grads),a}}function w1(e,t){A(Lr(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(c=>c instanceof Ur),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in M.registeredVariables)t.push(M.registeredVariables[c])}let a=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),A(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}=M.gradients(e,t,null,s);A(o.some(c=>c!=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()."),A(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((c,u)=>{o[u]!=null&&(l[c.name]=o[u])}),a!=null&&a.forEach(c=>l[c.name]=null),{value:i,grads:l}}function Ka(e){return M.customGrad(e)}function vh(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 FD(e){let t={x:E(e,"x","neg")};return M.runKernel(rl,t)}var Tt=O({neg_:FD});function $D(e){let t={x:E(e,"x","softplus")};return M.runKernel(vl,t)}var zl=O({softplus_:$D});function DD(e){let t=E(e,"x","logSigmoid");return Ka(n=>({value:Tt(zl(Tt(n))),gradFunc:a=>L(a,ca(Tt(n)))}))(t)}var k1=O({logSigmoid_:DD});function RD(e,t=null,n=!1){let a={x:E(e,"x","max")},r={reductionIndices:t,keepDims:n};return M.runKernel(js,a,r)}var Yn=O({max_:RD});function MD(e,t){let n=E(e,"a","sub"),a=E(t,"b","sub");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(fi,r)}var fe=O({sub_:MD});function PD(e,t=null,n=!1){let a=E(e,"x","sum");a.dtype==="bool"&&(a=ce(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return M.runKernel(di,r,s)}var Te=O({sum_:PD});function OD(e,t=-1){let n=E(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 Ka((a,r)=>{let s=!0,i=Yn(a,t,!0),o=fe(a,i),l=fe(ce(o,"float32"),Dn(Te(pn(o),t,s)));return r([l]),{value:l,gradFunc:(c,u)=>{let[p]=u,d=!0,h=pn(p);return fe(c,L(Te(c,t,d),h))}}})(n)}var wh=O({logSoftmax_:OD});function qy(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function I1(e,t,n){let a=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<a;o++)n.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function N1(e,t){let n=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&n.push(e[s]);let r=t.map(s=>e[s]);return[n,r]}function Ei(e,t){let n=t.map(a=>1);return I1(e,n,t)}function LD(e,t,n){A(qy(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function T1(e,t){if(qy(e,t))return null;let n=[];for(let a=0;a<t;++a)e.indexOf(a)===-1&&n.push(a);return e.forEach(a=>n.push(a)),n}function Ky(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function zD(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function BD(e,t=null,n=!1){let a=E(e,"x","logSumExp"),r=la(t,a.shape),s=Yn(a,r,!0),i=fe(a,s),o=pn(i),l=Te(o,r),c=Dn(l),u=Z(H(s,c.shape),c);if(n){let p=Ei(u.shape,r);return H(u,p)}return u}var Xy=O({logSumExp_:BD});function WD(e,t){let n=E(e,"a","logicalAnd","bool"),a=E(t,"b","logicalAnd","bool");xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(nl,r)}var da=O({logicalAnd_:WD});function VD(e){let t={x:E(e,"x","logicalNot","bool")};return M.runKernel(mc,t)}var Wc=O({logicalNot_:VD});function UD(e,t){let n=E(e,"a","logicalOr","bool"),a=E(t,"b","logicalOr","bool");xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(fc,r)}var kh=O({logicalOr_:UD});function GD(e,t){let n=E(e,"a","logicalXor","bool"),a=E(t,"b","logicalXor","bool");return xt(n.shape,a.shape),da(kh(e,t),Wc(da(e,t)))}var S1=O({logicalXor_:GD});function HD(e,t,n,a,r){let s=E(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=H(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),A(ja(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&A(Gt(a),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r},p=M.runKernel(Ks,c,u);return l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Ft=O({maxPool_:HD});function jD(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=E(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&A(Gt(a),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},p=M.runKernel(yc,c,u);return l?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Yy=O({maxPool3d_:jD});function qD(e,t,n,a,r=!1){let s={x:E(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=M.runKernel(Ud,s,i);return{result:o[0],indexes:o[1]}}var C1=O({maxPoolWithArgmax_:qD});function KD(e,t){let n=E(e,"a","maximum"),a=E(t,"b","maximum");[n,a]=Nt(n,a),n.dtype==="bool"&&(n=ce(n,"int32"),a=ce(a,"int32")),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(qs,r)}var Xa=O({maximum_:KD});function XD(e,t=null,n=!1){let a={x:E(e,"x","mean")},r={axis:t,keepDims:n};return M.runKernel(Xs,a,r)}var St=O({mean_:XD});function YD(e,t=null,n=!1){let a={x:E(e,"x","min")},r={axis:t,keepDims:n};return M.runKernel(Ys,a,r)}var Bl=O({min_:YD});function ZD(e,t){let n=E(e,"a","minimum"),a=E(t,"b","minimum");[n,a]=Nt(n,a),n.dtype==="bool"&&(n=ce(n,"int32"),a=ce(a,"int32")),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Zs,r)}var Wl=O({minimum_:ZD});function JD(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=E(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(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<a.rank;o++)A(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(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 M.runKernel(bc,i,s)}var Zy=O({mirrorPad_:JD});function QD(e,t){let n=E(e,"a","mod"),a=E(t,"b","mod");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(al,r)}var Jy=O({mod_:QD});function eR(e){let t=E(e,"x","square"),n={};return M.runKernel("Square",{x:t},n)}var lt=O({square_:eR});function tR(e,t=null,n=!1){e=E(e,"x","moments");let a=la(t,e.shape),r=St(e,a,n),s=r.shape;n||(s=Ei(r.shape,a));let i=lt(fe(ce(e,"float32"),H(r,s))),o=St(i,a,n);return{mean:r,variance:o}}var Ih=O({moments_:tR});function nR(e,t,n,a){let r=E(t,"data","multiRNNCell"),s=$c(n,"c","multiRNNCell"),i=$c(a,"h","multiRNNCell"),o=r,l=[];for(let p=0;p<e.length;p++){let d=e[p](o,s[p],i[p]);l.push(d[0]),l.push(d[1]),o=d[1]}let c=[],u=[];for(let p=0;p<l.length;p+=2)c.push(l[p]),u.push(l[p+1]);return[c,u]}var aR=O({multiRNNCell_:nR});function rR(e,t,n,a=!1){let r=E(e,"logits","multinomial"),s=r.size,i=r.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?H(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},c=M.runKernel(Gd,o,l);return i===1?H(c,[c.size]):c}var _1=O({multinomial_:rR});function sR(e,t){let n=E(e,"a","notEqual"),a=E(t,"b","notEqual");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(sl,r)}var Ai=O({notEqual_:sR});function vt(e,t="float32"){if(t==="complex64"){let a=vt(e,"float32"),r=vt(e,"float32");return Gr(a,r)}let n=xd(Pt(e),t);return M.makeTensor(n,e,t)}function Ya(e,t="float32"){if(t==="complex64"){let a=Ya(e,"float32"),r=vt(e,"float32");return Gr(a,r)}let n=Hg(Pt(e),t);return M.makeTensor(n,e,t)}function iR(e){let t={x:E(e,"x","onesLike")};return M.runKernel(ul,t)}var Rn=O({onesLike_:iR});function oR(e,t){let n=E(e,"v1","outerProduct"),a=E(t,"v2","outerProduct");A(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=H(n,[-1,1]),s=H(a,[1,-1]);return ze(r,s)}var lR=O({outerProduct_:oR});function uR(e,t,n=0){let a=E(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 M.runKernel(ei,s,r)}var Zn=O({pad_:uR});function cR(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Zn(e,[t],n)}var pR=O({pad1d_:cR});function dR(e,t,n=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Zn(e,t,n)}var hR=O({pad2d_:dR});function mR(e,t,n=0){return A(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."),Zn(e,t,n)}var fR=O({pad3d_:mR});function gR(e,t,n=0){return A(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."),Zn(e,t,n)}var yR=O({pad4d_:gR});function bR(e,t,n){let a=E(e,"x","spaceToBatchND");A(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),A(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),A(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 M.runKernel(wc,r,s)}var Vc=O({spaceToBatchND_:bR});function wR(e,t,n,a,r,s){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let i=E(e,"x","maxPool"),o=i,l=!1;i.rank===3&&(l=!0,o=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),A(ja(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let c=r1(o.shape,t,s,r,a),u=[c.dilationHeight,c.dilationWidth],p;a==="same"?p=vR([c.filterHeight,c.filterWidth],u):p=[[0,0],[0,0]];let d=u[0]===1&&u[1]===1,[h,m]=xR([c.inHeight,c.inWidth],u,p),f=d?a:"valid",g=d?o:Vc(o,u,h),y=(n==="avg"?()=>Xn(g,t,s,f):()=>Ft(g,t,s,f))(),b=d?y:Oc(y,u,m);return l?H(b,[b.shape[1],b.shape[2],b.shape[3]]):b}function xR(e,t,n){let a=n.map(u=>u[0]),r=n.map(u=>u[1]),s=e.concat(a,r),i=t.map((u,p)=>(u-s[p]%u)%u),o=r.map((u,p)=>u+i[p]),l=t.map((u,p)=>[a[p],o[p]]),c=t.map((u,p)=>[0,i[p]]);return[l,c]}function vR(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 E1=O({pool_:wR});function kR(e,t){let n=E(e,"base","pow"),a=E(t,"exp","pow");[n,a]=Nt(n,a);let r={a:n,b:a};return M.runKernel(ti,r)}var yr=O({pow_:kR});function IR(e,t){let n=E(e,"x","prelu"),a=E(t,"alpha","prelu"),r={x:n,alpha:a};return M.runKernel(ni,r)}var Uc=O({prelu_:IR});function NR(e,t=null,n=!1){let a=E(e,"x","prod");a.dtype==="bool"&&(a=ce(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return M.runKernel(pl,r,s)}var Nh=O({prod_:NR});function TR(e,t,n){let a=Pt(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<a;s++)r[s]=t();return M.makeTensor(r,e,n)}var SR=O({rand_:TR}),Qy=So(fd()),eb=class{constructor(e,t,n,a,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=a,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=r||Math.random();this.random=Qy.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let a=this.nextVal;return this.nextVal=NaN,a}let e,t,n=!1;for(;!n;){let a,r,s;do a=2*this.random()-1,r=2*this.random()-1,s=a*a+r*r;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*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}},CR=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=Qy.alea(r.toString()),this.randn=new eb(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(),r<t||Math.log(r)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},_R=class{constructor(e=0,t=1,n,a){if(this.canReturnFloat=()=>this.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=Qy.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function ER(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 CR(t,n,a,r),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var AR=O({randomGamma_:ER});function FR(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error(`Unsupported data type ${a}`);let s=new eb(t,n,a,!1,r),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var A1=O({randomNormal_:FR});function $R(e,t=0,n=1,a="float32",r){let s=Le(e,a),i=new _R(t,n,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Vl=O({randomUniform_:$R});function Th(e,t,n=1,a="float32"){if(n===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:n,dtype:a};return M.runKernel(xc,{},r)}function DR(e){let t={input:E(e,"input","real")};return M.runKernel(Hd,t)}var Gc=O({real_:DR});function RR(e){let t={x:E(e,"x","reciprocal")};return M.runKernel(dl,t)}var tb=O({reciprocal_:RR});function MR(e){let t={x:E(e,"x","relu")};return M.runKernel(ai,t)}var Ye=O({relu_:MR});function PR(e){let t={x:E(e,"x","relu6")};return M.runKernel(si,t)}var Sh=O({relu6_:PR});function OR(e,t){let n={x:E(e,"x","reverse")},a={dims:t};return M.runKernel(ii,n,a)}var Mn=O({reverse_:OR});function LR(e){let t=E(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Mn(t,0)}var zR=O({reverse1d_:LR});function BR(e,t){let n=E(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Mn(n,t)}var WR=O({reverse2d_:BR});function VR(e,t){let n=E(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Mn(n,t)}var UR=O({reverse3d_:VR});function GR(e,t){let n=E(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Mn(n,t)}var HR=O({reverse4d_:GR});function jR(e){let t={x:E(e,"x","round")};return M.runKernel(oi,t)}var nb=O({round_:jR});function qR(e){let t={x:E(e,"x","rsqrt")};return M.runKernel(li,t)}var Ch=O({rsqrt_:qR});function de(e,t){if((on(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"&&on(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Hr(e,[],[],t)}function KR(e){let t={x:E(e,"x","selu")};return M.runKernel(gl,t)}var _h=O({selu_:KR});function XR(e,t,n,a,r,s=[1,1],i="NHWC"){let o=E(e,"x","separableConv2d"),l=E(t,"depthwiseFilter","separableConv2d"),c=E(n,"pointwiseFilter","separableConv2d"),u=o,p=!1;if(o.rank===3&&(p=!0,u=H(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");A(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),A(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let d=l.shape[2],h=l.shape[3];A(c.shape[2]===d*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*h}, but got ${c.shape[2]}.`);let m=Yr(u,l,a,r,i,s),f=At(m,c,1,"valid",i);return p?H(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Fi=O({separableConv2d_:XR});async function YR(e,t){let n=E(e,"x","setdiff1d"),a=E(t,"y","setdiff1d");A(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),A(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),A(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 u=0;u<r.length;u++)i.has(r[u])||o++;let l=new Ot([o],n.dtype),c=new Ot([o],"int32");for(let u=0,p=0;u<r.length;u++)i.has(r[u])||(l.values[p]=r[u],c.values[p]=u,p++);return[l.toTensor(),c.toTensor()]}var F1=YR;function ZR(e){let t={x:E(e,"x","sign")};return M.runKernel(xl,t)}var ab=O({sign_:ZR});function JR(e){let t={x:E(e,"x","sin")};return M.runKernel(ui,t)}var Eh=O({sin_:JR});function QR(e){let t={x:E(e,"x","sinh")};return M.runKernel(bl,t)}var Ah=O({sinh_:QR});function eM(e,t,n){let a=E(e,"x","slice1d");return A(a.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),We(a,[t],[n])}var Fh=O({slice1d_:eM});function tM(e,t,n){let a=E(e,"x","slice2d");return A(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var rb=O({slice2d_:tM});function nM(e,t,n){let a=E(e,"x","slice3d");return A(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var Ul=O({slice3d_:nM});function aM(e,t,n){let a=E(e,"x","slice4d");return A(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var Hc=O({slice4d_:aM});function rM(e,t=-1){let n=E(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 M.runKernel(hi,a,r)}var Ta=O({softmax_:rM});function sM(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return M.runKernel(Pd,t)}var jc=O({fft_:sM});function iM(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return M.runKernel(Od,t)}var Gl=O({ifft_:iM});function oM(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=H(e,[n,t]);a=Gl(r)}else{let r=[n,2*(t-1)],s=H(Gc(e),[n,t]),i=H(yh(e),[n,t]),o=Mn(We(s,[0,1],[n,t-2]),1),l=L(Mn(We(i,[0,1],[n,t-2]),1),de(-1)),c=Qe([s,o],1),u=Qe([i,l],1),p=H(Gr(c,u),[r[0],r[1]]);a=Gl(p)}if(a=Gc(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=H(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var $h=O({irfft_:oM});function lM(e,t,n=0){let a={x:E(e,"x","split")},r={numOrSizeSplits:t,axis:n};return M.runKernel(wl,a,r)}var Pn=O({split_:lM});function uM(e,t){A(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&&t<n){let m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=We(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=Qe([e,vt(m)],e.shape.length-1),n=t}else r=e;let s=Ge(r),i=H(Gr(r,s),[a,n]),o=jc(i),l=Math.floor(n/2)+1,c=Gc(o),u=yh(o),p=Pn(c,[l,n-l],c.shape.length-1),d=Pn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,H(Gr(p[0],d[0]),h)}var qc=O({rfft_:uM});function cM(e){let t={x:E(e,"x","sqrt")};return M.runKernel(pi,t)}var en=O({sqrt_:cM});function pM(e,t){let n=E(e,"a","squaredDifference"),a=E(t,"b","squaredDifference");[n,a]=Nt(n,a),xt(n.shape,a.shape);let r={a:n,b:a},s={};return M.runKernel(mi,r,s)}var Dh=O({squaredDifference_:pM});function dM(e,t){let n=E(e,"x","squeeze");return H(n,Yw(n.shape,t).newShape)}var Qr=O({squeeze_:dM});function hM(e,t=0){let n=$c(e,"tensors","stack","string_or_numeric");A(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&A(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return M.runKernel(cl,a,r)}var $t=O({stack_:hM});function mM(e,t=0){let n={x:E(e,"x","step")},a={alpha:t};return M.runKernel(Vr,n,a)}var Hl=O({step_:mM});function fM(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let c={x:E(e,"x","stridedSlice")},u={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return M.runKernel(kl,c,u)}var sb=O({stridedSlice_:fM});function gM(e){let t={x:E(e,"x","tan")};return M.runKernel(Il,t)}var ib=O({tan_:gM});function tt(e,t){Ns(e);let n=Ga(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Hr(e,null,n,t)}function Sa(e,t,n){if(Ns(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=Ga(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 Hr(e,t,a,n)}function Ca(e,t,n){if(Ns(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=Ga(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 Hr(e,t,a,n)}function yM(e,t,n){if(Ns(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=Ga(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 Hr(e,t,a,n)}function bM(e,t,n){if(Ns(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=Ga(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,Hr(e,t,a,n)}function xM(e,t=1,n=!0){let a=E(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]=M.runKernel(Nl,s,i);return{values:o,indices:l}}var ob=O({topk_:xM});function vM(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new eb(t,n,a,!0,r),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Rh=O({truncatedNormal_:vM});function wM(e,t=0){let n=E(e,"x","unique","string_or_numeric");A(n.rank>0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=M.runKernel(Xd,a,r);return{values:s,indices:i}}var Mh=O({unique_:wM});function kM(e,t,n){let a=E(e,"x","unsortedSegmentSum"),r=E(t,"segmentIds","unsortedSegmentSum","int32");A(Gt(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return M.runKernel(Ic,s,i)}var lb=O({unsortedSegmentSum_:kM});function IM(e,t=0){let n=E(e,"x","unstack","string_or_numeric");A(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return M.runKernel(Tl,a,r)}var dt=O({unstack_:IM});function $1(e,t=!0,n,a){return M.makeVariable(e,t,n,a)}function D1(e,t){let n=[];for(let s=0;s<t.length;s++)t[s]&&n.push(s);let a=Le(e,"int32"),r=Le([n.length,e.length],"int32");for(let s=0;s<n.length;s++){let i=a.indexToLoc(n[s]),o=s*e.length;r.values.set(i,o)}return r.toTensor()}async function NM(e){let t=E(e,"condition","whereAsync","bool"),n=await t.data(),a=D1(t.shape,n);return e!==t&&t.dispose(),a}var ub=NM;async function TM(e,t,n){let a=E(e,"tensor","boolMask"),r=E(t,"mask","boolMask","bool"),s=n==null?0:n,i=r.rank,o=a.shape;A(i>0,()=>"mask cannot be scalar"),sn(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f<s+i;f++)l*=o[f];let c=o.slice(0,s).concat([l],o.slice(s+i)),u=H(a,c),p=H(r,[-1]),d=await ub(p),h=Qr(d,[1]),m=Ci(u,h,s);return e!==a&&a.dispose(),t!==r&&r.dispose(),h.dispose(),u.dispose(),p.dispose(),d.dispose(),m}var SM=TM;function CM(e,t="euclidean",n=null,a=!1){e=E(e,"x","norm");let r=R1(e,t,n),s=r.shape;if(a){let i=la(n,e.shape);s=Ei(r.shape,i)}return H(r,s)}function R1(e,t,n=null){if(e.rank===0)return Lt(e);if(e.rank!==1&&n===null)return R1(H(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return Te(Lt(e),n);if(t===Infinity)return Yn(Lt(e),n);if(t===-Infinity)return Bl(Lt(e),n);if(t==="euclidean"||t===2)return en(Te(yr(Lt(e),de(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return Yn(Te(Lt(e),n[0]),n[1]-1);if(t===Infinity)return Yn(Te(Lt(e),n[1]),n[0]);if(t===-Infinity)return Bl(Te(Lt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return en(Te(lt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var Ph=O({norm_:CM});function _M(e,t,n,a,r=!0){let s=E(e,"v","movingAverage"),i=E(t,"x","movingAverage"),o=E(n,"decay","movingAverage");h0(s,i),A(mr(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=de(1),c=fe(l,o),u=L(fe(i,s),c);if(r){A(a!=null,()=>"When using zeroDebias: true, step is required.");let p=E(a,"step","movingAverage");u=ve(u,fe(l,yr(o,p)))}return Z(s,u)}var EM=O({movingAverage_:_M});function AM(e,t,n){let a=E(e,"indices","scatterND","int32"),r=E(t,"updates","scatterND");wy(r,a,n);let s={indices:a,updates:r},i={shape:n};return M.runKernel(ml,s,i)}var M1=O({scatterND_:AM});function FM(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 $M(e,t,n,a=0){let r=E(e,"sparseIndices","sparseToDense","int32"),s=E(t,"sparseValues","sparseToDense"),i=E(a,"defaultValue","sparseToDense",s.dtype);FM(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return M.runKernel(Kd,o,l)}var cb=O({sparseToDense_:$M});function DM(e,t){let n=E(t,"indices","gatherND","int32"),a={params:E(e,"x","gatherND"),indices:n};return M.runKernel(Ko,a)}var P1=O({gatherND_:DM});function RM(e,t){if(t==null)return e.shape.slice();if(mr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a<e.shape.length;a++)t[a]==null&&e.shape[a]!=null?n.push(e.shape[a]):n.push(t[a]);return n}return t}function MM(e,t,n,a){let r=E(e,"x","dropout");if(A(r.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ae?r.clone():r;let s=RM(r,n),i=1-t,o=ve(Ll(Z(Vl(s,0,1,"float32",a),i)),i);return L(r,o)}var O1=O({dropout_:MM});function L1(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function pb(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+a-1);r[s]=t-n*Math.cos(i)}return tt(r,"float32")}async function PM(e,t,n=1){let a=E(e,"predictions","inTopK"),r=E(t,"targets","inTopK");A(a.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),A(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}`),sn(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];A(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,c]=[i.length/s,s],u=Zw("bool",l);for(let p=0;p<l;p++){let d=p*c,h=i.subarray(d,d+c),m=[];for(let f=0;f<h.length;f++)m.push({value:h[f],index:f});m.sort((f,g)=>g.value-f.value),u[p]=0;for(let f=0;f<n;f++)if(m[f].index===o[p]){u[p]=1;break}}return e!==a&&a.dispose(),t!==r&&r.dispose(),qn(u,r.shape,"bool")}var OM=PM,es={};Oe(es,{conv2d:()=>LM,depthwiseConv2d:()=>zM,matMul:()=>BM});function WM(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]])),A(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=s==="NHWC"?o.shape[3]:o.shape[1],u=s==="NHWC"?l.shape[3]:l.shape[1];A(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),A(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),i!=null&&A(Gt(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let p={x:o,dy:l},d={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return M.runKernel(Sd,p,d)}var db=O({conv2DBackpropFilter_:WM});function Oh(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,Hl(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Lh(e,t){let n=t,a=zt(e.shape,t.shape);return a.length>0&&(n=Te(n,a)),H(n,e.shape)}function zh(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Ye(e);if(t==="elu")return Ol(e);if(t==="relu6")return Sh(e);if(t==="prelu")return Uc(e,n);if(t==="leakyrelu")return Bc(e,a);throw new Error(`Unknown fused activation ${t}.`)}var Bh=(e,t)=>!(e>0)||t==="linear";function VM({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",Bh(M.state.gradientDepth,l)===!1){let N=At(e,t,n,a,r,s,i);return o!=null&&(N=Z(N,o)),zh(N,l,c,u)}let p=E(e,"x","conv2d"),d=E(t,"filter","conv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=H(p,[1,p.shape[0],p.shape[1],p.shape[2]])),A(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),A(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),i!=null&&A(Gt(a),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),A(h.shape[3]===d.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${d.shape[2]}.`),A(ja(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let f=Pc(h.shape,d.shape,n,s,a,i),g;o!=null&&(g=E(o,"bias","fused conv2d"),[g]=Nt(g,p),xt(f.outShape,g.shape));let y;c!=null&&(y=E(c,"prelu weights","fused conv2d"));let b=(N,T)=>{let[C,F,$,P]=T,B=Oh(N,$,l);A(Xr(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let W=Ly(F.shape,B,C,n,a),G=db(F,B,C.shape,n,a),q=[W,G];if(P!=null){let j=Lh(P,B);q.push(j)}return q},v={x:h,filter:d,bias:g,preluActivationWeights:y},x={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Ka((N,T,C)=>{let F=M.runKernel(xi,v,x);return C([T,N,F]),m&&(F=H(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}})(h,d):Ka((N,T,C,F)=>{let $=M.runKernel(xi,v,x);return F([T,N,$,C]),m&&($=H($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d,g)}var LM=O({fusedConv2d_:VM});function UM(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:o,dy:l},u={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return M.runKernel(Ad,c,u)}var z1=O({depthwiseConv2dNativeBackpropFilter_:UM});function GM(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:o,filter:n},u={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},p=M.runKernel(Fd,c,u);return l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var B1=O({depthwiseConv2dNativeBackpropInput_:GM});function HM({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(Bh(M.state.gradientDepth,l)===!1){let N=Yr(e,t,n,a,r,s,i);return o!=null&&(N=Z(N,o)),zh(N,l,c,u)}let p=E(e,"x","depthwiseConv2d"),d=E(t,"filter","depthwiseConv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=H(p,[1,p.shape[0],p.shape[1],p.shape[2]])),A(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),A(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),A(h.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),s==null&&(s=[1,1]),A(ja(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&A(Gt(a),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${a}.`);let f=Pc(h.shape,d.shape,n,s,a,i,!0),g;o!=null&&(g=E(o,"bias","fused conv2d"),[g]=Nt(g,p),xt(f.outShape,g.shape));let y;c!=null&&(y=E(c,"prelu weights","fused depthwiseConv2d"));let b=(N,T)=>{A(Xr(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,F,$,P]=T,B=Oh(N,$,l),W=B1(F.shape,B,C,n,a,s,i),G=z1(F,B,C.shape,n,a,s,i);if(P!=null){let q=Lh(g,B);return[W,G,q]}return[W,G]},v={x:h,filter:d,bias:g,preluActivationWeights:y},x={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Ka((N,T,C)=>{let F=M.runKernel(vi,v,x);return C([T,N,F]),m&&(F=H(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}})(h,d):Ka((N,T,C,F)=>{let $=M.runKernel(vi,v,x);return F([T,N,$,C]),m&&($=H($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d,g)}var zM=O({fusedDepthwiseConv2d_:HM});function jM({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(Bh(M.state.gradientDepth,s)===!1){let P=ze(e,t,n,a);return r!=null&&(P=Z(P,r)),zh(P,s,i,o)}let l=E(e,"a","fused matMul"),c=E(t,"b","fused matMul");[l,c]=Nt(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],p=a?c.shape[c.rank-1]:c.shape[c.rank-2],d=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=a?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),f=c.shape.slice(0,-2),g=Pt(m),y=Pt(f);A(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),A(mr(m,f),()=>`Error in fused matMul: outer dimensions (${m}) and (${f}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),A(u===p,()=>`Error in fused matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${a} must match.`);let b=l.shape.slice(0,-2).concat([d,h]),v=n?H(l,[g,u,d]):H(l,[g,d,u]),x=a?H(c,[y,h,p]):H(c,[y,p,h]),N;r!=null&&(N=E(r,"bias","fused matMul"),[N]=Nt(N,l),xt(b,N.shape));let T;i!=null&&(T=E(i,"prelu weights","fused matMul"));let C=(P,B)=>{let[W,G,q,j]=B,X=Oh(H(P,q.shape),q,s),K,ne;if(!n&&!a?(K=ze(X,G,!1,!0),ne=ze(W,X,!0,!1)):!n&&a?(K=ze(X,G,!1,!1),ne=ze(X,W,!0,!1)):n&&!a?(K=ze(G,X,!1,!0),ne=ze(W,X,!1,!1)):(K=ze(G,X,!0,!0),ne=ze(X,W,!0,!0)),r!=null){let J=Lh(j,X);return[K,ne,J]}else return[K,ne]},F={a:v,b:x,bias:N,preluActivationWeights:T},$={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?Ka((P,B,W)=>{let G=M.runKernel(bi,F,$);return W([P,B,G]),{value:H(G,b),gradFunc:C}})(v,x):Ka((P,B,W,G)=>{let q=M.runKernel(bi,F,$);return G([P,B,q,W]),{value:H(q,b),gradFunc:C}})(v,x,N)}var BM=O({fusedMatMul_:jM});function qM(e){return pb(e,.54,.46)}var KM=O({hammingWindow_:qM});function XM(e){return pb(e,.5,.5)}var W1=O({hannWindow_:XM});function YM(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(We(e,s,t)),s+=n;if(a)for(;s<e.size;){let o=s+t-e.size,l=Qe([We(e,s,t-o),wn([o],r)]);i.push(l),s+=n}return i.length===0?Sa([],[0,t]):H(Qe(i),[i.length,t])}var V1=O({frame_:YM});function ZM(e,t,n,a,r=W1){a==null&&(a=L1(t));let s=V1(e,t,n),i=L(s,r(t)),o=[];for(let l=0;l<s.shape[0];l++)o.push(qc(We(i,[l,0],[1,t]),a));return Qe(o)}var JM=O({stft_:ZM});function QM(e,t,n,a,r="bilinear",s=0){let i=E(e,"image","cropAndResize"),o=E(t,"boxes","cropAndResize","float32"),l=E(n,"boxInd","cropAndResize","int32"),c=o.shape[0];A(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`),A(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`),A(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),A(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),A(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:i,boxes:o,boxInd:l},p={method:r,extrapolationValue:s,cropSize:a};return M.runKernel(zo,u,p)}var eP=O({cropAndResize_:QM});function tP(e){let t=E(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return M.runKernel(jo,n,{})}var nP=O({flipLeftRight_:tP});function aP(e,t,n=0,a=.5){let r=E(e,"image","rotateWithOffset","float32");A(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 M.runKernel(Cl,s,i)}var rP=O({rotateWithOffset_:aP});function jl(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),A(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),A(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function sP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppression"),i=E(t,"scores","nonMaxSuppression"),o=jl(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return M.runKernel(il,{boxes:s,scores:i},l)}var iP=O({nonMaxSuppression_:sP});function lP(e,t,n){let a=oP(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function oP(e,t,n){return cP(e,t,n||uP)}function uP(e,t){return e>t?1:e<t?-1:0}function cP(e,t,n){let a=0,r=e.length,s=0,i=!1;for(;a<r;){s=a+(r-a>>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function U1(e,t,n,a,r){return hb(e,t,n,a,r,0)}function G1(e,t,n,a,r,s){return hb(e,t,n,a,r,0,!1,s,!0)}function H1(e,t,n,a,r,s){return hb(e,t,n,a,r,s,!0)}function hb(e,t,n,a,r,s,i=!1,o=!1,l=!1){let c=[];for(let g=0;g<t.length;g++)t[g]>r&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(j1);let u=s>0?-.5/s:0,p=[],d=[];for(;p.length<n&&c.length>0;){let g=c.pop(),{score:y,boxIndex:b,suppressBeginIndex:v}=g;if(y<r)break;let x=!1;for(let N=p.length-1;N>=v;--N){let T=pP(e,b,p[N]);if(T>=a){x=!0;break}if(g.score=g.score*dP(a,u,T),g.score<=r)break}g.suppressBeginIndex=p.length,x||(g.score===y?(p.push(b),d.push(g.score)):g.score>r&&lP(c,g,j1))}let h=p.length,m=n-h;o&&m>0&&(p.push(...new Array(m).fill(0)),d.push(...new Array(m).fill(0)));let f={selectedIndices:p};return i&&(f.selectedScores=d),l&&(f.validOutputs=h),f}function pP(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]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),p=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),h=(o-s)*(l-i),m=(p-c)*(d-u);if(h<=0||m<=0)return 0;let f=Math.max(s,c),g=Math.max(i,u),y=Math.min(o,p),b=Math.min(l,d),v=Math.max(y-f,0)*Math.max(b-g,0);return v/(h+m-v)}function dP(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function j1(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function hP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppressionAsync"),i=E(t,"scores","nonMaxSuppressionAsync"),o=jl(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),c=l[0],u=l[1],{selectedIndices:p}=U1(c,u,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),tt(p,"int32")}var mP=hP;function fP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=jl(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let c={boxes:i,scores:o},u={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},p=M.runKernel(ll,c,u);return{selectedIndices:p[0],selectedScores:p[1]}}var gP=O({nonMaxSuppressionWithScore_:fP});async function yP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=jl(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let c=await Promise.all([i.data(),o.data()]),u=c[0],p=c[1],{selectedIndices:d,selectedScores:h}=H1(u,p,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:tt(d,"int32"),selectedScores:tt(h)}}var bP=yP;function xP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=jl(i,o,n,a,r,null),c=l.maxOutputSize,u=l.iouThreshold,p=l.scoreThreshold,d={boxes:i,scores:o},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:p,padToMaxOutputSize:s},m=M.runKernel(ol,d,h);return{selectedIndices:m[0],validOutputs:m[1]}}var vP=O({nonMaxSuppressionPadded_:xP});async function wP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=jl(i,o,n,a,r,null),c=l.maxOutputSize,u=l.iouThreshold,p=l.scoreThreshold,[d,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=G1(d,h,c,u,p,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:tt(m,"int32"),validOutputs:de(f,"int32")}}var kP=wP;function IP(e,t,n=!1,a=!1){let r=E(e,"images","resizeBilinear");A(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),A(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=H(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=M.runKernel(ri,o,l);return i?H(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var q1=O({resizeBilinear_:IP});function NP(e,t,n=!1,a=!1){let r=E(e,"images","resizeNearestNeighbor");A(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(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=H(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=M.runKernel(vc,o,l);return i?H(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var K1=O({resizeNearestNeighbor_:NP});function TP(e,t,n){A(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let a=E(e,"a","bandPart");A(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=H(Th(0,s,1,"int32"),[-1,1]),l=Th(0,i,1,"int32"),c=fe(o,l),u=da(_i(c,de(+t,"int32")),Jr(c,de(-n,"int32"))),p=vt([s,i],a.dtype);return H($t(dt(H(a,[-1,s,i])).map(d=>vn(u,d,p))),r)}var SP=O({bandPart_:TP});function CP(e){let t;if(Array.isArray(e)){t=!1,A(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s<e.length;++s)A(e[s].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=Pn(e,e.shape[0],0).map(r=>Qr(r,[0]));A(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<e.length;++r)n.push(M.tidy(()=>{let s=a[r];if(r>0)for(let i=0;i<r;++i){let o=L(Te(L(n[i],s)),n[i]);s=fe(s,o)}return ve(s,Ph(s,"euclidean"))}));return t?$t(n,0):n}var _P=O({gramSchmidt_:CP});function EP(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return X1(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),a=dt(H(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[c,u]=X1(l,t);r.push(c),s.push(u)});let i=H($t(r,0),e.shape),o=H($t(s,0),e.shape);return[i,o]}}function X1(e,t=!1){return M.tidy(()=>{A(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=Hy(n),s=qr(e),i=Sa([[1]],[1,1]),o=qr(i),l=n>=a?a:n;for(let c=0;c<l;++c){let u=s,p=o,d=r;[o,s,r]=M.tidy(()=>{let h=We(s,[c,c],[n-c,1]),m=Ph(h),f=We(s,[c,c],[1,1]),g=vn(pa(f,0),Sa([[-1]]),Sa([[1]])),y=fe(f,L(g,m)),b=ve(h,y);b.shape[0]===1?o=qr(i):o=Qe([i,We(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let v=Tt(ve(ze(g,y),m)),x=We(s,[c,0],[n-c,a]),N=L(v,o),T=Ue(o);if(c===0)s=fe(x,ze(N,ze(T,x)));else{let $=fe(x,ze(N,ze(T,x)));s=Qe([We(s,[0,0],[c,a]),$],0)}let C=Ue(N),F=We(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=fe(F,ze(ze(F,o),C));else{let $=fe(F,ze(ze(F,o),C));r=Qe([We(r,[0,0],[n,c]),$],1)}return[o,s,r]}),Fe([u,p,d])}return!t&&n>a&&(r=We(r,[0,0],[n,a]),s=We(s,[0,0],[a,a])),[r,s]})}var AP=O({qr_:EP}),dn;(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"})(dn||(dn={}));function FP(e,t,n=dn.SUM_BY_NONZERO_WEIGHTS){let a=E(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=E(t,"weights","computeWeightedLoss"));let s=r==null?a:L(a,r);if(n===dn.NONE)return s;if(n===dn.SUM)return Te(s);if(n===dn.MEAN){if(r==null)return St(s);{let i=a.size/r.size,o=ve(Te(s),Te(r));return i>1?ve(o,de(i)):o}}if(n===dn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return ve(Te(s),de(a.size));{let i=L(r,Ya(a.shape)),o=ce(Te(Ai(i,de(0))),"float32");return ve(Te(s),o)}}throw Error(`Unknown reduction: ${n}`)}var br=O({computeWeightedLoss_:FP});function $P(e,t,n,a=dn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","absoluteDifference"),s=E(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=E(n,"weights","absoluteDifference")),sn(r.shape,s.shape,"Error in absoluteDifference: ");let o=Lt(fe(r,s));return br(o,i,a)}var DP=O({absoluteDifference_:$P});function RP(e,t,n,a,r=dn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","cosineDistance"),i=E(t,"predictions","cosineDistance"),o=null;a!=null&&(o=E(a,"weights","cosineDistance")),sn(s.shape,i.shape,"Error in cosineDistance: ");let l=de(1),c=fe(l,Te(L(s,i),n,!0));return br(c,o,r)}var MP=O({cosineDistance_:RP});function PP(e,t,n,a=dn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","hingeLoss"),s=E(t,"predictions","hingeLoss"),i=null;n!=null&&(i=E(n,"weights","hingeLoss")),sn(r.shape,s.shape,"Error in hingeLoss: ");let o=de(1);r=fe(L(de(2),r),o);let l=Ye(fe(o,L(r,s)));return br(l,i,a)}var OP=O({hingeLoss_:PP});function LP(e,t,n,a=1,r=dn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","huberLoss"),i=E(t,"predictions","huberLoss"),o=null;n!=null&&(o=E(n,"weights","huberLoss")),sn(s.shape,i.shape,"Error in huberLoss: ");let l=de(a),c=Lt(fe(i,s)),u=Wl(c,l),p=fe(c,u),d=Z(L(de(.5),lt(u)),L(l,p));return br(d,o,r)}var zP=O({huberLoss_:LP});function BP(e,t,n,a=1e-7,r=dn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","logLoss"),i=E(t,"predictions","logLoss"),o=null;n!=null&&(o=E(n,"weights","logLoss")),sn(s.shape,i.shape,"Error in logLoss: ");let l=de(1),c=de(a),u=Tt(L(s,Dn(Z(i,c)))),p=L(fe(l,s),Dn(Z(fe(l,i),c))),d=fe(u,p);return br(d,o,r)}var WP=O({logLoss_:BP});function VP(e,t,n,a=dn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","meanSquaredError"),s=E(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=E(n,"weights","meanSquaredError")),sn(r.shape,s.shape,"Error in meanSquaredError: ");let o=Dh(r,s);return br(o,i,a)}var UP=O({meanSquaredError_:VP});function GP(e,t){let n=E(e,"labels","sigmoidCrossEntropyWithLogits"),a=E(t,"logits","sigmoidCrossEntropyWithLogits");sn(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Ye(a),s=L(a,n),i=xh(pn(Tt(Lt(a))));return Z(fe(r,s),i)}function HP(e,t,n,a=0,r=dn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"multiClassLabels","sigmoidCrossEntropy"),i=E(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","sigmoidCrossEntropy")),sn(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let c=de(a),u=de(1),p=de(.5);s=Z(L(s,fe(u,c)),L(p,c))}let l=GP(s,i);return br(l,o,r)}var jP=O({sigmoidCrossEntropy_:HP});function qP(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 Ka((a,r,s)=>{let i=Xy(r,[n],!0),o=fe(ce(r,"float32"),i);s([a,o]);let l=Tt(L(o,a));return{value:Te(l,[n]),gradFunc:(c,u)=>{let[p,d]=u,h=Ei(c.shape,[n]);return[L(H(c,h),fe(ce(p,"float32"),pn(d))),L(H(c,h),fe(pn(d),ce(p,"float32")))]}}})(e,t)}function KP(e,t,n,a=0,r=dn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"onehotLabels","softmaxCrossEntropy"),i=E(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","softmaxCrossEntropy")),sn(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let c=de(a),u=de(1),p=de(s.shape[1]);s=Z(L(s,fe(u,c)),ve(c,p))}let l=qP(s,i);return br(l,o,r)}var XP=O({softmaxCrossEntropy_:KP}),YP={fft:jc,ifft:Gl,rfft:qc,irfft:$h},ZP={hammingWindow:KM,hannWindow:W1,frame:V1,stft:JM},Za={flipLeftRight:nP,resizeNearestNeighbor:K1,resizeBilinear:q1,rotateWithOffset:rP,cropAndResize:eP,nonMaxSuppression:iP,nonMaxSuppressionAsync:mP,nonMaxSuppressionWithScore:gP,nonMaxSuppressionWithScoreAsync:bP,nonMaxSuppressionPadded:vP,nonMaxSuppressionPaddedAsync:kP},Y1={bandPart:SP,gramSchmidt:_P,qr:AP},JP={absoluteDifference:DP,computeWeightedLoss:br,cosineDistance:MP,hingeLoss:OP,huberLoss:zP,logLoss:WP,meanSquaredError:UP,sigmoidCrossEntropy:jP,softmaxCrossEntropy:XP},xr=class extends Y0{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 Fe(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 w1(e,t)}dispose(){this.iterations_!=null&&Fe(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:de(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(xr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Wh=class extends xr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:D(()=>Ge(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;D(()=>{let l=Z(L(i,this.rho),L(lt(s),1-this.rho)),c=L(ve(en(Z(o,this.epsilon)),en(Z(i,this.epsilon))),s),u=Z(L(o,this.rho),L(lt(c),1-this.rho));i.assign(l),o.assign(u);let p=Z(L(c,-this.learningRate),a);a.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Fe(this.accumulatedGrads.map(e=>e.variable)),Fe(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)}};Wh.className="Adadelta";Kr(Wh);var Vh=class extends xr{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=M.registeredVariables[t];if(this.accumulatedGrads[n]==null){let i=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:D(()=>wn(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;D(()=>{let i=Z(s,lt(r));s.assign(i);let o=Z(L(ve(r,en(Z(i,M.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Fe(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)}};Vh.className="Adagrad";Kr(Vh);var Uh=class extends xr{constructor(e,t,n,a=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],D(()=>{this.accBeta1=de(t).variable(),this.accBeta2=de(n).variable()}),a==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=fe(1,this.accBeta1),a=fe(1,this.accBeta2);t.forEach((r,s)=>{let i=M.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:D(()=>Ge(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:D(()=>Ge(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[s].variable,u=this.accumulatedSecondMoment[s].variable,p=Z(L(c,this.beta1),L(l,1-this.beta1)),d=Z(L(u,this.beta2),L(lt(l),1-this.beta2)),h=ve(p,n),m=ve(d,a);c.assign(p),u.assign(d);let f=Z(L(ve(h,Z(en(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Fe(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Fe(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),D(()=>{this.accBeta1.assign(yr(this.beta1,this.iterations_+1)),this.accBeta2.assign(yr(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)}};Uh.className="Adam";Kr(Uh);var Gh=class extends xr{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=[],D(()=>{this.iteration=de(0).variable(),this.accBeta1=de(t).variable()}),a==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=fe(1,this.accBeta1),a=ve(-this.learningRate,Z(L(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=M.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Ge(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:Ge(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[s].variable,u=this.accumulatedWeightedInfNorm[s].variable,p=Z(L(c,this.beta1),L(l,1-this.beta1)),d=L(u,this.beta2),h=Lt(l),m=Xa(d,h);c.assign(p),u.assign(m);let f=Z(L(ve(a,n),ve(p,Z(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(Z(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Fe(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Fe(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)}};Gh.className="Adamax";Kr(Gh);var Kc=class extends xr{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=M.registeredVariables[t];D(()=>{let s=Z(L(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=jt(de(-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)}};Kc.className="SGD";Kr(Kc);var Hh=class extends Kc{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=de(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t];if(this.accumulations[n]==null){let i=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:D(()=>Ge(a).variable(i))}}let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&D(()=>{let i,o=Z(L(this.m,r),s);this.useNesterov?i=Z(L(this.c,Z(s,L(o,this.m))),a):i=Z(L(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Fe(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)}};Hh.className="Momentum";Kr(Hh);var jh=class extends xr{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=M.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=M.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:D(()=>Ge(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;D(()=>{let l=Z(L(i,this.decay),L(lt(s),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[n].variable,u=Z(L(c,this.decay),L(s,1-this.decay)),p=ve(L(s,this.learningRate),en(fe(l,Z(lt(u),this.epsilon)))),d=Z(L(o,this.momentum),p);i.assign(l),c.assign(u),o.assign(d);let h=fe(a,d);a.assign(h)}else{let c=Z(L(i,this.decay),L(lt(s),1-this.decay)),u=Z(L(o,this.momentum),ve(L(s,this.learningRate),en(Z(c,this.epsilon))));i.assign(c),o.assign(u);let p=fe(a,u);a.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Fe(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Fe(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Fe(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)}};jh.className="RMSProp";Kr(jh);var $i=class{static sgd(e){return new Kc(e)}static momentum(e,t,n=!1){return new Hh(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new jh(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new Uh(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new Wh(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new Gh(e,t,n,a,r)}static adagrad(e,t=.1){return new Vh(e,t)}},Di={sgd:$i.sgd,momentum:$i.momentum,adadelta:$i.adadelta,adagrad:$i.adagrad,rmsprop:$i.rmsprop,adamax:$i.adamax,adam:$i.adam},QP=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function qh(){return new Promise(e=>QP(()=>e()))}var _={};Oe(_,{ERF_A1:()=>cO,ERF_A2:()=>pO,ERF_A3:()=>dO,ERF_A4:()=>hO,ERF_A5:()=>mO,ERF_P:()=>uO,PARALLELIZE_THRESHOLD:()=>mb,SELU_SCALE:()=>J1,SELU_SCALEALPHA:()=>Z1,applyActivation:()=>zh,assertAndGetBroadcastShape:()=>xt,assertAxesAreInnerMostDims:()=>LD,assertParamsConsistent:()=>eO,assignToTypedArray:()=>kO,axesAreInnerMostDims:()=>qy,calculateShapes:()=>L0,combineLocations:()=>I1,complexWithEvenIndex:()=>xO,complexWithOddIndex:()=>vO,computeConv2DInfo:()=>Pc,computeConv3DInfo:()=>s1,computeDefaultPad:()=>My,computeDilation2DInfo:()=>l$,computeOptimalWindowSize:()=>nO,computeOutAndReduceShapes:()=>N1,computeOutShape:()=>tO,computePool2DInfo:()=>r1,computePool3DInfo:()=>u$,convertConv2DDataFormat:()=>a1,eitherStridesOrDilationsAreOne:()=>ja,expandShapeToKeepDim:()=>Ei,exponent:()=>NO,exponents:()=>IO,fromStringArrayToUint8:()=>CO,fromUint8ToStringArray:()=>SO,getAxesPermutation:()=>T1,getBroadcastDims:()=>eD,getComplexWithIndex:()=>wO,getFusedBiasGradient:()=>Lh,getFusedDyActivation:()=>Oh,getImageCenter:()=>aO,getInnerMostAxes:()=>zD,getPermuted:()=>sO,getReductionAxes:()=>zt,getReshaped:()=>rO,getReshapedPermuted:()=>iO,getSliceBeginCoords:()=>oO,getSliceSize:()=>lO,getUndoAxesPermutation:()=>Ky,log:()=>gO,mergeRealAndImagArrays:()=>yO,prepareAndValidate:()=>O0,prepareSplitSize:()=>TO,segment_util:()=>Q1,shouldFuse:()=>Bh,slice_util:()=>cn,splitRealAndImagArrays:()=>bO,tupleValuesAreOne:()=>Xr,upcastType:()=>ua,validateInput:()=>wy,validateUpdateShape:()=>vy,warn:()=>fO});function eO(e,t){let n=e[0].length;e.forEach((r,s)=>{A(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),A(t>=0&&t<n,()=>`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<n;i++)A(i===t||r[i]===a[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 tO(e,t){let n=e[0].slice();for(let a=1;a<e.length;a++)n[t]+=e[a][t];return n}var mb=30;function nO(e){return e<=mb?e:bd(e,Math.floor(Math.sqrt(e)))}function aO(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function rO(e,t,n,a=!0){let r=[];if(a)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)r=r.concat([e[i+1]/t[i],t[i]]);r=r.concat(e.slice(s+1))}return r}function sO(e,t,n=!0){let a=[];if(n){a.push(t);for(let r=t+1;r<e;++r)r<=2*t?(a.push(r),a.push(r-(t+1))):a.push(r)}else{let r=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2==1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function iO(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s<e.length;++s)s<=t.length?a?r.push(t[s-1]*e[s]):r.push(e[s]/t[s-1]):r.push(e[s]);return r}function oO(e,t){let n=[0];for(let a=0;a<t;++a)n.push(e[a][0]);return n}function lO(e,t,n){let a=e.slice(0,1);for(let r=0;r<n;++r)a.push(e[r+1]-t[r][0]-t[r][1]);return a}var Z1=1.7580993408473768,J1=1.0507009873554805,uO=.3275911,cO=.254829592,pO=-.284496736,dO=1.421413741,hO=-1.453152027,mO=1.061405429;function fO(...e){ee().getBool("IS_TEST")||console.warn(...e)}function gO(...e){ee().getBool("IS_TEST")||console.log(...e)}function yO(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let n=new Float32Array(e.length*2);for(let a=0;a<n.length;a+=2)n[a]=e[a/2],n[a+1]=t[a/2];return n}function bO(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let a=0;a<e.length;a+=2)t[a/2]=e[a],n[a/2]=e[a+1];return{real:t,imag:n}}function xO(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=0;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function vO(e){let t=Math.floor(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=2;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function wO(e,t){let n=e[t*2],a=e[t*2+1];return{real:n,imag:a}}function kO(e,t,n,a){e[a*2]=t,e[a*2+1]=n}function IO(e,t){let n=new Float32Array(e/2),a=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){let s=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(s),a[r]=Math.sin(s)}return{real:n,imag:a}}function NO(e,t,n){let a=(n?2:-2)*Math.PI*(e/t),r=Math.cos(a),s=Math.sin(a);return{real:r,imag:s}}function TO(e,t,n=0){let a=[];if(typeof t=="number")A(e.shape[n]%t==0,()=>"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);A(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}A(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 Q1={};Oe(Q1,{collectGatherOpShapeInfo:()=>AO,computeOutShape:()=>EO,segOpComputeOptimalWindowSize:()=>_O});function _O(e,t){let n=!1,a;for(e<=mb?(a=e,n=!0):a=bd(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=bd(e,a+1);return a}function EO(e,t,n){let a=[],r=e.length;for(let s=0;s<r;s++)s!==t?a.push(e[s]):a.push(n);return a}function AO(e,t,n,a){let r=t.shape.length,s=e.shape.length;if(a!==0&&(a<-r||a>r))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(n<a)throw new Error(`batchDims (${a}) must be less than or equal to axis (${n}).`);for(let p=0;p<a;++p)if(e.shape[p]!==t.shape[p])throw new Error(`x.shape[${p}]: ${e.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);let i=e.shape[n],o=[],l=1,c=1,u=1;for(let p=0;p<a;++p)o.push(e.shape[p]),l*=e.shape[p];for(let p=a;p<n;p++)o.push(e.shape[p]),c*=e.shape[p];for(let p=a;p<r;p++)o.push(t.shape[p]);for(let p=n+1;p<s;p++)o.push(e.shape[p]),u*=e.shape[p];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:i,outputShape:o}}function SO(e){try{return e.map(t=>eh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function CO(e){return e.map(t=>Cc(t))}var Ja={};Oe(Ja,{nonMaxSuppressionV3Impl:()=>U1,nonMaxSuppressionV4Impl:()=>G1,nonMaxSuppressionV5Impl:()=>H1,whereImpl:()=>D1});var ek={kernelName:Eo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Hl(ce(n,"float32"),-1))}}},FO={kernelName:Ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=lt(ce(n,"float32")),r=en(fe(de(1),a));return Tt(ve(e,r))}}}},$O={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=en(fe(lt(ce(n,"float32")),1));return ve(e,a)}}}},DO={kernelName:zr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=e,i=zt(n.shape,r);return i.length>0&&(s=Te(s,i)),H(s,n.shape)},b:()=>{let s=e,i=zt(a.shape,r);return i.length>0&&(s=Te(s,i)),H(s,a.shape)}}}},RO={kernelName:Ss,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},MO={kernelName:Cs,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},PO={kernelName:oc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},OO={kernelName:$o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,en(fe(de(1),lt(ce(n,"float32")))))}}},LO={kernelName:Do,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=en(Z(de(1),lt(ce(n,"float32"))));return ve(e,a)}}}},zO={kernelName:Po,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=Z(lt(n),lt(a)),i=L(e,ve(a,s)),o=zt(n.shape,r);return o.length>0&&(i=Te(i,o)),H(i,n.shape)},b:()=>{let s=Z(lt(n),lt(a)),i=Tt(L(e,ve(n,s))),o=zt(a.shape,r);return o.length>0&&(i=Te(i,o)),H(i,a.shape)}}}},BO={kernelName:Ro,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,Z(lt(ce(n,"float32")),1))}}},WO={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,fe(de(1),lt(ce(n,"float32"))))}}};function VO(e,t,n,a,r,s){let i=E(e,"dy","avgPool3dGrad"),o=E(t,"input","avgPool3dGrad"),l=i,c=o,u=!1;o.rank===4&&(u=!0,l=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),c=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),s!=null&&A(Gt(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let p={dy:l,input:c},d={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=M.runKernel(Id,p,d);return u?H(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var UO=O({avgPool3dGrad_:VO}),GO={kernelName:lc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>UO(e,a,r,s,i,o)}}};function HO(e,t,n,a,r){let s=E(e,"dy","avgPoolGrad"),i=E(t,"input","avgPoolGrad");A(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,c=!1;i.rank===3&&(c=!0,o=H(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=H(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),A(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let u={dy:l,input:o},p={filterSize:n,strides:a,pad:r},d=M.runKernel(kd,u,p);return c?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jO=O({avgPoolGrad_:HO}),qO={kernelName:_s,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>jO(e,a,r,s,i)}}},KO={kernelName:Es,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[a,r]=t,{transposeA:s,transposeB:i}=n;return!s&&!i?{a:()=>ze(e,r,!1,!0),b:()=>ze(a,e,!0,!1)}:!s&&i?{a:()=>ze(e,r,!1,!1),b:()=>ze(e,a,!0,!1)}:s&&!i?{a:()=>ze(r,e,!1,!0),b:()=>ze(a,e,!1,!1)}:{a:()=>ze(r,e,!0,!0),b:()=>ze(e,a,!0,!0)}}},XO={kernelName:uc,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>Vc(e,a,r)}}},YO={kernelName:l0,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;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>Te(e,o,!0)}}},ZO={kernelName:As,gradFunc:e=>({x:()=>e.clone()})},JO={kernelName:Fs,gradFunc:e=>({x:()=>Ge(e)})},QO={kernelName:Br,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>vn(da(Jr(a,r),_i(a,s)),e,Ge(e))}}},eL={kernelName:cc,inputsToSave:["x"],gradFunc:ek.gradFunc},tL={kernelName:Oo,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=la(r,t[0].shape)[0],i=a.map(o=>o[s]);return Pn(e,i,s).map(o=>()=>o)}},nL={kernelName:$s,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return A(Xr(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Ly(a.shape,e,r,i,o,l),filter:()=>db(a,e,r.shape,i,o,l)}}},aL={kernelName:Ds,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>At(e,r,s,i,o,1,l),filter:()=>db(e,a,r.shape,s,i,o,l)}}};function rL(e,t,n,a,r){let s=e;e.rank===4&&(s=H(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=H(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),A(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),A(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),A(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),A(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),A(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 M.runKernel(Cd,o,l)}var sL=O({conv3DBackpropFilter_:rL}),iL={kernelName:pc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;A(Xr(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:()=>m1(i.shape,e,o,r,s),filter:()=>sL(i,e,o.shape,r,s)}}},oL={kernelName:Rs,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Tt(Eh(ce(n,"float32"))),e)}}},lL={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Ah(ce(n,"float32")),e)}}},uL={kernelName:Ms,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=T1([r],a.rank),l=gh(e,r,s,!i);return o!=null&&(l=Ue(l,o)),l}}}},cL={kernelName:Ps,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;A(Xr(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,c]=t;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),A(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),A(ja(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),i!=null&&A(Gt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`),{x:()=>B1(l.shape,e,c,r,s,a,i),filter:()=>z1(l,e,c.shape,r,s,a,i)}}},pL={kernelName:dc,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:()=>M.runKernel(Dd,s,n),filter:()=>M.runKernel(Rd,i,n)}}},dL={kernelName:Wo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>M.runKernel(Md,a)}}},hL={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(pn(Tt(lt(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,a)}}},mL={kernelName:Ls,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},fL={kernelName:Go,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>H(e,n.shape)}}},gL={kernelName:Ho,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,pn(n))}}},yL={kernelName:zs,gradFunc:e=>({x:()=>Ge(e)})},bL={kernelName:Bs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=ve(e,ce(a,"float32")),i=zt(n.shape,r);return i.length>0?H(Te(s,i),n.shape):s},b:()=>{let s=L(e,ce(n,"float32")),i=zt(a.shape,r);i.length>0&&(s=H(Te(s,i),a.shape));let o=lt(a);return Tt(ve(s,ce(o,"float32")))}}}},xL={kernelName:Ws,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?de(1):o,c=zt(s.shape,r.shape),u=[];if(s.rank===1){for(let f=0;f<r.shape.length-1;++f)u.push(r.shape[f]);u.push(1)}let p=fe(r,s),d=L(e,l),h=Ch(Z(i,de(a))),m=L(L(L(h,h),h),de(-.5));return{x:()=>s.rank===1?H(L(L(e,qa(H(h,[1,1,1,s.shape[0]]),u)),l),r.shape):H(L(L(e,h),l),r.shape),mean:()=>{let f=L(L(h,de(-1)),d);return s.rank===1&&(f=Te(f,c)),H(f,s.shape)},variance:()=>{let f=L(L(m,p),d);return s.rank===1&&(f=Te(f,c)),H(f,s.shape)},scale:()=>{let f=L(p,h),g=L(e,f);return s.rank===1&&(g=Te(g,c)),H(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=Te(f,c)),H(f,s.shape)}}}},vL={kernelName:qo,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=la(s,a.shape)[0];return{x:()=>{let o=a.shape,l=r.size,c=o.slice(0,i),u=c.length,p=o.slice(s,o.length).slice(1),d=p.length,h=tk(0,u),m=tk(u+1,u+1+d),f=nk([c,[l],p]),g=H(e,f),y=H(r,[l]),b=nk([[u],h,m]),v=Ue(g,b),x=lb(v,y,a.shape[i]),N=Ky(b);return x=Ue(x,N),x},indices:()=>r}}};function tk(e,t){let n=[];for(let a=e;a<t;++a)n.push(a);return n}function nk(e){let t=[];for(let n=0;n<e.length;++n)for(let a=0;a<e[n].length;++a)t.push(e[n][a]);return t}var wL={kernelName:Vs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>Ge(n),b:()=>Ge(a)}}},kL={kernelName:Us,gradFunc:e=>({x:()=>ce(e,"float32")})},IL={kernelName:Yo,gradFunc:e=>({x:()=>Ge(e)})},NL={kernelName:Zo,gradFunc:e=>({x:()=>Ge(e)})},TL={kernelName:Jo,gradFunc:e=>({x:()=>Ge(e)})},SL={kernelName:Gs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=pa(a,0);return{x:()=>vn(s,e,L(e,r))}}},CL={kernelName:tl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,Z(n,1))}}},_L={kernelName:Hs,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,ce(n,"float32"))}}},EL={kernelName:u0,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=!0,i=pn(a);return fe(e,L(Te(e,r,s),i))}}}};function AL(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 M.runKernel(Bd,o,l)}var FL=O({localResponseNormalizationBackprop_:AL}),$L={kernelName:gc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>FL(a,r,e,s,i,o,l)}}};function ak(e,t,n,a){return t.rank<n.rank&&(t=H(t,Ei(t.shape,a))),e.rank<n.rank&&(e=H(e,Ei(e.shape,a))),{x:()=>L(e,ce(Zr(n,t),e.dtype))}}var rk={kernelName:js,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=la(r,s.shape),l=ak(e,i,s,o);return{x:()=>l.x()}}},DL={kernelName:qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,ce(Jr(n,a),"float32")),b:()=>L(e,ce(bh(n,a),"float32"))}}};function RL(e,t,n,a,r,s,i){let o=E(e,"dy","maxPool3dGrad"),l=E(t,"input","maxPool3dGrad"),c=E(n,"output","maxPool3dGrad"),u=o,p=l,d=c,h=!1;l.rank===4&&(h=!0,u=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),p=H(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=H(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),A(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),A(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),i!=null&&A(Gt(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let m={dy:u,input:p,output:d},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=M.runKernel(Vd,m,f);return h?H(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var ML=O({maxPool3dGrad_:RL}),PL={kernelName:yc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>ML(e,a,r,s,i,o,l)}}};function OL(e,t,n,a,r,s,i){let o=E(e,"dy","maxPoolGrad"),l=E(t,"input","maxPoolGrad"),c=E(n,"output","maxPoolGrad");A(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),A(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),i!=null&&A(Gt(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let u={dy:o,input:l,output:c},p={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return M.runKernel(Wd,u,p)}var LL=O({maxPoolGrad_:OL}),zL={kernelName:Ks,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>LL(e,a,r,s,i,o)}}},BL={kernelName:Xs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=la(r,a.shape),i=N1(a.shape,s)[1],o=Pt(i);return{x:()=>{let l=a.shape.slice();s.forEach(u=>{l[u]=1});let c=H(e,l);return ve(L(c,Ya(a.shape,"float32")),o)}}}},WL={kernelName:Ys,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=la(r,s.shape),l=ak(e,i,s,o);return{x:()=>l.x()}}},VL={kernelName:Zs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,ce(_i(n,a),"float32")),b:()=>L(e,ce(pa(n,a),"float32"))}}},UL={kernelName:bc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>We(e,s,a.shape)}}},GL={kernelName:al,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=zt(n.shape,r);return s.length>0?H(Te(e,s),n.shape):e},b:()=>{let s=L(e,Tt(Ll(ve(n,a)))),i=zt(a.shape,r);return i.length>0?H(Te(s,i),a.shape):s}}}},HL={kernelName:Js,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=L(e,ce(a,"float32")),i=zt(n.shape,r);return i.length>0?H(Te(s,i),n.shape):s},b:()=>{let s=L(e,ce(n,"float32")),i=zt(a.shape,r);return i.length>0?H(Te(s,i),a.shape):s}}}},jL={kernelName:rl,gradFunc:e=>({x:()=>Tt(e)})},qL={kernelName:Qs,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>vt(n.shape,"float32")}}},KL={kernelName:ul,gradFunc:e=>({x:()=>Ge(e)})},XL={kernelName:cl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return dt(e,a).map(r=>()=>r)}},sk={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>We(e,s,a.shape)}}},YL={kernelName:ti,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=xt(s.shape,i.shape);return{a:()=>{let l=ce(i,"float32"),c=L(e,L(l,yr(s,fe(l,de(1))))),u=zt(s.shape,o);return u.length>0&&(c=Te(c,u)),H(c,s.shape)},b:()=>{let l=pa(s,0),c=vn(l,Dn(s),Ge(s)),u=L(e,L(r,c)),p=zt(i.shape,o);return p.length>0&&(u=Te(u,p)),H(u,i.shape)}}}},ZL={kernelName:ni,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=pa(n,0);return{x:()=>vn(r,e,L(e,a)),alpha:()=>{let s=vn(r,Ge(e),L(e,n)),i=zt(a.shape,e.shape);return i.length>0&&(s=Te(s,i)),H(s,a.shape)}}}},JL={kernelName:Os,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=ve(e,ce(a,"float32")),i=zt(n.shape,r);return i.length>0?H(Te(s,i),n.shape):s},b:()=>{let s=L(e,ce(n,"float32")),i=zt(a.shape,r);i.length>0&&(s=H(Te(s,i),a.shape));let o=lt(a);return Tt(ve(s,ce(o,"float32")))}}}},QL={kernelName:dl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,Tt(lt(n)))}}},e3={kernelName:si,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(_i(n,6),Hl(n));return{x:()=>L(e,ce(a,"float32"))}}},t3={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ce(Hl(n),"float32"))}}},n3={kernelName:hl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>H(e,n.shape)}}},a3={kernelName:ri,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>M.runKernel(qd,r,n)}}},r3={kernelName:vc,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>M.runKernel(jd,r,n)}}},s3={kernelName:ii,gradFunc:(e,t,n)=>{let{dims:a}=n,r=la(a,e.shape);return{x:()=>Mn(e,r)}}},i3={kernelName:oi,gradFunc:e=>({x:()=>Ge(e)})},o3={kernelName:li,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Tt(ve(e,L(yr(n,1.5),2)))}}},l3={kernelName:fl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>ce(Ge(n),"float32"),t:()=>L(e,ce(n,e.dtype)),e:()=>L(e,ce(Wc(n),e.dtype))}}},u3={kernelName:gl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=pa(n,de(0)),r=de(Z1),s=de(J1),i=L(e,s),o=L(L(e,r),pn(ce(n,"float32")));return vn(a,i,o)}}}},c3={kernelName:ci,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,fe(de(1),n)))}}},p3={kernelName:xl,gradFunc:e=>({x:()=>Ge(e)})},d3={kernelName:ui,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(zc(ce(n,"float32")),e)}}},h3={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(fh(ce(n,"float32")),e)}}},m3={kernelName:yl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=q0(a,r,s),c=[];for(let u=0;u<e.rank;u++)c.push([o[u],i[u]-o[u]-l[u]]);return{x:()=>Zn(e,c)}}},f3={kernelName:hi,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=L(e,a);return{logits:()=>fe(i,L(Te(i,[r],s),a))}}},g3={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ca(n))}}},ik={kernelName:wc,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>Oc(e,a,r)}}},ok={kernelName:wl,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>Qe(e,a)}}},y3={kernelName:pi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,L(en(ce(n,"float32")),2))}}},b3={kernelName:kc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(ce(n,"float32"),2))}}},x3={kernelName:mi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=de(2);return{a:()=>L(e,L(r,fe(n,a))),b:()=>L(e,L(r,fe(a,n)))}}},v3={kernelName:Vr,gradFunc:e=>({x:()=>Ge(e)})},w3={kernelName:fi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=xt(n.shape,a.shape);return{a:()=>{let s=e,i=zt(n.shape,r);return i.length>0&&(s=Te(s,i)),H(s,n.shape)},b:()=>{let s=e,i=zt(a.shape,r);return i.length>0&&(s=Te(s,i)),H(Tt(s),a.shape)}}}},k3={kernelName:di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;la(s,a.shape).forEach(l=>{r[l]=1});let i=H(e,r),o=L(i,Ya(a.shape,"float32"));return{x:()=>o}}},I3={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,lt(zc(n)))}}},N3={kernelName:gi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(fe(de(1),lt(n)),e)}}},T3={kernelName:Wr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{reps:r}=n;return{x:()=>{let s=Ge(a);if(a.rank===1)for(let i=0;i<r[0];++i)s=Z(s,We(e,[i*a.shape[0]],[a.shape[0]]));else if(a.rank===2)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)s=Z(s,We(e,[i*a.shape[0],o*a.shape[1]],[a.shape[0],a.shape[1]]));else if(a.rank===3)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)s=Z(s,We(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2]],[a.shape[0],a.shape[1],a.shape[2]]));else if(a.rank===4)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)for(let c=0;c<r[3];++c)s=Z(s,We(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2],c*a.shape[3]],[a.shape[0],a.shape[1],a.shape[2],a.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${a.rank} tensors yet.`);return s}}}},S3={kernelName:yi,gradFunc:(e,t,n)=>{let a=n,{perm:r}=a,s=Ky(r);return{x:()=>Ue(e,s)}}},C3={kernelName:Tl,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>$t(e,r)}}},E3={kernelName:Ic,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>_3(e,n)}}};function _3(e,t){let n=Xa(t,Ge(t)),a=Ci(e,n),r=Jr(t,de(0,"int32")),s=a.rank-r.rank;for(let o=0;o<s;++o)r=$n(r,o+1);r=da(r,Ya(a.shape,"bool"));let i=Ge(a);return vn(r,a,i)}var A3={kernelName:Sl,gradFunc:e=>({x:()=>Ge(e)})},F3=[ek,FO,$O,DO,RO,MO,PO,OO,LO,zO,BO,WO,GO,qO,KO,XO,YO,ZO,JO,QO,eL,tL,aL,nL,iL,oL,lL,uL,cL,pL,JL,dL,hL,mL,fL,gL,bL,yL,xL,vL,wL,kL,IL,NL,TL,SL,CL,_L,EL,$L,rk,rk,DL,PL,zL,BL,WL,VL,UL,GL,HL,jL,qL,KL,XL,sk,sk,YL,ZL,QL,e3,t3,n3,a3,r3,s3,i3,o3,l3,u3,c3,p3,d3,h3,m3,f3,g3,ik,ik,ok,ok,y3,x3,b3,v3,w3,k3,I3,N3,T3,S3,C3,E3,A3];for(let e of F3)c0(e);Y().prototype.abs=function(){return this.throwIfDisposed(),Lt(this)};Y().prototype.acos=function(){return this.throwIfDisposed(),Sy(this)};Y().prototype.acosh=function(){return this.throwIfDisposed(),Cy(this)};Y().prototype.add=function(e){return this.throwIfDisposed(),Z(this,e)};Y().prototype.all=function(e,t){return this.throwIfDisposed(),ph(this,e,t)};Y().prototype.any=function(e,t){return this.throwIfDisposed(),Rc(this,e,t)};Y().prototype.argMax=function(e){return this.throwIfDisposed(),Mc(this,e)};Y().prototype.argMin=function(e){return this.throwIfDisposed(),_y(this,e)};Y().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),H(this,[])};Y().prototype.asType=function(e){return this.throwIfDisposed(),ce(this,e)};Y().prototype.as1D=function(){return this.throwIfDisposed(),H(this,[this.size])};Y().prototype.as2D=function(e,t){return this.throwIfDisposed(),H(this,[e,t])};Y().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),H(this,[e,t,n])};Y().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),H(this,[e,t,n,a])};Y().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),H(this,[e,t,n,a,r])};Y().prototype.asin=function(){return this.throwIfDisposed(),Ey(this)};Y().prototype.asinh=function(){return this.throwIfDisposed(),Ay(this)};Y().prototype.atan=function(){return this.throwIfDisposed(),Fy(this)};Y().prototype.atan2=function(e){return this.throwIfDisposed(),$y(this,e)};Y().prototype.atanh=function(){return this.throwIfDisposed(),Dy(this)};Y().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),Xn(this,e,t,n,a)};Y().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Oc(this,e,t)};Y().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),gr(this,e,t,n,a,r)};Y().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Lc(this,e)};Y().prototype.cast=function(e){return this.throwIfDisposed(),ce(this,e)};Y().prototype.ceil=function(){return this.throwIfDisposed(),Oy(this)};Y().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),qt(this,e,t)};Y().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ae&&(e=[e]),Qe([this,...e],t)};Y().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),hh(this,e,t,n,a,r,s)};Y().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),mh(this,e,t,n,a,r)};Y().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),At(this,e,t,n,a,r,s)};Y().prototype.cos=function(){return this.throwIfDisposed(),zc(this)};Y().prototype.cosh=function(){return this.throwIfDisposed(),fh(this)};Y().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),gh(this,e,t,n)};Y().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),By(this,e,t)};Y().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Yr(this,e,t,n,a,r,s)};Y().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),Wy(this,e,t,n,a,r)};Y().prototype.divNoNan=function(e){return this.throwIfDisposed(),Vy(this,e)};Y().prototype.div=function(e){return this.throwIfDisposed(),ve(this,e)};Y().prototype.dot=function(e){return this.throwIfDisposed(),g1(this,e)};Y().prototype.elu=function(){return this.throwIfDisposed(),Ol(this)};Y().prototype.equal=function(e){return this.throwIfDisposed(),Zr(this,e)};Y().prototype.erf=function(){return this.throwIfDisposed(),Uy(this)};Y().prototype.exp=function(){return this.throwIfDisposed(),pn(this)};Y().prototype.expandDims=function(e){return this.throwIfDisposed(),$n(this,e)};Y().prototype.expm1=function(){return this.throwIfDisposed(),Gy(this)};Y().prototype.fft=function(){return this.throwIfDisposed(),jc(this)};Y().prototype.flatten=function(){return this.throwIfDisposed(),H(this,[this.size])};Y().prototype.floor=function(){return this.throwIfDisposed(),Ll(this)};Y().prototype.floorDiv=function(e){return this.throwIfDisposed(),ch(this,e)};Y().prototype.gather=function(e,t){return this.throwIfDisposed(),Ci(this,e,t)};Y().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Jr(this,e)};Y().prototype.greater=function(e){return this.throwIfDisposed(),pa(this,e)};Y().prototype.ifft=function(){return this.throwIfDisposed(),Gl(this)};Y().prototype.irfft=function(){return this.throwIfDisposed(),$h(this)};Y().prototype.isFinite=function(){return this.throwIfDisposed(),y1(this)};Y().prototype.isInf=function(){return this.throwIfDisposed(),b1(this)};Y().prototype.isNaN=function(){return this.throwIfDisposed(),x1(this)};Y().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Bc(this,e)};Y().prototype.lessEqual=function(e){return this.throwIfDisposed(),_i(this,e)};Y().prototype.less=function(e){return this.throwIfDisposed(),bh(this,e)};Y().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),jy(this,e,t,n,a)};Y().prototype.logSigmoid=function(){return this.throwIfDisposed(),k1(this)};Y().prototype.logSoftmax=function(e){return this.throwIfDisposed(),wh(this,e)};Y().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Xy(this,e,t)};Y().prototype.log=function(){return this.throwIfDisposed(),Dn(this)};Y().prototype.log1p=function(){return this.throwIfDisposed(),xh(this)};Y().prototype.logicalAnd=function(e){return this.throwIfDisposed(),da(this,e)};Y().prototype.logicalNot=function(){return this.throwIfDisposed(),Wc(this)};Y().prototype.logicalOr=function(e){return this.throwIfDisposed(),kh(this,e)};Y().prototype.logicalXor=function(e){return this.throwIfDisposed(),S1(this,e)};Y().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),ze(this,e,t,n)};Y().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),Ft(this,e,t,n,a)};Y().prototype.max=function(e,t){return this.throwIfDisposed(),Yn(this,e,t)};Y().prototype.maximum=function(e){return this.throwIfDisposed(),Xa(this,e)};Y().prototype.mean=function(e,t){return this.throwIfDisposed(),St(this,e,t)};Y().prototype.min=function(e,t){return this.throwIfDisposed(),Bl(this,e,t)};Y().prototype.minimum=function(e){return this.throwIfDisposed(),Wl(this,e)};Y().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Zy(this,e,t)};Y().prototype.mod=function(e){return this.throwIfDisposed(),Jy(this,e)};Y().prototype.mul=function(e){return this.throwIfDisposed(),L(this,e)};Y().prototype.neg=function(){return this.throwIfDisposed(),Tt(this)};Y().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Ph(this,e,t,n)};Y().prototype.notEqual=function(e){return this.throwIfDisposed(),Ai(this,e)};Y().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Dl(this,e,t,n)};Y().prototype.onesLike=function(){return this.throwIfDisposed(),Rn(this)};Y().prototype.pad=function(e,t){return this.throwIfDisposed(),Zn(this,e,t)};Y().prototype.pool=function(e,t,n,a,r){return this.throwIfDisposed(),E1(this,e,t,n,a,r)};Y().prototype.pow=function(e){return this.throwIfDisposed(),yr(this,e)};Y().prototype.prelu=function(e){return this.throwIfDisposed(),Uc(this,e)};Y().prototype.prod=function(e,t){return this.throwIfDisposed(),Nh(this,e,t)};Y().prototype.reciprocal=function(){return this.throwIfDisposed(),tb(this)};Y().prototype.relu=function(){return this.throwIfDisposed(),Ye(this)};Y().prototype.relu6=function(){return this.throwIfDisposed(),Sh(this)};Y().prototype.reshapeAs=function(e){return this.throwIfDisposed(),H(this,e.shape)};Y().prototype.reshape=function(e){return this.throwIfDisposed(),H(this,e)};Y().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),q1(this,e,t,n)};Y().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),K1(this,e,t,n)};Y().prototype.reverse=function(e){return this.throwIfDisposed(),Mn(this,e)};Y().prototype.rfft=function(){return this.throwIfDisposed(),qc(this)};Y().prototype.round=function(){return this.throwIfDisposed(),nb(this)};Y().prototype.rsqrt=function(){return this.throwIfDisposed(),Ch(this)};Y().prototype.selu=function(){return this.throwIfDisposed(),_h(this)};Y().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Fi(this,e,t,n,a,r,s)};Y().prototype.sigmoid=function(){return this.throwIfDisposed(),ca(this)};Y().prototype.sign=function(){return this.throwIfDisposed(),ab(this)};Y().prototype.sin=function(){return this.throwIfDisposed(),Eh(this)};Y().prototype.sinh=function(){return this.throwIfDisposed(),Ah(this)};Y().prototype.slice=function(e,t){return this.throwIfDisposed(),We(this,e,t)};Y().prototype.softmax=function(e){return this.throwIfDisposed(),Ta(this,e)};Y().prototype.softplus=function(){return this.throwIfDisposed(),zl(this)};Y().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Vc(this,e,t)};Y().prototype.split=function(e,t){return this.throwIfDisposed(),Pn(this,e,t)};Y().prototype.sqrt=function(){return this.throwIfDisposed(),en(this)};Y().prototype.square=function(){return this.throwIfDisposed(),lt(this)};Y().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Dh(this,e)};Y().prototype.squeeze=function(e){return this.throwIfDisposed(),Qr(this,e)};Y().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Ae?[this,e]:[this,...e];return $t(n,t)};Y().prototype.step=function(e){return this.throwIfDisposed(),Hl(this,e)};Y().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),sb(this,e,t,n,a,r,s,i,o)};Y().prototype.sub=function(e){return this.throwIfDisposed(),fe(this,e)};Y().prototype.sum=function(e,t){return this.throwIfDisposed(),Te(this,e,t)};Y().prototype.tan=function(){return this.throwIfDisposed(),ib(this)};Y().prototype.tanh=function(){return this.throwIfDisposed(),Pl(this)};Y().prototype.tile=function(e){return this.throwIfDisposed(),qa(this,e)};Y().prototype.toBool=function(){return this.throwIfDisposed(),ce(this,"bool")};Y().prototype.toFloat=function(){return this.throwIfDisposed(),ce(this,"float32")};Y().prototype.toInt=function(){return this.throwIfDisposed(),ce(this,"int32")};Y().prototype.topk=function(e,t){return this.throwIfDisposed(),ob(this,e,t)};Y().prototype.transpose=function(e){return this.throwIfDisposed(),Ue(this,e)};Y().prototype.unique=function(e){return this.throwIfDisposed(),Mh(this,e)};Y().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),lb(this,e,t)};Y().prototype.unstack=function(e){return this.throwIfDisposed(),dt(this,e)};Y().prototype.where=function(e,t){return this.throwIfDisposed(),vn(e,this,t)};Y().prototype.zerosLike=function(){return this.throwIfDisposed(),Ge(this)};var lk={};Oe(lk,{maxNorm:()=>$3,minMaxNorm:()=>M3,nonNeg:()=>R3,unitNorm:()=>D3});var fb;function Bt(){return fb==null&&(fb=t1().epsilon()),fb}function _a(){return"channelsLast"}var vr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,vr.prototype)}},Ea=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ea.prototype)}},z=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,z.prototype)}},$e=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,$e.prototype)}},uk=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,uk.prototype)}};function Ri(e,t){if(Array.isArray(e)){let n=[];for(let a=0;a<t;a++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function Qa(e,t){if(!e)throw new uk(t)}function ck(e,t){let n=0;for(let a of e)a===t&&n++;return n}function kn(e){return e.length===1?e[0]:e}function yt(e){return Array.isArray(e)?e:[e]}function wr(e){let t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function Mi(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var ha={};function gb(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function yb(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>yb(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:yb(a))}}}function Xc(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 ha)i=ha[s];else if(i=t[s],i==null)throw new z(`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 z(`${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 ha?[o,l]=ha.className:i in t&&([o,l]=t[i]),o==null)throw new z(`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 c={};for(let h of Object.keys(ha))c[h]=ha[h];for(let h of Object.keys(n))c[h]=n[h];let u=s.config;u.customObjects=c;let p=Object.assign({},ha);for(let h of Object.keys(n))ha[h]=n[h];yb(s.config);let d=l(o,s.config,n,r);return ha=Object.assign({},p),d}else{let c=Object.assign({},ha);for(let p of Object.keys(n))ha[p]=n[p];let u=new o(s.config);return ha=Object.assign({},c),u}}}function P3(e,t){return e<t?-1:e>t?1:0}function Kh(e,t){return-1*P3(e,t)}function ts(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function O3(e){if(e==null)throw new z(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Pi(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new z(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function bb(e,t,n=0,a=Infinity){return Qa(n>=0),Qa(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function Kt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>Kt(n,`element ${a+1} of ${t}`))):k.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${pk(e)}.`)}function pk(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>pk(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function L3(e,t){let n=k.now(),a;return(...r)=>{let s=k.now();return s-n<t||(n=s,a=e(...r)),a}}function dk(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function xb(e,t){return D(()=>en(Te(L(e,e),t,!0)))}var Yc=class extends re.Serializable{getConfig(){return{}}},vb=class extends Yc{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 D(()=>{let t=xb(e,this.axis),n=qt(t,0,this.maxValue);return L(e,ve(n,Z(Bt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};vb.className="MaxNorm";re.registerClass(vb);var wb=class extends Yc{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>ve(e,Z(Bt(),xb(e,this.axis))))}getConfig(){return{axis:this.axis}}};wb.className="UnitNorm";re.registerClass(wb);var kb=class extends Yc{apply(e){return Ye(e)}};kb.className="NonNeg";re.registerClass(kb);var Ib=class extends Yc{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 D(()=>{let t=xb(e,this.axis),n=Z(L(this.rate,qt(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,ve(n,Z(Bt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Ib.className="MinMaxNorm";re.registerClass(Ib);var hk={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Wt(e){return gb(e)}function mk(e,t={}){return Xc(e,re.SerializationMap.getMap().classNameMap,t,"constraint")}function Vt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in hk?hk[e]:e,config:{}};return mk(t)}else return e instanceof Yc?e:mk(e)}function $3(e){return new vb(e)}function D3(e){return new wb(e)}function R3(){return new kb}function M3(e){return new Ib(e)}var fk={};Oe(fk,{constant:()=>W3,glorotNormal:()=>K3,glorotUniform:()=>q3,heNormal:()=>X3,heUniform:()=>Y3,identity:()=>H3,leCunNormal:()=>Z3,leCunUniform:()=>J3,ones:()=>B3,orthogonal:()=>Q3,randomNormal:()=>U3,randomUniform:()=>V3,truncatedNormal:()=>G3,varianceScaling:()=>j3,zeros:()=>z3});var ez=["channelsFirst","channelsLast"],tz=["nearest","bilinear"],nz=["valid","same","causal"],az=["max","avg"],rz=["sum","mul","concat","ave"],ql=new Map;function Dt(e){Pi(ez,"DataFormat",e)}function sz(e){Pi(tz,"InterpolationFormat",e)}function Jn(e){Pi(nz,"PaddingMode",e)}function gk(e){Pi(az,"PoolMode",e)}var Zc=[],yk="/";function Oi(e,t){Zc.push(e);try{let n=t();return Zc.pop(),n}catch(n){throw Zc.pop(),n}}function iz(){return Zc.length===0?"":Zc.join(yk)+yk}function xk(e){if(!bk(e))throw new Error("Not a valid tensor name: '"+e+"'");return iz()+e}function vk(e){if(!bk(e))throw new Error("Not a valid tensor name: '"+e+"'");ql.has(e)||ql.set(e,0);let t=ql.get(e);if(ql.set(e,ql.get(e)+1),t>0){let n=`${e}_${t}`;return ql.set(n,1),n}else return e}var oz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function bk(e){return!!e.match(oz)}function lz(e){return e===parseInt(e.toString(),10)}function ns(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;r<n;++r)a*=e[r];return a}function wk(e){return e=Array.isArray(e)?new Float32Array(e):e,tt(e)}function Kl(e){return Bl(wk(e)).dataSync()[0]}function as(e){return Yn(wk(e)).dataSync()[0]}function Aa(e,t){if(t<e)throw new z(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let a=e;a<t;++a)n.push(a);return n}function Jc(e,t){return e.asType(t)}function Qc(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),e.reshape(n)}function uz(e,t){return D(()=>{if(e.shape.length!==2)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Qc(e,1);return Nb(n,[1,t,1])})}function cz(e){let t=[ns(e.shape)];return e.reshape(t)}function pz(e){if(e.rank<=1)throw new z(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],ns(e.shape,1)];return e.reshape(t)}function Li(e,t,n){return D(()=>{switch(e.rank){case 1:return Fh(e,t,n);case 2:return rb(e,[t,0],[n,e.shape[1]]);case 3:return Ul(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Hc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return We(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return We(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 z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Tb(e,t,n){return D(()=>{switch(e.rank){case 1:return Fh(e,t,n);case 2:return rb(e,[0,t],[e.shape[0],n]);case 3:return Ul(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Hc(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Xh(e,t,n,a){return D(()=>{switch(e.rank){case 1:return Fh(e,t,n);case 2:switch(a){case 1:return Li(e,t,n);case 2:return Tb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return Li(e,t,n);case 2:return Ul(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Tb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return Li(e,t,n);case 2:return Hc(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Hc(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Tb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Sb(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Qe(e,t)}function kk(e,t){switch(e.rank){case 1:return c1([e,t]);case 2:return p1([e,t],0);case 3:return d1([e,t],0);case 4:return h1([e,t],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Nb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new z(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return qa(e,t)}function Yh(e,t=0,n=1,a,r){return A1(e,t,n,a,r)}function er(e,t,n,a){if(e.rank<2||t.rank<2)throw new $e(`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 $e(`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 es.matMul({a:e,b:t,transposeA:r,transposeB:s,bias:a?Cb(e.rank,a,_a()):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(),c=[...i,o],u=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=t.transpose(u).reshape([l,-1]);let p=[...r,...c],d=!1,h=!1;return es.matMul({a:e,b:t,transposeA:d,transposeB:h,bias:a?Cb(e.rank,a,_a()):null,activation:n}).reshape(p)}}function Ik(e,t,n){return D(()=>(Array.isArray(t)?t=tt(t,"int32"):t=t.toInt(),Ci(e,t,n)))}function ep(e){return L(e,e)}function Cb(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new z(`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 z(`Unsupported input rank by biasAdd: ${t.rank}`)}function tr(e,t,n){return D(()=>(n==null&&(n=_a()),Dt(n),e.add(Cb(e.rank,t,n))))}function dz(e,t=1){if(t!==1)throw new $e(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Ol(e)}function hz(e){return D(()=>ve(e,Lt(e).add(1)))}function Nk(e,t,n,a){return D(()=>O1(e,t,n,a))}function mz(e){return D(()=>{let t=Z(.5,L(.2,e));return qt(t,0,1)})}function tp(e,t,n=!1){return n?e():t()}var fz=["fanIn","fanOut","fanAvg"],gz=["normal","uniform","truncatedNormal"];function yz(e){Pi(fz,"FanMode",e)}function bz(e){Pi(gz,"Distribution",e)}var ma=class extends re.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},_b=class extends ma{apply(e,t){return vt(e,t)}};_b.className="Zeros";re.registerClass(_b);var Zh=class extends ma{apply(e,t){return Ya(e,t)}};Zh.className="Ones";re.registerClass(Zh);var Eb=class extends ma{constructor(e){super();if(typeof e!="object")throw new z(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new z(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return D(()=>L(de(this.value),Ya(e,t)))}getConfig(){return{value:this.value}}};Eb.className="Constant";re.registerClass(Eb);var Ab=class extends ma{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 Vl(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Ab.className="RandomUniform";re.registerClass(Ab);var Fb=class extends ma{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 $e(`randomNormal does not support dType ${t}.`);return Yh(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Fb.className="RandomNormal";re.registerClass(Fb);var $b=class extends ma{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 $e(`truncatedNormal does not support dType ${t}.`);return Rh(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};$b.className="TruncatedNormal";re.registerClass($b);var Db=class extends ma{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return D(()=>{if(e.length!==2||e[0]!==e[1])throw new z("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,Hy(e[0]))})}getConfig(){return{gain:this.gain}}};Db.className="Identity";re.registerClass(Db);function xz(e,t="channelsLast"){let n,a;if(Dt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=ns(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=ns(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=ns(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var In=class extends ma{constructor(e){super();if(e.scale<0)throw new z(`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,yz(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,bz(this.distribution),this.seed=e.seed}apply(e,t){let n=xz(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 $e(`${this.getClassName()} does not support dType ${t}.`);return Rh(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Vl(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};In.className="VarianceScaling";re.registerClass(In);var Jh=class extends In{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return In.className}};Jh.className="GlorotUniform";re.registerClass(Jh);var Qh=class extends In{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return In.className}};Qh.className="GlorotNormal";re.registerClass(Qh);var em=class extends In{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return In.className}};em.className="HeNormal";re.registerClass(em);var tm=class extends In{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return In.className}};tm.className="HeUniform";re.registerClass(tm);var nm=class extends In{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return In.className}};nm.className="LeCunNormal";re.registerClass(nm);var am=class extends In{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return In.className}};am.className="LeCunNormal";re.registerClass(am);var Rb=class extends ma{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 $e("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return D(()=>{if(e.length<2)throw new $e("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=Yh(n,0,1,"float32"),r=Y1.gramSchmidt(a);return e[0]>e[1]&&(r=r.transpose()),L(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Rb.className="Orthogonal";re.registerClass(Rb);var Tk={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 Sk(e,t={}){return Xc(e,re.SerializationMap.getMap().classNameMap,t,"initializer")}function Ct(e){return gb(e)}function wt(e){if(typeof e=="string"){let t=e in Tk?Tk[e]:e;if(t==="GlorotNormal")return new Qh;if(t==="GlorotUniform")return new Jh;if(t==="HeNormal")return new em;if(t==="HeUniform")return new tm;if(t==="LeCunNormal")return new nm;if(t==="LeCunUniform")return new am;{let n={};return n.className=t,n.config={},Sk(n)}}else return e instanceof ma?e:Sk(e)}function z3(){return new _b}function B3(){return new Zh}function W3(e){return new Eb(e)}function V3(e){return new Ab(e)}function U3(e){return new Fb(e)}function G3(e){return new $b(e)}function H3(e){return new Db(e)}function j3(e){return new In(e)}function q3(e){return new Jh(e)}function K3(e){return new Qh(e)}function X3(e){return new em(e)}function Y3(e){return new tm(e)}function Z3(e){return new nm(e)}function J3(e){return new am(e)}function Q3(e){return new Rb(e)}var Ck={};Oe(Ck,{Layer:()=>qe,RNN:()=>nr,RNNCell:()=>np,activation:()=>Mz,add:()=>Gz,alphaDropout:()=>CB,average:()=>Hz,averagePooling1d:()=>Mb,averagePooling2d:()=>Pb,averagePooling3d:()=>Ob,avgPool1d:()=>eB,avgPool2d:()=>nB,avgPool3d:()=>rB,avgPooling1d:()=>tB,avgPooling2d:()=>aB,avgPooling3d:()=>sB,batchNormalization:()=>Zz,bidirectional:()=>xB,concatenate:()=>jz,conv1d:()=>Cz,conv2d:()=>_z,conv2dTranspose:()=>Ez,conv3d:()=>Az,convLstm2d:()=>fB,convLstm2dCell:()=>gB,cropping2D:()=>$z,dense:()=>Pz,depthwiseConv2d:()=>Rz,dot:()=>Yz,dropout:()=>Oz,elu:()=>wz,embedding:()=>Uz,flatten:()=>zz,gaussianDropout:()=>SB,gaussianNoise:()=>TB,globalAveragePooling1d:()=>iB,globalAveragePooling2d:()=>oB,globalMaxPool1d:()=>wB,globalMaxPool2d:()=>kB,globalMaxPooling1d:()=>Ek,globalMaxPooling2d:()=>Ak,gru:()=>uB,gruCell:()=>cB,input:()=>_k,inputLayer:()=>vz,layerNormalization:()=>Jz,leakyReLU:()=>Iz,lstm:()=>pB,lstmCell:()=>dB,masking:()=>_B,maxPool1d:()=>IB,maxPool2d:()=>NB,maxPooling1d:()=>Fk,maxPooling2d:()=>$k,maxPooling3d:()=>lB,maximum:()=>qz,minimum:()=>Kz,multiply:()=>Xz,permute:()=>Vz,prelu:()=>Nz,reLU:()=>kz,repeatVector:()=>Bz,reshape:()=>Wz,rnn:()=>yB,separableConv2d:()=>Fz,simpleRNN:()=>hB,simpleRNNCell:()=>mB,softmax:()=>Tz,spatialDropout1d:()=>Lz,stackedRNNCells:()=>bB,thresholdedReLU:()=>Sz,timeDistributed:()=>vB,upSampling2d:()=>Dz,zeroPadding2d:()=>Qz});var EB=0;function Dk(){return EB++}var rm={};function sm(e=""){return e in rm||(rm[e]=0),rm[e]+=1,e+rm[e].toString()}function Lb(e){return Array.isArray(e)&&Array.isArray(e[0])}function im(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Me(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new z(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function ht(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new z(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function om(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 Rk="Variable",Mk=class{constructor(e,t="float32",n=Rk,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Dk(),n=n==null?Rk:n,this.originalName=xk(n),this.name=vk(this.originalName),this.trainable_=a,this.constraint=r,this.val=$1(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),AB(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 AB(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function zb(e){return e.map(t=>t.read())}function Bb(e){e.forEach(t=>{t[0].write(t[1])})}var Xt=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||{}}},Fa=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=Dk(),s!=null&&(this.originalName=xk(s),this.name=vk(this.originalName)),this.rank=t.length}},FB=0,lm=class{constructor(e,t){this.callArgs=t,this.id=FB++,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}}},$B=0,qe=class extends re.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=$B++,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=wr(n)+"_"+sm(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 Ea(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new z(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return kn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return kn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new vr(`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 vr(`Layer ${this.name} is not connected, no input to return.`);return kn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new vr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new vr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return kn(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=yt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=yt(this.inputSpec);if(e.length!==t.length)throw new z(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let a=e[n],r=t[n];if(r==null)continue;let s=a.rank;if(r.ndim!=null&&s!==r.ndim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${s}`);if(r.maxNDim!=null&&s>r.maxNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${s}`);if(r.minNDim!=null&&s<r.minNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${s}.`);if(r.dtype!=null&&a.dtype!==r.dtype)throw new z(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${a.dtype}.`);if(r.axes){let i=a.shape;for(let o in r.axes){let l=Number(o),c=r.axes[o],u=l>=0?i[l]:i[i.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${i}.`)}}if(r.shape!=null)for(let i=0;i<r.shape.length;++i){let o=r.shape[i],l=a.shape[i];if(o!=null&&l!=null&&o!==l)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${a.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let n=yt(e),a=!0;for(let s of n)if(!(s instanceof Fa)){a=!1;break}let r=!0;for(let s of n)if(s instanceof Fa){r=!1;break}if(a===r)throw new z("Arguments to apply() must be all SymbolicTensors or all Tensors");return Oi(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of yt(e))s.push(i.shape);this.build(kn(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=yt(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=kn(o),this.activityRegularizer!=null)throw new $e("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=DB(e),i=this.computeOutputShape(s),o,l=RB(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((c,u)=>new Fa(l,c,this,yt(e),t,this.name,u)):o=new Fa(l,i,this,yt(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new $e("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 vr(`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 vr(`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 Ea(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return om(this.weights)}build(e){this.built=!0}getWeights(e=!1){return zb(e?this.trainableWeights:this.weights)}setWeights(e){D(()=>{let t=this.weights;if(t.length!==e.length)throw new z(`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=zb(t);for(let r=0;r<a.length;++r){let s=a[r],i=t[r],o=e[r];if(!k.arraysEqual(s.shape,o.shape))throw new z(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}Bb(n)})}addWeight(e,t,n,a,r,s,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new z(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(a=wt("zeros"));let o=a.apply(t,n),l=new Mk(o,n,e,s,i);return o.dispose(),r!=null&&this.addLoss(()=>r.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=yt(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=yt(e);t=yt(t),n=yt(n),a=yt(a),r=im(r),s=im(s);let l=[],c=[],u=[];for(let p of o)l.push(p.sourceLayer),c.push(p.nodeIndex),u.push(p.tensorIndex);new lm({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:a,inputShapes:r,outputShapes:s},i);for(let p=0;p<t.length;p++)t[p].sourceLayer=this,t[p].nodeIndex=this.inboundNodes.length-1,t[p].tensorIndex=p}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function DB(e){e=yt(e);let t=[];for(let n of e)t.push(n.shape);return kn(t)}function RB(e){return"float32"}function Pk(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;s<a.inboundLayers.length;s++){let i=a.inputTensors[s],o=a.inboundLayers[s],l=a.nodeIndices[s],c=Pk(i,o,l);for(let u of c)r.indexOf(u)===-1&&r.push(u)}return r}}}var Xl=class extends qe{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:sm("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let a=new Fa(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new lm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new z(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};Xl.className="InputLayer";re.registerClass(Xl);function Ok(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;return n==null&&(n="float32"),new Xl({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}async function rs(e){if(e==null)return;let t=[],n=[],a=[];for(let r in e){let s=e[r];if(typeof s!="number"){let i=s;t.push(i.data()),n.push(r),a.push(i)}}if(t.length>0){let r=await Promise.all(t);for(let s=0;s<r.length;++s)e[n[s]]=r[s][0];Fe(a)}}function Lk(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var zk;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(zk||(zk={}));var MB=125,Yl=class{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}},Bk=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},PB=class extends Yl{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let a in t){let r=t[a];if(typeof r=="number")this.totals.hasOwnProperty(a)||(this.totals[a]=0),this.totals[a]=this.totals[a]+r*n;else{let s;a in this.totals?s=this.totals[a]:this.totals[a]=0;let i=D(()=>Z(this.totals[a],L(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:D(()=>{let a=L(ve(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),jt(t[n])}))}},Wk=class extends Yl{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;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(r),n.push(i)}}let a=await Promise.all(e);for(let r=0;r<a.length;++r)this.history[t[r]][n[r]].dispose(),this.history[t[r]][n[r]]=a[r][0]}},Vk=class extends Yl{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=MB),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");k.isNumber(this.yieldEvery)&&(this.maybeWait=L3(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){let a=[];this.yield!=null&&(await rs(n),a.push(this.yield(e,t,n))),a.push(qh()),await Promise.all(a)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await rs(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await rs(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(qh()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await rs(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await rs(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(qh()):k.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await rs(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await rs(e),await this.trainEnd(e))}};function Uk(e,t){return e==null&&(e={}),e instanceof Yl?[e]:Array.isArray(e)&&e[0]instanceof Yl?e:yt(e).map(n=>new Vk(n,t))}var fa=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}`),fa.checkForDuplicate(t),fa.constructors[e]==null&&(fa.constructors[e]=[]),fa.constructors[e].push(t)}static checkForDuplicate(e){for(let t in fa.constructors)fa.constructors[+t].forEach(n=>{if(n===e)throw new z("Duplicate callback constructor.")})}static clear(){fa.constructors={}}static createCallbacks(e){let t=[];for(let n in fa.constructors){let a=+n;e>=a&&t.push(...fa.constructors[a])}return t.map(n=>new n)}};fa.constructors={};function Gk(e,t,n,a,r,s,i,o,l){let c=new Wk,u=[new PB,...fa.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let p=new Bk(u);return p.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:p,history:c}}function $a(e,t={},n=!1){return Xc(e,re.SerializationMap.getMap().classNameMap,t,"layer",n)}function um(e,t){return D(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));let n=Te(ep(e),t,!0),a=wn(n.shape,Bt()),r=en(Xa(n,a));return ve(e,r)})}function zi(e,t){return D(()=>St(ep(fe(t,e)),-1))}function cm(e,t){return D(()=>St(Lt(fe(t,e)),-1))}function Zl(e,t){return D(()=>{let n=fe(e,t),a=qt(Lt(e),Bt(),Number.MAX_VALUE),r=Lt(ve(n,a));return L(100,St(r,-1))})}function OB(e,t){return D(()=>{let n=qt(t,Bt(),Number.MAX_VALUE),a=Dn(Z(1,n)),r=qt(e,Bt(),Number.MAX_VALUE),s=Dn(Z(1,r));return St(ep(fe(a,s)),-1)})}function LB(e,t){return D(()=>{let n=Xa(0,fe(1,L(e,t)));return St(ep(n),-1)})}function zB(e,t){return D(()=>{let n=Xa(0,fe(1,L(e,t)));return St(n,-1)})}function BB(e,t){return D(()=>{let n=Te(L(e,t),-1),a=Yn(L(fe(1,e),t),-1);return Xa(0,Z(1,fe(a,n)))})}function WB(e,t){return D(()=>{let n=Math.log(2),a=fe(t,e),r=fe(Z(a,zl(L(-2,a))),n);return St(r,-1)})}function ap(e,t,n=!1){return D(()=>{if(n)t=Ta(t);else{let a=Te(t,t.shape.length-1,!0);t=ve(t,a)}return t=qt(t,Bt(),1-Bt()),Tt(Te(L(e.toFloat(),Dn(t)),t.shape.length-1))})}function pm(e,t,n=!1){return D(()=>{let a=Ll(cz(e)).toInt();t=qt(t,Bt(),1-Bt());let r=t.shape,s=Dl(a,r[r.length-1]).reshape(r);return ap(s,t,n)})}function VB(e,t){if(!k.arraysEqual(e.shape,t.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return D(()=>{let n=t.relu(),a=t.abs().neg();return n.sub(t.mul(e)).add(a.exp().log1p())})}function dm(e,t){return D(()=>{let n;return n=qt(t,Bt(),1-Bt()),n=Dn(ve(n,fe(1,n))),St(VB(e,n),-1)})}function UB(e,t){return D(()=>{let n=qt(e,Bt(),1),a=qt(t,Bt(),1);return Te(L(e,Dn(ve(n,a))),-1)})}function GB(e,t){return D(()=>{let n=Dn(Z(Bt(),t));return St(fe(t,L(e,n)),-1)})}function Wb(e,t){return D(()=>{let n=um(e,-1),a=um(t,-1),r=L(n,a);return Tt(Te(r,-1))})}var hm={meanSquaredError:zi,meanAbsoluteError:cm,meanAbsolutePercentageError:Zl,meanSquaredLogarithmicError:OB,squaredHinge:LB,hinge:zB,categoricalHinge:BB,logcosh:WB,categoricalCrossentropy:ap,sparseCategoricalCrossentropy:pm,binaryCrossentropy:dm,kullbackLeiblerDivergence:UB,poisson:GB,cosineProximity:Wb};function Vb(e){if(typeof e=="string"){if(e in hm)return hm[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 z(t)}else return e}function Ub(e,t){return D(()=>{let n=L(.5,Rn(t)),a=Jc(pa(t,n),e.dtype);return St(Zr(e,a),-1)})}function Gb(e,t){return D(()=>Jc(Zr(Mc(e,-1),Mc(t,-1)),"float32"))}function Hk(e,t){return D(()=>da(e.equal(1),t.equal(1)).sum().cast("float32"))}function HB(e,t){return D(()=>da(e.equal(1),t.equal(0)).sum().cast("float32"))}function jB(e,t){return D(()=>da(e.equal(0),t.equal(1)).sum().cast("float32"))}function jk(e,t){return D(()=>{let n=Hk(e,t),a=jB(e,t),r=n.add(a);return vn(pa(r,0),n.div(r),0).cast("float32")})}function qB(e,t){return D(()=>{let n=Hk(e,t),a=HB(e,t),r=n.add(a);return vn(pa(r,0),n.div(r),0).cast("float32")})}function qk(e,t){return dm(e,t)}function Kk(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)),Zr(e,t).asType("float32")}var KB=zi,XB=zi,YB=cm,ZB=cm,JB=Zl,QB=Zl,Hb=ap,eW=Wb,Xk=pm,mm={binaryAccuracy:Ub,categoricalAccuracy:Gb,precision:jk,categoricalCrossentropy:Hb,sparseCategoricalCrossentropy:Xk,mse:KB,MSE:XB,mae:YB,MAE:ZB,mape:JB,MAPE:QB,cosine:eW};function tW(e){if(typeof e=="string"&&e in mm)return mm[e];if(typeof e!="string"&&e!=null)return e;throw new z(`Unknown metric ${e}`)}function fm(e){if(Qa(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(hm))if(hm[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(mm))if(mm[n]===e){t=n;break}return t!==void 0?t:e.name}}function nW(e){let t={Adagrad:()=>Di.adagrad(.01),Adadelta:()=>Di.adadelta(1,.95,Bt()),Adam:()=>Di.adam(.001,.9,.999,Bt()),Adamax:()=>Di.adamax(.002,.9,.999,Bt(),0),RMSProp:()=>Di.rmsprop(.001,.9,0,Bt()),SGD:()=>Di.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 z(`Unknown Optimizer ${e}`)}var Yk=1*1024*1024;function Zk(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!jb(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>Yk&&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 <= ${Yk}.`)}}function jb(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"||!jb(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!jb(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function oW(e,t,n,a=console.log){let r=rW(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(u=>Math.floor(t*u)));let i;if(!r){s.push("Receives inputs"),i=[];for(let u in e.nodesByDepth)i.push(...e.nodesByDepth[u])}a("_".repeat(t)),gm(s,n,a),a("=".repeat(t));let o=e.layers;for(let u=0;u<o.length;++u)r?sW(o[u],n,a):iW(o[u],n,i,a),a((u===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=aW(e),c=om(e.nonTrainableWeights);a(`Total params: ${l+c}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${c}`),a("_".repeat(t))}function aW(e){let t;return e.collectedTrainableWeights!=null?t=om(e.collectedTrainableWeights):t=om(e.trainableWeights),t}function rW(e){let t=!0,n=[],a=[];for(let r in e.nodesByDepth)n.push(e.nodesByDepth[r]);for(let r of n){if(r.length>1||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 gm(e,t,n=console.log){let a="";for(let r=0;r<e.length;++r)r>0&&(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 sW(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()];gm(i,t,n)}function iW(e,t,n,a){let r;try{r=JSON.stringify(e.outputShape)}catch(u){r="multiple"}let s=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let p=0;p<u.inboundLayers.length;++p){let d=u.inboundLayers[p].name,h=u.nodeIndices[p],m=u.tensorIndices[p];s.push(`${d}[${h}][${m}]`)}let i=e.name,o=e.getClassName(),l=s.length===0?"":s[0],c=[`${i} (${o})`,r,e.countParams().toString(),l];gm(c,t,a);for(let u=1;u<s.length;++u)gm(["","","",s[u]],t,a)}function Jk(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function rp(e,t){if(e===null)return null;if(typeof e=="string")return Mi(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];Jk(t,r,s)?n.push(s):n.push(rp(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a];if(a==="name"&&typeof r=="string")n[a]=r;else{let s=Mi(a);n[s]=rp(r,s)}}return n}}function qb(e,t){if(e==null)return null;if(typeof e=="string")return wr(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];Jk(t,r,s)?n.push(s):n.push(qb(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a],s=wr(a);(a==="name"||a==="className")&&typeof r=="string"?n[s]=r:n[s]=qb(r,a)}return n}}var ym="3.1.0";function lW(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ce(t,e.dtype)}catch(n){throw new z(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var Bi=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Bi)for(let t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(let t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=lW(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new z(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Fa){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Fa){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Fe(this.id2Mask)}},Kb={},Qk={};function sp(e,t,n,a){let r=n==null?!1:n.training,s=Array.isArray(e),i=s?e:[e],o=i.map(m=>m.name),l=[],c=t.names();for(let m of o)c.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);a!=null&&(a.maxNumTensors=-Infinity,a.minNumTensors=Infinity);let u=o.join(",")+"|"+t.names().join(","),p,d;if(Kb[u]==null){let m=uW(i,t);p=m.sorted,d=m.recipientCounts,Kb[u]=p,Qk[u]=d}p=Kb[u],d={},r||Object.assign(d,Qk[u]);let h=new Bi(t);for(let m=0;m<p.length;++m){if(a!=null){let $=lh().numTensors;$>a.maxNumTensors&&(a.maxNumTensors=$),$<a.minNumTensors&&(a.minNumTensors=$)}let f=p[m],g=f.sourceLayer;if(g instanceof Xl)continue;let y=[],b=[],v=[],x=!1;for(let $ of f.inputs){let P=h.getValue($),B=h.getMask($);y.push(P),b.push(B),B!=null&&(x=!0),r||(d[$.name]--,d[$.name]===0&&!t.hasKey($)&&o.indexOf($.name)===-1&&!P.isDisposed&&$.sourceLayer.stateful!==!0&&v.push(P))}x&&(n=n||{},n.mask=b[0]);let N=yt(g.apply(y,n)),T=null;g.supportsMasking&&(T=g.computeMask(y,b));let C=cW(f),F=Array.isArray(C)?C:[C];for(let $=0;$<F.length;++$){h.hasKey(F[$])||h.add(F[$],N[$],Array.isArray(T)?T[0]:T);let P=o.indexOf(F[$].name);P!==-1&&(l[P]=N[$])}r||Fe(v)}return h.disposeMasks(),s?l:l[0]}function uW(e,t){k.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=eI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=eI(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(c=>a[l].add(c))}}return{sorted:n,recipientCounts:pW(a)}}function pW(e){let t={};for(let n in e)t[n]=e[n].size;return t}function eI(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 c of o.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(o.name),!n.has(c.name)&&s.push(c)}}return{sorted:a,recipientMap:r}}function cW(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;a<e.sourceLayer.inboundNodes.length;++a)for(let r of e.sourceLayer.inboundNodes[a].outputTensors)if(r.id===e.id){n=a;break}t=e.sourceLayer.getOutputAt(n)}return t}var ar=class extends qe{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=sm(y)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],ts(this.inputs).length!==this.inputs.length)throw new z(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);ts(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 b=y.sourceLayer,v=y.nodeIndex,x=y.tensorIndex;this.outputLayers.push(b),this.outputLayersNodeIndices.push(v),this.outputLayersTensorIndices.push(x)}for(let y of this.inputs){let b=y.sourceLayer,v=y.nodeIndex,x=y.tensorIndex;Qa(v===0,"input layer has >1 nodes"),Qa(x===0,"input layer has >1 tensors"),this.inputLayers.push(b),this.inputLayersNodeIndices.push(v),this.inputLayersTensorIndices.push(x)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let b=this.inputLayers[y];if(!(b instanceof Xl))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${b.getClassName()}.`);this.inputNames.push(b.name),this.feedInputShapes.push(b.batchInputShape),this.feedInputNames.push(b.name)}for(let y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},n={},a={},r={},s={},i=[],o=(y,b,v,x,N,T)=>{(x==null||N==null||T==null)&&(x=y.sourceLayer,N=y.nodeIndex,T=y.tensorIndex);let C=x.inboundNodes[N];if(v.indexOf(C)!==-1)throw new Ea(`The tensor ${y.name} at layer "${x.name}" is part of a cycle.`);if(b.indexOf(C)!==-1)return;this.containerNodes.add(ar.nodeKey(x,N)),x.id in s||(s[x.id]=Object.keys(s).length),v.indexOf(C)===-1&&v.push(C);let F=C.inboundLayers.length;for(let $=0;$<F;$++){let P=C.inputTensors[$],B=C.inboundLayers[$],W=C.nodeIndices[$],G=C.tensorIndices[$];o(P,b,v,B,W,G)}for(b.push(C);v.indexOf(C)>=0;)v.splice(v.indexOf(C),1);i.push(C)},l=[],c=[];for(let y of this.outputs)o(y,l,c);let u=i.slice().reverse();for(let y of u){n[y.id]=y,y.id in t||(t[y.id]=0);let b=t[y.id],v=a[y.outboundLayer.id]==null?0:a[y.outboundLayer.id];b=Math.max(b,v),a[y.outboundLayer.id]=b,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=b;for(let x=0;x<y.inboundLayers.length;x++){let N=y.inboundLayers[x],T=y.nodeIndices[x],C=N.inboundNodes[T],F=t[C.id]==null?0:t[C.id];t[C.id]=Math.max(b+1,F),n[C.id]=C}}let p={};for(let y in t){let b=t[y];b in p||(p[b]=[]),p[b].push(n[y])}let d={};for(let y in a){let b=a[y];b in d||(d[b]=[]),d[b].push(r[y])}let h=Object.keys(d).map(y=>parseInt(y,10)).sort(Kh);this.layers=[];for(let y of h){let b=d[y];b.sort((v,x)=>{let N=s[v.id],T=s[x.id];return N<T?-1:N>T?1:0});for(let v of b)v instanceof ar&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=d,h=Object.keys(p).map(y=>parseInt(y,10)).sort(Kh);let m=this.inputs.slice(),f=[];for(let y of h)for(let b of p[y]){let v=b.outboundLayer;if(v!=null){for(let x of b.inputTensors)if(m.indexOf(x)===-1)throw new Ea(`Graph disconnected: cannot obtain value for tensor ${x} at layer "${v.name}". The following previous layers were accessed without issue: ${f}`);for(let x of b.outputTensors)m.push(x);f.push(v.name)}}this.nodesByDepth=p;let g=this.layers.map(y=>y.name);for(let y of g){let b=g.filter(v=>v===y).length;if(b!==1)throw new Ea(`The name "${y}" is used ${b} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new lm({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 z("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 z(`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 z(`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 z(`${s.length} of ${a} weights are not set: ${s}`)}Bb(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ym}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=qb(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return D(()=>{e=yt(e);let n=new Bi;for(let a=0;a<this.inputs.length;++a)n.add(this.inputs[a],e[a]);return sp(this.outputs,n,t)})}computeMask(e,t){return D(()=>{e=yt(e);let n;return t==null?n=Ri(null,e.length):n=yt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=im(e);if(t.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;i<t.length;i++){let o=this.inputLayers[i],l=t[i],c=o.name+"_0_0";n[c]=l}let a=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Kh);if(a.length>1)for(let i of a){let o=this.nodesByDepth[i];for(let l of o){let c=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(c.id)!==-1)continue;let u=[];for(let m=0;m<l.inboundLayers.length;m++){let f=l.inboundLayers[m],g=l.nodeIndices[m],y=l.tensorIndices[m],b=`${f.name}_${g}_${y}`,v=n[b];u.push(v)}let p=c.computeOutputShape(kn(u)),d=im(p),h=c.inboundNodes.indexOf(l);for(let m=0;m<d.length;m++){let f=`${c.name}_${h}_${m}`;n[f]=d[m]}}}let r=[],s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],c=this.outputLayersTensorIndices[i],u=`${o.name}_${l}_${c}`;s.push(u)}for(let i=0;i<s.length;i++){let o=s[i];Qa(o in n),r.push(n[o])}return kn(r)}runInternalGraph(e,t){t==null&&(t=Ri(null,e.length));let n={};for(let o=0;o<this.inputs.length;++o){let l=this.inputs[o],c=e[o],u=t[o];n[l.id]=[c,u]}let a=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Kh);for(let o of a){let l=this.nodesByDepth[o];for(let c of l){let u=c.outboundLayer,p=c.inputTensors,d=c.outputTensors,h=new Array;for(let m of p)m.id in n&&h.push(n[m.id]);if(h.length===p.length){let m={},f,g,y,b;if(c.callArgs!=null&&(m=c.callArgs),h.length===1){let[v,x]=h[0];m.mask==null&&(m.mask=x),y=yt(u.call(v,m)),b=yt(u.computeMask(v,x)),f=[v],g=[x]}else f=h.map(v=>v[0]),g=h.map(v=>v[1]),m.mask==null&&(m.mask=g),y=yt(u.call(f,m)),b=yt(u.computeMask(f,g));if(u.activityRegularizer)throw new $e("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let v=0;v<d.length;++v){let x=d[v],N=y[v],T=b[v];n[x.id]=[N,T]}}}}let r=[],s=[],i=[];for(let o of this.outputs){Qa(o.id in n,`Could not compute output ${o.name} : ${o.id}`);let[l,c]=n[o.id];i.push(l.shape),r.push(l),s.push(c)}return[r,s,i]}buildNodeConversionMap(e){let t={},n;for(let a of this.layers){n=a instanceof ar?1:0;for(let r=0;r<a.inboundNodes.length;r++){let s=ar.nodeKey(a,r);this.containerNodes.has(s)&&(t[s]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new z(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new z("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new z(`No such layer: ${e}`)}calculateLosses(){return D(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let a=ar.nodeKey(t,n);this.containerNodes.has(a)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let s of this.layers){let i=s.getClassName(),o=s.getConfig(),l=[];for(let u=0;u<s.inboundNodes.length;u++){let p=s.inboundNodes[u],d=ar.nodeKey(s,u),h={};if(this.containerNodes.has(d)){if(p.callArgs)try{JSON.stringify(p.callArgs),h=p.callArgs}catch(m){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${p.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(p.inboundLayers.length>0){let m=[];for(let f=0;f<p.inboundLayers.length;f++){let g=p.inboundLayers[f],y=p.nodeIndices[f],b=p.tensorIndices[f],v=ar.nodeKey(g,y),x=t[v];x==null&&(x=0),m.push([g.name,x,b,h])}l.push(m)}}}let c={};c.name=s.name,c.className=i,c.config=o,c.inboundNodes=l,n.push(c)}e.layers=n;let a=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=ar.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.inputLayersTensorIndices[s];a.push([i.name,c,u])}e.inputLayers=a;let r=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=ar.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.outputLayersTensorIndices[s];r.push([i.name,c,u])}return e.outputLayers=r,e}static fromConfig(e,t,n={},a=!1){let r={},s={};function i(f,g){f.name in s?s[f.name].push(g):s[f.name]=[g]}function o(f,g){let y=[],b;for(let v of g){let x=v[0],N=v[1],T=v[2];if(b=v[3]==null?{}:v[3],!(x in r)){i(f,g);return}let C=r[x];if(C.inboundNodes.length<=N){i(f,g);return}let F=C.inboundNodes[N];y.push(F.outputTensors[T])}y.length>0&&f.apply(kn(y),b)}function l(f){let g=f.name,y=$a(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),r[g]=y,f.inboundNodes.forEach(b=>{if(!(b instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${b}`);i(y,b)})}let c=t.name,u=t.layers;for(let f of u)l(f);for(;!O3(s);)for(let f of u){let g=r[f.name];if(g.name in s){let y=s[g.name];delete s[g.name];for(let b of y)o(g,b)}}let p=[],d=[],h=t.inputLayers;for(let f of h){let g=f[0],y=f[1],b=f[2];Qa(g in r);let v=r[g].inboundNodes[y].outputTensors;p.push(v[b])}let m=t.outputLayers;for(let f of m){let g=f[0],y=f[1],b=f[2];Qa(g in r);let v=r[g].inboundNodes[y].outputTensors;d.push(v[b])}return new e({inputs:p,outputs:d,name:c})}get stateful(){if(this._stateful)throw new z("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(){D(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function dW(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 tI(e,t){return dW(e,t,"classWeight")}async function nI(e,t,n,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=D(()=>{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());Fe(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])}),tt(i,"float32")}else return null}function hW(e,t){return L(e,t)}var mW=32;function rI(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=aI("input",e.inputNames,n),i=aI("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<s.length;l++)k.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)k.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function aI(e,t,n){if(n instanceof Ae)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 z(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function fW(e){if(e.length===3)throw new $e("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function yW(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(sI(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=fW(n.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),c;r?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();let u=Uk(n.callbacks,n.yieldEvery),p=n.verbose==null?1:n.verbose,{callbackList:d,history:h}=Gk(u,p,n.epochs,null,null,gW(t,n),null,r,c);d.setModel(e),e.history=h,await d.onTrainBegin(),e.stopTraining_=!1;let m=n.initialEpoch==null?0:n.initialEpoch,f=await t.iterator();for(;m<n.epochs;){let g={};await d.onEpochBegin(m);let y=0,b=0;for(a||(f=await t.iterator());a?y<n.batchesPerEpoch:!0;){let v=await f.next();if(a&&v.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(v.value!=null){let{xs:x,ys:N}=rI(e,v.value),T={};T.batch=b,T.size=x[0].shape[0],await d.onBatchBegin(b,T);let C=[];if(n.classWeight!=null){let P=tI(n.classWeight,e.outputNames);for(let B=0;B<P.length;++B)C.push(await nI(N[B],null,P[B]))}let F=x.concat(N).concat(C),$=o(F);Fe(F);for(let P=0;P<l.length;++P){let B=l[P],W=$[P];T[B]=W,jt(W)}await d.onBatchEnd(b,T),Lk(T),b++,y++}if(a?y>=n.batchesPerEpoch:v.done){if(r){let x;sI(n.validationData)?x=yt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):x=yt(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?mW:n.validationBatchSize,verbose:0}));for(let N=0;N<e.metricsNames.length;++N)g[`val_${e.metricsNames[N]}`]=x[N]}break}if(e.stopTraining_)break}if(await d.onEpochEnd(m,g),m++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function gW(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function sI(e){return typeof e.iterator=="function"}function bW(e){return typeof e.next=="function"}async function xW(e,t,n){n=n||{};let a=n.batches!=null,r=e.testFunction,s=[];if(n.verbose>0)throw new $e("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=bW(t)?t:await t.iterator(),o=0,l=0;for(;a?l<n.batches:!0;){let c=await i.next();if(s=D(()=>{if(c.value){let{xs:u,ys:p}=rI(e,c.value),d=u.concat(p),h=D(()=>r(d));if(Fe(d),l===0)for(let f=0;f<h.length;++f)s.push(de(0));let m=d[0].shape[0];for(let f=0;f<h.length;++f){let g=h[f],y=s[f];s[f]=D(()=>Z(s[f],L(m,g))),l>0&&Fe(y)}Fe(h),o+=m,++l}return s}),c.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 c=0;c<s.length;++c){let u=s[c];s[c]=ve(s[c],o),Fe(u)}return kn(s)}function Xb(e){k.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function ip(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>Li(a,t,n-t)):Li(e,t,n-t)}function Yb(e,t){return D(()=>e==null?null:Array.isArray(e)?e.map(n=>Yb(n,t)):Ik(e,t.dtype==="int32"?t:t.toInt()))}function Zb(e,t){let n=[],a=0,r=null;for(;a<e;)r=a+t,r>=e&&(r=e),n.push([a,r]),a=r;return n}async function vW(e,t,n,a,r,s,i,o,l,c,u,p,d,h,m){r==null&&(r=32),s==null&&(s=1),u==null&&(u=!0),d==null&&(d=0);let f=!1;if(l!=null&&c!=null&&(f=!0),m!=null&&(f=!0,h==null))throw new z("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),y;g!=null&&(y=Aa(0,g)),i==null&&(i=1);let{callbackList:b,history:v}=Gk(o,i,s,d,g,h,r,f,p);b.setModel(e),e.history=v,await b.onTrainBegin(),e.stopTraining_=!1;for(let x=d;x<s;++x){await b.onEpochBegin(x);let N={};if(h!=null)throw new $e("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new $e("batch shuffling is not implemneted yet");u&&k.shuffle(y);let T=tt(y),C=Zb(g,r);for(let F=0;F<C.length;++F){let $={};if(await b.onBatchBegin(F,$),D(()=>{let P=C[F][0],B=C[F][1],W=Li(T,P,B-P);$.batch=F,$.size=B-P;let G=Yb(n,W),q=t(G);for(let j=0;j<a.length;++j){let X=a[j],K=q[j];$[X]=K,jt(K)}if(F===C.length-1&&f){let j=e.testLoop(l,c,r);for(let X=0;X<a.length;++X){let K=a[X],ne=j[X];jt(ne),N["val_"+K]=ne}}}),await b.onBatchEnd(F,$),Lk($),e.stopTraining_)break}T.dispose()}if(await b.onEpochEnd(x,N),e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}async function wW(e,t,n,a={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let r,s,i,o,l,c,u;try{let p=a.batchSize==null?32:a.batchSize;Xb(p);let d=!1,h=await e.standardizeUserData(t,n,a.sampleWeight,a.classWeight,d,p);r=h[0],s=h[1],u=h[2];let m=!1,f;if(a.validationData!=null&&a.validationData.length>0){if(m=!0,a.validationData.length===2)i=a.validationData[0],o=a.validationData[1];else throw a.validationData.length===3?new $e("validationData including sample weights is not supported yet."):new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);let T=!0,C=await e.standardizeUserData(i,o,null,null,T,p);l=C[0],c=C[1],f=l.concat(c)}else if(a.validationSplit!=null&&a.validationSplit>0&&a.validationSplit<1){m=!0;let T=Math.floor(r[0].shape[0]*(1-a.validationSplit)),C=r[0].shape[0];l=ip(r,T,C),r=ip(r,0,T),c=ip(s,T,C),s=ip(s,0,T),f=l.concat(c)}else a.validationSteps!=null&&(m=!0);let g=r.concat(s).concat(u);e.checkTrainableWeightsConsistency();let y=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),v,x;m?(e.makeTestFunction(),v=e.testFunction,x=b.slice().concat(b.map(T=>"val_"+T))):(v=null,f=[],x=b.slice());let N=Uk(a.callbacks,a.yieldEvery);return await vW(e,y,g,b,p,a.epochs,a.verbose,N,v,f,a.shuffle,x,a.initialEpoch,null,null)}finally{e.isTraining=!1,Wi(r,t),Wi(s,n),Wi(l,i),Wi(c,o),u!=null&&Fe(u)}}function iI(e){let t=[];e instanceof Ae&&(e=[e]);for(let n=0;n<e.length;++n){let a=e[n];if(a.rank===1)t.push(Qc(a,1));else{if(a.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(a)}}return t}function Wi(e,t){if(e==null)return;let n=[];if(t instanceof Ae)n.push(t.id);else if(Array.isArray(t))t.forEach(r=>n.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 Ae)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 kW(e){return e instanceof Ae}function Jb(e){return Array.isArray(e)}function oI(e){return!kW(e)&&!Jb(e)}function lI(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(Jb(e)&&e.length>0)i=!0;else if(oI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new z(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(oI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new z(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(Jb(e)){if(e=e,e.length!==t.length)throw new z(`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 z(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=iI(s),n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new z(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let c=o.shape[l],u=n[i][l];if(u!=null&&u>=0&&c!==u)throw new z(`Error when checking ${r}: expected ${t[i]} to have shape [${n[i]}], but got array with shape [${o.shape}].`)}}return s}function IW(e,t,n){let a=ts(e.map(s=>s.shape[0]));a.sort();let r=ts(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new z(`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 z(`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 z(`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 NW(e,t,n){let a=[zi,dm,ap];for(let r=0;r<e.length;++r){let s=e[r],i=t[r],o=n[r];if(i!=null){if(i===ap&&s.shape[s.shape.length-1]===1)throw new z(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(a.indexOf(i)!==-1){let l=s.shape.slice(1),c=o.slice(1);for(let u=0;u<l.length;++u){let p=l[u],d=c[u];if(d!=null&&p!==d)throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function uI(e,t,n,a=!0,r=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new z(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new z(`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<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new z(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let c=o.shape[l],u=n[i][l];if(u!=null&&u!==c)throw new z(`Error when checking ${r}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function TW(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>[]);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 SW="layers-model",kr=class extends ar{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new z("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).");oW(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=nW(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof xr))throw new z("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 z(`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(Vb(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new z(`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=>Vb(s))}else{let s=Vb(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Oi("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=TW(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])};Oi("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=a[s];(o=>{let l="",c,u,p;for(let d of o){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===dm?["accuracy","acc"].indexOf(d)!==-1?u=Ub:["crossentropy","ce"].indexOf(d)!==-1&&(u=qk):this.lossFunctions[s]===pm?["accuracy","acc"].indexOf(d)!==-1?u=Kk:["crossentropy","ce"].indexOf(d)!==-1&&(u=Xk):["accuracy","acc"].indexOf(d)!==-1?u=Gb:["crossentropy","ce"].indexOf(d)!==-1&&(u=Hb);let f;["accuracy","acc"].indexOf(d)!==-1?f="acc":["crossentropy","ce"].indexOf(d)!==-1&&(f="ce"),p=u,c=l+f}else p=tW(d),c=l+fm(d);let h;Oi(c,()=>{h=p}),r(s,c,h)}})(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;Xb(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 kn(l)}finally{Wi(s[0],e),Wi(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),xW(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new z(`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 z(`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 z("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new Bi;if(e instanceof Ae&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new z(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new z(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=sp(r,s);return n?i:i[0]}retrieveSymbolicTensors(e){let t=Ri(null,e.length),n=e.length;for(let a of this.layers){let r=Array.isArray(a.output)?a.output:[a.output],s=r.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=r[o],n--),n===0)break}if(n===0)break}if(n>0){let a=[];throw t.forEach((r,s)=>{r==null&&a.push(e[s])}),new z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return D(()=>{let a=this.checkNumSamples(e);if(n)throw new $e("Verbose predictLoop() is not implemented yet.");let r=Zb(a,t),s=this.outputs.map(i=>[]);for(let i=0;i<r.length;++i)D(()=>{let o=r[i][0],l=r[i][1],c=ip(e,o,l),u=[];if(Array.isArray(c))for(let d=0;d<c.length;++d)u.push({key:this.inputs[d],value:c[d]});else u.push({key:this.inputs[0],value:c});let p=new Bi(u);return sp(this.outputs,p)}).forEach((o,l)=>s[l].push(o));return kn(s.map(i=>Qe(i,0)))})}predict(e,t={}){let n=iI(e);uI(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return Xb(a),this.predictLoop(n,a)}finally{Wi(n,e)}}predictOnBatch(e){uI(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 Ea("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===pm?r.push(i.slice(0,i.length-1).concat([1])):r.push(i)}if(e=lI(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=lI(t,this.feedOutputNames,r,!1,"target"),IW(e,t,null),NW(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!=0)throw new z(`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 c=tI(a,this.outputNames);l=[];for(let u=0;u<c.length;++u)l.push(await nI(o[u],null,c[u]))}return[i,o,l]}testLoop(e,t,n,a=0,r){return D(()=>{let s=this.checkNumSamples(t,n,r,"steps"),i=[];if(a>0)throw new $e("Verbose mode is not implemented yet.");if(r!=null)throw new $e("steps mode in testLoop() is not implemented yet");{let o=Zb(s,n),l=tt(Aa(0,s));for(let c=0;c<o.length;++c){let u=o[c][0],p=o[c][1],d=Li(l,u,p-u),h=Yb(t,d),m=e(h);if(c===0)for(let f=0;f<m.length;++f)i.push(de(0));for(let f=0;f<m.length;++f){let g=m[f];i[f]=Z(i[f],L(p-u,g))}}for(let c=0;c<i.length;++c)i[c]=ve(i[c],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let a=e[n],r=a;ck(e,a)>1&&(r+=`_${ck(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 c=[];for(let h=0;h<this.inputs.length;++h)c.push({key:this.inputs[h],value:n[h]});let u=new Bi(c),p=sp(this.outputs,u,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let m=this.lossFunctions[h](a[h],p[h]);r[h]!=null&&(m=hW(m,r[h]));let f=St(m);t.push(f),h===0?d=m:d=Z(d,m)}for(let h=0;h<this.metricsTensors.length;++h){let m;if(this.outputs.length>1&&h<this.outputs.length)m=t[h];else{let f=this.metricsTensors[h][0],g=this.metricsTensors[h][1];m=St(f(a[g],p[g]))}jt(m),s.push(m)}return d=St(d),this.calculateLosses().forEach(h=>{d=Z(d,h)}),d},o=this.collectedTrainableWeights.map(c=>c.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>D(()=>{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;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:a[l]});let i=new Bi(s),o=sp(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let c=this.lossFunctions[l],u=St(c(r[l],o[l]));l===0?n=u:n=Z(n,u),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let c=this.metricsTensors[l][0],u=this.metricsTensors[l][1],p=St(c(r[u],o[u]));t.push(p)}return t})}async fit(e,t,n={}){return wW(this,e,t,n)}async fitDataset(e,t){return yW(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),a=n[0],r=n[1],s=this.makeTrainFunction()(a.concat(r)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return Fe(s),kn(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,a=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let s=0;s<a.length;++s)n&&!a[s].trainable||t.push({name:a[s].originalName,tensor:r[s]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=lh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-lh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=wr(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>wr(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]=wr(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[wr(fm(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>wr(fm(e)));{let e={};for(let t in this.metrics)e[t]=wr(fm(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=rp(e.optimizer_config),n=$a(t),a;if(typeof e.loss=="string")a=Mi(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>Mi(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=Mi(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>Mi(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=Mi(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let i=Ht.getSaveHandlers(e);if(i.length===0)throw new z(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new z(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Ht.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:SW,generatedBy:`TensorFlow.js tfjs-layers v${ym}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Ht.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=Ht.concatenateArrayBuffers([n.data,o])}if(this.userDefinedMetadata!=null){let i=!0;Zk(this.userDefinedMetadata,this.name,i),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){Zk(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};kr.className="Model";re.registerClass(kr);var cI=class extends kr{};cI.className="Functional";re.registerClass(cI);async function CW(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=rp(n),r=$a(a,t);if(e.weightsManifest!=null){let s=await Ht.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),Fe(s)}return r}async function EW(e,t){if(t==null&&(t={}),typeof e=="string"){let n=Ht.getLoadHandlers(e,t);if(n.length===0)n.push(Ht.browserHTTPRequest(e,t));else if(n.length>1)throw new z(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return _W(e,void 0,t)}async function _W(e,t,n){if(n==null&&(n={}),e.load==null)throw new z("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=$a(rp(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 z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=AW(a.weightData,a.weightSpecs);o.loadWeights(c,s),o.optimizer!=null&&u.length>0&&await o.optimizer.setWeights(u),Fe(c),Fe(u.map(p=>p.tensor))}return o}function AW(e,t){let n=Ht.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 Jl=class extends kr{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:sm("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 z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof Jl||e instanceof kr,n;if(t){if(n=e,n.outputs.length!==1)throw new z("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 z("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 z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=Ok({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 z(`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 z("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=Pk(this.outputs[0])}this.inboundNodes=[],new lm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ri(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(ht(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 kr({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 Ea("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 Ea("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 Ea("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 Ea("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 z("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 Jl))throw new $e(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=$a(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new z("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 z("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}}};Jl.className="Sequential";re.registerClass(Jl);function FW(e){return new kr(e)}function $W(e){return new Jl(e)}function DW(e,t){return t==null&&(t={}),EW(e,t)}function _k(e){return Ok(e)}function RW(e,t){fa.registerCallbackConstructor(e,t)}var On=class extends re.Serializable{getConfig(){return{}}},pI=class extends On{apply(e,t=1){return dz(e,t)}};pI.className="elu";re.registerClass(pI);var dI=class extends On{apply(e){return _h(e)}};dI.className="selu";re.registerClass(dI);var hI=class extends On{apply(e){return Ye(e)}};hI.className="relu";re.registerClass(hI);var mI=class extends On{apply(e){return D(()=>Wl(6,Ye(e)))}};mI.className="relu6";re.registerClass(mI);var fI=class extends On{apply(e){return e}};fI.className="linear";re.registerClass(fI);var gI=class extends On{apply(e){return ca(e)}};gI.className="sigmoid";re.registerClass(gI);var yI=class extends On{apply(e){return mz(e)}};yI.className="hardSigmoid";re.registerClass(yI);var bI=class extends On{apply(e){return zl(e)}};bI.className="softplus";re.registerClass(bI);var xI=class extends On{apply(e){return hz(e)}};xI.className="softsign";re.registerClass(xI);var vI=class extends On{apply(e){return Pl(e)}};vI.className="tanh";re.registerClass(vI);var Qb=class extends On{apply(e,t=-1){return Ta(e,t)}};Qb.className="softmax";re.registerClass(Qb);var wI=class extends On{apply(e,t=-1){return wh(e,t)}};wI.className="logSoftmax";re.registerClass(wI);var kI=class extends On{apply(e,t=1){return D(()=>ca(e.mul(t)).mul(e))}};kI.className="swish";re.registerClass(kI);function ss(e){return e.getClassName()}function ex(e,t={}){return Xc(e,re.SerializationMap.getMap().classNameMap,t,"activation")}function is(e){if(e==null){let t={};return t.className="linear",t.config={},ex(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},ex(t)}else return e instanceof On?e:ex(e)}function tx(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 II=class extends re.Serializable{},op=class extends II{constructor(e){super();tx(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 D(()=>{let t=vt([1]);return this.hasL1&&(t=Z(t,Te(L(this.l1,Lt(e))))),this.hasL2&&(t=Z(t,Te(L(this.l2,ep(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};op.className="L1L2";re.registerClass(op);function MW(e){return tx(e),new op({l1:e!=null?e.l1:null,l2:0})}function PW(e){return tx(e),new op({l2:e!=null?e.l2:null,l1:0})}var NI={l1l2:"L1L2"};function mt(e){return gb(e)}function TI(e,t={}){return Xc(e,re.SerializationMap.getMap().classNameMap,t,"regularizer")}function kt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in NI?NI[e]:e,config:{}};return TI(t)}else return e instanceof II?e:TI(e)}var nx=class extends qe{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Me(e);let n=Ye(e);return this.maxValue!=null&&(n=qt(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};nx.className="ReLU";re.registerClass(nx);var ax=class extends qe{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=Me(e);return Bc(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};ax.className="LeakyReLU";re.registerClass(ax);var rx=class extends qe{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=wt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=kt(e.alphaRegularizer),this.alphaConstraint=Vt(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 z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=ht(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<e.length;++a)n[a]=e[a];this.inputSpec=[new Xt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Me(e),Uc(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Ct(this.alphaInitializer),alphaRegularizer:mt(this.alphaRegularizer),alphaConstraint:Wt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};rx.className="PReLU";re.registerClass(rx);var sx=class extends qe{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new $e(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Me(e);return Ol(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};sx.className="ELU";re.registerClass(sx);var ix=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Me(e);return n.mul(Jc(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};ix.className="ThresholdedReLU";re.registerClass(ix);var ox=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Qb().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Me(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};ox.className="Softmax";re.registerClass(ox);function Ql(e,t,n){if(typeof e=="number")return Ri(e,t);if(e.length!==t)throw new z(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){let r=e[a];if(!lz(r))throw new z(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`)}return e}function Da(e,t,n,a,r=1){if(e==null)return e;let s=t+(t-1)*(r-1),i;return n==="same"?i=e:i=e-s+1,Math.floor((i+a-1)/a)}function bm(e,t,n,a){if(e==null)return null;if(a==="valid")e=e*t+as([n-t,0]);else if(a==="same")e=e*t;else throw new z(`Unsupport padding mode: ${a}.`);return e}function lx(e,t){return D(()=>(Dt(t),t==="channelsFirst"?Ue(e,[0,2,3,1]):e))}function SI(e,t){return D(()=>(Dt(t),t==="channelsFirst"?Ue(e,[0,2,3,4,1]):e))}function OW(e,t,n,a=1,r="valid",s,i=1){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.shape.length!==3)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=Ue(e,[0,2,1])),r==="causal")throw new $e("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=hh(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=tr(o,n)),o})}function CI(e,t,n,a=[1,1],r="valid",s,i,o=null){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.rank!==3&&e.rank!==4)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=lx(e,s);if(r==="causal")throw new $e("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=es.conv2d({x:l,filter:t,strides:a,pad:r==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),s==="channelsFirst"&&(l=Ue(l,[0,3,1,2])),l})}function LW(e,t,n,a=[1,1,1],r="valid",s,i){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.rank!==4&&e.rank!==5)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=SI(e,s);if(r==="causal")throw new $e("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=zy(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=tr(o,n)),s==="channelsFirst"&&(o=Ue(o,[0,4,1,2,3])),o})}var ux=class extends qe{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",ux.verifyArgs(t),this.rank=e,Kt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new $e(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Ql(t.kernelSize,e,"kernelSize"),this.strides=Ql(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Jn(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Dt(this.dataFormat),this.activation=is(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=wt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Vt(t.biasConstraint),this.biasRegularizer=kt(t.biasRegularizer),this.activityRegularizer=kt(t.activityRegularizer),this.dilationRate=Ql(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new z(`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 z(`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 z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Qa("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!bb(e.kernelSize,"number",1,3))throw new z(`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:ss(this.activation),useBias:this.useBias,biasInitializer:Ct(this.biasInitializer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),biasConstraint:Wt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},lp=class extends ux{constructor(e,t){super(e,t);this.kernel=null,lp.verifyArgs(t),this.filters=t.filters,Kt(this.filters,"filters"),this.kernelInitializer=wt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Vt(t.kernelConstraint),this.kernelRegularizer=kt(t.kernelRegularizer)}build(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z(`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 D(()=>{e=Me(e);let n,a=this.bias==null?null:this.bias.read(),r=dk(this.activation.getClassName());if(r!=null&&this.rank===2)n=CI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=OW(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=CI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=LW(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new $e("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=ht(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r<n.length;++r){let s=Da(n[r],this.kernelSize[r],this.padding,this.strides[r],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[r]);t.push(s)}let a=[e[0]];return this.dataFormat==="channelsLast"?(a=a.concat(t),a.push(this.filters)):(a.push(this.filters),a=a.concat(t)),a}getConfig(){let e={filters:this.filters,kernelInitializer:Ct(this.kernelInitializer),kernelRegularizer:mt(this.kernelRegularizer),kernelConstraint:Wt(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},up=class extends lp{constructor(e){super(2,e);up.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!bb(e.kernelSize,"number",1,2))throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};up.className="Conv2D";re.registerClass(up);var xm=class extends lp{constructor(e){super(3,e);xm.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 z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};xm.className="Conv3D";re.registerClass(xm);var cx=class extends up{constructor(e){super(e);if(this.inputSpec=[new Xt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ht(e),e.length!==4)throw new z("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 z("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 Xt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{let n=Me(e);if(n.shape.length!==4)throw new z(`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],c=this.kernelSize[0],u=this.kernelSize[1],p=this.strides[0],d=this.strides[1],h=bm(o,p,c,this.padding),m=bm(l,d,u,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=Ue(n,[0,2,3,1]));let g=mh(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Ue(g,[0,3,1,2])),this.bias!=null&&(g=tr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=ht(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]=bm(t[a],o,s,this.padding),t[r]=bm(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};cx.className="Conv2DTranspose";re.registerClass(cx);var _I=class extends lp{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 z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new z("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 z(`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=wt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=kt(t.depthwiseRegularizer),this.depthwiseConstraint=Vt(t.depthwiseConstraint),this.pointwiseInitializer=wt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=kt(t.pointwiseRegularizer),this.pointwiseConstraint=Vt(t.pointwiseConstraint)}build(e){if(e=ht(e),e.length<this.rank+2)throw new z(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new z(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],a=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let i=0;i<this.rank;++i)r.push(1);r.push(n*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Xt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{e=Me(e);let n;if(this.rank===1)throw new $e("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ue(e,[0,2,3,1])),n=Fi(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=tr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Ue(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=Ct(this.depthwiseInitializer),e.pointwiseInitializer=Ct(this.pointwiseInitializer),e.depthwiseRegularizer=mt(this.depthwiseRegularizer),e.pointwiseRegularizer=mt(this.pointwiseRegularizer),e.depthwiseConstraint=Wt(this.depthwiseConstraint),e.pointwiseConstraint=Wt(this.pointwiseConstraint),e}};_I.className="SeparableConv";var px=class extends _I{constructor(e){super(2,e)}};px.className="SeparableConv2D";re.registerClass(px);var vm=class extends lp{constructor(e){super(1,e);vm.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"&&!bb(e.kernelSize,"number",1,1))throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};vm.className="Conv1D";re.registerClass(vm);var dx=class extends qe{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 D(()=>{if(e=Me(e),this.dataFormat==="channelsLast"){let n=Xh(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Xh(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Xh(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Xh(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};dx.className="Cropping2D";re.registerClass(dx);var hx=class extends qe{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,Dt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,sz(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 D(()=>{let n=Me(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=Ue(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 Ue(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}};hx.className="UpSampling2D";re.registerClass(hx);function zW(e,t,n=[1,1],a="valid",r,s){return D(()=>{r==null&&(r=_a()),Dt(r);let i=lx(e,r);if(e.rank!==4)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Yr(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=Ue(i,[0,3,1,2])),i})}var mx=class extends ux{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=wt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Vt(e.depthwiseConstraint),this.depthwiseRegularizer=kt(e.depthwiseRegularizer)}build(e){if(e=ht(e),e.length<4)throw new z(`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 z(`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 D(()=>{e=Me(e);let n=zW(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=tr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=ht(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=Da(t,this.kernelSize[0],this.padding,this.strides[0]),s=Da(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=Ct(this.depthwiseInitializer),e.depthwiseRegularizer=mt(this.depthwiseRegularizer),e.depthwiseConstraint=Wt(this.depthwiseRegularizer),e}};mx.className="DepthwiseConv2D";re.registerClass(mx);function EI(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new z("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 AI(e,t,n,a=!1,r,s,i=!1,o=!1){return D(()=>{let l=t.shape.length;if(l<3)throw new z(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(Aa(2,l));if(t=Ue(t,c),s!=null)throw new $e("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=$n(r,-1)),r=Ue(r,c)),a&&(t=Mn(t,0),r!=null&&(r=Mn(r,0)));let u=[],p,d=n,h=t.shape[0],m=dt(t),f;r!=null&&(f=dt(r));for(let y=0;y<h;++y){let b=m[y],v=D(()=>e(b,d));if(r==null)p=v[0],d=v[1];else{let x=D(()=>{let N=f[y],T=Rn(N).sub(N),C=v[0].mul(N).add(d[0].mul(T)),F=d.map(($,P)=>v[1][P].mul(N).add($.mul(T)));return{output:C,newStates:F}});p=x.output,d=x.newStates}o&&u.push(p)}let g;return o&&(g=$t(u,1)),[p,g,d]})}var nr=class extends qe{constructor(e){super(e);let t;if(e.cell==null)throw new z("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new wm({cells:e.cell}):t=e.cell,t.stateSize==null)throw new z("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 Xt({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 Aa(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Lb(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 D(()=>{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;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){let t=null;if(this.numConstants!=null)throw new $e("Constants support is not implemented in RNN yet.");Lb(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,a=e.slice(2);this.inputSpec[0]=new Xt({shape:[n,null,...a]});let r=[e[0]].concat(e.slice(2));if(t!=null)throw new $e("Constants support is not implemented in RNN yet.");this.cell.build(r);let s;if(Array.isArray(this.cell.stateSize)?s=this.cell.stateSize:s=[this.cell.stateSize],this.stateSpec!=null){if(!k.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),s))throw new z(`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 Xt({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new vr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>vt([n,a])):this.states_=[vt([n,this.cell.stateSize])];else if(e==null)Fe(this.states_),this.keptStates!=null&&(Fe(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>vt([n,a])):this.states_[0]=vt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`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()):Fe(this.states_);for(let a=0;a<this.states_.length;++a){let r=e[a],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[a]:this.cell.stateSize,i=[n,s];if(!k.arraysEqual(r.shape,i))throw new z(`State ${a} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${r.shape}`);this.states_[a]=r}}this.states_=this.states_.map(a=>jt(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=EI(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 Xt({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 Fa){let o=[e].concat(s),l=this.inputSpec.concat(i),c=this.inputSpec;this.inputSpec=l;let u=super.apply(o,t);return this.inputSpec=c,u}else return super.apply(e,t)}call(e,t){return D(()=>{let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;e=Me(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 z(`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=AI((d,h)=>{let m=this.cell.call([d].concat(h),i);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],c=o[1],u=o[2];this.stateful&&this.resetStates(u,a);let p=this.returnSequences?c:l;return this.returnState?[p].concat(u):p})}getInitialState(e){return D(()=>{let t=vt(e.shape);return t=Te(t,[1,2]),t=Qc(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Nb(t,[1,n]):t):this.cell.stateSize>1?[Nb(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()===nr.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let a=t.cell,r=$a(a,n);return new e(Object.assign(t,{cell:r}))}};nr.className="RNN";re.registerClass(nr);var np=class extends qe{},km=class extends np{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,Kt(this.units,"units"),this.activation=is(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=wt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=wt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=wt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=kt(e.kernelRegularizer),this.recurrentRegularizer=kt(e.recurrentRegularizer),this.biasRegularizer=kt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Kl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Kl([1,as([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ht(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 D(()=>{if(e=e,e.length!==2)throw new z(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=os({ones:()=>Rn(e),rate:this.dropout,training:a})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=os({ones:()=>Rn(n),rate:this.recurrentDropout,training:a}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=er(L(e,s),this.kernel.read()):r=er(e,this.kernel.read()),this.bias!=null&&(r=tr(r,this.bias.read())),i!=null&&(n=L(n,i));let o=Z(r,er(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:ss(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};km.className="SimpleRNNCell";re.registerClass(km);var fx=class extends nr{constructor(e){e.cell=new km(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Fe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Fe(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)}};fx.className="SimpleRNN";re.registerClass(fx);var Im=class extends np{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 z("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Kt(this.units,"units"),this.activation=is(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=is(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=wt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=wt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=wt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=kt(e.kernelRegularizer),this.recurrentRegularizer=kt(e.recurrentRegularizer),this.biasRegularizer=kt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Kl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Kl([1,as([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ht(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 D(()=>{if(e=e,e.length!==2)throw new z(`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<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=os({ones:()=>Rn(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=os({ones:()=>Rn(a),rate:this.recurrentDropout,training:n,count:3}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=L(e,r[0]));let c=er(e,this.kernel.read());this.useBias&&(c=tr(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,s[0]));let u=this.recurrentKernel.read(),[p,d]=Pn(u,[2*this.units,this.units],u.rank-1),h=er(a,p),[m,f,g]=Pn(c,3,c.rank-1),[y,b]=Pn(h,2,h.rank-1);i=this.recurrentActivation.apply(Z(m,y)),o=this.recurrentActivation.apply(Z(f,b));let v=er(L(o,a),d);l=this.activation.apply(Z(g,v));let x=Z(L(i,a),L(Z(1,Tt(i)),l));return[x,x]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ss(this.activation),recurrentActivation:ss(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Im.className="GRUCell";re.registerClass(Im);var gx=class extends nr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Im(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Fe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Fe(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)}};gx.className="GRU";re.registerClass(gx);var cp=class extends np{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,Kt(this.units,"units"),this.activation=is(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=is(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=wt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=wt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=wt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=kt(e.kernelRegularizer),this.recurrentRegularizer=kt(e.recurrentRegularizer),this.biasRegularizer=kt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Kl([1,as([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Kl([1,as([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=ht(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 ma{apply(i,o){let l=r.apply([s]),c=new Zh().apply([s]),u=r.apply([s*2]);return kk(kk(l,c),u)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return D(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=os({ones:()=>Rn(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=os({ones:()=>Rn(a),rate:this.recurrentDropout,training:n,count:4}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,c,u;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let p=er(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,i[0])),p=Z(p,er(a,this.recurrentKernel.read())),this.useBias&&(p=tr(p,this.bias.read()));let[d,h,m,f]=Pn(p,4,p.rank-1);o=this.recurrentActivation.apply(d),l=this.recurrentActivation.apply(h),c=Z(L(l,r),L(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);let g=L(u,this.activation.apply(c));return[g,g,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ss(this.activation),recurrentActivation:ss(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:mt(this.kernelRegularizer),recurrentRegularizer:mt(this.recurrentRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};cp.className="LSTMCell";re.registerClass(cp);var yx=class extends nr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new cp(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Fe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Fe(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)}};yx.className="LSTM";re.registerClass(yx);var wm=class extends np{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 D(()=>{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<this.cells.length;++i){let o=this.cells[i];n=a[i],i===0?s=[e[0]].concat(n):s=[s[0]].concat(n),s=o.call(s,t),r.push(s.slice(1))}n=[];for(let i of r.slice().reverse())n.push(...i);return[s[0]].concat(n)})}build(e){Lb(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,a)=>{Oi(`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 Object.assign({},e,n)}static fromConfig(e,t,n={}){let a=[];for(let r of t.cells)a.push($a(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 zb(e)}setWeights(e){let t=[];for(let n of this.cells){let a=n.weights.length,r=e.splice(a);for(let s=0;s<n.weights.length;++s)t.push([n.weights[s],r[s]])}Bb(t)}};wm.className="StackedRNNCells";re.registerClass(wm);function os(e){let{ones:t,rate:n,training:a=!1,count:r=1}=e,s=()=>Nk(t(),n),i=()=>tp(s,t,a);return!r||r<=1?jt(i().clone()):Array(r).fill(void 0).map(i).map(o=>jt(o.clone()))}var BW=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n},FI=class extends nr{constructor(e){if(e.unroll)throw new $e("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new $e("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Xt({ndim:5})]}call(e,t){return D(()=>{if(this.cell.dropoutMask!=null&&(Fe(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Fe(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new z("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 D(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=vt(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new vr("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 z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>vt(r)):this.states_=[vt(r)];else if(e==null)Fe(this.states_),this.keptStates!=null&&(Fe(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>vt(r)):this.states_[0]=vt(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`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()):Fe(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=r;if(!k.arraysEqual(i.shape,o))throw new z(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>jt(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],c=e[o?4:3],u=Da(l,a[0],r,s[0],i[0]),p=Da(c,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,u,p]:[u,p,n]]}};FI.className="ConvRNN2D";var Nm=class extends cp{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super(Object.assign({},e,{units:t}));this.filters=t,Kt(this.filters,"filters"),this.kernelSize=Ql(n,2,"kernelSize"),this.kernelSize.forEach(o=>Kt(o,"kernelSize")),this.strides=Ql(a||1,2,"strides"),this.strides.forEach(o=>Kt(o,"strides")),this.padding=r||"valid",Jn(this.padding),this.dataFormat=s||"channelsLast",Dt(this.dataFormat),this.dilationRate=Ql(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>Kt(o,"dilationRate"))}build(e){var t;e=ht(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new z(`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,c=this.filters;o=new(t=class extends ma{apply(u,p){let d=l.apply([c]),h=Ya([c]),m=l.apply([c*2]);return Sb([d,h,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 D(()=>{if(e.length!==3)throw new z(`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<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=os({ones:()=>Rn(a),rate:this.dropout,training:n,count:i}));let o=this.dropoutMask,l=(J,se,Q)=>!se||!se[Q]?J:L(se[Q],J),c=l(a,o,0),u=l(a,o,1),p=l(a,o,2),d=l(a,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=os({ones:()=>Rn(r),rate:this.recurrentDropout,training:n,count:i}));let h=this.recurrentDropoutMask,m=l(r,h,0),f=l(r,h,1),g=l(r,h,2),y=l(r,h,3),b=3,[v,x,N,T]=Pn(this.kernel.read(),i,b),[C,F,$,P]=this.useBias?Pn(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,v,C,this.padding),u=this.inputConv(u,x,F,this.padding),p=this.inputConv(p,N,$,this.padding),d=this.inputConv(d,T,P,this.padding);let[B,W,G,q]=Pn(this.recurrentKernel.read(),i,b);m=this.recurrentConv(m,B),f=this.recurrentConv(f,W),g=this.recurrentConv(g,G),y=this.recurrentConv(y,q);let j=this.recurrentActivation.apply(Z(c,m)),X=this.recurrentActivation.apply(Z(u,f)),K=Z(L(X,s),L(j,this.activation.apply(Z(p,g)))),ne=L(this.recurrentActivation.apply(Z(d,y)),this.activation.apply(K));return[ne,ne,K]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=BW(e,["units"]),a={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,a)}inputConv(e,t,n,a){let r=At(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?tr(r,n,this.dataFormat):r}recurrentConv(e,t){return At(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Nm.className="ConvLSTM2DCell";re.registerClass(Nm);var bx=class extends FI{constructor(e){let t=new Nm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};bx.className="ConvLSTM2D";re.registerClass(bx);var Tm=class extends qe{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.noiseShape.length;++a)n.push(this.noiseShape[a]==null?t[a]:this.noiseShape[a]);return n}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,r=this.getNoiseShape(n);return tp(()=>Nk(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()}};Tm.className="Dropout";re.registerClass(Tm);var xx=class extends Tm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};xx.className="SpatialDropout1D";re.registerClass(xx);var vx=class extends qe{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,Kt(this.units,"units"),this.activation=is(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=wt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=wt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Vt(e.kernelConstraint),this.biasConstraint=Vt(e.biasConstraint),this.kernelRegularizer=kt(e.kernelRegularizer),this.biasRegularizer=kt(e.biasRegularizer),this.activityRegularizer=kt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=ht(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=ht(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e),a=dk(this.activation.getClassName()),r;return a!=null?r=er(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=er(n,this.kernel.read()),this.bias!=null&&(r=tr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:ss(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:mt(this.kernelRegularizer),biasRegularizer:mt(this.biasRegularizer),activityRegularizer:mt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),biasConstraint:Wt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};vx.className="Dense";re.registerClass(vx);var wx=class extends qe{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=ht(e);for(let t of e.slice(1))if(t==null)throw new z(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ns(e,1)]}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r<n.rank;++r)a.push(r);a.push(1),n=n.transpose(a)}return pz(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};wx.className="Flatten";re.registerClass(wx);var kx=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.activation=is(e.activation)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);return this.activation.apply(n)})}getConfig(){let e={activation:ss(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};kx.className="Activation";re.registerClass(kx);var Ix=class extends qe{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 D(()=>(e=Me(e),uz(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Ix.className="RepeatVector";re.registerClass(Ix);var Nx=class extends qe{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",a=t.slice(),r=1,s=null;for(let o=0;o<a.length;++o){let l=a[o];if(this.isUnknown(l))if(s===null)s=o;else throw new z("Can only specifiy one unknown dimension.");else r*=l}let i=ns(e);if(s!==null){if(r===0||i%r!=0)throw new z(n);a[s]=i/r}else if(i!==r)throw new z(n);return a}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(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}};Nx.className="Reshape";re.registerClass(Nx);var Tx=class extends qe{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=Aa(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 Xt({ndim:this.dims.length+1})]}computeOutputShape(e){e=ht(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return Ue(Me(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Tx.className="Permute";re.registerClass(Tx);var Sx=class extends qe{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=Me(e),a=-1;return Rc(Ai(n,this.maskValue),a)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e),a=-1,r=!0,s=Rc(Ai(n,this.maskValue),a,r);return n.mul(s.asType(n.dtype))})}};Sx.className="Masking";re.registerClass(Sx);var Cx=class extends qe{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(yt(e.inputLength))}this.inputDim=e.inputDim,Kt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Kt(this.outputDim,"outputDim"),this.embeddingsInitializer=wt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=kt(e.embeddingsRegularizer),this.activityRegularizer=kt(e.activityRegularizer),this.embeddingsConstraint=Vt(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 D(()=>this.maskZero?(e=Me(e),Ai(e,Ge(e))):null)}computeOutputShape(e){if(e=ht(e),this.inputLength==null)return[...e,this.outputDim];let t=yt(this.inputLength);if(t.length!==e.length-1)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a<t.length;++a){let r=t[a],s=e[a+1];if(r!=null&&s!=null&&r!==s)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);r==null&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);return n.dtype!=="int32"&&(n=Jc(n,"int32")),Ik(this.embeddings.read(),n.as1D()).reshape(ht(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ct(this.embeddingsInitializer),embeddingsRegularizer:mt(this.embeddingsRegularizer),activityRegularizer:mt(this.activityRegularizer),embeddingsConstraint:Wt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Cx.className="Embedding";re.registerClass(Cx);var Vi=class extends qe{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new $e}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let a=0;a<t.length;++a){let r=e[e.length-t.length+a],s=t[a];if(r==null||s==null||r<0||s<0)n.push(null);else if(r===1)n.push(s);else if(s===1)n.push(r);else{if(r!==s)throw new z("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[ht(e)]),e=e,e.length<2)throw new z(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let r of e)r!=null&&r[0]!==null&&t.push(r[0]);if(t=ts(t),t.length>1)throw new z(`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;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}let a=e.map(r=>r.length);e.indexOf(null)===-1&&ts(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return D(()=>{if(e=e,this.reshapeRequired){let n=[],a=e.map(r=>r.rank);if(a.indexOf(null)===-1){let r=as(a);for(let s of e){let i=s.rank;for(let o=0;o<r-i;++o)s=Qc(s,1);n.push(s)}return this.mergeFunction(n)}else{let r=!1;for(let o of e){let l=o.rank;if(l==null){let c=o.shape,u=c[0],p=c.slice(1).concat([u]),d=o.reshape([u].concat(ns(c.slice(1))));d=Ue(d,[1,0]),d=d.reshape(p),n.push(d),r=!0}else if(l>1){let c=Aa(1,l).concat([0]);n.push(Ue(o,c)),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,c=o[l-1],u=[c].concat(o.slice(0,o.length-1));s=Ue(s.reshape([-1,c]),[1,0]).reshape(u)}else if(i>1){let o=[i-1].concat(Aa(0,i-1));s=Ue(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a<e.length;++a){let r=e[a]==null?null:e[a].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(let a of e)a!=null&&a[0]!==null&&n.push(a[0]);return n=ts(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return D(()=>{if(t==null)return null;if(!Array.isArray(t))throw new z("`mask` should be an Array");if(!Array.isArray(e))throw new z("`inputs` should be an Array");if(t.length!==e.length)throw new z(`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:$n(a,0));let n=t[0];for(let a=1;a<t.length-1;++a)n=da(n,t[a]);return n})}},_x=class extends Vi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Z(t,e[n]);return t})}};_x.className="Add";re.registerClass(_x);var Ex=class extends Vi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=L(t,e[n]);return t})}};Ex.className="Multiply";re.registerClass(Ex);var Ax=class extends Vi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Z(t,e[n]);return L(1/e.length,t)})}};Ax.className="Average";re.registerClass(Ax);var Fx=class extends Vi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Xa(t,e[n]);return t})}};Fx.className="Maximum";re.registerClass(Fx);var $x=class extends Vi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Wl(t,e[n]);return t})}};$x.className="Minimum";re.registerClass($x);var Dx=class extends Vi{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new z("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let a of e)if(a!=null){t=!1;break}if(t)return;let n=[];for(let a=0;a<e.length;++a){let r=e[a].slice();r.splice(this.axis,1);let s=!1;for(let i of n)if(k.arraysEqual(i,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return D(()=>Sb(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new z("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 z("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new z("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new z(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return D(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s<e.length;++s)t[s]==null?a.push(Rn(e[s]).asType("bool")):t[s].rank<e[s].rank?a.push($n(t[s],-1)):a.push(t[s]);let r=Qe(a,this.axis);return ph(r,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Dx.className="Concatenate";re.registerClass(Dx);function pp(e,t){for(;e<0;)e+=t;return e}function WW(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new $e("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 $e("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 D(()=>{let i;if(a>r){i=a-r;let l=[];for(let c=0;c<i;++c)l.push(1);t=t.reshape(t.shape.concat(l))}else if(r>a){i=r-a;let l=[];for(let c=0;c<i;++c)l.push(1);e=e.reshape(e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=e.mul(t).sum(s[0]):o=e.transpose([1,0]).mul(t).sum(s[1]);else{let l=s[0]!==e.shape.length-1,c=s[1]===t.shape.length-1;o=e.matMul(t,l,c)}if(i>0){let l;a>r?l=a+r-3:l=a-1;let c=[];for(let u=l;u<l+i;++u)c.push(u);o=o.squeeze(c)}return o.shape.length===1&&(o=o.expandDims(1)),o})}var Rx=class extends Vi{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(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],n=e[1];if(t.length>3||n.length>3)throw new $e("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 z(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new z(`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)=>pp(r,e[s].shape.length)):a=[pp(this.axes,t.shape.length),pp(this.axes,n.shape.length)],this.normalize&&(t=um(t,a[0]),n=um(n,a[1])),WW(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[pp(this.axes,e.length),pp(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 $e("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}};Rx.className="Dot";re.registerClass(Rx);var Mx=class extends qe{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 D(()=>{this.invokeCallHook(e,t);let n=Me(e);return tp(()=>Yh(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Mx.className="GaussianNoise";re.registerClass(Mx);var Px=class extends qe{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 D(()=>{this.invokeCallHook(e,t);let n=Me(e);return this.rate>0&&this.rate<1?tp(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return n.mul(Yh(n.shape,1,a))},()=>n,t.training||!1):n})}};Px.className="GaussianDropout";re.registerClass(Px);var Ox=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Me(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 D(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return tp(()=>{let a=Me(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=Jr(Vl(n),this.rate);o=Jc(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,c=-l*i*this.rate;return a.mul(o).add(o.add(-1).mul(i)).mul(l).add(c)},()=>Me(e),t.training||!1)}return e})}};Ox.className="AlphaDropout";re.registerClass(Ox);function dp(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=i1(e,t,n,a,r,s);else if(e.rank===3)i=o1(e,t,n,a,r,s);else if(e.rank===4)i=l1(e,t,n,a,r,s);else throw new $e(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function VW(e,t,n,a,r=.001){return D(()=>{let s=Ih(e,a),i=s.mean,o=s.variance;return[dp(e,i,o,n,t,r),i,o]})}function UW(e,t,n,a,r=.001){return D(()=>{let s=Ih(e,a),i=s.mean,o=s.variance,l=[];for(let h of Aa(0,e.rank))a.indexOf(h)!==-1?l.push(1):l.push(e.shape[h]);let c=i.reshape(l),u=o.reshape(l),p=t==null?null:t.reshape(l),d=n==null?null:n.reshape(l);return[dp(e,c,u,d,p,r),i,o]})}function GW(e,t,n,a,r=.001){return k.arraysEqual(a.slice().sort(),Aa(0,e.rank-1))?VW(e,t,n,a,r):UW(e,t,n,a,r)}var Lx=class extends qe{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=wt(e.betaInitializer||"zeros"),this.gammaInitializer=wt(e.gammaInitializer||"ones"),this.movingMeanInitializer=wt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=wt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Vt(e.betaConstraint),this.gammaConstraint=Vt(e.gammaConstraint),this.betaRegularizer=kt(e.betaRegularizer),this.gammaRegularizer=kt(e.gammaRegularizer)}build(e){e=ht(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new z(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Xt({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 D(()=>{let n=t.training==null?!1:t.training,a=Me(e),r=a.shape,s=r.length,i=Aa(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=Ri(1,s);l[o]=r[o];let c=i.slice();c.sort();let u=!k.arraysEqual(c,Aa(0,s).slice(0,s-1)),p=()=>{if(u){let g=this.movingMean.read().reshape(l),y=this.movingVariance.read().reshape(l),b=this.center?this.beta.read().reshape(l):null,v=this.scale?this.gamma.read().reshape(l):null;return dp(a,g,y,b,v,this.epsilon)}else return dp(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 p();let[d,h,m]=GW(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,y,b)=>{D(()=>{let v=1-b,x=g.read(),N=x.sub(y).mul(v);g.write(x.sub(N))})};return(()=>{f(this.movingMean,h,this.momentum),f(this.movingVariance,m,this.momentum)})(),d})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ct(this.betaInitializer),gammaInitializer:Ct(this.gammaInitializer),movingMeanInitializer:Ct(this.movingMeanInitializer),movingVarianceInitializer:Ct(this.movingVarianceInitializer),betaRegularizer:mt(this.betaRegularizer),gammaRegularizer:mt(this.gammaRegularizer),betaConstraint:Wt(this.betaConstraint),gammaConstraint:Wt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Lx.className="BatchNormalization";re.registerClass(Lx);var zx=class extends qe{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=wt(e.betaInitializer||"zeros"),this.gammaInitializer=wt(e.gammaInitializer||"ones"),this.betaRegularizer=kt(e.betaRegularizer),this.gammaRegularizer=kt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=ht(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r<this.axis.length;++r)this.axis[r]<0&&(this.axis[r]+=t);for(let r of this.axis)if(r<0||r>=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==ts(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=Me(e),a=n.shape,r=a.length;return D(()=>{let s=!0,{mean:i,variance:o}=Ih(n,this.axis,s),l=Ri(1,r);for(let m of this.axis)l[m]=a[m];let c=m=>m!=null&&m.shape.length!==r&&this.axis!==[r-1]?m.reshape(l):m,u=c(this.gamma.read()),p=c(this.beta.read()),d=[],h=[];for(let m=0;m<r;++m)this.axis.indexOf(m)!==-1?(d.push(a[m]),h.push(1)):(d.push(1),h.push(a[m]));return i=i.tile(d),o=o.tile(d),u=u.tile(h),p=p.tile(h),dp(n,i,o,p,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ct(this.betaInitializer),gammaInitializer:Ct(this.gammaInitializer),betaRegularizer:mt(this.betaRegularizer),gammaRegularizer:mt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};zx.className="LayerNormalization";re.registerClass(zx);function HW(e,t,n){return D(()=>{if(e.rank!==4)throw new z(`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 z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=_a()),n!=="channelsLast"&&n!=="channelsFirst")throw new z(`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]],Zn(e,a)})}var Bx=class extends qe{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?_a():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 z(`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 z(`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 z(`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 Xt({ndim:4})]}computeOutputShape(e){e=ht(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 D(()=>HW(Me(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Bx.className="ZeroPadding2D";re.registerClass(Bx);function Sm(e,t,n,a,r,s){return D(()=>{Dt(r),gk(s),Jn(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=_a()),s==null&&(s="max"),e=lx(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Ft(e,t,n,o):i=Xn(e,t,n,o),r==="channelsFirst"&&(i=Ue(i,[0,3,1,2])),i})}function $I(e,t,n,a,r,s){return D(()=>{Dt(r),gk(s),Jn(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=_a()),s==null&&(s="max"),e=SI(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Yy(e,t,n,o):i=Py(e,t,n,o),r==="channelsFirst"&&(i=Ue(i,[0,4,1,2,3])),i})}var DI=class extends qe{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 z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Kt(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 z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Jn(this.padding),this.inputSpec=[new Xt({ndim:3})]}computeOutputShape(e){e=ht(e);let t=Da(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return D(()=>{this.invokeCallHook(e,t),e=Qc(Me(e),2);let n=this.poolingFunction(Me(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Qr(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Wx=class extends DI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),Sm(e,t,n,a,r,"max")}};Wx.className="MaxPooling1D";re.registerClass(Wx);var Vx=class extends DI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),Sm(e,t,n,a,r,"avg")}};Vx.className="AveragePooling1D";re.registerClass(Vx);var RI=class extends qe{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 z(`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];Kt(this.poolSize,"poolSize"),Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),Jn(this.padding),this.inputSpec=[new Xt({ndim:4})]}computeOutputShape(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Da(t,this.poolSize[0],this.padding,this.strides[0]),n=Da(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 D(()=>(this.invokeCallHook(e,t),this.poolingFunction(Me(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}},Ux=class extends RI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),Sm(e,t,n,a,r,"max")}};Ux.className="MaxPooling2D";re.registerClass(Ux);var Gx=class extends RI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),Sm(e,t,n,a,r,"avg")}};Gx.className="AveragePooling2D";re.registerClass(Gx);var MI=class extends qe{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 z(`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];Kt(this.poolSize,"poolSize"),Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),Jn(this.padding),this.inputSpec=[new Xt({ndim:5})]}computeOutputShape(e){e=ht(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=Da(t,this.poolSize[0],this.padding,this.strides[0]),n=Da(n,this.poolSize[1],this.padding,this.strides[1]),a=Da(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 D(()=>(this.invokeCallHook(e,t),this.poolingFunction(Me(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}},Hx=class extends MI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),$I(e,t,n,a,r,"max")}};Hx.className="MaxPooling3D";re.registerClass(Hx);var jx=class extends MI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),Jn(a),$I(e,t,n,a,r,"avg")}};jx.className="AveragePooling3D";re.registerClass(jx);var PI=class extends qe{constructor(e){super(e);this.inputSpec=[new Xt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new $e}},qx=class extends PI{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Me(e);return St(n,1)})}};qx.className="GlobalAveragePooling1D";re.registerClass(qx);var Kx=class extends PI{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Me(e);return Yn(n,1)})}};Kx.className="GlobalMaxPooling1D";re.registerClass(Kx);var OI=class extends qe{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),this.inputSpec=[new Xt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new $e}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Xx=class extends OI{call(e,t){return D(()=>{let n=Me(e);return this.dataFormat==="channelsLast"?St(n,[1,2]):St(n,[2,3])})}};Xx.className="GlobalAveragePooling2D";re.registerClass(Xx);var Yx=class extends OI{call(e,t){return D(()=>{let n=Me(e);return this.dataFormat==="channelsLast"?Yn(n,[1,2]):Yn(n,[2,3])})}};Yx.className="GlobalMaxPooling2D";re.registerClass(Yx);var LI=class extends qe{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=$a(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},Zx=class extends LI{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=ht(e),e.length<3)throw new z(`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=ht(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 D(()=>(e=Me(e),AI((n,a)=>[Me(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Zx.className="TimeDistributed";re.registerClass(Zx);function jW(e){Pi(rz,"BidirectionalMergeMode",e)}var qW="concat",Jx=class extends LI{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=$a(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=$a(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?qW:e.mergeMode,jW(this.mergeMode),e.weights)throw new $e("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()):kn(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=EI(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 z("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 c=n.map(u=>new Xt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),i.push(...c)}if(a!=null)throw new $e("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Fa;for(let l of s)if(l instanceof Fa!==o)throw new z("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),c=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=c;let p=super.apply(l,t);return this.inputSpec=u,p}else return super.apply(e,t)}call(e,t){return D(()=>{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=Mn(r,1));let i;return this.mergeMode==="concat"?i=Sb([a,r]):this.mergeMode==="sum"?i=Z(a,r):this.mergeMode==="ave"?i=L(.5,Z(a,r)):this.mergeMode==="mul"?i=L(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){Oi(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Oi(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=$a(t.layer);if(delete t.layer,t.numConstants!=null)throw new $e("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};Jx.className="Bidirectional";re.registerClass(Jx);function vz(e){return new Xl(e)}function wz(e){return new sx(e)}function kz(e){return new nx(e)}function Iz(e){return new ax(e)}function Nz(e){return new rx(e)}function Tz(e){return new ox(e)}function Sz(e){return new ix(e)}function Cz(e){return new vm(e)}function _z(e){return new up(e)}function Ez(e){return new cx(e)}function Az(e){return new xm(e)}function Fz(e){return new px(e)}function $z(e){return new dx(e)}function Dz(e){return new hx(e)}function Rz(e){return new mx(e)}function Mz(e){return new kx(e)}function Pz(e){return new vx(e)}function Oz(e){return new Tm(e)}function Lz(e){return new xx(e)}function zz(e){return new wx(e)}function Bz(e){return new Ix(e)}function Wz(e){return new Nx(e)}function Vz(e){return new Tx(e)}function Uz(e){return new Cx(e)}function Gz(e){return new _x(e)}function Hz(e){return new Ax(e)}function jz(e){return new Dx(e)}function qz(e){return new Fx(e)}function Kz(e){return new $x(e)}function Xz(e){return new Ex(e)}function Yz(e){return new Rx(e)}function Zz(e){return new Lx(e)}function Jz(e){return new zx(e)}function Qz(e){return new Bx(e)}function Mb(e){return new Vx(e)}function eB(e){return Mb(e)}function tB(e){return Mb(e)}function Pb(e){return new Gx(e)}function nB(e){return Pb(e)}function aB(e){return Pb(e)}function Ob(e){return new jx(e)}function rB(e){return Ob(e)}function sB(e){return Ob(e)}function iB(e){return new qx(e)}function oB(e){return new Xx(e)}function Ek(e){return new Kx(e)}function Ak(e){return new Yx(e)}function Fk(e){return new Wx(e)}function $k(e){return new Ux(e)}function lB(e){return new Hx(e)}function uB(e){return new gx(e)}function cB(e){return new Im(e)}function pB(e){return new yx(e)}function dB(e){return new cp(e)}function hB(e){return new fx(e)}function mB(e){return new km(e)}function fB(e){return new bx(e)}function gB(e){return new Nm(e)}function yB(e){return new nr(e)}function bB(e){return new wm(e)}function xB(e){return new Jx(e)}function vB(e){return new Zx(e)}var wB=Ek,kB=Ak,IB=Fk,NB=$k;function TB(e){return new Mx(e)}function SB(e){return new Px(e)}function CB(e){return new Ox(e)}function _B(e){return new Sx(e)}var zI={};Oe(zI,{MAPE:()=>r4,MSE:()=>o4,binaryAccuracy:()=>KW,binaryCrossentropy:()=>XW,categoricalAccuracy:()=>ZW,categoricalCrossentropy:()=>JW,cosineProximity:()=>t4,mape:()=>s4,meanAbsoluteError:()=>n4,meanAbsolutePercentageError:()=>a4,meanSquaredError:()=>i4,mse:()=>l4,precision:()=>QW,recall:()=>e4,sparseCategoricalAccuracy:()=>YW});function KW(e,t){return Ub(e,t)}function XW(e,t){return qk(e,t)}function YW(e,t){return Kk(e,t)}function ZW(e,t){return Gb(e,t)}function JW(e,t){return Hb(e,t)}function QW(e,t){return jk(e,t)}function e4(e,t){return qB(e,t)}function t4(e,t){return Wb(e,t)}function n4(e,t){return cm(e,t)}function a4(e,t){return Zl(e,t)}function r4(e,t){return Zl(e,t)}function s4(e,t){return Zl(e,t)}function i4(e,t){return zi(e,t)}function o4(e,t){return zi(e,t)}function l4(e,t){return zi(e,t)}var BI={};Oe(BI,{modelFromJSON:()=>CW});var WI={};Oe(WI,{l1:()=>c4,l1l2:()=>u4,l2:()=>p4});function u4(e){return new op(e)}function c4(e){return MW(e)}function p4(e){return PW(e)}var VI=class extends Yl{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof kr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Cm(e,t){return e<t}function UI(e,t){return e>t}var GI=class extends VI{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new $e("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=Cm:this.mode==="max"?this.monitorFunc=UI:this.monitor.indexOf("acc")!==-1?this.monitorFunc=UI:this.monitorFunc=Cm,this.monitorFunc===Cm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Cm?Infinity:-Infinity}async onEpochEnd(e,t){await rs(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 d4(e){return new GI(e)}var h4={earlyStopping:d4},Ra;(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"})(Ra||(Ra={}));var HI;(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={}))})(HI||(HI={}));var Qx={};function m4(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Qx[e]=n}function jI(e){return Qx[e]}function f4(e){delete Qx[e]}function I(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 Nn(t.inputNames[s.inputIndexStart],n,a,r);if(s.type==="tensors")return t.inputNames.slice(o,l).map(p=>Nn(p,n,a,r));let c=Nn(t.inputNames.slice(o)[0],n,a,r),u=c.dataSync();return s.type==="number"?u[0]:k.toNestedArray(c.shape,u)}let i=t.attrParams[e];return i&&i.value}function Nn(e,t,n,a){let[r,s]=Ln(e);if(a!=null){let o=a.getHashTableHandleByName(r);if(o!=null)return o}let i=n.currentContextIds.find(o=>!!t[_m(r,o)]);return i!==void 0?t[_m(r,i)][s]:void 0}function g4(e,t,n){return t[_m(e,n.currentContextId)]}function Ir(e,t){let[n,a]=Ln(e);return[_m(n,t&&t.currentContextId),a]}function _m(e,t){return t?`${e}-${t}`:e}function Ln(e){let t=e.split(":");return t.length===1?[e,0]:[t[0],Number(t[t.length-1])]}function Em(e,t,n){let a=I("pad",e,t,n);if(a==="explicit"){a=I("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 Nr(e){return e.kept?e:qr(e)}var qI={};Oe(qI,{json:()=>y4});var y4=[{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}]}],KI={};Oe(KI,{json:()=>b4});var b4=[{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}]}],XI={};Oe(XI,{json:()=>x4});var x4=[{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"}]}],YI={};Oe(YI,{json:()=>v4});var v4=[{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"}]}],ZI={};Oe(ZI,{json:()=>w4});var w4=[{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"}]}],JI={};Oe(JI,{json:()=>k4});var k4=[{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}]}],QI={};Oe(QI,{json:()=>I4});var I4=[{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"}]}],eN={};Oe(eN,{json:()=>N4});var N4=[{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"}]}],tN={};Oe(tN,{json:()=>T4});var T4=[{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}]}],nN={};Oe(nN,{json:()=>S4});var S4=[{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"}]}],aN={};Oe(aN,{json:()=>C4});var C4=[{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}]}],rN={};Oe(rN,{json:()=>_4});var _4=[{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}]}],sN={};Oe(sN,{json:()=>E4});var E4=[{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}]}],iN={};Oe(iN,{json:()=>A4});var A4=[{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"}]}],oN={};Oe(oN,{json:()=>F4});var F4=[{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}]}],lN={};Oe(lN,{json:()=>$4});var $4=[{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}]}],uN={};Oe(uN,{json:()=>D4});var D4=[{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:[]}],pN=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[qI,KI,XI,YI,ZI,JI,QI,aN,nN,eN,rN,sN,iN,oN,lN,uN,tN],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=[],c={},u={};t!=null&&(c=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let p=Object.keys(i);p.forEach(m=>{let f=i[m];f.inputNames.forEach(g=>{let[y]=Ir(g);f.inputs.push(i[y]),i[y].children.push(f)})}),Object.keys(u).length===0?p.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(u).forEach(m=>{let[f]=Ir(m),g=i[f];g!=null&&(g.signatureKey=u[m],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(m=>{let[f]=Ir(m),g=i[f];g&&(g.signatureKey=c[m],o.push(g))}):o=a;let d={};e.library!=null&&e.library.function!=null&&(d=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let h={nodes:i,inputs:o,outputs:l,weights:r,placeholders:a,signature:t,functions:d};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=jI(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};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=ev(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=ev(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=lv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=lv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=nv(e.attr,r.tfName,r.defaultValue||0),i===void 0&&!!r.tfDeprecatedName&&(i=nv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=ov(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=ov(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=tv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=tv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=cv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=cv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=iv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=iv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=uv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=uv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=rv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=rv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=sv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=sv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=cN(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=cN(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((c,u)=>(c[u.name]=this.mapNode(u),u.op==="Const"&&a.push(c[u.name]),c),{}));let s=[],i=[];e.signature.inputArg.forEach(c=>{let[u]=Ir(c.name),p={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:av(c.type),type:"dtype"}},children:[]};p.signatureKey=c.name,s.push(p),r[u]=p}),Object.keys(r).forEach(c=>{let u=r[c];u.inputNames.forEach(p=>{let[d]=Ir(p);u.inputs.push(r[d]),r[d].children.push(u)})});let o=e.ret;e.signature.outputArg.forEach(c=>{let[u,p]=Ir(o[c.name]),d=r[u];d!=null&&(d.defaultOutput=p,i.push(d))});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 R4(e){let t=ee().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 dN(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):R4(e);return t?n:n.toLowerCase()}function ev(e,t,n,a=!1){let r=e[t];return r!=null?dN(r.s,a):n}function tv(e,t,n){let a=e[t];return a?a.b:n}function nv(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 av(e){switch(typeof e=="string"&&(e=Ra[e]),e){case Ra.DT_FLOAT:return"float32";case Ra.DT_INT32:case Ra.DT_INT64:case Ra.DT_INT8:case Ra.DT_UINT8:return"int32";case Ra.DT_BOOL:return"bool";case Ra.DT_DOUBLE:return"float32";case Ra.DT_STRING:return"string";default:return null}}function cN(e,t,n){let a=e[t];return a&&a.func?a.func.name:n}function rv(e,t,n){let a=e[t];return a&&a.type?av(a.type):n}function sv(e,t,n){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(r=>av(r)):n}function hN(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function iv(e,t,n){let a=e[t];return a&&a.shape?hN(a.shape):n}function ov(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 lv(e,t,n,a=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>dN(s,a)):n}function uv(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>hN(r)):n}function cv(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var M4=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 Nn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Nn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return nv(this.node.rawAttrs,e,t);if(n.s!=null)return ev(this.node.rawAttrs,e,t);if(n.b!=null)return tv(this.node.rawAttrs,e,t);if(n.shape!=null)return iv(this.node.rawAttrs,e,t);if(n.type!=null)return rv(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return ov(this.node.rawAttrs,e,t);if(n.list.s!=null)return lv(this.node.rawAttrs,e,t);if(n.list.shape!=null)return uv(this.node.rawAttrs,e,t);if(n.list.b!=null)return cv(this.node.rawAttrs,e,t);if(n.list.type!=null)return sv(this.node.rawAttrs,e,t)}return t}},P4=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[Z(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[n1(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[Jy(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[L(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[ve(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[Vy(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[ch(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[fe(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[Wl(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[Xa(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[yr(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[Dh(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},O4=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Lt(I("x",e,t,n))];case"Acos":return[Sy(I("x",e,t,n))];case"Acosh":return[Cy(I("x",e,t,n))];case"Asin":return[Ey(I("x",e,t,n))];case"Asinh":return[Ay(I("x",e,t,n))];case"Atan":return[Fy(I("x",e,t,n))];case"Atan2":return[$y(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[Dy(I("x",e,t,n))];case"Ceil":return[Oy(I("x",e,t,n))];case"Complex":return[Gr(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[zc(I("x",e,t,n))];case"Cosh":return[fh(I("x",e,t,n))];case"Elu":return[Ol(I("x",e,t,n))];case"Erf":return[Uy(I("x",e,t,n))];case"Exp":return[pn(I("x",e,t,n))];case"Expm1":return[Gy(I("x",e,t,n))];case"Floor":return[Ll(I("x",e,t,n))];case"Log":return[Dn(I("x",e,t,n))];case"Log1p":return[xh(I("x",e,t,n))];case"Imag":return[yh(I("x",e,t,n))];case"Neg":return[Tt(I("x",e,t,n))];case"Reciprocal":return[tb(I("x",e,t,n))];case"Real":return[Gc(I("x",e,t,n))];case"Relu":return[Ye(I("x",e,t,n))];case"Round":return[nb(I("x",e,t,n))];case"Selu":return[_h(I("x",e,t,n))];case"Sigmoid":return[ca(I("x",e,t,n))];case"Sin":return[Eh(I("x",e,t,n))];case"Sign":return[ab(I("x",e,t,n))];case"Sinh":return[Ah(I("x",e,t,n))];case"Softplus":return[zl(I("x",e,t,n))];case"Sqrt":return[en(I("x",e,t,n))];case"Square":return[lt(I("x",e,t,n))];case"Tanh":return[Pl(I("x",e,t,n))];case"Tan":return[ib(I("x",e,t,n))];case"ClipByValue":return[qt(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[Sh(I("x",e,t,n))];case"Rsqrt":return[Ch(Nn(e.inputNames[0],t,n))];case"Prod":return[Nh(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[Bc(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[Uc(I("x",e,t,n),I("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function ga(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;a<e.length;a++){let r=e[a],s=t[a];k.assert(r<0||s<0||r===s,()=>n+` Shapes ${e} and ${t} must match`)}}}function mN(e){return!(typeof e=="number"||e.some(t=>t<0))}function hp(e,t,n){let a=pv(e,n),r=!mN(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=pv(s.shape,a)}),!mN(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function pv(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<e.length;++a){let r=e[a],s=t[a];if(r>=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[a]=r>=0?r:s}return n}var L4=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=de(0),jt(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),ga(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,jt(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.size();a++)e.push(a)}if(e.length===0)return qn([],[0].concat(this.elementShape));let n=this.readMany(e);return ga(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),$t(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return qn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return ga(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Qe(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,dt(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=[];D(()=>{t=H(t,[1,n,r]);for(let o=0;o<e.length;++o){let l=o===0?0:a[o-1],c=[0,l,0],u=[1,e[o],r];s[o]=H(We(t,c,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},mp=class{constructor(e,t,n,a=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(r=>{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);ga(t,r.shape,"TensorList shape mismatch: "),jt(r)}),this.idTensor=de(0),this.maxNumElements=a,jt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new mp([...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.`);ga(e,this.elementShape,"TensorList shape mismatch: ");let a=hp(this.elementShape,this.tensors,e);return D(()=>{let r=this.tensors.map(s=>H(s,a));return $t(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=hp(this.elementShape,this.tensors,e),a=this.tensors.pop();return ga(a.shape,e,"TensorList shape mismatch: "),H(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(ga(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");jt(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.`);ga(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=hp(this.elementShape,this.tensors,t);return H(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.`);ga(this.elementShape,t.shape,"TensorList shape mismatch: "),jt(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}`);ga(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=hp(this.elementShape,this.tensors,n);return e.length===0?qn([],[0].concat(a)):D(()=>{let r=e.map(s=>H(this.tensors[s],a));return $t(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);ga(this.elementShape,t,"TensorList shape mismatch: ");let n=hp(this.elementShape,this.tensors,t);return this.size()===0?qn([],[0].concat(n)):D(()=>{let a=this.tensors.map(r=>H(r,n));return Qe(a,0)})}};function z4(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);ga(r,t,"TensorList shape mismatch: ");let s=dt(e);return new mp(s,t,a)}function B4(e,t,n){return new mp([],e,t,n)}function W4(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 mp([],n,e.dtype,a),i=dt(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function V4(e,t,n){let a=0,r=t.map(u=>(a+=u,a));if(a!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${a}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=pv(s,n),o=a===0?0:e.size/a,l=D(()=>{let u=[];e=H(e,[1,a,o]);for(let p=0;p<t.length;++p){let d=p===0?0:r[p-1],h=[0,d,0],m=[1,t[p],o];u[p]=H(We(e,h,m),i)}return e.dispose(),u}),c=new mp([],n,e.dtype,t.length);for(let u=0;u<l.length;u++)c.setItem(u,l[u]);return c}var U4=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),s=I("cond",e,t,n),i=I("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=I("body",e,t,n),r=I("cond",e,t,n),s=I("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(u=>u.id),l=await i[0].data();i.forEach(u=>{!u.kept&&o.indexOf(u.id)===-1&&u.dispose()});let c=s;for(;l[0];){let u=c;c=await n.functionMap[a].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let p=c.map(h=>h.id);u.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()});let d=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await d[0].data(),d.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let a=I("pred",e,t,n);return[Nr(a)]}case"Switch":{let a=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=Nr(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>Nn(r,t,n)!==void 0);if(a){let r=Nn(a,t,n);return[Nr(r)]}return}case"Enter":{let a=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(a),[Nr(r)]}case"Exit":{let a=I("tensor",e,t,n);return n.exitFrame(),[Nr(a)]}case"NextIteration":{let a=I("tensor",e,t,n);return n.nextIteration(),[Nr(a)]}case"TensorArrayV3":{let a=I("size",e,t,n),r=I("dtype",e,t,n),s=I("elementShape",e,t,n),i=I("dynamicSize",e,t,n),o=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),c=I("name",e,t,n),u=new L4(c,r,a,s,l,i,o);return n.addTensorArray(u),[u.idTensor,de(1)]}case"TensorArrayWriteV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=I("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),s=I("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[de(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=I("indices",e,t,n),r=I("tensor",e,t,n),s=I("elementShape",e,t,n),i=I("numElements",e,t,n),o=W4(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=I("elementShape",e,t,n),r=I("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=I(s,e,t,n),o=B4(a,r,i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=I("tensorListId",e,t,n),r=I("indices",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}case"TensorListStack":{let a=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),s=I("elementDType",e,t,n),i=I("numElements",e,t,n);return[n.getTensorList(a.id).stack(r,s,i)]}case"TensorListFromTensor":{let a=I("tensor",e,t,n),r=I("elementShape",e,t,n),s=I("elementDType",e,t,n),i=z4(a,r,s);return n.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let a=I("tensorListId",e,t,n),r=n.getTensorList(a.id),s=I("dtype",e,t,n),i=I("elementShape",e,t,n);return[r.concat(s,i)]}case"TensorListPushBack":{let a=I("tensorListId",e,t,n),r=I("tensor",e,t,n),s=n.getTensorList(a.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let a=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),s=I("elementDType",e,t,n);return[n.getTensorList(a.id).popBack(r,s)]}case"TensorListSplit":{let a=I("tensor",e,t,n),r=I("elementShape",e,t,n),s=I("lengths",e,t,n),i=V4(a,s,r);return n.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function fN(e,t,n){let[a,r]=I("fusedOps",e,t,n),s=a==="biasadd",i=r==="prelu",o=a==="fusedbatchnorm",l=I("numArgs",e,t,n);if(s){if(i&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(o)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");let c=I("strides",e,t,n),u=Em(e,t,n),p=I("dataFormat",e,t,n).toUpperCase(),d=I("dilations",e,t,n),[h,m]=I("args",e,t,n),f=I("leakyreluAlpha",e,t,n);return{stride:c,pad:u,dataFormat:p,dilations:d,biasArg:h,preluArg:m,activationFunc:r,leakyreluAlpha:f}}var G4=(e,t,n)=>{switch(e.op){case"Conv1D":{let a=I("stride",e,t,n),r=I("pad",e,t,n),s=I("dataFormat",e,t,n).toUpperCase(),i=I("dilation",e,t,n);return[hh(I("x",e,t,n),I("filter",e,t,n),a,r,s,i)]}case"Conv2D":{let a=I("strides",e,t,n),r=Em(e,t,n),s=I("dataFormat",e,t,n).toUpperCase(),i=I("dilations",e,t,n);return[At(I("x",e,t,n),I("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:c,leakyreluAlpha:u}=fN(e,t,n);return[es.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[a[1],a[2]],pad:r,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:a,pad:r,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:c,leakyreluAlpha:u}=fN(e,t,n);return[es.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[a[1],a[2]],pad:r,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let a=I("outputShape",e,t,n),r=I("strides",e,t,n),s=Em(e,t,n);return[mh(I("x",e,t,n),I("filter",e,t,n),a,[r[1],r[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let a=I("strides",e,t,n),r=Em(e,t,n),s=I("dilations",e,t,n),i=I("dataFormat",e,t,n).toUpperCase();return[Yr(I("input",e,t,n),I("filter",e,t,n),[a[1],a[2]],r,i,[s[1],s[2]])]}case"Conv3D":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("dataFormat",e,t,n).toUpperCase(),i=I("dilations",e,t,n);return[zy(I("x",e,t,n),I("filter",e,t,n),[a[1],a[2],a[3]],r,s,[i[1],i[2],i[3]])]}case"AvgPool":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("kernelSize",e,t,n);return[Xn(I("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPool":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("kernelSize",e,t,n);return[Ft(I("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPoolWithArgmax":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("kernelSize",e,t,n),i=I("includeBatchInIndex",e,t,n),{result:o,indexes:l}=C1(I("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r,i);return[o,l]}case"AvgPool3D":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("kernelSize",e,t,n);return[Py(I("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"MaxPool3D":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("kernelSize",e,t,n);return[Yy(I("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"Dilation2D":{let a=I("strides",e,t,n),r=I("pad",e,t,n),s=I("dilations",e,t,n),i=a[1],o=a[2],l=s[1],c=s[2];return[Wy(I("x",e,t,n),I("filter",e,t,n),[i,o],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},H4=(e,t,n)=>{switch(e.op){case"Fill":{let a=I("shape",e,t,n),r=I("dtype",e,t,n),s=I("value",e,t,n);return[wn(a,s,r)]}case"LinSpace":{let a=I("start",e,t,n),r=I("stop",e,t,n),s=I("num",e,t,n);return[v1(a,r,s)]}case"Multinomial":{let a=I("logits",e,t,n),r=I("numSamples",e,t,n),s=I("seed",e,t,n);return[_1(a,r,s)]}case"OneHot":{let a=I("indices",e,t,n),r=I("depth",e,t,n),s=I("onValue",e,t,n),i=I("offValue",e,t,n);return[Dl(a,r,s,i)]}case"Ones":return[Ya(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[Rn(I("x",e,t,n))];case"RandomUniform":return[Vl(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let a=I("start",e,t,n),r=I("stop",e,t,n),s=I("step",e,t,n);return[Th(a,r,s,I("dtype",e,t,n))]}case"TruncatedNormal":{let a=I("shape",e,t,n),r=I("mean",e,t,n),s=I("stdDev",e,t,n),i=I("seed",e,t,n);return[Rh(a,r,s,I("dtype",e,t,n),i)]}case"Zeros":return[vt(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[Ge(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function dv(e,t,n){let a=I("boxes",e,t,n),r=I("scores",e,t,n),s=I("maxOutputSize",e,t,n),i=I("iouThreshold",e,t,n),o=I("scoreThreshold",e,t,n),l=I("softNmsSigma",e,t,n);return{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var j4=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=dv(e,t,n),c=await Za.nonMaxSuppressionWithScoreAsync(a,r,s,i,o,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=dv(e,t,n),l=I("padToMaxOutputSize",e,t,n),c=await Za.nonMaxSuppressionPaddedAsync(a,r,s,i,o,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=dv(e,t,n);return[await Za.nonMaxSuppressionAsync(a,r,s,i,o)]}case"Where":{let a=ce(I("condition",e,t,n),"bool"),r=[await ub(a)];return a.dispose(),r}case"ListDiff":return F1(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},q4=(e,t,n)=>{switch(e.op){case"TopKV2":{let a=I("x",e,t,n),r=I("k",e,t,n),s=I("sorted",e,t,n),i=ob(a,r,s);return[i.values,i.indices]}case"Unique":{let a=I("x",e,t,n),r=Mh(a);return[r.values,r.indices]}case"UniqueV2":{let a=I("x",e,t,n),r=I("axis",e,t,n),s=Mh(a,r);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},K4=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=I("default",e,t,n);return[Nn(e.name,t,n)||a];case"Placeholder":return[Nn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[Nr(c)]}case"IdentityN":return I("x",e,t,n).map(c=>Nr(c));case"Snapshot":let r=I("x",e,t,n);return[Nr(r)];case"Shape":return[tt(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>tt(c.shape));case"Size":return[de(I("x",e,t,n).size,"int32")];case"Rank":return[de(I("x",e,t,n).rank,"int32")];case"NoOp":return[de(1)];case"Print":let s=I("x",e,t,n),i=I("data",e,t,n),o=I("message",e,t,n),l=I("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 c=0;c<i.length;c++)console.log(Array.prototype.slice.call(i[c].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}},X4=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=de(0),this.tensorMap=new Map,jt(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),D(()=>{let a=dt(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<r;i++){let o=n[i],l=a[i];jt(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return D(()=>{let a=[];for(let r=0;r<n.length;r++){let s=n[r],i=this.findWithDefault(s,t);a.push(i)}return $t(a)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},Y4=async(e,t,n,a)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=I("keyDType",e,t,n),s=I("valueDType",e,t,n),i=new X4(r,s);return a.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=I("tableHandle",e,t,n,a),s=I("keys",e,t,n),i=I("values",e,t,n);return[await a.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=I("tableHandle",e,t,n,a),s=I("keys",e,t,n),i=I("defaultValue",e,t,n);return[await a.getHashTableById(r.id).find(s,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Z4=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let a=I("images",e,t,n),r=I("size",e,t,n),s=I("alignCorners",e,t,n),i=I("halfPixelCenters",e,t,n);return[Za.resizeBilinear(a,[r[0],r[1]],s,i)]}case"ResizeNearestNeighbor":{let a=I("images",e,t,n),r=I("size",e,t,n),s=I("alignCorners",e,t,n),i=I("halfPixelCenters",e,t,n);return[Za.resizeNearestNeighbor(a,[r[0],r[1]],s,i)]}case"CropAndResize":{let a=I("image",e,t,n),r=I("boxes",e,t,n),s=I("boxInd",e,t,n),i=I("cropSize",e,t,n),o=I("method",e,t,n),l=I("extrapolationValue",e,t,n);return[Za.cropAndResize(a,r,s,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},J4=(e,t,n)=>{switch(e.op){case"Equal":return[Zr(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[Ai(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[pa(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[Jr(I("a",e,t,n),I("b",e,t,n))];case"Less":return[bh(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[_i(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[da(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Wc(I("a",e,t,n))];case"LogicalOr":return[kh(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[vn(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Q4=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[ze(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Transpose":return[Ue(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[a,r]=I("fusedOps",e,t,n),s=a==="biasadd",i=r==="prelu",o=I("numArgs",e,t,n),l=I("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[c,u]=I("args",e,t,n);return[es.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},eV=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[gr(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[gr(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[jy(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[Ta(I("x",e,t,n))];case"LogSoftmax":return[wh(I("x",e,t,n))];case"SparseToDense":return[cb(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},tV=(e,t,n)=>{switch(e.op){case"Max":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Yn(I("x",e,t,n),i,o)]}case"Mean":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[St(I("x",e,t,n),i,o)]}case"Min":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Bl(I("x",e,t,n),i,o)]}case"Sum":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Te(I("x",e,t,n),i,o)]}case"All":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[ph(I("x",e,t,n),i,o)]}case"Any":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Rc(I("x",e,t,n),i,o)]}case"ArgMax":{let i=I("axis",e,t,n);return[Mc(I("x",e,t,n),i)]}case"ArgMin":{let i=I("axis",e,t,n);return[_y(I("x",e,t,n),i)]}case"Prod":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Nh(I("x",e,t,n),i,o)]}case"Cumsum":{let i=I("axis",e,t,n),o=I("exclusive",e,t,n),l=I("reverse",e,t,n);return[gh(I("x",e,t,n),i,o,l)]}case"Bincount":let a=I("x",e,t,n),r=I("weights",e,t,n),s=I("size",e,t,n);return[u1(a,r,s)];case"DenseBincount":{let i=I("x",e,t,n),o=I("weights",e,t,n),l=I("size",e,t,n),c=I("binaryOutput",e,t,n);return[f1(i,o,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},nV=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let a=I("n",e,t,n),r=I("axis",e,t,n),s=I("tensors",e,t,n);return s=s.slice(0,a),[Qe(s,r)]}case"Gather":{let a=I("x",e,t,n),r=I("indices",e,t,n);return[Ci(a,ce(r,"int32"),0)]}case"GatherV2":{let a=I("axis",e,t,n),r=I("batchDims",e,t,n),s=I("x",e,t,n),i=I("indices",e,t,n);return[Ci(s,ce(i,"int32"),a,r)]}case"Reverse":{let a=I("dims",e,t,n),r=[];for(let i=0;i<a.length;i++)a[i]&&r.push(i);let s=I("x",e,t,n);return[Mn(s,r)]}case"ReverseV2":{let a=I("axis",e,t,n),r=I("x",e,t,n);return[Mn(r,a)]}case"Slice":{let a=I("begin",e,t,n),r=I("size",e,t,n);return[We(I("x",e,t,n),a,r)]}case"StridedSlice":{let a=I("begin",e,t,n),r=I("end",e,t,n),s=I("strides",e,t,n),i=I("beginMask",e,t,n),o=I("endMask",e,t,n),l=I("ellipsisMask",e,t,n),c=I("newAxisMask",e,t,n),u=I("shrinkAxisMask",e,t,n),p=I("x",e,t,n);return[sb(p,a,r,s,i,o,l,c,u)]}case"Pack":return D(()=>{let a=I("axis",e,t,n),r=I("tensors",e,t,n),s=r[0].shape,i=Qr(r[0]).shape,o=r.map(l=>{let c=k.arraysEqual(l.shape,s);if(!c&&!k.arraysEqual(Qr(l).shape,i))throw new Error("the input tensors shape does not match");return c?l:H(l,s)});return[$t(o,a)]});case"Unpack":{let a=I("axis",e,t,n),r=I("tensor",e,t,n);return dt(r,a)}case"Tile":{let a=I("reps",e,t,n);return[qa(I("x",e,t,n),a)]}case"Split":case"SplitV":{let a=I("axis",e,t,n),r=I("numOrSizeSplits",e,t,n),s=I("x",e,t,n);return Pn(s,r,a)}case"ScatterNd":{let a=I("indices",e,t,n),r=I("values",e,t,n),s=I("shape",e,t,n);return[M1(a,r,s)]}case"GatherNd":{let a=I("x",e,t,n),r=I("indices",e,t,n);return[P1(a,r)]}case"SparseToDense":{let a=I("sparseIndices",e,t,n),r=I("outputShape",e,t,n),s=I("sparseValues",e,t,n),i=I("defaultValue",e,t,n);return[cb(a,s,r,s.dtype===i.dtype?i:ce(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},aV=(e,t,n)=>{switch(e.op){case"FFT":return[jc(I("x",e,t,n))];case"IFFT":return[Gl(I("x",e,t,n))];case"RFFT":return[qc(I("x",e,t,n))];case"IRFFT":return[$h(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},rV=(e,t,n)=>{switch(e.op){case"Cast":return[ce(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let a=I("axis",e,t,n);return[$n(I("x",e,t,n),a)]}case"Squeeze":{let a=I("axis",e,t,n);return[Qr(I("x",e,t,n),a)]}case"Reshape":return[H(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[Zy(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[Zn(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let a=I("blockShape",e,t,n),r=I("paddings",e,t,n);return[Vc(I("x",e,t,n),a,r)]}case"BatchToSpaceND":{let a=I("blockShape",e,t,n),r=I("crops",e,t,n);return[Oc(I("x",e,t,n),a,r)]}case"DepthToSpace":{let a=I("blockSize",e,t,n),r=I("dataFormat",e,t,n).toUpperCase();return[By(I("x",e,t,n),a,r)]}case"BroadcastTo":return[Lc(I("x",e,t,n),I("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function gN(e,t,n,a){let r=((s,i,o)=>{switch(s.category){case"arithmetic":return D(()=>P4(s,i,o));case"basic_math":return D(()=>O4(s,i,o));case"control":return U4(s,i,o);case"convolution":return D(()=>G4(s,i,o));case"creation":return D(()=>H4(s,i,o));case"dynamic":return j4(s,i,o);case"evaluation":return D(()=>q4(s,i,o));case"image":return D(()=>Z4(s,i,o));case"graph":return D(()=>K4(s,i,o));case"logical":return D(()=>J4(s,i,o));case"matrices":return D(()=>Q4(s,i,o));case"normalization":return D(()=>eV(s,i,o));case"reduction":return D(()=>tV(s,i,o));case"slice_join":return D(()=>nV(s,i,o));case"spectral":return D(()=>aV(s,i,o));case"transformation":return D(()=>rV(s,i,o));case"hash_table":return Y4(s,i,o,a);case"custom":let l=jI(s.op);if(l&&l.customExecutor)return l.customExecutor(new M4(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 yN=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;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function xN(e,t,n,a){let r=new Set,s=[],i=null,o=null,l=new Set,c=Object.keys(e).map(d=>Ln(d)[0]),u=[];a!=null&&(u=a.map(d=>Ln(d.name)[0]));let p=[...t];for(;p.length>0;){let d=p.pop();if((bN(d)||sV(d)||iV(d))&&i==null&&(i=d,o=i.children.map(h=>h.name).filter(h=>r.has(h))),r.add(d.name),n[d.name]==null&&c.indexOf(d.name)===-1&&u.indexOf(d.name)===-1){if(d.inputs.length===0){s.push(d.name);continue}d.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),p.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:s,dynamicNode:i,syncInputs:o}}function oV(e,t,n){let{usedNodes:a,inputs:r}=n,s=[],i=Object.keys(r).map(u=>Ln(u)[0]).map(u=>e.nodes[u]),o=e.initNodes;i.forEach(u=>{a.has(u.name)&&s.push(u)}),e.weights.forEach(u=>{a.has(u.name)&&s.push(u)}),o!=null&&o.forEach(u=>{a.has(u.name)&&s.push(u)});let l=new Set,c=[];for(;s.length>0;){let u=s.pop();l.add(u.name),t[u.name]||c.push(u),u.children.forEach(p=>{!l.has(p.name)&&a.has(p.name)&&p.inputs.every(d=>l.has(d.name))&&s.push(p)})}return c}var lV=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],uV=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],cV=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function bN(e){return lV.indexOf(e.op)>=0}function sV(e){return uV.indexOf(e.op)>=0}function iV(e){return cV.indexOf(e.op)>=0}var hv=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 hv(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=xN(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 oV(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(u=>this.graph.nodes[Ln(u)[0]]),r=t.map(u=>Ln(u)[0]),s=r.map(u=>this.graph.nodes[u]);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={},c={};return D(()=>{let u=new yN(this.weightMap,l,c,this.functionExecutorMap),p=Object.assign({},this.weightMap);Object.keys(e).forEach(m=>{let[f,g]=Ln(m),y=[];y[g]=e[m],p[f]=y});let d=this.getFrozenTensorIds(p),h={};for(let m=0;m<o.length;m++){let f=o[m];if(!p[f.name]){let g=gN(f,p,u,this._resourceManager);if(k.isPromise(g))throw new Error(`The execution of the op '${f.op}' returned a promise. Please use model.executeAsync() instead.`);p[f.name]=g,this.checkTensorForDisposal(f.name,f,p,u,d,r,h)}}return this.parent==null&&u.dispose(d),t.map(m=>Nn(m,p,u))})}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=g4(o.name,n,a);l!=null&&l.forEach(c=>{if(c&&!r.has(c.id)){let u=i[c.id];u===1?(c.dispose(),delete i[c.id]):u!=null&&i[c.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 yN(this.weightMap,a,r,this.functionExecutorMap),i=await this.executeWithControlFlow(e,s,t,n),o=t.map(p=>Nn(p,i,s)),l=o.map(p=>p.id),c=Object.keys(e).map(p=>e[p].id),u=new Set([...l,...c,...this.weightIds]);return Object.keys(i).forEach(p=>{i[p].forEach(d=>{d&&!d.isDisposed&&!u.has(d.id)&&d.dispose()})}),this.parent==null&&s.dispose(u),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(b=>this.graph.nodes[Ln(b)[0]]),i=n.map(b=>Ln(b)[0]),o=i.map(b=>this.graph.nodes[b]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:c,dynamicNode:u,syncInputs:p}=xN(e,o,this.weightMap,this._initNodes),d=[...s,...this.graph.weights,...this._initNodes||[]].map(b=>({node:b,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(b=>{let[v,x]=Ln(b),N=[];N[x]=e[b],h[v]=N});let m={},f=this.getFrozenTensorIds(h),g={};for(;d.length>0;){let b=this.processStack(s,d,t,h,g,f,i,m,l);await Promise.all(b)}u==null&&!a&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=o.filter(b=>!bN(b)&&!Nn(b.name,h,t)).map(b=>b.name);if(y.length>0){let b="";throw u!=null&&(b=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${b}`)}return h}processStack(e,t,n,a,r,s,i,o,l){let c=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let p="";if(u.node.op==="Enter"&&I("isConstant",u.node,a,n)&&([p]=Ir(u.node.name,n)),a[u.node.name]==null){let d=gN(u.node,a,n,this._resourceManager);p||([p]=Ir(u.node.name,n));let h=n.currentContext;k.isPromise(d)?c.push(d.then(m=>(a[p]=m,n.currentContext=h,this.checkTensorForDisposal(p,u.node,a,n,s,i,o),this.processChildNodes(u.node,t,n,a,r,l),m))):(a[p]=d,this.checkTensorForDisposal(p,u.node,a,n,s,i,o),this.processChildNodes(u.node,t,n,a,r,l))}else this.processChildNodes(u.node,t,n,a,r,l)}return c}processChildNodes(e,t,n,a,r,s){e.children.forEach(i=>{let[o]=Ir(i.name,n);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Nn(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(l=>!!Nn(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]=Ln(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]=Ln(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]=Ln(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},pV=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]}},dV="?tfjs-format=file",hV="model.json",vN=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new pV}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=Ht.browserHTTPRequest(e,this.loadOptions);else{let t=Ht.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Ht.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=Ht.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new hv(pN.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=pN.Instance.transformGraph(e.modelInitializer);this.initializer=new hv(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=Ht.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 Ae)&&!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 mV(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}${hV}${dV}`);let n=new vN(e,t);return await n.load(),n}var wN="3.1.0",kN={};Oe(kN,{CSVDataset:()=>NN,Dataset:()=>eu,FileDataSource:()=>TN,TextLineDataset:()=>IN,URLDataSource:()=>SN,array:()=>fV,csv:()=>yV,func:()=>bV,generator:()=>xV,microphone:()=>wV,version_data:()=>CN,webcam:()=>vV,zip:()=>gV});var kV=So(fd()),IV=So(fd());function NV(e,t){return Am(e,t)}function Am(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(tu(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=Am(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 TV(e,t=EN){return _N(e,t)}function _N(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(tu(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(c=>c[i]),l=_N(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 EN(e){return e===null?null:tu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function AN(e,t){let n=new Map;Am(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 Am(e,t,n)}function tu(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ae))}function CV(e){return e==null||SV(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ae||k.isTypedArray(e)}function SV(e){return e===null||typeof e!="object"&&typeof e!="function"}function EV(e){return NV(e,_V)}function _V(e){return e instanceof Ae?{value:e.clone(),recurse:!1}:tu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var FN=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}},mv=class extends FN{constructor(){super(mv.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;a<n;a++)t[a]=this.get(this.wrap(this.begin+a));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};mv.INITIAL_CAPACITY=32;function $N(e){return new AV(e)}function fv(e){return new FV(e)}function $V(e,t){return new DN(e,t)}function RV(e,t=ls.FAIL){return new DV(e,t)}var Yt=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new WV(this,e)}filter(e){return new zV(this,e)}map(e){return new BV(this,e)}mapAsync(e){return new RN(this,e)}serialMapAsync(e){return new RN(this,e).serial()}flatmap(e){return new VV(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new LV(this,e,t)}columnMajorBatch(e,t=!0,n=EN){return this.rowMajorBatch(e,t).map(a=>TV(a,n))}concatenate(e,t){return new DN($N([this,e]),t)}take(e){return e<0||e==null?this:new OV(this,e)}skip(e){return e<0||e==null?this:new PV(this,e)}prefetch(e){return new MN(this,e)}shuffle(e,t){return new UV(this,e,t)}serial(){return new MV(this)}},AV=class extends Yt{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:EV(e),done:!1}}},FV=class extends Yt{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}}},MV=class extends Yt{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()}},PV=class extends Yt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;Fe(e.value)}return this.upstream.next()}},OV=class extends Yt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},LV=class extends Yt{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},zV=class extends Yt{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;Fe(e.value)}}},BV=class extends Yt{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=Na.getTensorsInContainer(e.value),n=this.transform(e.value),a=Na.getTensorsInContainer(n);for(let r of t)Na.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},WV=class extends Yt{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}}}},RN=class extends Yt{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=Na.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Na.getTensorsInContainer(n);for(let r of t)Na.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},gv=class extends Yt{constructor(){super();this.outputQueue=new mv,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}}},VV=class extends gv{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=Na.getTensorsInContainer(e.value),n=this.transform(e.value),a=Na.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Na.isTensorInList(r,a)||r.dispose();return!0}},DN=class extends Yt{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}},ls;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(ls||(ls={}));var DV=class extends Yt{constructor(e,t=ls.FAIL){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 Yt?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await AN(this.iterators,a);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case ls.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case ls.SHORTEST:return{value:null,done:!0};case ls.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},MN=class extends Yt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new FN(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()}},UV=class extends MN{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=IV.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}}},eu=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),zn(async()=>(await n.iterator()).columnMajorBatch(e,t,GV),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,zn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,zn(async()=>(await t.iterator()).filter(a=>D(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return zn(async()=>(await t.iterator()).map(n=>D(()=>e(n))),this.size)}mapAsync(e){let t=this;return zn(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 zn(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,zn(async()=>{let a=fv(async()=>({value:await t.iterator(),done:!1}));return $V(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<e||e===void 0||e<0)?n=0:n=null,zn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let a=this,r=kV.alea(t||k.now().toString());return zn(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,zn(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()}};eu.MAX_BUFFER_SIZE=1e4;function zn(e,t=null){return new class extends eu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function fV(e){return zn(async()=>$N(e),e.length)}function gV(e){if(!tu(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(let n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return zn(async()=>{let n=await AN(e,a=>{if(a instanceof eu)return{value:a.iterator(),recurse:!1};if(tu(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return RV(n,ls.SHORTEST)},t)}function GV(e){if(e===null)return null;let t=e[0];return CV(t)?{value:HV(e),recurse:!1}:{value:null,recurse:!0}}function HV(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ae?$t(e):qn(e)}var IN=class extends eu{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))}},Fm='"',fp=Symbol("out"),PN=Symbol("field"),$m=Symbol("quote"),yv=Symbol("quoteafterquote"),ON=Symbol("quoteinquote"),NN=class extends eu{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 IN(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;r<this.fullColumnNames.length;r++){let s=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[r],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let c=Number(o);if(isNaN(c))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=c;else switch(i.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(o);break;default:l=c}}i&&i.isLabel?a[s]=l:n[s]=l}}return Object.keys(a).length===0?n:{xs:n,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],a=0,r=e.length,s=fp;for(let i=0;i<r;i++)switch(s){case fp:switch(e.charAt(i)){case Fm:a=i+1,s=$m;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=fp;break;default:s=PN,a=i;break}break;case PN:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=fp,a=i+1;break;default:}break;case $m:switch(e.charAt(i)){case Fm:s=yv;break;default:}break;case yv:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=fp,a=i+1;break;case Fm:s=$m;break;default:s=ON;break}break;case ON:switch(e.charAt(i)){case Fm:s=$m;break;default:}break;default:}if(s===yv?n.push(e.substring(a,r-1)):n.push(e.substring(a)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},LN=class extends Yt{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(ee().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new LN(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),qn(n,t)}},zN=class extends Yt{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=tt([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=Sa([s,r,o,i],[1,4])}else this.cropBox=Sa([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(ee().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 zN(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=Ni.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 D(()=>{let t=$n(ce(e,"float32"),0),n;n=Za.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return H(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.")}},BN=class{},WN=class extends Yt{split(e){return new jV(this,e)}},jV=class extends WN{constructor(e,t){super();this.upstream=e,this.impl=new qV(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},qV=class extends gv{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}},XV=class extends Yt{decodeUTF8(){return new KV(this)}},KV=class extends WN{constructor(e){super();this.upstream=e,this.impl=new YV(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},YV=class extends gv{constructor(e){super();if(this.upstream=e,ee().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=vE();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 ee().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},VN=class extends XV{constructor(e,t={}){super();this.file=e,this.options=t,k.assert(e instanceof Uint8Array||(ee().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 JV(e,t={}){let n,a;typeof e=="string"?n=e:(n=e.url,a=ZV(e));let r=await k.fetch(n,a);if(r.ok){let s=new Uint8Array(await r.arrayBuffer());return new VN(s,t)}else throw new Error(r.statusText)}var ZV=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 UN(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var TN=class extends BN{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(UN(this.input)&&ee().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new VN(this.input,this.options)}},SN=class extends BN{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return UN(this.url)?new TN(this.url,this.fileOptions).iterator():JV(this.url,this.fileOptions)}};function yV(e,t={}){return new NN(new SN(e),t)}function bV(e){let t=fv(e);return zn(async()=>t)}function xV(e){return zn(async()=>{let t=await e();return fv(()=>t.next())})}async function vV(e,t){return zN.create(e,t)}async function wV(e){return LN.create(e)}var CN="3.1.0";function we(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 QV=Ja.whereImpl,bv=class extends rc{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new gd(this,Ha())}nextDataId(){return bv.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,ee().get("IS_NODE")&&_.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 _.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 Le(e.shape,e.dtype,n)}makeOutput(e,t,n){let a=this.write(e,t,n);return Ha().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){we([e],"where");let t=this.readSync(e.dataId);return QV(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};bv.nextDataId=0;var GN={};Oe(GN,{addImpl:()=>jN,bincountImpl:()=>xv,bincountReduceImpl:()=>qN,ceilImpl:()=>KN,concatImpl:()=>vv,expImpl:()=>XN,expm1Impl:()=>YN,floorImpl:()=>ZN,gatherV2Impl:()=>JN,greaterImpl:()=>QN,lessImpl:()=>eT,linSpaceImpl:()=>tT,logImpl:()=>nT,maxImpl:()=>aT,maximumImpl:()=>rT,minimumImpl:()=>sT,multiplyImpl:()=>wv,negImpl:()=>iT,notEqualImpl:()=>oT,prodImpl:()=>lT,rangeImpl:()=>Iv,rsqrtImpl:()=>uT,simpleAbsImpl:()=>HN,sliceImpl:()=>Dm,squaredDifferenceImpl:()=>cT,stridedSliceImpl:()=>pT,subImpl:()=>dT,tileImpl:()=>hT,topKImpl:()=>mT,transposeImpl:()=>kv,uniqueImpl:()=>fT});function HN(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var eU=e=>{let{x:t}=e.inputs,n=e.backend;we(t,"abs");let a=new Float32Array(k.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=HN(r),n.makeOutput(a,t.shape,"float32")},tU={kernelName:Eo,backendName:"cpu",kernelFunc:eU};function Rt(e){return(t,n,a,r,s)=>{let i=_.assertAndGetBroadcastShape(t,n),o=i.length,l=k.computeStrides(i),c=k.sizeFromShape(i),u=k.getTypedArrayFromDType(s,c),p=t.length,d=n.length,h=k.computeStrides(t),m=k.computeStrides(n),f=_.getBroadcastDims(t,i),g=_.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(a[y%a.length],r[y%r.length]);else for(let y=0;y<u.length;++y){let b=k.indexToLoc(y,o,l),v=b.slice(-p);f.forEach(C=>v[C]=0);let x=k.locToIndex(v,p,h),N=b.slice(-d);g.forEach(C=>N[C]=0);let T=k.locToIndex(N,d,m);u[y]=e(a[x],r[T])}return[u,i]}}function Bn(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 nU={kernelName:Td,backendName:"cpu",kernelFunc:Bn};function Rm(e,t,n="float32"){if(n==="complex64"){let r=Rm(e,t,"float32"),s=Rm(e,t,"float32");return Bn({inputs:{real:r,imag:s},backend:e})}let a=k.makeZerosTypedArray(k.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function rr(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 aU={kernelName:Us,backendName:"cpu",kernelFunc:rr};function Ui(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 rU={kernelName:Hd,backendName:"cpu",kernelFunc:Ui};function us(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return rr({inputs:{x:r},backend:n});let i=Rm(n,r.shape,r.dtype),o=us({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Bn({inputs:{real:o,imag:i},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Ui({inputs:{input:r},backend:n}),o=us({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=rr({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,c]=Rt((u,p)=>u!==p?1:0)(r.shape,[],i,o,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var sU={kernelName:As,backendName:"cpu",kernelFunc:us};function Zt(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;we([i,o],e);let c=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,p=a||i.dtype,[d,h]=t(i.shape,o.shape,c,u,p);return l.makeTensorInfo(h,p,d)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let c=us({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),p=u.complexTensorInfos.real,d=u.complexTensorInfos.imag,h=l.data.get(p.dataId).values,m=l.data.get(d.dataId).values,f=us({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,v=l.data.get(y.dataId).values,x=l.data.get(b.dataId).values,[N,T,C]=n(i.shape,o.shape,h,m,v,x),F=l.makeTensorInfo(C,"float32",N),$=l.makeTensorInfo(C,"float32",T),P=Bn({inputs:{real:F,imag:$},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo($),P}else{let c=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,p=a||i.dtype,[d,h]=t(i.shape,o.shape,c,u,p);return l.makeTensorInfo(h,p,d)}}}function Nv(e){return(t,n,a,r,s,i)=>{let o=_.assertAndGetBroadcastShape(t,n),l=k.sizeFromShape(o),c=o.length,u=k.computeStrides(o),p=k.getTypedArrayFromDType("float32",l),d=k.getTypedArrayFromDType("float32",l),h=_.getBroadcastDims(t,o),m=_.getBroadcastDims(n,o),f=_.mergeRealAndImagArrays(a,r),g=_.mergeRealAndImagArrays(s,i),y=t.length,b=k.computeStrides(t),v=n.length,x=k.computeStrides(n);if(h.length+m.length===0)for(let N=0;N<p.length;N++){let T=N%f.length,C=N%g.length,F=e(f[T*2],f[T*2+1],g[C*2],g[C*2+1]);p[N]=F.real,d[N]=F.imag}else for(let N=0;N<p.length;N++){let T=k.indexToLoc(N,c,u),C=T.slice(-y);h.forEach(W=>C[W]=0);let F=k.locToIndex(C,y,b),$=T.slice(-v);m.forEach(W=>$[W]=0);let P=k.locToIndex($,v,x),B=e(f[F*2],f[F*2+1],g[P*2],g[P*2+1]);p[N]=B.real,d[N]=B.imag}return[p,d,o]}}var jN=Rt((e,t)=>e+t),iU=Nv((e,t,n,a)=>({real:e+n,imag:t+a})),gp=Zt(zr,jN,iU),oU={kernelName:zr,backendName:"cpu",kernelFunc:gp};function xv(e,t,n,a,r){let s=k.sizeFromShape(a),i=k.makeZerosTypedArray(r,n);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function qN(e,t,n,a=!1){let r=e.shape[0],s=e.shape[1],i=Le([r,n],t.dtype);for(let o=0;o<r;o++)for(let l=0;l<s;l++){let c=e.get(o,l);if(c<0)throw new Error("Input x must be non-negative!");c>=n||(a?i.set(1,o,c):t.size>0?i.set(i.get(o,c)+t.get(o,l),o,c):i.set(i.get(o,c)+1,o,c))}return i}function nu(e){return(t,n,a)=>{let r=k.getTypedArrayFromDType(n,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],a);return r}}function it(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(we(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,c=k.sizeFromShape(i.shape),u=n||i.dtype,p=k.getArrayFromDType(u,c);for(let d=0;d<c;++d)p[d]=t(l[d],r);return o.makeTensorInfo(i.shape,u,p)}}function au(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(we(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,c=n||i.dtype,u=t(l,c,r);return o.makeTensorInfo(i.shape,c,u)}}var KN=nu(e=>Math.ceil(e)),lU=au(Fs,KN),uU={kernelName:Fs,backendName:"cpu",kernelFunc:lU};function vv(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"?_.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let c=0;c<i.shape[0];++c){let u=c*t[1]+s;for(let p=0;p<i.shape[1];++p)r[u+p]=o[l++]}s+=i.shape[1]})}return r}var XN=nu(e=>Math.exp(e)),gT=au(Ls,XN),cU={kernelName:Ls,backendName:"cpu",kernelFunc:gT},YN=nu(e=>Math.expm1(e)),pU=au(Ho,YN),dU={kernelName:Ho,backendName:"cpu",kernelFunc:pU},ZN=nu(e=>Math.floor(e)),hU=au(zs,ZN),mU={kernelName:zs,backendName:"cpu",kernelFunc:hU};function JN(e,t,n){let a=Le(n,e.dtype);for(let r=0;r<a.size;++r){let s=a.indexToLoc(r).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let c=e.locToIndex(s);a.values[r]=e.values[c]}return a}var QN=Rt((e,t)=>e>t?1:0),fU=Zt(Xo,QN,null,"bool"),gU={kernelName:Xo,backendName:"cpu",kernelFunc:fU},eT=Rt((e,t)=>e<t?1:0),yU=Zt(Qo,eT,null,"bool"),bU={kernelName:Qo,backendName:"cpu",kernelFunc:yU};function tT(e,t,n){let a=(t-e)/(n-1),r=k.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;s<r.length;s++)r[s]=r[s-1]+a;return r}var nT=nu(e=>Math.log(e)),xU=au(Hs,nT),vU={kernelName:Hs,backendName:"cpu",kernelFunc:xU};function aT(e,t,n,a){let r=k.getTypedArrayFromDType(a,k.sizeFromShape(n));for(let s=0;s<r.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let c=e[i+l];c>o&&(o=c)}r[s]=o}return r}var rT=Rt((e,t)=>Math.max(e,t)),wU=Zt(qs,rT),kU={kernelName:qs,backendName:"cpu",kernelFunc:wU},sT=Rt((e,t)=>Math.min(e,t)),IU=Zt(Zs,sT),NU={kernelName:Zs,backendName:"cpu",kernelFunc:IU},wv=Rt((e,t)=>e*t),TU=Nv((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),Tv=Zt(Js,wv,TU),SU={kernelName:Js,backendName:"cpu",kernelFunc:Tv};function iT(e,t,n){let a=k.createScalarValue(-1,n);return wv([],t,a,e,n)}function CU(e){let{inputs:t,backend:n}=e,{x:a}=t;we(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=iT(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var _U={kernelName:rl,backendName:"cpu",kernelFunc:CU},oT=Rt((e,t)=>e!==t?1:0),EU=Zt(sl,oT,null,"bool"),AU={kernelName:sl,backendName:"cpu",kernelFunc:EU};function kv(e,t,n,a,r){let s=t.length,i=k.sizeFromShape(t),o=k.computeStrides(t),l=k.computeStrides(r),c=k.getTypedArrayFromDType(n,k.sizeFromShape(r));for(let u=0;u<i;++u){let p=k.indexToLoc(u,s,o),d=new Array(p.length);for(let m=0;m<d.length;m++)d[m]=p[a[m]];let h=k.locToIndex(d,s,l);c[h]=e[u]}return c}function ya(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{perm:s}=n;we(r,"transpose");let i=r.shape.length,o=new Array(i);for(let u=0;u<o.length;u++)o[u]=r.shape[s[u]];let l=a.data.get(r.dataId).values,c=kv(l,r.shape,r.dtype,s,o);return{dataId:a.write(c,o,r.dtype),shape:o,dtype:r.dtype}}var FU={kernelName:yi,backendName:"cpu",kernelFunc:ya};function lT(e,t,n,a){let[r,s]=_.computeOutAndReduceShapes(e,a),i=ua(t,"int32"),o=k.makeZerosTypedArray(k.sizeFromShape(r),i),l=k.sizeFromShape(s);for(let c=0;c<o.length;++c){let u=c*l,p=1;for(let d=0;d<l;++d)p*=n[u+d];o[c]=p}return{outVals:o,outShape:r,outDtype:i}}function $U(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;we(r,"prod");let o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=_.getAxesPermutation(l,o),u=l,p=r,d=[];c!=null&&(p=ya({inputs:{x:r},backend:n,attrs:{perm:c}}),d.push(p),u=_.getInnerMostAxes(u.length,o));let h=n.data.get(p.dataId).values,{outVals:m,outShape:f,outDtype:g}=lT(p.shape,p.dtype,h,u),y=f;return i&&(y=_.expandShapeToKeepDim(f,l)),d.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.makeTensorInfo(y,g,m)}var DU={kernelName:pl,backendName:"cpu",kernelFunc:$U};function Iv(e,t,n,a){let r=e===t,s=e<t&&n<0,i=t<e&&n>1;if(r||s||i)return k.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=k.makeZerosTypedArray(o,a);t<e&&n===1&&(n=-1),l[0]=e;for(let c=1;c<l.length;c++)l[c]=l[c-1]+n;return l}var uT=nu(e=>1/Math.sqrt(e)),RU=au(li,uT),MU={kernelName:li,backendName:"cpu",kernelFunc:RU};function Dm(e,t,n,a,r){let s=cn.isSliceContinous(a,t,n),i=k.sizeFromShape(n),o=k.computeStrides(a);if(s){let p=cn.computeFlatOffset(t,o);return r==="string"?e.slice(p,p+i):e.subarray(p,p+i)}let l=r==="string"?_.fromUint8ToStringArray(e):e,c=Le(a,r,l),u=Le(n,r);for(let p=0;p<u.size;++p){let d=u.indexToLoc(p),h=d.map((m,f)=>m+t[f]);u.set(c.get(...h),...d)}return r==="string"?_.fromStringArrayToUint8(u.values):u.values}function Gi(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;we(r,"slice");let[o,l]=cn.parseSliceParams(r,s,i);cn.assertParamsValid(r,o,l);let c=n.data.get(r.dataId).values,u=Dm(c,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var PU={kernelName:yl,backendName:"cpu",kernelFunc:Gi},cT=Rt((e,t)=>{let n=e-t;return n*n}),OU=Zt(mi,cT),LU={kernelName:mi,backendName:"cpu",kernelFunc:OU};function pT(e,t,n,a){let r=Le(e,t.dtype);for(let s=0;s<r.size;s++){let i=r.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*n[l]+a[l];r.set(t.get(...o),...i)}return r}var dT=Rt((e,t)=>e-t),zU=Nv((e,t,n,a)=>({real:e-n,imag:t-a})),Sv=Zt(fi,dT,zU),BU={kernelName:fi,backendName:"cpu",kernelFunc:Sv};function hT(e,t){let n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];let a=Le(n,e.dtype);for(let r=0;r<a.values.length;++r){let s=a.indexToLoc(r),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);a.values[r]=e.values[o]}return a}function mT(e,t,n,a,r){let s=t[t.length-1],[i,o]=[e.length/s,s],l=k.getTypedArrayFromDType(n,i*a),c=k.getTypedArrayFromDType("int32",i*a);for(let p=0;p<i;p++){let d=p*o,h=e.subarray(d,d+o),m=[];for(let b=0;b<h.length;b++)m.push({value:h[b],index:b});m.sort((b,v)=>v.value-b.value);let f=p*a,g=l.subarray(f,f+a),y=c.subarray(f,f+a);for(let b=0;b<a;b++)g[b]=m[b].value,y[b]=m[b].index}let u=t.slice();return u[u.length-1]=a,[Le(u,n,l),Le(u,"int32",c)]}function fT(e,t,n,a){let r=k.parseAxisParam(t,n)[0],s=[1,n[0],1];for(let m=0;m<r;m++)s[0]*=n[m];s[1]=n[r];for(let m=r+1;m<n.length;m++)s[2]*=n[m];let i={},o=new Int32Array(n[r]),l=new Ot(s,a,e),c=[],u=s[0]===1&&s[2]===1;for(let m=0;m<n[r];m++){let f;if(u)f=e[m].toString();else{let g=[];for(let y=0;y<s[0];y++)for(let b=0;b<s[2];b++)g.push(l.get(y,m,b));f=g.join(",")}if(i[f]!==void 0)o[m]=i[f];else{let g=Object.keys(i).length;i[f]=g,o[m]=g,c.push(m)}}let p=s.slice();p[1]=Object.keys(i).length;let d=new Ot(p,a);c.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)d.set(l.get(g,m,y),g,f,y)});let h=n.slice();return h[r]=p[1],{outputValues:d.values,outputShape:h,indices:o}}var WU="3.1.0";uh("cpu",()=>new bv,1);var yT=it(Wo,e=>e>=0?e:Math.exp(e)-1),VU={kernelName:Wo,backendName:"cpu",kernelFunc:yT};function bT(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;we([r],"leakyRelu");let i=k.sizeFromShape(r.shape),o=n.data.get(r.dataId).values,l=k.getTypedArrayFromDType("float32",i);for(let c=0;c<o.length;c++)l[c]=o[c]<0?s*o[c]:o[c];return n.makeTensorInfo(r.shape,"float32",l)}var UU={kernelName:Gs,backendName:"cpu",kernelFunc:bT},GU=Rt((e,t)=>e<0?t*e:e);function xT(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;we([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=GU(a.shape,r.shape,s,i,a.dtype);return n.makeTensorInfo(l,a.dtype,o)}var HU={kernelName:ni,backendName:"cpu",kernelFunc:xT},vT=it(ai,e=>Math.max(0,e)),jU={kernelName:ai,backendName:"cpu",kernelFunc:vT},wT=it(si,e=>Math.min(Math.max(0,e),6)),qU={kernelName:si,backendName:"cpu",kernelFunc:wT};function Cv(e,t,n,a,r){if(n==="linear")return rr({inputs:{x:t},backend:e});if(n==="relu")return vT({inputs:{x:t},backend:e});if(n==="elu")return yT({inputs:{x:t},backend:e});if(n==="relu6")return wT({inputs:{x:t},backend:e});if(n==="prelu")return xT({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return bT({inputs:{x:t},backend:e,attrs:{alpha:r}});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function It(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 c=n.data.get(r.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,p=c.complexTensorInfos.imag;u.shape=o,p.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var KU={kernelName:hl,backendName:"cpu",kernelFunc:It};function kT(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;we([r,s],"matMul");let l=r.shape.length,c=s.shape.length,u=i?r.shape[l-2]:r.shape[l-1],p=o?s.shape[c-1]:s.shape[c-2],d=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[c-2]:s.shape[c-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=k.sizeFromShape(m),y=k.sizeFromShape(f),b=g===y||g===1||y===1;k.assert(l>=2&&c>=2&&b,()=>`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 v=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([d,h]);k.assert(u===p,()=>`Error in matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,d]:[g,d,u],N=o?[y,h,p]:[y,p,h],T=It({inputs:{x:r},backend:n,attrs:{shape:x}}),C=It({inputs:{x:s},backend:n,attrs:{shape:N}}),F=i?T.shape[1]:T.shape[2],$=i?T.shape[2]:T.shape[1],P=o?C.shape[1]:C.shape[2],B=Math.max(g,y),W=n.data.get(T.dataId).values,G=n.data.get(C.dataId).values,q=k.computeStrides(T.shape),j=k.computeStrides(C.shape),[X,K,ne]=i?[q[0],1,q[1]]:[q[0],q[1],1],[J,se,Q]=o?[1,j[1],j[0]]:[j[1],1,j[0]],oe=$*P,ae=Le([B,$,P],T.dtype),pe=ae.values,ue=n.blockSize;for(let ge=0;ge<B;ge++)for(let ye=0;ye<$;ye+=ue)for(let ke=0;ke<P;ke+=ue)for(let Se=0;Se<F;Se+=ue){let Ce=Math.min(ye+ue,$),Re=Math.min(ke+ue,P),Ke=Math.min(Se+ue,F);for(let Ve=ye;Ve<Ce;Ve++)for(let rt=ke;rt<Re;rt++){let ot=0;for(let He=Se;He<Ke;He++){let ct=Math.min(ge,g-1)*X,pt=Math.min(ge,y-1)*Q,Gn=W[ct+Ve*K+He*ne],Je=G[He*J+rt*se+pt];ot+=Gn*Je}pe[ge*oe+(Ve*P+rt)]+=ot}}return n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(C),n.makeTensorInfo(v,ae.dtype,ae.values)}var XU={kernelName:Es,backendName:"cpu",kernelFunc:kT};function YU(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:p}=a,d,h,m,f=[];d=kT({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:c},backend:n}),i&&(h=gp({inputs:{a:d,b:i},backend:n}),f.push(d),d=h),u&&(m=Cv(n,d,u,o,p),f.push(d),d=m);for(let g of f)n.disposeIntermediateTensorInfo(g);return d}var ZU={kernelName:bi,backendName:"cpu",kernelFunc:YU},JU=it(Ao,e=>Math.acos(e)),QU={kernelName:Ao,backendName:"cpu",kernelFunc:JU},eG=it(Fo,e=>Math.acosh(e)),tG={kernelName:Fo,backendName:"cpu",kernelFunc:eG};function nG(e){let{inputs:t,backend:n}=e,a=t;we(t,"addN");let r=a.map(o=>n.data.get(o.dataId).values),s=Le(a[0].shape,a[0].dtype),i=s.values;for(let o=0;o<a.length;o++){let l=r[o];for(let c=0;c<i.length;c++)i[c]+=l[c]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}var aG={kernelName:Ss,backendName:"cpu",kernelFunc:nG};function rG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;we(r,"all");let o=k.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=ya({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("all",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=k.sizeFromShape(d),m=k.makeZerosTypedArray(k.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,v=f[b];for(let x=0;x<h;++x){let N=f[b+x];v=v&&N}m[y]=v}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=It({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var sG={kernelName:vd,backendName:"cpu",kernelFunc:rG};function iG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;we(r,"any");let o=k.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=ya({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("any",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=k.sizeFromShape(d),m=k.makeZerosTypedArray(k.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,v=f[b];for(let x=0;x<h;++x){let N=f[b+x];v=v||N}m[y]=v}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=It({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var oG={kernelName:wd,backendName:"cpu",kernelFunc:iG};function lG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;we(r,"argMax");let i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=ya({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[u,p]=_.computeOutAndReduceShapes(l.shape,i),d=k.sizeFromShape(u),h=k.makeZerosTypedArray(d,"int32"),m=k.sizeFromShape(p),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,b=f[y],v=0;for(let x=0;x<m;++x){let N=f[y+x];N>b&&(b=N,v=x)}h[g]=v}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var uG={kernelName:Cs,backendName:"cpu",kernelFunc:lG};function cG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;we(r,"argMin");let i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=ya({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[u,p]=_.computeOutAndReduceShapes(l.shape,i),d=k.sizeFromShape(u),h=k.makeZerosTypedArray(d,"int32"),m=k.sizeFromShape(p),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,b=f[y],v=0;for(let x=0;x<m;++x){let N=f[y+x];N<b&&(b=N,v=x)}h[g]=v}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var pG={kernelName:oc,backendName:"cpu",kernelFunc:cG},dG=it($o,e=>Math.asin(e)),hG={kernelName:$o,backendName:"cpu",kernelFunc:dG},mG=it(Do,e=>Math.asinh(e)),fG={kernelName:Do,backendName:"cpu",kernelFunc:mG},gG=it(Ro,e=>Math.atan(e)),yG={kernelName:Ro,backendName:"cpu",kernelFunc:gG},bG=Rt((e,t)=>Math.atan2(e,t)),xG=Zt(Po,bG),vG={kernelName:Po,backendName:"cpu",kernelFunc:xG},wG=it(Mo,e=>Math.atanh(e)),kG={kernelName:Mo,backendName:"cpu",kernelFunc:wG};function _v(e,t,n,a,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=r.padInfo.top,h=r.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=Le(r.outShape,n),g=f.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],b=r.outShape[2]*r.outShape[3],v=r.outShape[3];for(let x=0;x<r.batchSize;++x){let N=x*y,T=x*a[0];for(let C=0;C<r.inChannels;++C)for(let F=0;F<r.outHeight;++F){let $=F*i-d,P=Math.max(0,$),B=Math.min(r.inHeight,u+$),W=N+F*b;for(let G=0;G<r.outWidth;++G){let q=G*o-h,j=Math.max(0,q),X=Math.min(r.inWidth,p+q),K=m,ne=0,J=0;for(let Q=P;Q<B;Q+=l){let oe=T+Q*a[1];for(let ae=j;ae<X;ae+=c){let pe=oe+ae*a[2],ue=e[pe+C];s==="max"&&ue>K?K=ue:s==="avg"&&(ne+=ue,J++)}if(isNaN(K))break}let se=W+G*v+C;g[se]=s==="avg"?ne/J:K}}}return f}function IT(e,t,n,a,r=!1,s=!1){let i=Le(a.outShape,"int32"),o=a.strideHeight,l=a.strideWidth,c=a.dilationHeight,u=a.dilationWidth,p=a.effectiveFilterHeight,d=a.effectiveFilterWidth,h=a.padInfo.top,m=a.padInfo.left,f=Le(t,n,e);for(let g=0;g<a.batchSize;++g)for(let y=0;y<a.inChannels;++y)for(let b=0;b<a.outHeight;++b){let v=b*o-h,x=v;for(;x<0;)x+=c;let N=Math.min(a.inHeight,p+v);for(let T=0;T<a.outWidth;++T){let C=T*l-m,F=C;for(;F<0;)F+=u;let $=Math.min(a.inWidth,d+C),P=Number.NEGATIVE_INFINITY,B=-1;for(let W=x;W<N;W+=c){let G=W-v;for(let q=F;q<$;q+=u){let j=q-C,X=f.get(g,W,q,y);X>P&&(P=X,r?B=s?((g*a.inHeight+W)*a.inWidth+q)*a.inChannels+y:(W*a.inWidth+q)*a.inChannels+y:B=G*d+j)}}i.set(B,g,b,T,y)}}return i}function NT(e,t,n,a,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,p=r.dilationWidth,d=r.effectiveFilterDepth,h=r.effectiveFilterHeight,m=r.effectiveFilterWidth,f=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=Le(r.outShape,n),x=v.values,N=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],T=r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[3]*r.outShape[4],F=r.outShape[4];for(let $=0;$<r.batchSize;++$){let P=$*N,B=$*a[0];for(let W=0;W<r.inChannels;++W)for(let G=0;G<r.outDepth;++G){let q=G*i-f,j=q;for(;j<0;)j+=c;let X=Math.min(r.inDepth,d+q),K=P+G*T;for(let ne=0;ne<r.outHeight;++ne){let J=ne*o-g,se=J;for(;se<0;)se+=u;let Q=Math.min(r.inHeight,h+J),oe=K+ne*C;for(let ae=0;ae<r.outWidth;++ae){let pe=ae*l-y,ue=pe;for(;ue<0;)ue+=p;let ge=Math.min(r.inWidth,m+pe),ye=oe+ae*F,ke=b,Se=0,Ce=0;for(let Ke=j;Ke<X;Ke+=c){let Ve=B+Ke*a[1];for(let rt=se;rt<Q;rt+=u){let ot=Ve+rt*a[2];for(let He=ue;He<ge;He+=p){let ct=ot+He*a[3],pt=e[ct+W];if(s==="max"&&pt>ke?ke=pt:s==="avg"&&(Se+=pt,Ce++),isNaN(ke))break}if(isNaN(ke))break}if(isNaN(ke))break}let Re=ye+W;x[Re]=s==="avg"?Se/Ce:ke}}}}return v}function IG(e,t){let n=Le(t.outShape,"int32"),a=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,h=t.padInfo.top,m=t.padInfo.left;for(let f=0;f<t.batchSize;++f)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let b=y*a-d,v=b;for(;v<0;)v+=i;let x=Math.min(t.inDepth,c+b);for(let N=0;N<t.outHeight;++N){let T=N*r-h,C=T;for(;C<0;)C+=o;let F=Math.min(t.inHeight,u+T);for(let $=0;$<t.outWidth;++$){let P=$*s-m,B=P;for(;B<0;)B+=l;let W=Math.min(t.inWidth,p+P),G=Number.NEGATIVE_INFINITY,q=-1;for(let j=v;j<x;j+=i){let X=j-b;for(let K=C;K<F;K+=o){let ne=K-T;for(let J=B;J<W;J+=l){let se=J-P,Q=e.get(f,j,K,J,g);Q>=G&&(G=Q,q=X*u*p+ne*u+se)}}}n.set(q,f,y,N,$,g)}}}return n}function NG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;we(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))p=rr({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=k.computeStrides(r.shape),m=_v(d,r.shape,r.dtype,h,u,"avg");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var TG={kernelName:_s,backendName:"cpu",kernelFunc:NG};function SG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a;we(r,"avgPool3d");let u=_.computePool3DInfo(r.shape,s,i,1,o,l,c),p=n.data.get(r.dataId).values,d=NT(p,r.shape,r.dtype,k.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}var CG={kernelName:lc,backendName:"cpu",kernelFunc:SG};function _G(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=a;we([r,s],"avgPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,c),p=u.strideDepth,d=u.strideHeight,h=u.strideWidth,m=u.filterDepth,f=u.filterHeight,g=u.filterWidth,y=u.dilationDepth,b=u.dilationHeight,v=u.dilationWidth,x=u.effectiveFilterDepth,N=u.effectiveFilterHeight,T=u.effectiveFilterWidth,C=x-1-u.padInfo.front,F=T-1-u.padInfo.left,$=N-1-u.padInfo.top,P=Le(s.shape,"float32"),B=1/(m*f*g),W=n.bufferSync(r);for(let G=0;G<u.batchSize;++G)for(let q=0;q<u.inChannels;++q)for(let j=0;j<u.inDepth;++j)for(let X=0;X<u.inHeight;++X)for(let K=0;K<u.inWidth;++K){let ne=j-C,J=X-$,se=K-F,Q=0;for(let oe=0;oe<x;oe+=y){let ae=(ne+oe)/p;if(!(ae<0||ae>=u.outDepth||Math.floor(ae)!==ae))for(let pe=0;pe<N;pe+=b){let ue=(J+pe)/d;if(!(ue<0||ue>=u.outHeight||Math.floor(ue)!==ue))for(let ge=0;ge<T;ge+=v){let ye=(se+ge)/h;ye<0||ye>=u.outWidth||Math.floor(ye)!==ye||(Q+=W.get(G,ae,ue,ye,q))}}}P.set(Q*B,G,j,X,K,q)}return n.makeTensorInfo(P.shape,P.dtype,P.values)}var EG={kernelName:Id,backendName:"cpu",kernelFunc:_G};function AG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;we([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=_.computePool2DInfo(i.shape,o,l,1,c),p=u.strideHeight,d=u.strideWidth,h=u.filterHeight,m=u.filterWidth,f=u.dilationHeight,g=u.dilationWidth,y=u.effectiveFilterHeight,b=u.effectiveFilterWidth,v=b-1-u.padInfo.left,x=y-1-u.padInfo.top,N=Le(i.shape,"float32"),T=1/(h*m),C=n.data.get(r.dataId).values,F=Le(r.shape,"float32",C);for(let $=0;$<u.batchSize;++$)for(let P=0;P<u.inChannels;++P)for(let B=0;B<u.inHeight;++B)for(let W=0;W<u.inWidth;++W){let G=B-x,q=W-v,j=0;for(let X=0;X<y;X+=f){let K=(G+X)/p;if(!(K<0||K>=u.outHeight||Math.floor(K)!==K))for(let ne=0;ne<b;ne+=g){let J=(q+ne)/d;J<0||J>=u.outWidth||Math.floor(J)!==J||(j+=F.get($,K,J,P))}}N.set(j*T,$,B,W,P)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}var FG={kernelName:kd,backendName:"cpu",kernelFunc:AG};function $G(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."),we([r,o,l,s,i],"batchNorm");let{varianceEpsilon:c}=a;c==null&&(c=.001);let u=n.data.get(r.dataId).values,p=n.data.get(o.dataId).values,d=n.data.get(l.dataId).values,h=s?n.data.get(s.dataId).values:new Float32Array([1]),m=i?n.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(u.length),g=m.length,y=h.length,b=d.length,v=p.length,x=0,N=0,T=0,C=0;for(let F=0;F<u.length;++F)f[F]=m[x++]+(u[F]-p[N++])*h[T++]/Math.sqrt(d[C++]+c),x>=g&&(x=0),N>=v&&(N=0),T>=y&&(T=0),C>=b&&(C=0);return n.makeTensorInfo(r.shape,r.dtype,f)}var DG={kernelName:Ws,backendName:"cpu",kernelFunc:$G};function RG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;we([r],"batchToSpaceND");let o=s.reduce((y,b)=>y*b),l=_.getReshaped(r.shape,s,o),c=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(r.shape,s,o),p=_.getSliceBeginCoords(i,s.length),d=_.getSliceSize(u,i,s.length),h=It({inputs:{x:r},backend:n,attrs:{shape:l}}),m=ya({inputs:{x:h},backend:n,attrs:{perm:c}}),f=It({inputs:{x:m},backend:n,attrs:{shape:u}}),g=Gi({inputs:{x:f},backend:n,attrs:{begin:p,size:d}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var MG={kernelName:uc,backendName:"cpu",kernelFunc:RG};function PG(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,c=xv(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var OG={kernelName:Nd,backendName:"cpu",kernelFunc:PG},LG=it(Br,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),zG={kernelName:Br,backendName:"cpu",kernelFunc:LG},BG=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 c=0;c<o.length;c++){let u=o[c],p=l[c];a[c]=Math.hypot(u,p)}return n.makeOutput(a,t.shape,"float32")},WG={kernelName:cc,backendName:"cpu",kernelFunc:BG};function ru(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.imag,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var VG={kernelName:Ld,backendName:"cpu",kernelFunc:ru};function su(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=_.computeOutShape(t.map(f=>f.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 rr({inputs:{x:o[0]},backend:n});let l=o.map(f=>f.shape);if(_.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let f=o.map(x=>Ui({inputs:{input:x},backend:n})),g=o.map(x=>ru({inputs:{input:x},backend:n})),y=su({inputs:f,backend:n,attrs:{axis:s}}),b=su({inputs:g,backend:n,attrs:{axis:s}}),v=Bn({inputs:{real:y,imag:b},backend:n});return f.forEach(x=>n.disposeIntermediateTensorInfo(x)),g.forEach(x=>n.disposeIntermediateTensorInfo(x)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),v}let c=o.map(f=>{let g=k.sizeFromShape(f.shape.slice(s));return It({inputs:{x:f},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));i=_.computeOutShape(c.map(f=>f.shape),1);let p=c[0].shape[0]===1,d=vv(u,i,t[0].dtype,p),h=_.computeOutShape(o.map(f=>f.shape),s),m=n.makeTensorInfo(h,t[0].dtype,d);return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var UG={kernelName:Oo,backendName:"cpu",kernelFunc:su};function TT(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:c,dimRoundingMode:u}=a;we([r,s],"conv2d");let p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!1,p),h=d.filterHeight,m=d.filterWidth,f=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,b=d.padInfo.top,v=d.dataFormat==="channelsLast",x=new Ot(d.outShape,r.dtype),N=k.computeStrides(r.shape),T=k.computeStrides(s.shape),C=N[0],F=v?N[1]:N[2],$=v?N[2]:1,P=v?1:N[1],B=x.strides[0],W=v?x.strides[1]:x.strides[2],G=v?x.strides[2]:1,q=v?1:x.strides[1],j=n.data.get(r.dataId).values,X=n.data.get(s.dataId).values,K=x.values;for(let ne=0;ne<d.batchSize;++ne){let J=ne*C,se=ne*B;for(let Q=0;Q<d.outHeight;++Q){let oe=se+Q*W,ae=Q*d.strideHeight-b;for(let pe=0;pe<h;++pe){let ue=ae+pe*f;if(ue<0||ue>=d.inHeight)continue;let ge=pe*T[0],ye=J+ue*F;for(let ke=0;ke<d.outWidth;++ke){let Se=oe+ke*G,Ce=ke*d.strideWidth-y;for(let Re=0;Re<m;++Re){let Ke=Ce+Re*g;if(Ke<0||Ke>=d.inWidth)continue;let Ve=ge+Re*T[1],rt=ye+Ke*$,ot=Ve;for(let He=0;He<d.inChannels;++He){let ct=j[rt+He*P];for(let pt=0;pt<d.outChannels;++pt)K[Se+pt*q]+=ct*X[ot+pt];ot+=d.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,K)}var GG={kernelName:$s,backendName:"cpu",kernelFunc:TT};function HG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,filterShape:u}=a;we([r,s],"conv2dBackpropFilter");let p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),{strideHeight:h,strideWidth:m,filterHeight:f,filterWidth:g}=d,y=d.dataFormat==="channelsLast",b=new Ot(d.filterShape,"float32"),v=d.padInfo.left,x=d.padInfo.top,N=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=new Ot(r.shape,r.dtype,N),F=new Ot(s.shape,s.dtype,T);for(let $=0;$<f;++$){let P=Math.max(0,Math.ceil((x-$)/h)),B=Math.min(d.outHeight,(d.inHeight+x-$)/h);for(let W=0;W<g;++W){let G=Math.max(0,Math.ceil((v-W)/m)),q=Math.min(d.outWidth,(d.inWidth+v-W)/m);for(let j=0;j<d.inChannels;++j)for(let X=0;X<d.outChannels;++X){let K=0;for(let ne=0;ne<d.batchSize;++ne)for(let J=P;J<B;++J){let se=$+J*h-x;for(let Q=G;Q<q;++Q){let oe=W+Q*m-v;y?K+=C.get(ne,se,oe,j)*F.get(ne,J,Q,X):K+=C.get(ne,j,se,oe)*F.get(ne,X,J,Q)}}b.set(K,$,W,j,X)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var jG={kernelName:Sd,backendName:"cpu",kernelFunc:HG};function qG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:c,dimRoundingMode:u}=a;we([r,s],"conv2dBackpropInput");let p=k.computeStrides(s.shape),d=k.computeStrides(r.shape),h=_.convertConv2DDataFormat(c),m=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,h),f=new Ot(m.inShape,"float32"),g=f.values,y=n.data.get(r.dataId).values,b=n.data.get(s.dataId).values,[v,x,N]=p,{batchSize:T,filterHeight:C,filterWidth:F,inChannels:$,inHeight:P,inWidth:B,outChannels:W,outHeight:G,outWidth:q,strideHeight:j,strideWidth:X}=m;h=m.dataFormat;let K=C-1-m.padInfo.top,ne=F-1-m.padInfo.left,J=h==="channelsLast",se=f.strides[0],Q=J?f.strides[1]:f.strides[2],oe=J?f.strides[2]:1,ae=J?1:f.strides[1],pe=d[0],ue=J?d[1]:d[2],ge=J?d[2]:1,ye=J?1:d[1];for(let ke=0;ke<T;++ke)for(let Se=0;Se<$;++Se)for(let Ce=0;Ce<P;++Ce){let Re=Ce-K,Ke=Math.max(0,Math.ceil(Re/j)),Ve=Math.min(G,(C+Re)/j);for(let rt=0;rt<B;++rt){let ot=rt-ne,He=Math.max(0,Math.ceil(ot/X)),ct=Math.min(q,(F+ot)/X),pt=0;for(let Je=Ke;Je<Ve;++Je){let En=Je*j-Re;for(let Qt=He;Qt<ct;++Qt){let An=Qt*X-ot,na=pe*ke+ue*Je+ge*Qt,xn=v*(C-1-En)+x*(F-1-An)+N*Se;for(let ln=0;ln<W;++ln){let aa=y[na+ye*ln],Ba=b[xn+ln];pt+=aa*Ba}}}let Gn=se*ke+Q*Ce+oe*rt+ae*Se;g[Gn]=pt}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var KG={kernelName:Ds,backendName:"cpu",kernelFunc:qG};function XG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;we([r,s],"conv3d");let c=_.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:u,filterHeight:p,filterWidth:d,dilationDepth:h,dilationHeight:m,dilationWidth:f,padInfo:g}=c,y=g.front,b=g.left,v=g.top,x=new Ot(c.outShape,r.dtype),N=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=x.values,F=k.computeStrides(r.shape),$=k.computeStrides(s.shape);for(let P=0;P<c.batchSize;++P){let B=P*F[0],W=P*x.strides[0];for(let G=0;G<c.outDepth;++G){let q=W+G*x.strides[1],j=G*c.strideDepth-y;for(let X=0;X<u;++X){let K=j+X*h;if(K<0||K>=c.inDepth)continue;let ne=X*$[0],J=B+K*F[1];for(let se=0;se<c.outHeight;++se){let Q=q+se*x.strides[2],oe=se*c.strideHeight-v;for(let ae=0;ae<p;++ae){let pe=oe+ae*m;if(pe<0||pe>=c.inHeight)continue;let ue=ne+ae*$[1],ge=J+pe*F[2];for(let ye=0;ye<c.outWidth;++ye){let ke=Q+ye*c.outChannels,Se=ye*c.strideWidth-b;for(let Ce=0;Ce<d;++Ce){let Re=Se+Ce*f;if(Re<0||Re>=c.inWidth)continue;let Ke=ue+Ce*$[2],Ve=ge+Re*c.inChannels,rt=Ke;for(let ot=0;ot<c.inChannels;++ot){let He=N[Ve+ot];for(let ct=0;ct<c.outChannels;++ct)C[ke+ct]+=He*T[rt+ct];rt+=c.outChannels}}}}}}}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}var YG={kernelName:pc,backendName:"cpu",kernelFunc:XG};function ZG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;we([r,s],"conv3dBackpropFilterV2");let c=k.computeStrides(r.shape),u=k.computeStrides(s.shape),p=_.computeConv3DInfo(r.shape,l,i,1,o),d=p.strideDepth,h=p.strideHeight,m=p.strideWidth,f=p.filterDepth,g=p.filterHeight,y=p.filterWidth,b=new Ot(p.filterShape,"float32"),v=b.values,[x,N,T,C]=b.strides,F=n.data.get(s.dataId).values,[$,P,B,W]=u,G=n.data.get(r.dataId).values,[q,j,X,K]=c,ne=p.padInfo.front,J=p.padInfo.left,se=p.padInfo.top;for(let Q=0;Q<f;++Q){let oe=Math.max(0,Math.ceil((ne-Q)/d)),ae=Math.min(p.outDepth,(p.inDepth+ne-Q)/d),pe=Q*x;for(let ue=0;ue<g;++ue){let ge=Math.max(0,Math.ceil((se-ue)/h)),ye=Math.min(p.outHeight,(p.inHeight+se-ue)/h),ke=ue*N+pe;for(let Se=0;Se<y;++Se){let Ce=Math.max(0,Math.ceil((J-Se)/m)),Re=Math.min(p.outWidth,(p.inWidth+J-Se)/m),Ke=Se*T+ke;for(let Ve=0;Ve<p.inChannels;++Ve){let rt=Ve*C+Ke;for(let ot=0;ot<p.outChannels;++ot){let He=0;for(let ct=0;ct<p.batchSize;++ct){let pt=ct*q,Gn=ct*$;for(let Je=oe;Je<ae;++Je){let En=(Q+Je*d-ne)*j+pt,Qt=Je*P+Gn;for(let An=ge;An<ye;++An){let na=(ue+An*h-se)*X+En,xn=An*B+Qt;for(let ln=Ce;ln<Re;++ln){let aa=(Se+ln*m-J)*K+na,Ba=ln*W+xn;He+=G[aa+Ve]*F[Ba+ot]}}}}v[rt+ot]=He}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var JG={kernelName:Cd,backendName:"cpu",kernelFunc:ZG};function QG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;we([r],"conv3dBackpropInputV2");let c=k.computeStrides(r.shape),u=k.computeStrides(s.shape),p=_.computeConv3DInfo(l,s.shape,o,1,i),d=new Ot(p.inShape,"float32"),h=d.values,[m,f,g,y]=d.strides,b=n.data.get(r.dataId).values,[v,x,N,T]=c,C=n.data.get(s.dataId).values,[F,$,P,B]=u,{batchSize:W,filterDepth:G,filterHeight:q,filterWidth:j,inChannels:X,inDepth:K,inHeight:ne,inWidth:J,outChannels:se,outDepth:Q,outHeight:oe,outWidth:ae,strideDepth:pe,strideHeight:ue,strideWidth:ge}=p,ye=G-1-p.padInfo.front,ke=q-1-p.padInfo.top,Se=j-1-p.padInfo.left;for(let Ce=0;Ce<W;++Ce)for(let Re=0;Re<X;++Re)for(let Ke=0;Ke<K;++Ke){let Ve=Ke-ye,rt=Math.max(0,Math.ceil(Ve/pe)),ot=Math.min(Q,(G+Ve)/pe);for(let He=0;He<ne;++He){let ct=He-ke,pt=Math.max(0,Math.ceil(ct/ue)),Gn=Math.min(oe,(q+ct)/ue);for(let Je=0;Je<J;++Je){let En=Je-Se,Qt=Math.max(0,Math.ceil(En/ge)),An=Math.min(ae,(j+En)/ge),na=0;for(let xn=rt;xn<ot;++xn){let ln=xn*pe-Ve;for(let aa=pt;aa<Gn;++aa){let Ba=aa*ue-ct;for(let Fn=Qt;Fn<An;++Fn){let ho=Fn*ge-En,zu=v*Ce+x*xn+N*aa+T*Fn,ka=F*(G-1-ln)+$*(q-1-Ba)+P*(j-1-ho)+B*Re;for(let ra=0;ra<se;++ra){let Ia=b[zu+ra],mo=C[ka+ra];na+=Ia*mo}}}}h[m*Ce+f*Ke+g*He+y*Je+Re]=na}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}var eH={kernelName:_d,backendName:"cpu",kernelFunc:QG},tH=it(Rs,e=>Math.cos(e)),nH={kernelName:Rs,backendName:"cpu",kernelFunc:tH},aH=it(Lo,e=>Math.cosh(e)),rH={kernelName:Lo,backendName:"cpu",kernelFunc:aH};function sH(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:c}=a,[u,p,d,h]=r.shape,m=s.shape[0],[f,g]=o,y=Le([m,f,g,h],"float32"),b=n.data.get(s.dataId).values,v=n.data.get(i.dataId).values,x=n.data.get(r.dataId).values,N=k.computeStrides(r.shape),T=k.computeStrides(y.shape);for(let C=0;C<m;C++){let F=C*4,$=b[F],P=b[F+1],B=b[F+2],W=b[F+3],G=v[C];if(G>=u)continue;let q=f>1?(B-$)*(p-1)/(f-1):0,j=g>1?(W-P)*(d-1)/(g-1):0;for(let X=0;X<f;X++){let K=f>1?$*(p-1)+X*q:.5*($+B)*(p-1);if(K<0||K>p-1){for(let ne=0;ne<g;ne++)for(let J=0;J<h;J++){let se=J+ne*T[2]+X*T[1]+C*T[0];y.values[se]=c}continue}if(l==="bilinear"){let ne=Math.floor(K),J=Math.ceil(K),se=K-ne;for(let Q=0;Q<g;Q++){let oe=g>1?P*(d-1)+Q*j:.5*(P+W)*(d-1);if(oe<0||oe>d-1){for(let ge=0;ge<h;ge++){let ye=ge+Q*T[2]+X*T[1]+C*T[0];y.values[ye]=c}continue}let ae=Math.floor(oe),pe=Math.ceil(oe),ue=oe-ae;for(let ge=0;ge<h;ge++){let ye=ge+ae*N[2]+ne*N[1]+G*N[0],ke=x[ye];ye=ge+pe*N[2]+ne*N[1]+G*N[0];let Se=x[ye];ye=ge+ae*N[2]+J*N[1]+G*N[0];let Ce=x[ye];ye=ge+pe*N[2]+J*N[1]+G*N[0];let Re=x[ye],Ke=ke+(Se-ke)*ue,Ve=Ce+(Re-Ce)*ue;ye=ge+Q*T[2]+X*T[1]+C*T[0],y.values[ye]=Ke+(Ve-Ke)*se}}}else for(let ne=0;ne<g;++ne){let J=g>1?P*(d-1)+ne*j:.5*(P+W)*(d-1);if(J<0||J>d-1){for(let oe=0;oe<h;oe++){let ae=oe+ne*T[2]+X*T[1]+C*T[0];y.values[ae]=c}continue}let se=Math.round(J),Q=Math.round(K);for(let oe=0;oe<h;oe++){let ae=oe+se*N[2]+Q*N[1]+G*N[0],pe=oe+ne*T[2]+X*T[1]+C*T[0];y.values[pe]=x[ae]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var iH={kernelName:zo,backendName:"cpu",kernelFunc:sH};function oH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;we(r,"cumsum");let l=_.getAxesPermutation([s],r.shape.length),c=r;l!=null&&(c=ya({inputs:{x:r},backend:n,attrs:{perm:l}}));let u=_.getInnerMostAxes(1,r.shape.length)[0];if(u!==c.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${c.shape.length-1} but got axis=${u}`);let p=ua(c.dtype,"int32"),d=k.makeZerosTypedArray(k.sizeFromShape(c.shape),p),h=n.data.get(c.dataId).values,m=c.shape[c.shape.length-1],f=o?(y,b)=>y+m-b-1:(y,b)=>y+b;for(let y=0;y<h.length;y+=m)for(let b=0;b<m;b++){let v=f(y,b);if(b===0)d[v]=i?0:h[v];else{let x=f(y,b-1);d[v]=i?h[x]+d[x]:h[v]+d[x]}}let g=n.makeTensorInfo(c.shape,p,d);if(l!=null){let y=_.getUndoAxesPermutation(l),b=ya({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(c),b}return g}var lH={kernelName:Ms,backendName:"cpu",kernelFunc:oH};function uH(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.data.get(r.dataId).values,c=n.data.get(s.dataId).values,u=xv(l,c,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(s),u=qN(l,c,i,o);return n.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var cH={kernelName:Ed,backendName:"cpu",kernelFunc:uH};function pH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;k.assert(i==="NHWC",()=>`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],c=r.shape[2],u=r.shape[3],p=l*s,d=c*s,h=u/(s*s),m=n.data.get(r.dataId).values,f=new Float32Array(o*p*d*h),g=0;for(let y=0;y<o;++y)for(let b=0;b<p;++b){let v=Math.floor(b/s),x=b%s;for(let N=0;N<d;++N){let T=Math.floor(N/s),C=N%s,F=(x*s+C)*h;for(let $=0;$<h;++$){let P=$+F+u*(T+c*(v+l*y));f[g++]=m[P]}}}return n.makeTensorInfo([o,p,d,h],r.dtype,f)}var dH={kernelName:Bo,backendName:"cpu",kernelFunc:pH};function ST(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=a;we([r,s],"depthwiseConv2DNative");let u=k.computeStrides(r.shape),p=k.computeStrides(s.shape),d=l;d==null&&(d=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=_.computeConv2DInfo(r.shape,s.shape,i,d,o,c,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:y,padInfo:b}=h,v=b.left,x=b.top,N=h.outChannels/h.inChannels,T=new Ot(h.outShape,r.dtype),C=n.data.get(r.dataId).values,F=n.data.get(s.dataId).values,$=T.values;for(let P=0;P<h.batchSize;++P){let B=P*u[0],W=P*T.strides[0];for(let G=0;G<h.outHeight;++G){let q=W+G*T.strides[1],j=G*h.strideHeight-v;for(let X=0;X<m;++X){let K=j+X*g;if(K<0||K>=h.inHeight)continue;let ne=X*p[0],J=B+K*u[1];for(let se=0;se<h.outWidth;++se){let Q=q+se*T.strides[2],oe=se*h.strideWidth-x;for(let ae=0;ae<f;++ae){let pe=oe+ae*y;if(pe<0||pe>=h.inWidth)continue;let ue=ne+ae*p[1],ge=J+pe*h.inChannels,ye=Q,ke=ue;for(let Se=0;Se<h.inChannels;++Se){let Ce=C[ge+Se];for(let Re=0;Re<N;++Re)$[ye+Re]+=Ce*F[ke+Re];ye+=N,ke+=N}}}}}}return n.makeTensorInfo(T.shape,T.dtype,T.values)}var hH={kernelName:Ps,backendName:"cpu",kernelFunc:ST};function mH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,filterShape:u}=a;we([r,s],"depthwiseConv2dNativeBackpropFilter");let p=_.computeConv2DInfo(r.shape,u,i,o,l,c,!0),{strideHeight:d,strideWidth:h,filterHeight:m,filterWidth:f}=p,g=new Ot(p.filterShape,"float32"),y=p.padInfo.left,b=p.padInfo.top,v=p.outChannels/p.inChannels,x=n.data.get(r.dataId).values,N=new Ot(r.shape,r.dtype,x),T=n.data.get(s.dataId).values,C=new Ot(s.shape,s.dtype,T);for(let F=0;F<m;++F){let $=Math.max(0,Math.ceil((b-F)/d)),P=Math.min(p.outHeight,(p.inHeight+b-F)/d);for(let B=0;B<f;++B){let W=Math.max(0,Math.ceil((y-B)/h)),G=Math.min(p.outWidth,(p.inWidth+y-B)/h);for(let q=0;q<p.outChannels;++q){let j=Math.trunc(q/v),X=q%v,K=0;for(let ne=0;ne<p.batchSize;++ne)for(let J=$;J<P;++J){let se=F+J*d-b;for(let Q=W;Q<G;++Q){let oe=B+Q*h-y;K+=N.get(ne,se,oe,j)*C.get(ne,J,Q,q)}}g.set(K,F,B,j,X)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var fH={kernelName:Ad,backendName:"cpu",kernelFunc:mH};function gH(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,inputShape:u}=a;we([r,s],"depthwiseConv2DNativeBackpropInput");let p=k.computeStrides(r.shape),d=k.computeStrides(s.shape),h=_.computeConv2DInfo(u,s.shape,i,o,l,c,!0),m=new Ot(h.inShape,"float32"),f=m.values,[g,y,b]=m.strides,v=n.data.get(r.dataId).values,[x,N,T]=p,C=n.data.get(s.dataId).values,[F,$,P]=d,{batchSize:B,filterHeight:W,filterWidth:G,inChannels:q,inHeight:j,inWidth:X,outChannels:K,outHeight:ne,outWidth:J,strideHeight:se,strideWidth:Q}=h,oe=W-1-h.padInfo.top,ae=G-1-h.padInfo.left,pe=K/q;for(let ue=0;ue<B;++ue)for(let ge=0;ge<q;++ge)for(let ye=0;ye<j;++ye){let ke=ye-oe,Se=Math.max(0,Math.ceil(ke/se)),Ce=Math.min(ne,(W+ke)/se);for(let Re=0;Re<X;++Re){let Ke=Re-ae,Ve=Math.max(0,Math.ceil(Ke/Q)),rt=Math.min(J,(G+Ke)/Q),ot=0;for(let He=Se;He<Ce;++He){let ct=He*se-ke;for(let pt=Ve;pt<rt;++pt){let Gn=pt*Q-Ke,Je=x*ue+N*He+T*pt,En=F*(W-1-ct)+$*(G-1-Gn)+P*ge;for(let Qt=0;Qt<pe;++Qt){let An=ge*pe+Qt,na=v[Je+An],xn=C[En+Qt];ot+=na*xn}}}f[g*ue+y*ye+b*Re+ge]=ot}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var yH={kernelName:Fd,backendName:"cpu",kernelFunc:gH};function bH(e){let{inputs:t,backend:n}=e,{x:a}=t,r=k.sizeFromShape(a.shape),s=n.data.get(a.dataId).values,i=Le([r,r],a.dtype),o=i.values;for(let c=0;c<s.length;c++)o[c*r+c]=s[c];let l=[...a.shape,...a.shape];return n.makeTensorInfo(l,i.dtype,i.values)}var xH={kernelName:$d,backendName:"cpu",kernelFunc:bH},vH={kernelName:dc,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r}=e,{strides:s,pad:i,dilations:o}=n,l=t,c=l.data.get(a.dataId).values,u=a.shape.length,p=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:h,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:b,padInfo:v,strideHeight:x,strideWidth:N,filterHeight:T,filterWidth:C,dilationHeight:F,dilationWidth:$,outShape:P}=_.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),B=k.sizeFromShape(P),W=P.length,G=k.getArrayFromDType(a.dtype,B);for(let q=0;q<h;++q)for(let j=0;j<y;++j){let X=j*x-v.top;for(let K=0;K<b;++K){let ne=K*N-v.left;for(let J=0;J<g;++J){let se=Number.MIN_SAFE_INTEGER;for(let oe=0;oe<T;++oe){let ae=X+oe*F;if(ae>=0&&ae<m)for(let pe=0;pe<C;++pe){let ue=ne+pe*$;if(ue>=0&&ue<f){let ge=k.locToIndex([q,ae,ue,J],u,k.computeStrides(a.shape)),ye=k.locToIndex([oe,pe,J],d,k.computeStrides(r.shape)),ke=c[ge]+p[ye];ke>se&&(se=ke)}}}let Q=k.locToIndex([q,j,K,J],W,k.computeStrides(P));G[Q]=se}}}return{dataId:l.write(k.toTypedArray(G,a.dtype),P,a.dtype),shape:P,dtype:a.dtype}}},wH={kernelName:Rd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,c=t,u=k.toNestedArray(a.shape,c.data.get(a.dataId).values),p=k.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:b,strideHeight:v,strideWidth:x,filterHeight:N,filterWidth:T,dilationHeight:C,dilationWidth:F,outShape:$}=_.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===$.length,()=>`Error in ${Rd}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let P=k.toNestedArray($,c.data.get(s.dataId).values),B=k.makeZerosNestedTypedArray(r.shape,r.dtype);for(let W=0;W<d;++W)for(let G=0;G<g;++G){let q=G*v-b.top;for(let j=0;j<y;++j){let X=j*x-b.left;for(let K=0;K<f;++K){let ne=Number.MIN_SAFE_INTEGER,J=0,se=0;for(let Q=0;Q<N;++Q){let oe=q+Q*C;if(oe>=0&&oe<h)for(let ae=0;ae<T;++ae){let pe=X+ae*F;if(pe>=0&&pe<m){let ue=u[W][oe][pe][K]+p[Q][ae][K];ue>ne&&(ne=ue,J=Q,se=ae)}}}B[J][se][K]+=P[W][G][j][K]}}}return{dataId:c.write(k.toTypedArray(B,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},kH={kernelName:Dd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,c=t,u=k.toNestedArray(a.shape,c.data.get(a.dataId).values),p=k.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:b,strideHeight:v,strideWidth:x,filterHeight:N,filterWidth:T,dilationHeight:C,dilationWidth:F,outShape:$}=_.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===$.length,()=>`Error in ${Dd}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let P=k.toNestedArray($,c.data.get(s.dataId).values),B=k.makeZerosNestedTypedArray(a.shape,a.dtype);for(let W=0;W<d;++W)for(let G=0;G<g;++G){let q=G*v-b.top;for(let j=0;j<y;++j){let X=j*x-b.left;for(let K=0;K<f;++K){let ne=Number.MIN_SAFE_INTEGER,J=q<0?0:q,se=X<0?0:X;for(let Q=0;Q<N;++Q){let oe=q+Q*C;if(oe>=0&&oe<h)for(let ae=0;ae<T;++ae){let pe=X+ae*F;if(pe>=0&&pe<m){let ue=u[W][oe][pe][K]+p[Q][ae][K];ue>ne&&(ne=ue,J=oe,se=pe)}}}B[W][J][se][K]+=P[W][G][j][K]}}}return{dataId:c.write(k.toTypedArray(B,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function IH(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;we([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<i.length;++l){let c=i[l];c>=1?s[l]=o[l]:s[l]=o[l]*(c+1)}return n.makeTensorInfo(r.shape,"float32",s)}var NH={kernelName:Md,backendName:"cpu",kernelFunc:IH},TH=Rt((e,t)=>e===t?1:0),CT=Zt(Uo,TH,null,"bool"),SH={kernelName:Uo,backendName:"cpu",kernelFunc:CT},CH=_.ERF_P,_H=_.ERF_A1,EH=_.ERF_A2,AH=_.ERF_A3,FH=_.ERF_A4,$H=_.ERF_A5,DH=it(Vo,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+CH*n);return t*(1-(((($H*a+FH)*a+AH)*a+EH)*a+_H)*a*Math.exp(-n*n))}),RH={kernelName:Vo,backendName:"cpu",kernelFunc:DH};function Mm(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),It({inputs:{x:r},backend:n,attrs:{shape:o}})}var MH={kernelName:Go,backendName:"cpu",kernelFunc:Mm},PH=Rt((e,t)=>e/t),Ev=Zt(Os,PH),Av={kernelName:Os,backendName:"cpu",kernelFunc:Ev};function _T(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,c=[r,s],u=k.sizeFromShape(c),p=k.getTypedArrayFromDType("float32",u),d=k.getTypedArrayFromDType("float32",u);for(let g=0;g<r;g++){let y=Gi({inputs:{x:o},backend:n,attrs:{begin:[g,0],size:[1,s]}}),b=Gi({inputs:{x:l},backend:n,attrs:{begin:[g,0],size:[1,s]}}),v=Bn({inputs:{real:y,imag:b},backend:n}),{real:x,imag:N}=OH(v,t,n),T=_.mergeRealAndImagArrays(x,N);for(let C=0;C<s;C++){let F=_.getComplexWithIndex(T,C);p[g*s+C]=F.real,d[g*s+C]=F.imag}n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(v)}let h=n.makeTensorInfo(c,"float32",p),m=n.makeTensorInfo(c,"float32",d),f=Bn({inputs:{real:h,imag:m},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}function OH(e,t,n){let a=k.sizeFromShape(e.shape),r=n.data.get(e.dataId),s=n.data.get(r.complexTensorInfos.real.dataId).values,i=n.data.get(r.complexTensorInfos.imag.dataId).values;if(LH(a)){let o=Fv(s,i,a,t,n),l=[e.shape[0],e.shape[1]];if(t){let c=n.makeTensorInfo(l,"float32",o.real),u=n.makeTensorInfo(l,"float32",o.imag),p=n.makeTensorInfo([],"float32",k.createScalarValue(a,"float32")),d=rr({inputs:{x:p},backend:n}),h=Av.kernelFunc({inputs:{a:c,b:p},backend:n}),m=Av.kernelFunc({inputs:{a:u,b:d},backend:n}),f=n.data.get(h.dataId).values,g=n.data.get(m.dataId).values;return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=_.mergeRealAndImagArrays(s,i),l=zH(o,a,t);return _.splitRealAndImagArrays(l)}}function LH(e){return(e&e-1)==0}function Fv(e,t,n,a,r){if(n===1)return{real:e,imag:t};let s=_.mergeRealAndImagArrays(e,t),i=n/2,o=_.complexWithEvenIndex(s),l=o.real,c=o.imag,u=[l.length],p=r.makeTensorInfo(u,"float32",l),d=r.makeTensorInfo(u,"float32",c),h=Bn({inputs:{real:p,imag:d},backend:r}),m=_.complexWithOddIndex(s),f=m.real,g=m.imag,y=[f.length],b=r.makeTensorInfo(y,"float32",f),v=r.makeTensorInfo(y,"float32",g),x=Bn({inputs:{real:b,imag:v},backend:r}),N=Fv(l,c,i,a,r),T=N.real,C=N.imag,F=[T.length],$=r.makeTensorInfo(F,"float32",T),P=r.makeTensorInfo(F,"float32",C),B=Bn({inputs:{real:$,imag:P},backend:r}),W=Fv(f,g,i,a,r),G=W.real,q=W.imag,j=[G.length],X=r.makeTensorInfo(j,"float32",G),K=r.makeTensorInfo(j,"float32",q),ne=Bn({inputs:{real:X,imag:K},backend:r}),J=_.exponents(n,a),se=[J.real.length],Q=r.makeTensorInfo(se,"float32",J.real),oe=r.makeTensorInfo(se,"float32",J.imag),ae=Bn({inputs:{real:Q,imag:oe},backend:r}),pe=Tv({inputs:{a:ae,b:ne},backend:r}),ue=gp({inputs:{a:B,b:pe},backend:r}),ge=Sv({inputs:{a:B,b:pe},backend:r}),ye=Ui({inputs:{input:ue},backend:r}),ke=Ui({inputs:{input:ge},backend:r}),Se=ru({inputs:{input:ue},backend:r}),Ce=ru({inputs:{input:ge},backend:r}),Re=su({inputs:[ye,ke],backend:r,attrs:{axis:0}}),Ke=su({inputs:[Se,Ce],backend:r,attrs:{axis:0}}),Ve=r.data.get(Re.dataId).values,rt=r.data.get(Ke.dataId).values;return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(P),r.disposeIntermediateTensorInfo(B),r.disposeIntermediateTensorInfo(X),r.disposeIntermediateTensorInfo(K),r.disposeIntermediateTensorInfo(ne),r.disposeIntermediateTensorInfo(Q),r.disposeIntermediateTensorInfo(oe),r.disposeIntermediateTensorInfo(ae),r.disposeIntermediateTensorInfo(pe),r.disposeIntermediateTensorInfo(ue),r.disposeIntermediateTensorInfo(ge),r.disposeIntermediateTensorInfo(ye),r.disposeIntermediateTensorInfo(Se),r.disposeIntermediateTensorInfo(ke),r.disposeIntermediateTensorInfo(Ce),r.disposeIntermediateTensorInfo(Re),r.disposeIntermediateTensorInfo(Ke),{real:Ve,imag:rt}}function zH(e,t,n){let a=new Float32Array(t*2);for(let r=0;r<t;r++){let s=0,i=0;for(let o=0;o<t;o++){let l=_.exponent(r*o,t,n),c=_.getComplexWithIndex(e,o);s+=c.real*l.real-c.imag*l.imag,i+=c.real*l.imag+c.imag*l.real}n&&(s/=t,i/=t),_.assignToTypedArray(a,s,i,r)}return a}function BH(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=It({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=_T(o,!1,n),c=It({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var WH={kernelName:Pd,backendName:"cpu",kernelFunc:BH};function $v(e){let{backend:t,attrs:n}=e,{shape:a,value:r,dtype:s}=n,i=s||k.inferDtype(r),o=k.getArrayFromDType(i,k.sizeFromShape(a));return VH(o,r,i),t.makeTensorInfo(a,i,o)}var UH={kernelName:hc,backendName:"cpu",kernelFunc:$v};function VH(e,t,n){e.fill(t)}var GH={kernelName:jo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,r=n,s=k.getTypedArrayFromDType(a.dtype,k.sizeFromShape(a.shape)),[i,o,l,c]=a.shape,u=r.data.get(a.dataId).values;for(let p=0;p<i;p++){let d=p*l*o*c;for(let h=0;h<o;h++){let m=h*(l*c);for(let f=0;f<l;f++){let g=f*c;for(let y=0;y<c;y++){let b=[i,h,f,y][2],v=Math.round(l-b),x=d+m+g+y,N=u[x];if(v>=0&&v<l){let T=v*c,C=d+m+T+y;N=u[C]}s[x]=N}}}}return{dataId:r.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},HH=Rt((e,t)=>Math.floor(e/t)),jH=Zt(Bs,HH,null,"int32"),qH={kernelName:Bs,backendName:"cpu",kernelFunc:jH};function KH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=a,f=TT({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=gp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Cv(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var XH={kernelName:xi,backendName:"cpu",kernelFunc:KH};function YH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=a,f=ST({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=gp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Cv(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var ZH={kernelName:vi,backendName:"cpu",kernelFunc:YH};function JH(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,c,u,p]=_.prepareAndValidate(a,r);if(c===0)return n.makeTensorInfo(l,a.dtype,[]);let d=Le([c,u],a.dtype),h=n.data.get(r.dataId).values,m=n.data.get(a.dataId).values;for(let f=0;f<c;f++){let g=[],y=0;for(let b=0;b<o;b++){let v=h[f*o+b];y+=v*p[b],g.push(v)}if(y<0||y>=s/u)throw new Error(`Invalid indices: ${g} does not index into ${a.shape}`);for(let b=0;b<u;b++)d.values[f*u+b]=m[y*u+b]}return n.makeTensorInfo(l,d.dtype,d.values)}var QH={kernelName:Ko,backendName:"cpu",kernelFunc:JH};function e6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;we([r,s],"gatherV2");let l=o;o==null&&(l=0);let c=k.sizeFromShape(s.shape),u=k.parseAxisParam(i,r.shape)[0],p=_.segment_util.collectGatherOpShapeInfo(r,s,u,l),d=It({inputs:{x:r},backend:n,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),h=It({inputs:{x:s},backend:n,attrs:{shape:[p.batchSize,c/p.batchSize]}}),m=[p.batchSize,p.outerSize,c/p.batchSize,p.sliceSize],f=n.bufferSync(h),g=n.bufferSync(d),y=JN(g,f,m);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.makeTensorInfo(p.outputShape,y.dtype,y.values)}var t6={kernelName:qo,backendName:"cpu",kernelFunc:e6},n6=Rt((e,t)=>e>=t?1:0),a6=Zt(Vs,n6,null,"bool"),r6={kernelName:Vs,backendName:"cpu",kernelFunc:a6};function s6(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=It({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=_T(o,!0,n),c=It({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var i6={kernelName:Od,backendName:"cpu",kernelFunc:s6},o6=it(Yo,e=>Number.isFinite(e)?1:0,"bool"),l6={kernelName:Yo,backendName:"cpu",kernelFunc:o6},u6=it(Zo,e=>Math.abs(e)===Infinity?1:0,"bool"),c6={kernelName:Zo,backendName:"cpu",kernelFunc:u6},p6=it(Jo,e=>Number.isNaN(e)?1:0,"bool"),d6={kernelName:Jo,backendName:"cpu",kernelFunc:p6},h6=Rt((e,t)=>e<=t?1:0),m6=Zt(el,h6,null,"bool"),f6={kernelName:el,backendName:"cpu",kernelFunc:m6};function g6(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=tT(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var y6={kernelName:zd,backendName:"cpu",kernelFunc:g6},b6=it(tl,e=>Math.log1p(e)),x6={kernelName:tl,backendName:"cpu",kernelFunc:b6},v6=Rt((e,t)=>e&&t),w6=Zt(nl,v6,null,"bool"),k6={kernelName:nl,backendName:"cpu",kernelFunc:w6},I6=it(mc,e=>e?0:1,"bool"),N6={kernelName:mc,backendName:"cpu",kernelFunc:I6},T6=Rt((e,t)=>e||t),S6=Zt(fc,T6,null,"bool"),C6={kernelName:fc,backendName:"cpu",kernelFunc:S6};function _6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;we(r,"LRN");let c=r.shape[3],u=c-1,p=n.data.get(r.dataId).values,d=k.sizeFromShape(r.shape),h=new Float32Array(d);function m(f){let g=f%c,y=f-g+Math.max(0,g-s),b=f-g+Math.min(g+s,u),v=0;for(;y<=b;y++){let x=p[y];v+=x*x}return v}for(let f=0;f<d;f++){let g=m(f),y=p[f]*Math.pow(i+o*g,-l);h[f]=y}return n.makeTensorInfo(r.shape,r.dtype,h)}var E6={kernelName:gc,backendName:"cpu",kernelFunc:_6};function A6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:c,beta:u}=a;we(i,"LRNGrad");let p=k.sizeFromShape(i.shape),d=i.shape[3],h=n.data.get(i.dataId).values,m=n.data.get(r.dataId).values,f=n.data.get(s.dataId).values,g=new Float32Array(p),y=p;for(let b=0;b<y;b++){let v=b%d,x=b-v+Math.max(0,v-o),N=b-v+Math.min(d,v+o+1),T=0;for(let C=x;C<N;C++)T+=Math.pow(m[C],2);T=c*T+l;for(let C=x;C<N;C++){let F=-2*c*u*m[C]*f[b]/T;b===C&&(F+=Math.pow(T,-u)),F*=h[b],g[C]+=F}}return n.makeTensorInfo(i.shape,r.dtype,g)}var F6={kernelName:Bd,backendName:"cpu",kernelFunc:A6};function ET(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=n,l=r.shape,c=l.length,u=k.parseAxisParam(s,l),p=u,d=_.getAxesPermutation(p,c),h=o.data.get(r.dataId).values;if(d!=null){let x=new Array(c);for(let N=0;N<x.length;N++)x[N]=l[d[N]];h=kv(h,l,r.dtype,d,x),p=_.getInnerMostAxes(p.length,c),l=x}we(r,"max"),_.assertAxesAreInnerMostDims("max",p,c);let[m,f]=_.computeOutAndReduceShapes(l,p),g=k.sizeFromShape(f),y=aT(h,g,m,r.dtype),b=o.write(y,m,r.dtype),v=m;return i&&(v=_.expandShapeToKeepDim(m,u)),{dataId:b,shape:v,dtype:r.dtype}}var $6={kernelName:js,backendName:"cpu",kernelFunc:ET};function D6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;we(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))p=rr({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=k.computeStrides(r.shape),m=_v(d,r.shape,r.dtype,h,u,"max");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var R6={kernelName:Ks,backendName:"cpu",kernelFunc:D6};function M6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a;we(r,"maxPool3d");let u=_.computePool3DInfo(r.shape,s,i,1,o,l,c),p=n.data.get(r.dataId).values,d=NT(p,r.shape,r.dtype,k.computeStrides(r.shape),u,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}var P6={kernelName:yc,backendName:"cpu",kernelFunc:M6};function O6(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=a;we([r,s],"maxPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,c),p=n.bufferSync(s),d=IG(p,u),h=u.strideDepth,m=u.strideHeight,f=u.strideWidth,g=u.dilationDepth,y=u.dilationHeight,b=u.dilationWidth,v=u.effectiveFilterDepth,x=u.effectiveFilterHeight,N=u.effectiveFilterWidth,T=v-1-u.padInfo.front,C=N-1-u.padInfo.left,F=x-1-u.padInfo.top,$=Le(s.shape,"float32"),P=n.bufferSync(r);for(let B=0;B<u.batchSize;++B)for(let W=0;W<u.inChannels;++W)for(let G=0;G<u.inDepth;++G)for(let q=0;q<u.inHeight;++q)for(let j=0;j<u.inWidth;++j){let X=G-T,K=q-F,ne=j-C,J=0;for(let se=0;se<v;se+=g){let Q=(X+se)/h;if(!(Q<0||Q>=u.outDepth||Math.floor(Q)!==Q))for(let oe=0;oe<x;oe+=y){let ae=(K+oe)/m;if(!(ae<0||ae>=u.outHeight||Math.floor(ae)!==ae))for(let pe=0;pe<N;pe+=b){let ue=(ne+pe)/f;if(ue<0||ue>=u.outWidth||Math.floor(ue)!==ue)continue;let ge=v*x*N-1-d.get(B,Q,ae,ue,W),ye=se*x*N+oe*N+pe,ke=ge===ye?1:0;ke!==0&&(J+=P.get(B,Q,ae,ue,W)*ke)}}}$.set(J,B,G,q,j,W)}return n.makeTensorInfo($.shape,$.dtype,$.values)}var L6={kernelName:Vd,backendName:"cpu",kernelFunc:O6};function z6(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;we([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=_.computePool2DInfo(o.shape,l,c,1,u,p),h=n.data.get(o.dataId).values,m=Le(d.outShape,o.dtype,IT(h,o.shape,o.dtype,d).values),f=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,b=d.dilationWidth,v=d.effectiveFilterHeight,x=d.effectiveFilterWidth,N=x-1-d.padInfo.left,T=v-1-d.padInfo.top,C=Le(o.shape,"float32"),F=n.data.get(r.dataId).values,$=Le(r.shape,"float32",F);for(let P=0;P<d.batchSize;++P)for(let B=0;B<d.inChannels;++B)for(let W=0;W<d.inHeight;++W)for(let G=0;G<d.inWidth;++G){let q=W-T,j=G-N,X=0;for(let K=0;K<v;K+=y){let ne=(q+K)/f;if(!(ne<0||ne>=d.outHeight||Math.floor(ne)!==ne))for(let J=0;J<x;J+=b){let se=(j+J)/g;if(se<0||se>=d.outWidth||Math.floor(se)!==se)continue;let Q=v*x-1-m.get(P,ne,se,B),oe=K*x+J,ae=Q===oe?1:0;ae!==0&&(X+=$.get(P,ne,se,B)*ae)}}C.set(X,P,W,G,B)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var B6={kernelName:Wd,backendName:"cpu",kernelFunc:z6};function W6(e,t,n,a,r){let s=k.computeStrides(t),i=_v(e,t,n,s,r,"max"),o=IT(e,t,n,r,!0,a);return[i.values,o.values]}var V6={kernelName:Ud,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;we(a,"MaxPoolWithArgmax");let c=l.data.get(a.dataId).values,u=_.computePool2DInfo(a.shape,r,s,[1,1],i),[p,d]=W6(c,a.shape,a.dtype,o,u),h=l.write(p,u.outShape,a.dtype),m=l.write(d,u.outShape,a.dtype);return[{dataId:h,shape:u.outShape,dtype:a.dtype},{dataId:m,shape:u.outShape,dtype:"int32"}]}};function Pm(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;we(r,"sum");let o;r.dtype==="bool"?o=us({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=rr({inputs:{x:r},backend:n});let l=o.shape.length,c=k.parseAxisParam(s,o.shape),u=_.getAxesPermutation(c,l),p=c,d=o;u!=null&&(d=ya({inputs:{x:o},backend:n,attrs:{perm:u}}),p=_.getInnerMostAxes(p.length,l)),_.assertAxesAreInnerMostDims("sum",p,d.shape.length);let[h,m]=_.computeOutAndReduceShapes(d.shape,p),f=_.upcastType(d.dtype,"int32"),g=Rm(n,h,f),y=k.sizeFromShape(m),b=n.data.get(g.dataId).values,v=n.data.get(d.dataId).values;for(let x=0;x<b.length;++x){let N=x*y,T=0;for(let C=0;C<y;++C)T+=v[N+C];b[x]=T}if(i){let x=_.expandShapeToKeepDim(g.shape,c),N=g;g=It({inputs:{x:g},backend:n,attrs:{shape:x}}),n.disposeIntermediateTensorInfo(N)}return n.disposeIntermediateTensorInfo(o),u!=null&&n.disposeIntermediateTensorInfo(d),g}var U6={kernelName:di,backendName:"cpu",kernelFunc:Pm};function G6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=k.parseAxisParam(s,r.shape),l=_.computeOutAndReduceShapes(r.shape,o)[1],c=k.sizeFromShape(l),u=[],p=n.makeTensorInfo([],"float32",new Float32Array([c]));u.push(p);let d=us({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(d);let h=Ev({inputs:{a:d,b:p},backend:n});u.push(h);let m=Pm({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var H6={kernelName:Xs,backendName:"cpu",kernelFunc:G6};function j6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;we(r,"min");let o=k.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=ya({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("min",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=k.sizeFromShape(d),m=k.makeZerosTypedArray(k.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,v=f[b];for(let x=0;x<h;++x){let N=f[b+x];N<v&&(v=N)}m[y]=v}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=It({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var q6={kernelName:Ys,backendName:"cpu",kernelFunc:j6};function K6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,mode:i}=a;we(r,"mirrorPad");let o=s.map((b,v)=>b[0]+r.shape[v]+b[1]),l=s.map(b=>b[0]),c=s.map((b,v)=>b[0]+r.shape[v]),u=i==="reflect"?0:1,p=n.data.get(r.dataId).values,d=r.shape.length,h=k.computeStrides(r.shape),m=k.sizeFromShape(o),f=o.length,g=k.computeStrides(o),y=k.getTypedArrayFromDType(r.dtype,m);for(let b=0;b<m;b++){let v=k.indexToLoc(b,f,g);for(let N=0;N<f;N++)v[N]<l[N]?v[N]=l[N]*2-v[N]-u:v[N]>=c[N]&&(v[N]=(c[N]-1)*2-v[N]+u);v=v.map((N,T)=>N-l[T]);let x=k.locToIndex(v,d,h);y[b]=p[x]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}var X6={kernelName:bc,backendName:"cpu",kernelFunc:K6},Y6=Rt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),Z6=Zt(al,Y6),J6={kernelName:al,backendName:"cpu",kernelFunc:Z6},Q6=So(fd());function AT(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),c=ET({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=_.expandShapeToKeepDim(c.shape,l),p=It({inputs:{x:c},backend:n,attrs:{shape:u}}),d=Sv({inputs:{a:r,b:p},backend:n}),h=gT({inputs:{x:d},backend:n}),m=Pm({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),f=It({inputs:{x:m},backend:n,attrs:{shape:u}}),g=Ev({inputs:{a:h,b:f},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var ej={kernelName:hi,backendName:"cpu",kernelFunc:AT};function tj(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;we(r,"multinomial");let l=o?r:AT({inputs:{logits:r},backend:n,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],p=n.data.get(l.dataId).values,d=[c,s],h=k.makeZerosTypedArray(k.sizeFromShape(d),"int32");for(let m=0;m<c;++m){let f=m*u,g=new Float32Array(u-1);g[0]=p[f];for(let v=1;v<g.length;++v)g[v]=g[v-1]+p[f+v];let y=Q6.alea(i.toString()),b=m*s;for(let v=0;v<s;++v){let x=y();h[b+v]=g.length;for(let N=0;N<g.length;N++)if(x<g[N]){h[b+v]=N;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(d,"int32",h)}var nj={kernelName:Gd,backendName:"cpu",kernelFunc:tj},aj=Ja.nonMaxSuppressionV3Impl;function rj(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;we(r,"NonMaxSuppression");let c=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,{selectedIndices:p}=aj(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var sj={kernelName:il,backendName:"cpu",kernelFunc:rj},ij=Ja.nonMaxSuppressionV4Impl;function oj(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:c}=a;we(r,"NonMaxSuppressionPadded");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,{selectedIndices:d,validOutputs:h}=ij(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var lj={kernelName:ol,backendName:"cpu",kernelFunc:oj},uj=Ja.nonMaxSuppressionV5Impl;function cj(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:c}=a;we(r,"NonMaxSuppressionWithScore");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,d=i,h=o,m=l,f=c,{selectedIndices:g,selectedScores:y}=uj(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var pj={kernelName:ll,backendName:"cpu",kernelFunc:cj};function dj(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a;we(r,"oneHot");let l=k.sizeFromShape(r.shape),c=new Float32Array(l*s);c.fill(o);let u=n.data.get(r.dataId).values;for(let p=0;p<l;++p)u[p]>=0&&u[p]<s&&(c[p*s+u[p]]=i);return n.makeTensorInfo([...r.shape,s],"int32",c)}var hj={kernelName:Qs,backendName:"cpu",kernelFunc:dj};function Om(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(a.dtype==="complex64"){let r=Ui({inputs:{input:a},backend:n}),s=Om({inputs:{x:r},backend:n}),i=ru({inputs:{input:a},backend:n}),o=Om({inputs:{x:i},backend:n}),l=Bn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return $v({backend:n,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var mj={kernelName:Sl,backendName:"cpu",kernelFunc:Om};function FT(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(a.dtype==="complex64"){let r=Ui({inputs:{input:a},backend:n}),s=FT({inputs:{x:r},backend:n}),i=ru({inputs:{input:a},backend:n}),o=Om({inputs:{x:i},backend:n}),l=Bn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return $v({backend:n,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var fj={kernelName:ul,backendName:"cpu",kernelFunc:FT};function $T(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Mm({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=Mm({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=su({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var gj={kernelName:cl,backendName:"cpu",kernelFunc:$T};function yj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;we(r,"pad");let o=s.map((y,b)=>y[0]+r.shape[b]+y[1]),l=s.map(y=>y[0]),c=n.data.get(r.dataId).values,u=k.sizeFromShape(r.shape),p=r.shape.length,d=k.computeStrides(r.shape),h=k.sizeFromShape(o),m=o.length,f=k.computeStrides(o),g=k.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let y=0;y<u;y++){let b=k.indexToLoc(y,p,d).map((x,N)=>x+l[N]),v=k.locToIndex(b,m,f);g[v]=c[y]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var DT={kernelName:ei,backendName:"cpu",kernelFunc:yj},bj=Rt((e,t)=>Math.pow(e,t)),xj=Zt(ti,bj),vj={kernelName:ti,backendName:"cpu",kernelFunc:xj};function wj(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=Iv(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var kj={kernelName:xc,backendName:"cpu",kernelFunc:wj},Ij=it(dl,e=>1/e),Nj={kernelName:dl,backendName:"cpu",kernelFunc:Ij};function Tj(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;we(r,"resizeBilinear");let l=k.computeStrides(r.shape),[c,u]=o,[p,d,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(k.sizeFromShape([p,c,u,m])),y=[s&&c>1?d-1:d,s&&u>1?h-1:h],b=[s&&c>1?c-1:c,s&&u>1?u-1:u],v=0,x=y[0]/b[0],N=y[1]/b[1];for(let T=0;T<p;T++)for(let C=0;C<c;C++){let F;i?F=x*(C+.5)-.5:F=x*C;let $=Math.max(0,Math.floor(F)),P=F-$,B=Math.min(d-1,Math.ceil(F)),W=T*l[0]+$*l[1],G=T*l[0]+B*l[1];for(let q=0;q<u;q++){let j;i?j=N*(q+.5)-.5:j=N*q;let X=Math.max(0,Math.floor(j)),K=j-X,ne=Math.min(h-1,Math.ceil(j)),J=W+X*l[2],se=G+X*l[2],Q=W+ne*l[2],oe=G+ne*l[2];for(let ae=0;ae<m;ae++){let pe=f[J+ae],ue=f[se+ae],ge=f[Q+ae],ye=f[oe+ae],ke=pe+(ge-pe)*K,Se=ue+(ye-ue)*K,Ce=ke+(Se-ke)*P;g[v++]=Ce}}}return n.makeTensorInfo([p,c,u,m],"float32",g)}var Sj={kernelName:ri,backendName:"cpu",kernelFunc:Tj};function Cj(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;we([s,r],"resizeBilinearGrad");let o=k.computeStrides(r.shape),[l,c,u,p]=r.shape,[,d,h]=s.shape,m=new Float32Array(l*c*u*p),f=[i&&d>1?c-1:c,i&&h>1?u-1:u],g=[i&&d>1?d-1:d,i&&h>1?h-1:h],y=f[0]/g[0],b=f[1]/g[1],v=n.data.get(s.dataId).values,x=0;for(let N=0;N<l;N++){let T=N*o[0];for(let C=0;C<d;C++){let F=C*y,$=Math.floor(F),P=Math.min(Math.ceil(F),c-1),B=T+$*o[1],W=T+P*o[1],G=F-$,q=1-G;for(let j=0;j<h;j++){let X=j*b,K=Math.floor(X),ne=Math.min(Math.ceil(X),u-1),J=X-K,se=1-J,Q=B+K*o[2],oe=B+ne*o[2],ae=W+K*o[2],pe=W+ne*o[2],ue=q*se,ge=q*J,ye=G*se,ke=G*J;for(let Se=0;Se<p;Se++){let Ce=v[x++];m[Q+Se]+=Ce*ue,m[oe+Se]+=Ce*ge,m[ae+Se]+=Ce*ye,m[pe+Se]+=Ce*ke}}}}return n.makeTensorInfo([l,u,c,p],"float32",m)}var _j={kernelName:qd,backendName:"cpu",kernelFunc:Cj};function Ej(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;we(r,"resizeNearestNeighbor");let l=k.computeStrides(r.shape),[c,u]=o,[p,d,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(p*c*u*m),y=[s&&c>1?d-1:d,s&&u>1?h-1:h],b=[s&&c>1?c-1:c,s&&u>1?u-1:u],v=y[0]/b[0],x=y[1]/b[1],N=0;for(let T=0;T<p;T++){let C=T*l[0];for(let F=0;F<c;F++){let $=i?v*(F+.5):v*F,P=Math.min(d-1,s?Math.round($):Math.floor($));i&&(P=Math.max(0,P));let B=C+P*l[1];for(let W=0;W<u;W++){let G=i?x*(W+.5):x*W,q=Math.min(h-1,s?Math.round(G):Math.floor(G));i&&(q=Math.max(0,q));let j=B+q*l[2];for(let X=0;X<m;X++){let K=f[j+X];g[N++]=K}}}}return n.makeTensorInfo([p,c,u,m],r.dtype,g)}var Aj={kernelName:vc,backendName:"cpu",kernelFunc:Ej};function Fj(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;we([s,r],"resizeNearestNeighborGrad");let o=k.computeStrides(r.shape),l=k.computeStrides(s.shape),[c,u,p,d]=r.shape,[,h,m]=s.shape,f=new Float32Array(c*u*p*d),g=n.data.get(s.dataId).values,y=[i&&h>1?u-1:u,i&&m>1?p-1:p],b=[i&&h>1?h-1:h,i&&m>1?m-1:m],v=y[0]/b[0],x=y[1]/b[1],N=1/v,T=1/x,C=Math.ceil(N)*2+2,F=Math.ceil(T)*2+2;for(let $=0;$<c;$++){let P=$*o[0];for(let B=0;B<u;B++){let W=P+B*o[1],G=Math.floor(B*N),q=Math.floor(G-C/2);for(let j=0;j<p;j++){let X=W+j*o[2],K=Math.floor(j*T),ne=Math.floor(K-F/2);for(let J=0;J<d;J++){let se=0;for(let Q=0;Q<C;Q++){let oe=Q+q;if(oe<0||oe>=h)continue;let ae=P+oe*l[1],pe=oe*v,ue=Math.min(u-1,i?Math.round(pe):Math.floor(pe));if(B===ue)for(let ge=0;ge<F;ge++){let ye=ge+ne;if(ye<0||ye>=m)continue;let ke=ae+ye*l[2],Se=ye*x,Ce=Math.min(p-1,i?Math.round(Se):Math.floor(Se));j===Ce&&(se+=g[ke+J])}}f[X+J]=se}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var $j={kernelName:jd,backendName:"cpu",kernelFunc:Fj};function Dj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;we(r,"reverse");let i=r.shape.length,o=k.parseAxisParam(s,r.shape);if(i===0)return rr({inputs:{x:r},backend:n});let l=new Ot(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;u<l.size;u++){let p=l.indexToLoc(u),d=p.slice();o.forEach(h=>d[h]=r.shape[h]-1-d[h]),l.set(c.get(...d),...p)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var Rj={kernelName:ii,backendName:"cpu",kernelFunc:Dj},Mj={kernelName:Cl,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)),[c,u,p,d]=a.shape,[h,m]=_.getImageCenter(i,u,p),f=255,g=Math.sin(r),y=Math.cos(r),b=o.data.get(a.dataId).values;for(let v=0;v<c;v++){let x=v*p*u*d;for(let N=0;N<u;N++){let T=N*(p*d);for(let C=0;C<p;C++){let F=C*d;for(let $=0;$<d;$++){let P=[c,N,C,$],B=P[2],W=P[1],G=(B-h)*y-(W-m)*g,q=(B-h)*g+(W-m)*y;G=Math.round(G+h),q=Math.round(q+m);let j=s;if(typeof s!="number"&&($===3?j=f:j=s[$]),G>=0&&G<p&&q>=0&&q<u){let K=q*(p*d),ne=G*d,J=x+K+ne+$;j=b[J]}let X=x+T+F+$;l[X]=j}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},Pj=it(oi,e=>{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),Oj={kernelName:oi,backendName:"cpu",kernelFunc:Pj};function RT(e,t,n,a,r,s,i,o,l,c){let u=[a/r,r],p=e.values,d=t.values;if(a===0)return Le(n,t.dtype);let h=Le(u,t.dtype);h.values.fill(l);for(let m=0;m<s;m++){let f=[],g=0;for(let y=0;y<i;y++){let b=p[m*i+y];f.push(b),g+=b*o[y]}if(g<0||g>=a/r)throw new Error(`Invalid indices: ${f} does not index into ${n}`);for(let y=0;y<r;y++)c?h.values[g*r+y]+=d[m*r+y]:h.values[g*r+y]=t.rank===0?d[0]:d[m*r+y]}return h}function Lj(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:c,strides:u,outputSize:p}=_.calculateShapes(s,r,i),d=!0,h=n.bufferSync(r),m=n.bufferSync(s),f=RT(h,m,i,p,c,l,o,u,0,d);return n.makeTensorInfo(i,f.dtype,f.values)}var zj={kernelName:ml,backendName:"cpu",kernelFunc:Lj};function Bj(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t;we([a,r,s],"select");let i=a.shape.length,o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,u=ua(r.dtype,s.dtype),p=k.makeZerosTypedArray(k.sizeFromShape(r.shape),u),d=0,h=i===0||i>1||r.shape.length===1?1:k.sizeFromShape(r.shape.slice(1));for(let m=0;m<o.length;m++)for(let f=0;f<h;f++)o[m]===1?p[d++]=l[m]:p[d++]=c[m];return n.makeTensorInfo(r.shape,u,p)}var Wj={kernelName:fl,backendName:"cpu",kernelFunc:Bj},Vj=_.SELU_SCALEALPHA,Uj=_.SELU_SCALE,Gj=it(gl,e=>e>=0?Uj*e:Vj*(Math.exp(e)-1)),Hj={kernelName:gl,backendName:"cpu",kernelFunc:Gj},jj=it(ci,e=>1/(1+Math.exp(-e))),qj={kernelName:ci,backendName:"cpu",kernelFunc:jj},Kj=it(xl,e=>e<0?-1:e>0?1:0),Xj={kernelName:xl,backendName:"cpu",kernelFunc:Kj},Yj=it(ui,e=>Math.sin(e)),Zj={kernelName:ui,backendName:"cpu",kernelFunc:Yj},Jj=it(bl,e=>Math.sinh(e)),Qj={kernelName:bl,backendName:"cpu",kernelFunc:Jj},eq=11920928955078125e-23,MT=Math.log(eq)+2,tq=it(vl,e=>{let t=e>-MT,n=e<MT,a=Math.exp(e),r;return n?r=a:t?r=e:r=Math.log(1+a),r}),nq={kernelName:vl,backendName:"cpu",kernelFunc:tq};function aq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;we([r],"spaceToBatchND");let o=k.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let c=DT.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),u=_.getReshaped(c.shape,s,o,!1),p=_.getPermuted(u.length,s.length,!1),d=_.getReshapedPermuted(c.shape,s,o,!1),h=It({inputs:{x:c},backend:n,attrs:{shape:u}}),m=ya({inputs:{x:h},backend:n,attrs:{perm:p}}),f=It({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}var rq={kernelName:wc,backendName:"cpu",kernelFunc:aq};function sq(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:c,sliceSize:u,strides:p,outputSize:d}=_.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f=n.bufferSync(s),g=n.data.get(i.dataId).values[0],y=RT(m,f,o,d,u,c,l,p,g,h);return n.makeTensorInfo(o,y.dtype,y.values)}var iq={kernelName:Kd,backendName:"cpu",kernelFunc:sq};function oq(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=_.prepareSplitSize(r,s,o),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(p=>{let d=[...u];d[o]=p;let h=Gi({inputs:{x:r},backend:n,attrs:{begin:c,size:d}});return c[o]+=p,h})}var lq={kernelName:wl,backendName:"cpu",kernelFunc:oq},uq=it(pi,e=>Math.sqrt(e)),cq={kernelName:pi,backendName:"cpu",kernelFunc:uq},pq={kernelName:kc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;we(n,"square");let r=a.data.get(n.dataId).values,s=new Float32Array(r.length);for(let i=0;i<r.length;++i){let o=r[i];s[i]=o*o}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},dq=it(Vr,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),hq={kernelName:Vr,backendName:"cpu",kernelFunc:dq};function mq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:d}=a;we(r,"stridedSlice");let{nonStrided:h,$begin:m,$strides:f,size:g,newShape:y,outShape:b}=cn.sliceInfo(r.shape,s,i,o,l,c,u,p,d),v=It({inputs:{x:r},backend:n,attrs:{shape:y}}),x;if(h){let T=Gi({inputs:{x:v},backend:n,attrs:{begin:m,size:g}});x=It({inputs:{x:T},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(T)}else if(b.some(T=>T===0))x=n.makeTensorInfo(b,r.dtype,[]);else{let T=n.bufferSync(v),C=pT(b,T,f,m);x=n.makeTensorInfo(C.shape,C.dtype,C.values)}let N=It({inputs:{x},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),N}var fq={kernelName:kl,backendName:"cpu",kernelFunc:mq},gq=it(Il,e=>Math.tan(e)),yq={kernelName:Il,backendName:"cpu",kernelFunc:gq},bq=it(gi,e=>Math.tanh(e)),xq={kernelName:gi,backendName:"cpu",kernelFunc:bq};function vq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;we(r,"tile");let i=hT(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var wq={kernelName:Wr,backendName:"cpu",kernelFunc:vq};function kq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;we(r,"topk");let o=n.data.get(r.dataId).values,[l,c]=mT(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var Iq={kernelName:Nl,backendName:"cpu",kernelFunc:kq};function Nq(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;we(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:c}=fT(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var Tq={kernelName:Xd,backendName:"cpu",kernelFunc:Nq};function Sq(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.length,o=r.shape[s],l=new Array(i-1),c=0;for(let h=0;h<i;h++)h!==s&&(l[c++]=r.shape[h]);let u=new Array(i).fill(0),p=r.shape.slice();p[s]=1;let d=new Array(o);for(let h=0;h<d.length;h++){u[s]=h;let m=Gi({inputs:{x:r},backend:n,attrs:{begin:u,size:p}});d[h]=It({inputs:{x:m},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(m)}return d}var Cq={kernelName:Tl,backendName:"cpu",kernelFunc:Sq};function _q(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a;we(r,"unsortedSegmentSum");let o=r.shape.length,l=s.shape.length,c=[],u=[],p=o-l,d=s;for(let m=0;m<p;++m){let f=Mm({inputs:{input:d},backend:n,attrs:{dim:m+1}});d=f,u.push(f)}for(let m=0;m<i;++m){let f=k.createScalarValue(m,"int32"),g=n.makeTensorInfo([],"int32",f),y=CT({inputs:{a:g,b:d},backend:n}),b=us({inputs:{x:y},backend:n,attrs:{dtype:"float32"}}),v=Tv({inputs:{a:b,b:r},backend:n}),x=Pm({inputs:{x:v},backend:n,attrs:{axis:0,keepDims:!1}});c.push(x),u.push(g),u.push(y),u.push(b),u.push(v),u.push(x)}let h=$T({inputs:c,backend:n,attrs:{axis:0}});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var Eq={kernelName:Ic,backendName:"cpu",kernelFunc:_q},Aq=[ZU,tU,QU,tG,oU,aG,sG,oG,uG,pG,hG,fG,yG,vG,kG,TG,CG,EG,FG,XU,DG,MG,OG,sU,uU,zG,nU,WG,UG,jG,KG,GG,JG,eH,YG,nH,rH,iH,lH,cH,dH,hH,fH,yH,xH,vH,kH,wH,Av,VU,NH,SH,RH,cU,MH,dU,WH,UH,GH,mU,qH,XH,ZH,QH,t6,gU,r6,aU,i6,VG,l6,c6,d6,UU,bU,f6,y6,vU,x6,k6,N6,C6,E6,F6,kU,R6,P6,L6,B6,V6,$6,H6,q6,NU,X6,J6,nj,SU,_U,sj,lj,pj,AU,hj,fj,gj,DT,vj,HU,DU,kj,rU,Nj,jU,qU,KU,Sj,_j,Aj,$j,Rj,Mj,Oj,MU,zj,Wj,Hj,qj,Xj,Zj,Qj,PU,ej,nq,rq,iq,lq,cq,pq,LU,hq,fq,BU,U6,yq,xq,wq,Iq,FU,Tq,Cq,Eq,mj];for(let e of Aq)Tc(e);var Hi={},Dv={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Fq(e,t){Hi[e]=t}function sr(e){if(!(e in Hi)){let n=$q(e);if(n!==null)Hi[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=Hi[e];return t.isContextLost()?(delete Hi[e],sr(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),Hi[e])}function Dq(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 $q(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=Dq(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Hi[e]},!1),e===1?t.getContext("webgl",Dv)||t.getContext("experimental-webgl",Dv):t.getContext("webgl2",Dv)}var yp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(yp||(yp={}));var Qn;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(Qn||(Qn={}));var tn;(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"})(tn||(tn={}));function bp(e,t){return[t,e]}function Rq(e,t){return e*t}function xp(e){let t=k.sizeFromShape(e),n=Math.ceil(t/4);return k.sizeToSquarishShape(n)}function iu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Mq(e,t){let[n,a]=iu(e,t);return n*a*4}function Rv(e,t){let n=e,a,r,s,i,o,l,c,u,p,d;return ee().getNumber("WEBGL_VERSION")===2?(a=n.R32F,r=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=n.RED,c=4,u=1,p=n.HALF_FLOAT,d=n.FLOAT):(a=e.RGBA,r=e.RGBA,s=e.RGBA,i=n.RGBA,o=e.RGBA,c=4,u=4,p=t!=null?t.HALF_FLOAT_OES:null,d=e.FLOAT),l=e.RGBA,{internalFormatFloat:a,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:p,textureTypeFloat:d}}function Ne(e,t){let n=t();return ee().getBool("DEBUG")&&Pq(e),n}function Pq(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+Oq(e,t))}var Lq=596e-10,zq=65504;function Bq(e){return!!(ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Lq<Math.abs(e)&&Math.abs(e)<zq)}function Oq(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function Lm(e,t){return Tr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function Wq(e,t){let n=Tr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ne(e,()=>e.shaderSource(n,t)),Ne(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 Uq(e,t){let n=Tr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ne(e,()=>e.shaderSource(n,t)),Ne(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Vq(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var Gq=/ERROR: [0-9]+:([0-9]+):/g;function Vq(e,t){let n=Gq.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((p,d)=>k.rightPad((d+1).toString(),s)+p),o=0;for(let p=0;p<i.length;p++)o=Math.max(i[p].length,o);let l=i.slice(0,a-1),c=i.slice(a-1,a),u=i.slice(a);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${k.rightPad(c[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
|
|
`))}function Hq(e){return Tr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function jq(e,t){if(Ne(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 Mv(e,t){if(Ne(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function qq(e,t){let n=Tr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ne(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ne(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Kq(e,t){let n=Tr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ne(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ne(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Xq(e){return Tr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Yq(e,t){let n=ee().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 Zq(e){return Tr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function PT(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(Ne(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),Ne(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),Ne(e,()=>e.enableVertexAttribArray(o)),!0)}function Qq(e,t,n){Jq(e,n),Ne(e,()=>e.activeTexture(e.TEXTURE0+n)),Ne(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function e5(e,t,n){return Tr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function t5(e,t,n){return e.getUniformLocation(t,n)}function n5(e,t,n,a){Ne(e,()=>Qq(e,t,a)),Ne(e,()=>e.uniform1i(n,a))}function Pv(e,t,n){Ne(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ne(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function OT(e,t){Ne(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ne(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function zm(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+a5(e,t))}function a5(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 Tr(e,t,n){let a=Ne(e,()=>t());if(a==null)throw new Error(n);return a}function Jq(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>n){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function ou(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function lu(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 Ov(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[ou(e),...lu(e)]),t}function r5(e,t=!1){let n=ee().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=ou(e),s=2,i=2;return e.length&&([s,i]=lu(e)),a=r*(s/2)*(i/2),k.sizeToSquarishShape(a).map(o=>o*2)}return k.sizeToSquarishShape(a)}function Bm(e){return e%2==0}function Wm(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||Bm(n)&&Bm(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Bm(e[0])&&Bm(t[0])}var Lv,zv;function s5(e){if(Lv==null){let t=sr(e);Lv=t.getParameter(t.MAX_TEXTURE_SIZE)}return Lv}function i5(e){if(zv==null){let t=sr(e);zv=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,zv)}function o5(e){if(e===0)return 0;let t,n=sr(e);return ba(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:ba(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function ba(e,t){return e.getExtension(t)!=null}function LT(e){try{if(sr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function l5(e){if(e===0)return!1;let t=sr(e);if(e===1){if(!ba(t,"OES_texture_float"))return!1}else if(!ba(t,"EXT_color_buffer_float"))return!1;return Bv(t)}function c5(e){if(e===0)return!1;let t=sr(e);if(e===1){if(!ba(t,"OES_texture_float")||!ba(t,"WEBGL_color_buffer_float"))return!1}else{if(ba(t,"EXT_color_buffer_float"))return Bv(t);let n="EXT_color_buffer_half_float";if(ba(t,n)){let a=t.getExtension(n);return u5(t,a)}return!1}return Bv(t)}function Bv(e){let t=Rv(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 u5(e,t){let n=Rv(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 p5(e){return e!==2?!1:sr(e).fenceSync!=null}function vp(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 Ee=ee();Ee.registerFlag("HAS_WEBGL",()=>Ee.getNumber("WEBGL_VERSION")>0);Ee.registerFlag("WEBGL_VERSION",()=>LT(2)?2:LT(1)?1:0);Ee.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ee.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ee.get("WEBGL_VERSION")===2);Ee.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ee.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ee.registerFlag("WEBGL_PACK",()=>Ee.getBool("HAS_WEBGL"));Ee.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_CLIP",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);Ee.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_REDUCE",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_CONV_IM2COL",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>s5(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>i5(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Ee.getNumber("WEBGL_VERSION");return e===0?0:o5(e)});Ee.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ee.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ah.isMobile());Ee.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>l5(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ee.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ee.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ee.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>c5(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_FENCE_API_ENABLED",()=>p5(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ee.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ee.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}.`)});function hn(){let e,t,n,a,r,s,i,o,l,c;return ee().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="",c=`
|
|
#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));
|
|
}
|
|
`,c=`
|
|
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:c}}function ji(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 Wv(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 zT=`
|
|
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;
|
|
}
|
|
`,d5=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=yp.DENSE;let t=xp(e),n=hn();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${ji(["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;
|
|
}
|
|
`}},h5=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=yp.DENSE;let t=xp(e),n=hn();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${ji(["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;
|
|
}
|
|
`}},m5=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Qn.DOWNLOAD;let t=hn();this.outputShape=e,this.userCode=`
|
|
${zT}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},f5=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Qn.DOWNLOAD;let t=hn();this.outputShape=e,this.userCode=`
|
|
${zT}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},g5=class{constructor(e,t,n=!1){this.variableNames=["A"];let a=hn(),[r,s]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${Wv(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.);
|
|
}
|
|
`}},y5=class{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let a=hn(),[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 c=0;c<=1;c++){let u=l*2+c;i+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${c} < ${e[2]}) {
|
|
localCoords[2] += ${c};
|
|
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[${u}] = values[0];
|
|
} else if(offset == 1) {
|
|
result[${u}] = values[1];
|
|
} else if(offset == 2) {
|
|
result[${u}] = values[2];
|
|
} else {
|
|
result[${u}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${Wv(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};
|
|
}
|
|
`}};function b5(e){let t=hn(),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 Wq(e,n)}function x5(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 qq(e,t)}function v5(e){let t=new Uint16Array([0,1,2,2,1,3]);return Kq(e,t)}function wp(e,t,n,a,r,s){Yq(t,n);let i=Xq(e),o=e.TEXTURE_2D;return Ne(e,()=>e.bindTexture(o,i)),Ne(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ne(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ne(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ne(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ne(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)),Ne(e,()=>e.bindTexture(e.TEXTURE_2D,null)),i}function BT(e){return e.internalFormatFloat}function w5(e,t,n,a){let[r,s]=bp(t,n);return wp(e,r,s,BT(a),a.textureFormatFloat,e.FLOAT)}function WT(e){return e.internalFormatHalfFloat}function k5(e,t,n,a){let[r,s]=bp(t,n);return wp(e,r,s,WT(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function VT(e){return e.downloadTextureFormat}function I5(e,t,n,a){let[r,s]=bp(t,n);return wp(e,r,s,VT(a),e.RGBA,e.UNSIGNED_BYTE)}function UT(e){return e.internalFormatPackedFloat}function N5(e,t,n,a){let[r,s]=iu(t,n);return wp(e,r,s,UT(a),e.RGBA,e.FLOAT)}function GT(e){return e.internalFormatPackedHalfFloat}function T5(e,t,n,a){let[r,s]=iu(t,n);return wp(e,r,s,GT(a),e.RGBA,a.textureTypeHalfFloat)}function S5(e,t,n){let a=0,r=3*4,s=3*4+2*4;return Ne(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),PT(e,t,"clipSpacePos",n,3,s,a)&&PT(e,t,"uv",n,2,s,r)}function C5(e,t,n,a,r,s){Ne(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),Ne(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),Ne(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function _5(e,t,n){Ne(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ne(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ne(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ne(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function E5(e,t,n,a){let r=e.createBuffer();Ne(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return Ne(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),Ne(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ne(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function A5(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 F5(e,t,n,a){let[r,s]=bp(t,n),i=4,o=new Uint8Array(Rq(t*n,i));return Ne(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function $5(e,t,n,a,r,s,i,o){let l=e,c=new Float32Array(Mq(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function D5(e,t,n){let a=new Float32Array(t*n*4);return Ne(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var M5=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=ee().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Fq(t,e)):this.gl=sr(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(ee().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Lm(this.gl,r),ba(this.gl,s))this.textureHalfFloatExtension=Lm(this.gl,s);else if(ee().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),ba(this.gl,a))this.colorBufferHalfFloatExtension=Lm(this.gl,a);else if(ee().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",ba(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(ba(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=x5(this.gl),this.indexBuffer=v5(this.gl),this.framebuffer=Zq(this.gl),this.textureConfig=Rv(this.gl,this.textureHalfFloatExtension)}get debug(){return ee().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;Ne(e,()=>e.finish()),Ne(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ne(e,()=>e.deleteFramebuffer(this.framebuffer)),Ne(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ne(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ne(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),w5(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),k5(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),I5(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),_5(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),C5(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),T5(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),N5(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(OT(this.gl,this.framebuffer),this.outputTexture=null),Ne(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>F5(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return $5(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return A5(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=E5(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(ee().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 ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>D5(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=Uq(t,e),a=b5(t),r=Hq(t);return Ne(t,()=>t.attachShader(r,a)),Ne(t,()=>t.attachShader(r,n)),jq(t,r),this.debug&&Mv(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=S5(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ne(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Mv(this.gl,this.program),Ne(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?e5(this.gl,e,t):t5(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ne(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(),n5(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=iu(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&&Mv(this.gl,this.program),zm(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ne(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ne(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Lm(this.gl,ee().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(ee().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(ee().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,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,ee().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=R5(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(),Pv(this.gl,e,this.framebuffer),this.debug&&zm(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Pv(this.gl,this.outputTexture,this.framebuffer),this.debug&&zm(this.gl)):OT(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;Pv(a,e,this.framebuffer),this.debug&&zm(a),this.outputTexture=e,Ne(a,()=>a.viewport(0,0,t,n)),Ne(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),Ne(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 R5(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{getBroadcastDims:HT}=_;function G5(e,t,n,a){let r=[];e.forEach(h=>{let m=k.sizeFromShape(h.shapeInfo.logicalShape);h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${m>1?`[${m}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`))});let s=r.join(`
|
|
`),i=e.map(h=>P5(h,t,a)).join(`
|
|
`),o=t.texShape,l=hn(),c=z5(l),u,p,d=V5(l);return t.isPacked?(u=O5(t.logicalShape,o),p=W5(l)):(u=L5(t.logicalShape,o),p=B5(l)),a&&(d+=U5),[d,c,p,s,u,i,n].join(`
|
|
`)}function uu(e){let t=e.shapeInfo.logicalShape;switch(t.length){case 0:return H5(e);case 1:return j5(e);case 2:return q5(e);case 3:return K5(e);case 4:return X5(e);case 5:return Y5(e);case 6:return Z5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function jT(e){switch(e.shapeInfo.logicalShape.length){case 0:return J5(e);case 1:return Q5(e);case 2:return e8(e);case 3:return t8(e);default:return n8(e)}}function P5(e,t,n=!1){let a="";n?a+=jT(e):a+=uu(e);let r=e.shapeInfo.logicalShape,s=t.logicalShape;return r.length<=s.length&&(n?a+=a8(e,t):a+=r8(e,t)),a}function O5(e,t){switch(e.length){case 0:return qT();case 1:return s8(e,t);case 2:return l8(e,t);case 3:return i8(e,t);default:return o8(e,t)}}function L5(e,t){switch(e.length){case 0:return qT();case 1:return u8(e,t);case 2:return m8(e,t);case 3:return c8(e,t);case 4:return p8(e,t);case 5:return d8(e,t);case 6:return h8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function z5(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function B5(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function W5(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function V5(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);
|
|
}
|
|
|
|
${f8}
|
|
${g8}
|
|
${y8}
|
|
`}var f8=`
|
|
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);
|
|
}
|
|
`,g8=`
|
|
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);
|
|
}
|
|
`,y8=`
|
|
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);
|
|
}
|
|
`,U5=`
|
|
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 qT(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function s8(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 u8(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 i8(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 c8(e,t){let n=ji(["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 o8(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<e.length-1;l++)s*=e[e.length-l-1],i=`
|
|
int b${l} = index / ${s};
|
|
index -= b${l} * ${s};
|
|
`+i,o=`b${l}, `+o;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
|
|
${i}
|
|
|
|
int b = index / ${r};
|
|
index -= b * ${r};
|
|
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec${e.length}(${o});
|
|
}
|
|
`}function p8(e,t){let n=ji(["r","c","d","d2"],e);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${n}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function d8(e,t){let n=ji(["r","c","d","d2","d3"],e);return`
|
|
ivec5 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
|
|
${t[1]}));
|
|
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${n}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function h8(e,t){let n=ji(["r","c","d","d2","d3","d4"],e);return`
|
|
ivec6 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${n}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function l8(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(k.arraysEqual(e,t))return`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
|
|
}
|
|
`;let a=Math.ceil(e[1]/2);return`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function m8(e,t){return k.arraysEqual(e,t)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`:e[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:e[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = index / ${e[1]};
|
|
int c = index - r * ${e[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function qi(e){return`offset${e}`}function J5(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=hn();return`
|
|
vec4 ${n}() {
|
|
return ${a.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function H5(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;let[a,r]=e.shapeInfo.texShape;if(a===1&&r===1)return`
|
|
float ${n}() {
|
|
return sampleTexture(${t}, halfCR);
|
|
}
|
|
`;let[s,i]=e.shapeInfo.texShape,o=qi(t);return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, ${o});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function Q5(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=e.shapeInfo.texShape,r=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=hn();return`
|
|
vec4 ${n}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${r[0]}, ${r[1]}, index);
|
|
return ${s.texture2D}(${t}, uv);
|
|
}
|
|
`}function j5(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${cu(e)}
|
|
}
|
|
`;let a=e.shapeInfo.texShape,r=a[0],s=a[1];if(s===1&&r===1)return`
|
|
float ${n}(int index) {
|
|
return sampleTexture(${t}, halfCR);
|
|
}
|
|
`;let i=qi(t);return s===1?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${r}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:r===1?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${s}.0, 0.5);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${r}, ${s}, index + ${i});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function e8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=r[0],i=r[1],o=hn();if(r!=null&&k.arraysEqual(t,r))return`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${s}.0);
|
|
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`;let l=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],c=Math.ceil(t[1]/2);return`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`}function q5(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape;if(r!=null&&k.arraysEqual(t,r)){let p=r[0],d=r[1];return`
|
|
float ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}let{newShape:s,keptDims:i}=k.squeezeShape(t),o=s;if(o.length<t.length){let p=pu(e,o),d=["row","col"];return`
|
|
${uu(p)}
|
|
float ${a}(int row, int col) {
|
|
return ${a}(${du(d,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
|
|
${cu(e)}
|
|
}
|
|
`;let l=r[0],c=r[1],u=qi(n);return c===1?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${u}), vec3(${t[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:l===1?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${u}), vec3(${t[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${t[1]} + col + ${u};
|
|
vec2 uv = uvFromFlat(${l}, ${c}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function t8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];if(t[0]===1){let p=t.slice(1),d=[1,2],h=pu(e,p),m=["b","row","col"];return`
|
|
${jT(h)}
|
|
vec4 ${a}(int b, int row, int col) {
|
|
return ${a}(${du(m,d)});
|
|
}
|
|
`}let i=s[0],o=s[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),u=hn();return`
|
|
vec4 ${a}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${i}, ${o}, ${c}, ${l}, b, row, col);
|
|
return ${u.texture2D}(${n}, uv);
|
|
}
|
|
`}function K5(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[1]*t[2],s=t[2],{newShape:i,keptDims:o}=k.squeezeShape(t),l=i;if(l.length<t.length){let m=pu(e,l),f=["row","col","depth"];return`
|
|
${uu(m)}
|
|
float ${a}(int row, int col, int depth) {
|
|
return ${a}(${du(f,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${r}, ${s}, 1)));
|
|
${cu(e)}
|
|
}
|
|
`;let c=e.shapeInfo.texShape,u=c[0],p=c[1],d=e.shapeInfo.flatOffset;if(p===r&&d==null)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(p===s&&d==null)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let h=qi(n);return`
|
|
float ${a}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r} + col * ${s} + depth + ${h};
|
|
vec2 uv = uvFromFlat(${u}, ${p}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function n8(e){let t=e.shapeInfo.logicalShape,n=t.length,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=i[0],l=i[1],c=Math.ceil(t[n-1]/2),u=c*Math.ceil(t[n-2]/2),p="int b, int row, int col",d=`b * ${u} + (row / 2) * ${c} + (col / 2)`;for(let m=2;m<n-1;m++)p=`int b${m}, `+p,u*=t[n-m-1],d=`b${m} * ${u} + `+d;let h=hn();return`
|
|
vec4 ${r}(${p}) {
|
|
int index = ${d};
|
|
int texR = index / ${l};
|
|
int texC = index - texR * ${l};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${o});
|
|
return ${h.texture2D}(${a}, uv);
|
|
}
|
|
`}function X5(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[3],s=t[2]*r,i=t[1]*s,{newShape:o,keptDims:l}=k.squeezeShape(t);if(o.length<t.length){let m=pu(e,o),f=["row","col","depth","depth2"];return`
|
|
${uu(m)}
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
return ${a}(${du(f,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${s}, ${r}, 1)));
|
|
${cu(e)}
|
|
}
|
|
`;let c=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,p=u[0],d=u[1];if(d===i&&c==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${s}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(d===r&&c==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${t[1]*t[2]}, ${t[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let h=qi(n);return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${s} +
|
|
depth * ${r} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${d}, index + ${h});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function Y5(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:c}=k.squeezeShape(t);if(l.length<t.length){let f=pu(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${uu(f)}
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${a}(${du(g,c)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, ${r})) +
|
|
depth3;
|
|
${cu(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1];if(h===o&&u==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===r&&u==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=qi(n);return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} + depth * ${s} +
|
|
depth2 * ${r} + depth3 + ${m};
|
|
vec2 uv = uvFromFlat(${d}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function Z5(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=k.squeezeShape(t);if(r.length<t.length){let g=pu(e,r),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${uu(g)}
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${a}(${du(y,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,c=t[2]*l,u=t[1]*c;if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${u}, ${c}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${cu(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],m=d[1];if(m===u&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${c}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(m===i&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=qi(n);return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${u} + col * ${c} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
|
|
vec2 uv = uvFromFlat(${h}, ${m}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function cu(e){let t=e.name,n=k.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function a8(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=HT(e.shapeInfo.logicalShape,t.logicalShape),l=ft(i),c=i-s,u,p=["x","y","z","w","u","v"];s===0?u="":i<2&&o.length>=1?u="coords = 0;":u=o.map(g=>`coords.${p[g+c]} = 0;`).join(`
|
|
`);let d="";i<2&&s>0?d="coords":d=e.shapeInfo.logicalShape.map((g,y)=>`coords.${p[y+c]}`).join(", ");let h="return outputValue;",m=k.sizeFromShape(e.shapeInfo.logicalShape)===1,f=k.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!f)i===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${r}() {
|
|
${l} coords = getOutputCoords();
|
|
${u}
|
|
vec4 outputValue = get${a}(${d});
|
|
${h}
|
|
}
|
|
`}function r8(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 c=ft(l),u=HT(e.shapeInfo.logicalShape,t.logicalShape),p=l-o,d,h=["x","y","z","w","u","v"];o===0?d="":l<2&&u.length>=1?d="coords = 0;":d=u.map(f=>`coords.${h[f+p]} = 0;`).join(`
|
|
`);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${h[g+p]}`).join(", "),`
|
|
float ${r}() {
|
|
${c} coords = getOutputCoords();
|
|
${d}
|
|
return get${a}(${m});
|
|
}
|
|
`}function ft(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function pu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function du(e,t){return t.map(n=>e[n]).join(", ")}function b8(e,t,n,a){let r=t.userCode,s=n.map((h,m)=>{let f={logicalShape:h.shape,texShape:h.isUniform?null:h.texData.texShape,isUniform:h.isUniform,isPacked:h.isUniform?!1:h.texData.isPacked,flatOffset:null};return h.texData!=null&&h.texData.slice!=null&&h.texData.slice.flatOffset>0&&(f.flatOffset=h.texData.slice.flatOffset),{name:t.variableNames[m],shapeInfo:f}}),i=s.map(h=>h.shapeInfo),o={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},l=G5(s,o,r,t.packedInputs),c=e.createProgram(l),u=null,p=e.getUniformLocation(c,"NAN",!1);ee().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let d={};for(let h=0;h<t.variableNames.length;h++){let m=t.variableNames[h],f=!1;d[m]=e.getUniformLocation(c,m,f),d[`offset${m}`]=e.getUniformLocation(c,`offset${m}`,f)}return{program:t,source:l,webGLProgram:c,uniformLocations:d,inShapeInfos:i,outShapeInfo:o,infLoc:u,nanLoc:p}}function KT(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,a)=>{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 x8(e,t,n,a,r){KT(t.inShapeInfos,n),KT([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),ee().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 c=t.program.variableNames[l],u=t.uniformLocations[c],p=t.uniformLocations[`offset${c}`];if(u!=null){if(o.isUniform){if(k.sizeFromShape(o.shape)<2)e.gl.uniform1f(u,o.uniformValues[0]);else{let d=o.uniformValues;d instanceof Float32Array||(d=new Float32Array(d)),e.gl.uniform1fv(u,d)}return}o.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,o.texData.slice.flatOffset),e.setInputMatrixTexture(o.texData.texture,u,l)}}),r!=null&&r(e,t.webGLProgram),e.executeProgram()}function v8(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{addImpl:w8,bincountImpl:XT,bincountReduceImpl:k8,ceilImpl:I8,concatImpl:N8,expImpl:T8,expm1Impl:S8,floorImpl:C8,gatherV2Impl:_8,greaterImpl:E8,lessImpl:A8,linSpaceImpl:F8,logImpl:$8,maxImpl:D8,maximumImpl:R8,minimumImpl:M8,multiplyImpl:P8,negImpl:O8,prodImpl:L8,rangeImpl:z8,rsqrtImpl:B8,simpleAbsImpl:YT,sliceImpl:W8,stridedSliceImpl:V8,subImpl:U8,tileImpl:G8,topKImpl:H8,transposeImpl:Vv,uniqueImpl:j8}=GN;function ZT(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function mn(e,t){return t===1?[e]:ZT(e,t)}function q8(e,t){if(e===1)return"rc";let n="";for(let a=0;a<e;a++)n+=t[a],a<e-1&&(n+=",");return n}var Z8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;let t=e.length;if(t===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let n=mn("rc",t),a=ft(t),r=K8(t,e,n),s=X8(t,e[e.length-1],e[e.length-2],n),i=Y8(e,n);this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
|
|
if(${r}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${s}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function J8(e,t){let n=[];for(let a=0;a<=1;a++)for(let r=0;r<=1;r++){let s=`${a===0?"r":"rp1"}, ${r===0?"c":"cp1"}`;for(let i=2;i<e;i++)s=`${t[t.length-1-i]},`+s;n.push(s)}return n}function K8(e,t,n){if(e===1)return`rc > ${t[0]}`;let a="";for(let r=e-2;r<e;r++)a+=`${n[r]} >= ${t[r]}`,r<e-1&&(a+="||");return a}function X8(e,t,n,a){if(e===1)return"";let r=a.slice(-2);return`
|
|
int r = ${r[0]};
|
|
int c = ${r[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${t};
|
|
bool rEdge = rp1 >= ${n};
|
|
`}function Y8(e,t){let n=e.length,a=J8(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 JT=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=`
|
|
${Q8(t)}
|
|
${Wv(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function Q8(e){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${ji(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var eK=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=eS(t,n),r=tS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=QT(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===tn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===tn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===tn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===tn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===tn.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=eS(n,a),s=tS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=QT(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=ee().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],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,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 tK(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 QT(e,t,n,a,r){let s=nK(t,a),i;if(r){let[l,c]=iu(e[0],e[1]);i=l*c}else{let[l,c]=bp(e[0],e[1]);i=l*c}let o=tK(n,s);return i*o}function nK(e,t){switch(e){case tn.PACKED_2X2_FLOAT32:return UT(t);case tn.PACKED_2X2_FLOAT16:return GT(t);case tn.UNPACKED_FLOAT32:return BT(t);case tn.UNPACKED_FLOAT16:return WT(t);case tn.PACKED_4X1_UNSIGNED_BYTE:return VT(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function aK(e){return ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?tn.PACKED_2X2_FLOAT32:tn.UNPACKED_FLOAT32:e?tn.PACKED_2X2_FLOAT16:tn.UNPACKED_FLOAT16}function eS(e,t){if(e===Qn.UPLOAD)return tn.PACKED_2X2_FLOAT32;if(e===Qn.RENDER||e==null)return aK(t);if(e===Qn.DOWNLOAD||e===Qn.PIXELS)return tn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function tS(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var cs=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);
|
|
}
|
|
`}},Ma="if (isnan(x)) return x;",rK="return x;",nS="return abs(x);",sK="return (x >= 0.0) ? x : (exp(x) - 1.0);",iK=Ma+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,oK=Ma+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Vm="return x;",lK="return x;",uK=`
|
|
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;
|
|
`,cK=`
|
|
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;
|
|
`,pK=`
|
|
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;
|
|
`,hu=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);
|
|
}
|
|
`}},dK=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=mn("rc",t),a=ft(t),r=q8(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}));
|
|
}
|
|
`}},hK=Ja.whereImpl,mK=1e-7,fK=1e-4,Uv={};function gK(e){return e in Uv||(Uv[e]={}),Uv[e]}var yK=128,bK=600;function xK(){return ee().global.screen==null?1024:ee().global.screen.height*ee().global.screen.width*window.devicePixelRatio*bK/1024/1024}var Gv=class extends rc{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.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!ee().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=sr(ee().getNumber("WEBGL_VERSION"));this.binaryCache=gK(ee().getNumber("WEBGL_VERSION")),this.gpgpu=new M5(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 eK(this.gpgpu),this.numMBBeforeWarning=xK(),this.texData=new gd(this,Ha())}nextDataId(){return Gv.nextDataId++}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((ee().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ee().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:Qn.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(ee().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:Qn.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 p;o?p=new hu(i,Vm):p=new cs(i,Vm);let d=this.runWebGLProgram(p,[{dataId:e,shape:i,dtype:a}],a),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return n;let l=this.activeTimers!=null,c;l&&(c=k.now());let u;if(a==="complex64"){let p=this.readSync(r.real.dataId),d=this.readSync(r.imag.dataId);u=_.mergeRealAndImagArrays(p,d)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=k.now()-c),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(m=>h.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 h;o?h=new hu(a,Vm):h=new cs(a,Vm);let m=this.runWebGLProgram(h,[{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(!ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ee().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,c;if(s!=="complex64"&&ee().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...xp(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=h[0],f=h[1];u=_.mergeRealAndImagArrays(m,f)}else if(l==null)u=this.getValuesFromTexture(e);else{let h=k.sizeFromShape(a);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}c!=null&&this.disposeIntermediateTensorInfo(c);let p=this.convertAndCacheOnCPU(e,u),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Ha().removeDataId(e,this),this.pendingDeletes--),p}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 Le(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!Bq(n))throw ee().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:a}=this.texData.get(e),r=k.sizeFromShape(t);if(ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(e),d=this.texData.get(p.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(d.texture,...xp(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(p),h}let s=ee().getBool("WEBGL_PACK")&&a===!0,i=s?Ov(t):t,o=s?new f5(i):new m5(i),l=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),c=this.texData.get(l.dataId),u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),u}timerAvailable(){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}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(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(r);i.kernelMs=k.sum(o),i.getExtraProfileInfo=()=>o.map((l,c)=>({name:s[c],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 ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:k.now(),endMs:null}}endTimer(e){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=k.now(),e)}async getQueryTime(e){if(ee().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 c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return ee().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Ha().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=yK){let n=this.getCPUBackend();return!ee().getBool("IS_TEST")&&!this.warnedAboutCPUBackend&&n==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),n!=null&&e.every(a=>this.texData.get(a.dataId).texture==null&&k.sizeFromShape(a.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){_.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return hK(e.shape,t)}packedUnaryOp(e,t,n){let a=new hu(e.shape,t),r=this.compileAndRun(a,[e],n);return Ha().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let a=YT(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,a)}if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,nS,e.dtype);let t=new cs(e.shape,nS),n=this.compileAndRun(t,[e]);return Ha().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}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 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 Ha().makeTensorFromDataId(a,e,t,this)}unpackTensor(e){let t=new dK(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new Z8(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[ou(e.shape),...lu(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},r=[ou(t),...lu(t)],s=new JT(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=Ov(a),i;n?i=new h5(s):i=new d5(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===yp.DENSE){let m=xp(e.outputShape);i.texShape=m.map(f=>f*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(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let f=this.texData.get(m.dataId);if(f.texture==null){if(!e.packedInputs&&k.sizeFromShape(m.shape)<=ee().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:f.values};e.packedInputs&&(f.isPacked=!0,f.shape=m.shape)}else if(!!f.isPacked!=!!e.packedInputs)m=f.isPacked?this.unpackTensor(m):this.packTensor(m),o.push(m),f=this.texData.get(m.dataId);else if(f.isPacked&&!Wm(f.shape,m.shape)){let g=m,y=m.shape;m.shape=f.shape,m=this.packedReshape(m,y),o.push(m),f=this.texData.get(m.dataId),g.shape=y}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:f,isUniform:!1}});this.uploadToGPU(s.dataId);let c={shape:s.shape,texData:i,isUniform:!1},u=v8(e,l,c),p=this.getAndSaveBinary(u,()=>b8(this.gpgpu,e,l,c)),d=this.activeTimers!=null,h;if(d&&(h=this.startTimer()),x8(this.gpgpu,p,l,c,a),o.forEach(m=>this.disposeIntermediateTensorInfo(m)),d&&(h=this.endTimer(h),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)})),!ee().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&r===!1){let m=this.unpackTensor(s);return this.disposeIntermediateTensorInfo(s),m}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||(ee().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=D(()=>{if(!ee().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=ee().getBool("DEBUG");ee().set("DEBUG",!1);let t=this.abs(de(1e-8)).dataSync()[0];if(ee().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?mK:fK}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,c;l&&(c=k.now());let u=t.texShape;if(u==null&&(u=r5(n,o),t.texShape=u),r!=null){let p=Ov(n),d,h=u[1],m=u[0],f=r instanceof Uint8Array;o?([h,m]=iu(u[0],u[1]),d=new y5(p,[m,h],f)):d=new g5(p,[m,h],f);let g=this.makeTensorInfo([m,h],a);f?this.texData.get(g.dataId).usage=Qn.PIXELS:this.texData.get(g.dataId).usage=Qn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),h,m,r);let y=!0,b=this.runWebGLProgram(d,[g],a,null,y),v=this.texData.get(b.dataId);t.texture=v.texture,t.texShape=v.texShape,t.isPacked=v.isPacked,t.usage=v.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(b.dataId),t.values=null,l&&(this.uploadWaitMs+=k.now()-c)}else{let p=this.acquireTexture(u,i,a,o);t.texture=p}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:a}=n;return this.releaseGPUData(e),t!=null&&(n.values=vK(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)}};Gv.nextDataId=0;function vK(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;a<n.length;++a)n[a]=Math.round(e[a]);return n}else throw new Error(`Unknown dtype ${t}`)}var wK="3.1.0";ah.isBrowser()&&uh("webgl",()=>new Gv,2);var aS=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,mu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Um=`
|
|
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;
|
|
`,kp=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.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=`
|
|
${ft(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=mn("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 Wn(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 kK={kernelName:Us,backendName:"webgl",kernelFunc:Wn};function ps(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=Wn({inputs:{x:a},backend:n}),l=Wn({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var IK={kernelName:Td,backendName:"webgl",kernelFunc:ps},rS="return (a < 0.) ? b * a : a;",sS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function NK(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",k.createScalarValue(s,"float32")),o=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new kp(sS,r.shape,i.shape):new mu(rS,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],r.dtype);return n.disposeIntermediateTensorInfo(i),l}var TK={kernelName:Gs,backendName:"webgl",kernelFunc:NK},iS="return (a < 0.) ? b * a : a;",oS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function SK(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new kp(oS,a.shape,r.shape):new mu(iS,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)}var CK={kernelName:ni,backendName:"webgl",kernelFunc:SK},lS="if (isnan(x)) return x;",_K=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,EK=`
|
|
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 Ze({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 p=o.texData.get(i.dataId),d=n(p.values,l);return o.makeTensorInfo(i.shape,l,d)}let c=ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new hu(i.shape,t):u=new cs(i.shape,e),o.runWebGLProgram(u,[i],l)}}function nn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:c}=i,u=o;if(a&&l.dtype==="complex64"){let m=u.texData.get(l.dataId),f=u.texData.get(c.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(v=>{let[x,N]=v,T={dataId:x.dataId,dtype:x.dtype,shape:l.shape},C={dataId:N.dataId,dtype:N.dtype,shape:c.shape},F=new mu(e,l.shape,c.shape);return u.runWebGLProgram(F,[T,C],ua(x.dtype,N.dtype))}),b=ps({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),b}let p=s||ua(l.dtype,c.dtype);if(u.shouldExecuteOnCPU([l,c])&&r!=null){let m=u.texData.get(l.dataId),f=u.texData.get(c.dataId),[g,y]=r(l.shape,c.shape,m.values,f.values,p),b=u.makeTensorInfo(y,p),v=u.texData.get(b.dataId);return v.values=g,b}let d=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new kp(t,l.shape,c.shape,n):h=new mu(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],p)}}function Gm(e,t=!1){if(e==="linear")return t?lK:rK;if(e==="relu")return t?cK:iK;if(e==="elu")return t?uK:sK;if(e==="relu6")return t?pK:oK;if(e==="prelu")return t?oS:iS;if(e==="leakyrelu")return t?sS:rS;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var uS=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 c=a?e[1]:e[2],u=Math.ceil(c/2),p=a?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",h=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 b="rc.x",v="rc.x";e[0]<t[0]?b=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(v=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${f}
|
|
|
|
const float sharedDimension = ${u}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${u}; i++) {
|
|
int batchA = ${b};
|
|
int batchB = ${v};
|
|
vec4 a = getMatrixA(batchA, ${p});
|
|
vec4 b = getMatrixB(batchB, ${d});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${m[0]});
|
|
result += (${h[1]} * ${m[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},cS={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},pS=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`}},dS="return a * b;";function hS(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=_.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),c=new pS(cS.REAL,a.shape,r.shape),u=new pS(cS.IMAG,a.shape,r.shape),p=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],d=n.runWebGLProgram(c,p,"float32"),h=n.runWebGLProgram(u,p,"float32"),m=ps({inputs:{real:d,imag:h},backend:n});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),m}if(n.shouldExecuteOnCPU([a,r])){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),[c,u]=P8(a.shape,r.shape,o.values,l.values,s),p=n.makeTensorInfo(u,s),d=n.texData.get(p.dataId);return d.values=c,p}let i;return ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new kp(dS,a.shape,r.shape):i=new mu(dS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var AK={kernelName:Js,backendName:"webgl",kernelFunc:hS};function FK(e,t,n){let a=[ou(e.shape),...lu(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[ou(t),...lu(t)],i=new JT(s,a),o=!0,l=n.runWebGLProgram(i,[r],e.dtype,null,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function be(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=k.sizeFromShape(r.shape),l=k.inferFromImplicitShape(s,o),c=k.sizeFromShape(l);k.assert(o===c,()=>`The new shape (${l}) has ${c} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let u=i.texData.get(r.dataId);return u.isPacked&&!Wm(r.shape,l)&&!(u.texture!==null&&Wm(u.shape,l))?FK(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var $K={kernelName:hl,backendName:"webgl",kernelFunc:be},mS=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 u=1/t;l=`sumValue += dot(values * ${k.isInt(u)?u.toPrecision(2):u}, ones);`}let c="";r%n>0&&(c=`
|
|
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) {
|
|
${c}
|
|
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);
|
|
}
|
|
`}},DK=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 c=Math.floor(n/4)*4,u=n%4,p=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${o}(values, minMaxValue);
|
|
}
|
|
`,d="vec4";t==="all"?(i="1.0",p=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,d="bvec4"):t==="any"&&(i="0.0",p=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,d="bvec4");let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${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 < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${u===1}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===2}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===3}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function RK(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=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function Ki(e,t,n,a){let r=RK(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:c}=r[i],u,p;n==="mean"?u=i===0?new mS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},o):new mS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c}):u=new DK({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},n),p=s,s=a.runWebGLProgram(u,[s],t),p.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(p)}return s}var PK=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;let a=ft(this.rank),r=MK(t);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function MK(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let r=0;r<e.length;r++)a[e[r]]=n[r];return a.join()}var OK=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let c=0;c<n.length;c++)n[c]=e[t[c]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let a=ft(this.rank),r=ZT("rc",this.rank),s=new Array(this.rank);for(let c=0;c<t.length;c++)s[t[c]]=r[c];let i=`vec2(${s.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${o}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${r[this.rank-1]};
|
|
if(++${r[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${o}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Hm(e,t,n){let a=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new OK(e.shape,t):new PK(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function LK(e,t,n,a){let r=t,s=e.shape.length,i=k.parseAxisParam(r,e.shape),o=i,l=_.getAxesPermutation(o,s),c=l!=null,u=e;c&&(u=Hm(e,l,a),o=_.getInnerMostAxes(o.length,s)),_.assertAxesAreInnerMostDims("sum",o,s);let[p,d]=_.computeOutAndReduceShapes(u.shape,o),h=p;n&&(h=_.expandShapeToKeepDim(p,i));let m=k.sizeFromShape(d),f=k.sizeFromShape(e.shape)/m,g=be({inputs:{x:u},attrs:{shape:[f,m]},backend:a}),y=nh(e.dtype),b=Ki(g,y,"sum",a),v=be({inputs:{x:b},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(b),c&&a.disposeIntermediateTensorInfo(u),v}function Hv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return LK(r,s,i,n)}var zK={kernelName:di,backendName:"webgl",kernelFunc:Hv};function Tn(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{perm:s}=a,i=n,o=r.shape.length,l=new Array(o);for(let u=0;u<l.length;u++)l[u]=r.shape[s[u]];let c;if(i.shouldExecuteOnCPU([r])){let u=i.texData.get(r.dataId).values,p=Vv(u,r.shape,r.dtype,s,l);c=i.makeTensorInfo(l,r.dtype);let d=i.texData.get(c.dataId);d.values=p}else c=Hm(r,s,i);return c}var BK={kernelName:yi,backendName:"webgl",kernelFunc:Tn},fS=1e3;function jm({a:e,b:t,transposeA:n,transposeB:a,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,p=n?e.shape[c-2]:e.shape[c-1],d=a?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],m=a?t.shape[u-2]:t.shape[u-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=k.sizeFromShape(f),b=k.sizeFromShape(g),v=y===b||y===1||b===1;k.assert(c>=2&&u>=2&&v,()=>`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 x=(y>b?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,m]);k.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`);let N=n?[y,p,h]:[y,h,p],T=a?[b,m,d]:[b,d,m],C=be({inputs:{x:e},backend:r,attrs:{shape:N}}),F=be({inputs:{x:t},backend:r,attrs:{shape:T}}),$=[C,F],P=Math.max(y,b),B=n?C.shape[1]:C.shape[2],W=s!=null,G=i!=null,q=l==="leakyrelu",j=l!=null?Gm(l,!0):null,X=W||G||q||j!=null,K;if((h===1||m===1)&&B>fS&&X===!1){let J=C,se=F;n&&(J=Tn({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),$.push(J)),a&&(se=Tn({inputs:{x:F},backend:r,attrs:{perm:[0,2,1]}}),$.push(se));let Q=m!==1,oe=m===1,ae=J;Q&&(ae=be({inputs:{x:J},backend:r,attrs:{shape:[P,B,1]}}),$.push(ae));let pe=m===1?2:1,ue=se;oe&&(ue=be({inputs:{x:se},backend:r,attrs:{shape:[P,1,B]}}),$.push(ue));let ge=hS({inputs:{a:ae,b:ue},backend:r});K=Hv({inputs:{x:ge},backend:r,attrs:{axis:pe,keepDims:!0}}),$.push(ge)}else{let J=ua(e.dtype,t.dtype),se=new uS(N,T,[P,h,m],n,a,W,j,G,q),Q=[C,F];if(s!=null&&Q.push(s),G&&Q.push(i),q){let oe=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));Q.push(oe),$.push(oe)}K=r.runWebGLProgram(se,Q,J)}let ne=be({inputs:{x:K},backend:r,attrs:{shape:x}});$.push(K);for(let J of $)r.disposeIntermediateTensorInfo(J);return ne}function WK(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:p}=a;return jm({a:r,b:s,transposeA:l,transposeB:c,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var VK={kernelName:bi,backendName:"webgl",kernelFunc:WK},gS="return abs(x);";function UK(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=YT(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new hu(a.shape,gS):r=new cs(a.shape,gS),n.runWebGLProgram(r,[a],a.dtype)}var GK={kernelName:Eo,backendName:"webgl",kernelFunc:UK},HK=Ma+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,jK=Ze({opSnippet:HK}),qK={kernelName:Ao,backendName:"webgl",kernelFunc:jK},KK=Ma+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,XK=Ze({opSnippet:KK}),YK={kernelName:Fo,backendName:"webgl",kernelFunc:XK},yS="return a + b;",ZK=nn({opSnippet:yS,packedOpSnippet:yS,supportsComplex:!0,cpuKernelImpl:w8}),JK={kernelName:zr,backendName:"webgl",kernelFunc:ZK},QK=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);
|
|
}
|
|
`}},eX=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 qm(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return Wn({inputs:{x:a[0]},backend:n});if(a.length>ee().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=qm({inputs:a.slice(0,o),backend:n}),c=qm({inputs:a.slice(o),backend:n});return qm({inputs:[l,c],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>ua(o,l)),s=a.map(o=>o.shape),i=ee().getBool("WEBGL_PACK")?new eX(a[0].shape,s):new QK(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var tX={kernelName:Ss,backendName:"webgl",kernelFunc:qm};function nX(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),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=Tn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("all",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=be({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Ki(f,f.dtype,"all",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=be({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var aX={kernelName:vd,backendName:"webgl",kernelFunc:nX};function rX(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),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=Tn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("any",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=be({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Ki(f,f.dtype,"any",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=be({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var sX={kernelName:wd,backendName:"webgl",kernelFunc:rX},iX=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));
|
|
}
|
|
`}},oX=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=ft(o),c=mn("coords",o),u,p;if(s===1){p=o+1;let C=ft(p);u=`
|
|
${C} sourceLocR = ${C}(${c.join()}, 0);
|
|
++${c[o-1]};
|
|
${C} sourceLocG = ${C}(${c.join()}, 0);
|
|
++${c[o-2]};
|
|
${C} sourceLocA = ${C}(${c.join()}, 0);
|
|
--${c[o-1]};
|
|
${C} sourceLocB = ${C}(${c.join()}, 0);
|
|
--${c[o-2]};`}else p=o,u=`
|
|
${l} sourceLocR = coords;
|
|
++${c[o-1]};
|
|
${l} sourceLocG = coords;
|
|
++${c[o-2]};
|
|
${l} sourceLocA = coords;
|
|
--${c[o-1]};
|
|
${l} sourceLocB = coords;
|
|
--${c[o-2]};`;let d=["x","y","z","w","u","v"].slice(0,p),h="."+d[p-1],m=d.map(C=>"int "+C),f=mn("sourceLocR",p-1).concat("inIdx.r"),g=mn("sourceLocG",p-1).concat("inIdx.g"),y=mn("sourceLocB",p-1).concat("inIdx.b"),b=mn("sourceLocA",p-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=a?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${b.join()})));`,N=`vec4(
|
|
getAChannel(${f.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,T=a?"":`
|
|
float getBestIndicesAChannel(${m.join()}) {
|
|
return getChannel(getBestIndicesA(${d.join()}),
|
|
vec2(${d.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${m.join()}) {
|
|
return getChannel(getA(${d.join()}),
|
|
vec2(${d.slice(-2).join()}));
|
|
}
|
|
${T}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${c[o-1]} < ${i[o-1]-1};
|
|
bool hasNextRow = ${c[o-2]} < ${i[o-2]-1};
|
|
${u}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${N};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${x}
|
|
vec4 candidate = ${N};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${v}(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 bS(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=_.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new iX(o,n,a==null),c=[t];a!=null&&c.push(a);let u=e.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;let p=bS(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}function xS(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=_.computeOptimalWindowSize(s),o=new oX(r,i,n,a==null),l=a==null?[t]:[t,a],c=e.runWebGLProgram(o,l,"int32");if(c.shape.length===t.shape.length){let u=xS(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function vS(e,t,n,a){let r=[n];if(_.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!ee().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],[i,o]=_.computeOutAndReduceShapes(t.shape,r),l=k.sizeFromShape(o),c=be({inputs:{x:t},backend:e,attrs:{shape:[-1,l]}});s.push(c);let u=bS(e,c,a);s.push(u);let p=be({inputs:{x:u},backend:e,attrs:{shape:i}});return s.forEach(d=>e.disposeIntermediateTensorInfo(d)),p}return xS(e,t,a)}function lX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=Tn({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=vS(n,l,i[0],"max");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var uX={kernelName:Cs,backendName:"webgl",kernelFunc:lX};function cX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=Tn({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=vS(n,l,i[0],"min");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var pX={kernelName:oc,backendName:"webgl",kernelFunc:cX},dX=Ma+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,hX=Ze({opSnippet:dX}),mX={kernelName:$o,backendName:"webgl",kernelFunc:hX},fX=Ma+"return log(x + sqrt(x * x + 1.0));",gX=Ze({opSnippet:fX}),yX={kernelName:Do,backendName:"webgl",kernelFunc:gX},bX=Ma+`
|
|
return atan(x);
|
|
`,xX=Ze({opSnippet:bX}),vX={kernelName:Ro,backendName:"webgl",kernelFunc:xX},wX=_K+`
|
|
return atan(a, b);
|
|
`,kX=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+EK+`
|
|
return result;
|
|
`,IX=nn({opSnippet:wX,packedOpSnippet:kX}),NX={kernelName:Po,backendName:"webgl",kernelFunc:IX},TX=Ma+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,SX=Ze({opSnippet:TX}),CX={kernelName:Mo,backendName:"webgl",kernelFunc:SX},Ip=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,c=e.dilationWidth,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(m||(y="-1.0 / 1e-20"),n){let C=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p};
|
|
wC += ${c}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${C} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?r?f:g:`wR * ${p} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let x=Math.floor(s/4)*4,N=s%4,T=`
|
|
if (${m}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
const float initializationValue = ${y};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${y});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${x}; wC += 4) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
getValue(batch, xR, xC + 3 * ${c}, d)
|
|
);
|
|
|
|
${T}
|
|
}
|
|
|
|
int xC = xCCorner + ${x};
|
|
if (${N===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${T}
|
|
} else if (${N===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${T}
|
|
} else if (${N===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${T}
|
|
}
|
|
}
|
|
setOutput(${v});
|
|
}
|
|
`}},jv=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,c=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let b=t==="avg",v="0.0";if(b||(v="-1.0 / 1e-20"),n){let $=">=";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 < ${d};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${p}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${$} 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 * ${h} * ${m} +
|
|
wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let x="max",N=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(N="avgValue / count");let T=Math.floor(s/4)*4,C=s%4,F=`
|
|
if (${b}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${x}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${y});
|
|
const float initializationValue = ${v};
|
|
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(${v});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${d};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${T}; wC += 4) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${p}, ch)
|
|
);
|
|
|
|
${F}
|
|
}
|
|
|
|
int xC = xCCorner + ${T};
|
|
if (${C===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
} else if (${C===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
} else if (${C===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
}
|
|
}
|
|
setOutput(${N});
|
|
}
|
|
}
|
|
`}};function _X(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;vp(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Wn({inputs:{x:r},backend:n});let p=new Ip(u,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var EX={kernelName:_s,backendName:"webgl",kernelFunc:_X};function AX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,l,c),d=new jv(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var FX={kernelName:lc,backendName:"webgl",kernelFunc:AX},$X=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,c=o-1-e.padInfo.top,u=l-1-e.padInfo.left,p=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${c}, ${u});
|
|
const float avgMultiplier = float(${p});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${o};
|
|
wR += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC+= ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${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);
|
|
}
|
|
`}},DX=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,c=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=u-1-e.padInfo.front,m=p-1-e.padInfo.top,f=d-1-e.padInfo.left,g=1/(t*n*a);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${m}, ${f});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${u};
|
|
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 < ${p};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${c}) {
|
|
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 RX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new DX(d);return n.runWebGLProgram(h,[r],i.dtype)}var MX={kernelName:Id,backendName:"webgl",kernelFunc:RX};function PX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;vp([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=_.computePool2DInfo(i.shape,o,l,1,c),p=new $X(u);return n.runWebGLProgram(p,[r],i.dtype)}var OX={kernelName:kd,backendName:"webgl",kernelFunc:PX};function LX(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return jm({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var zX={kernelName:Es,backendName:"webgl",kernelFunc:LX},BX=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(_.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)));
|
|
}
|
|
`}},WX=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(_.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);
|
|
}
|
|
`}},VX=({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 c=[a,r,s],u=null;i!=null&&(u=i.shape,c.push(i));let p=null;o!=null&&(p=o.shape,c.push(o));let d=ee().getBool("WEBGL_PACK_NORMALIZATION")?new WX(a.shape,r.shape,s.shape,u,p,l):new BX(a.shape,r.shape,s.shape,u,p,l);return t.runWebGLProgram(d,c,c[0].dtype)},UX={kernelName:Ws,backendName:"webgl",kernelFunc:VX},HX=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=ft(this.rank),n=`uniform int start[${this.rank}];`,a=GX(this.rank),r,s=e.map((i,o)=>`sourceLoc.${qv[o]} = start[${o}] + coords.${qv[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)}}},qv=["x","y","z","w","u","v"];function GX(e){if(e===1)return"sourceLoc";if(e<=6)return qv.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var jX=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=ft(this.rank),n=mn("coords",this.rank),a=mn("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((c,u)=>`start[${u}]`).join()});`:e.map((c,u)=>`${a[u]} = ${n[u]} + start[${u}];`).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 qX(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 Np(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 p=n.texData.get(r.dataId),d=W8(p.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}let{isPacked:c}=n.texData.get(r.dataId),u=cn.isSliceContinous(r.shape,o,l);if(c||!u){let p=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jX(l):new HX(l),d=p.getCustomSetupFunc(o);return n.runWebGLProgram(p,[r],r.dtype,d)}return n.uploadToGPU(r.dataId),qX(r,o,l,n)}var KX={kernelName:yl,backendName:"webgl",kernelFunc:Np},XX=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((b,v)=>b*v),l=_.getReshaped(r.shape,s,o),c=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(r.shape,s,o),p=_.getSliceBeginCoords(i,s.length),d=_.getSliceSize(u,i,s.length),h=[],m=be({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Tn({inputs:{x:m},backend:n,attrs:{perm:c}}),g=be({inputs:{x:f},backend:n,attrs:{shape:u}}),y=Np({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(m),h.push(f),h.push(g),h.forEach(b=>n.disposeIntermediateTensorInfo(b)),y},YX={kernelName:uc,backendName:"webgl",kernelFunc:XX};function ZX(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),c=XT(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var JX={kernelName:Nd,backendName:"webgl",kernelFunc:ZX},QX="return float(a != b);",wS=nn({opSnippet:QX,dtype:"bool"}),eY={kernelName:sl,backendName:"webgl",kernelFunc:wS};function Tp(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Wn({inputs:{x:r.complexTensorInfos.real},backend:n})}var tY={kernelName:Hd,backendName:"webgl",kernelFunc:Tp},nY="return float(int(x));";function aY(e,t){let n=new cs(e.shape,nY),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function Kv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return Wn({inputs:{x:r},backend:n});let i=vt(r.shape),o=Kv({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=ps({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Tp({inputs:{input:r},backend:n}),o=Kv({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=Wn({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return aY(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),o=wS({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 rY={kernelName:As,backendName:"webgl",kernelFunc:Kv},kS="return ceil(x);",sY=Ze({opSnippet:kS,packedOpSnippet:kS,cpuKernelImpl:I8}),iY={kernelName:Fs,backendName:"webgl",kernelFunc:sY},oY=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)}}},lY=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 uY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;ee().getBool("WEBGL_PACK_CLIP")?o=new lY(r.shape):o=new oY(r.shape);let l=o.getCustomSetupFunc(s,i);return n.runWebGLProgram(o,[r],r.dtype,l)}var cY={kernelName:Br,backendName:"webgl",kernelFunc:uY},pY=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 IS(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function dY(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new pY(a.shape),i=[IS(a,r.complexTensorInfos.real),IS(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var hY={kernelName:cc,backendName:"webgl",kernelFunc:dY},mY=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];n.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let a=t.length,r=t[t.length-1];n.push(`else setOutput(getT${a}(yR, yC-${r}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},fY=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=ft(a),s=mn("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((m,f)=>`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],c=i.slice(-2),u=i.join(),p=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${u}), vec2(${c.join()}));
|
|
}`;for(let m=1;m<o.length;m++){let f=o[m-1];p+=`
|
|
if (${l} < ${o[m]} && ${l} >= ${o[m-1]}) {
|
|
return getChannel(
|
|
getT${m}(${Km(i,l,f)}),
|
|
vec2(${Km(c,l,f)}));
|
|
}`}let d=o.length,h=o[o.length-1];p+=`
|
|
return getChannel(
|
|
getT${d}(${Km(i,l,h)}),
|
|
vec2(${Km(c,l,h)}));`,this.userCode=`
|
|
float getValue(${i.map(m=>"int "+m)}) {
|
|
${p}
|
|
}
|
|
|
|
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 Km(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function Xm(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Wn({inputs:{x:r.complexTensorInfos.imag},backend:n})}var gY={kernelName:Ld,backendName:"webgl",kernelFunc:Xm};function fu(e,t,n){let a=e[0].dtype;if(a==="complex64"){let c=e.map(m=>Tp({inputs:{input:m},backend:n})),u=e.map(m=>Xm({inputs:{input:m},backend:n})),p=fu(c,t,n),d=fu(u,t,n),h=ps({inputs:{real:p,imag:d},backend:n});return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),u.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),h}if(a==="string"){let{tensors2D:c,outShape:u}=NS(e,t,n),p=c.map(g=>({vals:n.readSync(g.dataId),shape:g.shape})),d=c[0].shape[0]===1,h=N8(p,u,a,d),m=_.computeOutShape(e.map(g=>g.shape),t),f=n.makeTensorInfo(m,a,h);return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}if(e.length>ee().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(e.length/2),u=fu(e.slice(0,c),t,n),p=fu(e.slice(c),t,n),d=fu([u,p],t,n);return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),d}if(ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let c=new fY(e.map(u=>u.shape),t);return n.runWebGLProgram(c,e,a)}let{tensors2D:r,outShape:s}=NS(e,t,n),i=new mY(r.map(c=>c.shape)),o=n.runWebGLProgram(i,r,a);r.forEach(c=>n.disposeIntermediateTensorInfo(c));let l=be({inputs:{x:o},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(o),l}function NS(e,t,n){let a=_.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 TS(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=_.computeOutShape(t.map(c=>c.shape),s);if(k.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(c=>k.sizeFromShape(c.shape)>0);if(o.length===1)return Wn({inputs:{x:o[0]},backend:n});let l=o.map(c=>c.shape);return _.assertParamsConsistent(l,s),fu(o,s,n)}var yY={kernelName:Oo,backendName:"webgl",kernelFunc:TS},SS=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,c=e.dilationHeight,u=e.dilationWidth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,b=f?3:1,v="",x="";n&&(a?v=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?v=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:v=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,x="result = activation(result);");let N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${v}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${b}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${c};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${m===1}) {
|
|
|
|
if (${f}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${h}) *
|
|
getW(wR, wC, ${h}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${h}, xR, xC) *
|
|
getW(wR, wC, ${h}, d2);
|
|
}
|
|
|
|
} else if (${m===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${m===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1),
|
|
getX(batch, xR, xC, ${h} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC),
|
|
getX(batch, ${h} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${N}
|
|
${x}
|
|
setOutput(result);
|
|
}
|
|
`}},bY=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,c=e.dilationWidth,u=e.filterDepth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${r}, ${s}, ${i});
|
|
const ivec3 pads = ivec3(${t}, ${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 < ${u}; wF++) {
|
|
int xF = xFCorner + wF * ${o};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d}; wC++) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${m===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${m===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${m===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1),
|
|
getX(batch, xF, xR, xC, ${h} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2),
|
|
getW(wF, wR, wC, ${h} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},xY=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:c,dilationHeight:u,dataFormat:p}=n,{left:d,top:h}=o,m=r*a,f=hn(),g=p==="channelsLast",y=g?0:1,b=g?1:2,v="";for(let x=0;x<=1;x++)for(let N=0;N<=1;N++)v+=`
|
|
blockIndex = rc.y + ${N};
|
|
pos = rc.x + ${x};
|
|
|
|
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
|
|
offsetY = int(blockIndex / (${l})) * ${i} - ${h};
|
|
d0 = offsetY + ${u} * (pos / ${m});
|
|
|
|
if(d0 < ${t[y]} && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), ${l}.) * ${s}. - ${d}.);
|
|
d1 = offsetX + ${c} * (int(mod(float(pos), ${m}.) / ${r}.));
|
|
|
|
if(d1 < ${t[b]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${r}.));
|
|
|
|
if (${g}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${x*2+N}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${x*2+N}] = 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;
|
|
|
|
${v}
|
|
|
|
${f.output} = result;
|
|
}
|
|
`}};function CS({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,c=a.texData.get(e.dataId),u=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,h=n.dataFormat==="channelsLast",m=!1,f=!1,g,y=[],b=(p===1||d===1)&&u>fS,v=l[2]%2!=0&&!!c.isPacked;if(b||!ee().getBool("WEBGL_LAZILY_UNPACK")||!ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){let x=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],N=be({inputs:{x:e},backend:a,attrs:{shape:[1,x,n.inChannels]}}),T=be({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),C=jm({a:N,b:T,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=be({inputs:{x:C},backend:a,attrs:{shape:n.outShape}}),y.push(N),y.push(T),y.push(C)}else{let x=h?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),N={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},T=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,k.assert(Wm(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);let C=be({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(C);let F=jm({a:N,b:C,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),$=a.texData.get(F.dataId);k.assert($.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=T,$.shape=n.outShape,g=Wn({inputs:{x:F},backend:a}),g.shape=n.outShape,y.push(F)}for(let x of y)a.disposeIntermediateTensorInfo(x);return g}function _S({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:p,outHeight:d,dataFormat:h}=n,m=h==="channelsLast",f=l*c*u,g=d*p,y=[f,g],b=!0,v=!1,x=[],N=be({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),T=be({inputs:{x:t},backend:a,attrs:{shape:[1,f,k.sizeFromShape(t.shape)/f]}});x.push(N),x.push(T);let C=new xY(y,N.shape,n),F=a.runWebGLProgram(C,[N],"float32"),$=be({inputs:{x:F},backend:a,attrs:{shape:[1,y[0],y[1]]}});x.push(F),x.push($);let P=r!=null,B=s!=null,W=o==="leakyrelu",G=o?Gm(o,!0):null,q=new uS($.shape,T.shape,[1,g,n.outChannels],b,v,P,G,B,W),j=[$,T];if(r&&j.push(r),B&&j.push(s),W){let J=a.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));j.push(J),x.push(J)}let X=a.runWebGLProgram(q,j,"float32"),K=m?[1,d,p,n.outChannels]:[1,n.outChannels,d,p],ne=be({inputs:{x:X},backend:a,attrs:{shape:K}});x.push(X);for(let J of x)a.disposeIntermediateTensorInfo(J);return ne}function vY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!1,p),h;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))h=CS({x:r,filter:s,convInfo:d,backend:n});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=_S({x:r,filter:s,convInfo:d,backend:n});else{let f=new SS(d);h=n.runWebGLProgram(f,[r,s],"float32")}let m=be({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),m}var wY={kernelName:$s,backendName:"webgl",kernelFunc:vY},kY=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);
|
|
}
|
|
`}},IY=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,c=s?2:3,u=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${u}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - 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);
|
|
}
|
|
`}},NY=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);
|
|
}
|
|
`}},TY=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,c=a-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${o}, ${l}, ${c});
|
|
|
|
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 SY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,filterShape:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),h=new kY(d);return n.runWebGLProgram(h,[r,s],"float32")}var CY={kernelName:Sd,backendName:"webgl",kernelFunc:SY};function _Y(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(c),d=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),h=new IY(d);return n.runWebGLProgram(h,[r,s],"float32")}var EY={kernelName:Ds,backendName:"webgl",kernelFunc:_Y};function AY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeConv3DInfo(r.shape,s.shape,i,l,o),u=new bY(c);return n.runWebGLProgram(u,[r,s],"float32")}var FY={kernelName:pc,backendName:"webgl",kernelFunc:AY};function $Y(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,c=_.computeConv3DInfo(r.shape,l,i,1,o),u=new NY(c);return n.runWebGLProgram(u,[r,s],"float32")}var DY={kernelName:Cd,backendName:"webgl",kernelFunc:$Y};function RY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,c=_.computeConv3DInfo(l,s.shape,o,1,i),u=new TY(c);return n.runWebGLProgram(u,[r,s],"float32")}var MY={kernelName:_d,backendName:"webgl",kernelFunc:RY},PY=lS+`
|
|
return cos(x);
|
|
`,OY=Ze({opSnippet:PY}),LY={kernelName:Rs,backendName:"webgl",kernelFunc:OY},zY=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,BY=Ze({opSnippet:zY}),WY={kernelName:Lo,backendName:"webgl",kernelFunc:BY},VY=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[c]=t,[u,p]=n;this.outputShape=[c,u,p,l];let d=a==="bilinear"?1:0,[h,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,y]=u>1?[`${(i-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[b,v,x]=p>1?[`${(o-1)/(p-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(${b});
|
|
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 = ${v};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
float in_x = ${x};
|
|
if( in_x < 0.0 || in_x > ${m} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${d} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},UY=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:c}=a,u=new VY(r.shape,s.shape,o,l,c);return n.runWebGLProgram(u,[r,s,i],"float32")},GY={kernelName:zo,backendName:"webgl",kernelFunc:UY},FS=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let a=e.length,r=t?"0.0":`getX(${ES(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() {
|
|
${ft(a)} coords = getOutputCoords();
|
|
int end = ${AS(a,"coords")};
|
|
float val = ${r};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${AS(a,"coords")} = idx;
|
|
val += getX(${ES(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 ES(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 AS(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 HY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length,c=_.getAxesPermutation([s],l),u=r;c!=null&&(u=Tn({inputs:{x:r},backend:n,attrs:{perm:c}}));let p=_.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${r.shape.length-1} but got axis=${s}`);let d=u.shape[p],h=Wn({inputs:{x:u},backend:n});for(let m=0;m<=Math.ceil(Math.log2(d))-1;m++){let f=new FS(u.shape,!1,o),g=f.getCustomSetupFunc(m),y=h;h=n.runWebGLProgram(f,[h],h.dtype,g),n.disposeIntermediateTensorInfo(y)}if(i){let m=new FS(u.shape,i,o),f=h;h=n.runWebGLProgram(m,[h],h.dtype),n.disposeIntermediateTensorInfo(f)}if(c!=null){let m=_.getUndoAxesPermutation(c),f=Tn({inputs:{x:h},backend:n,attrs:{perm:m}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),f}return h}var jY={kernelName:Ms,backendName:"webgl",kernelFunc:HY};function qY(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),c=n.readSync(s.dataId),u=XT(l,c,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(s),u=k8(l,c,i,o);return n.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var KY={kernelName:Ed,backendName:"webgl",kernelFunc:qY},XY=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 YY(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],c=i==="NHWC"?r.shape[2]:r.shape[3],u=i==="NHWC"?r.shape[3]:r.shape[1],p=l*s,d=c*s,h=u/(s*s),m=i==="NHWC"?[o,p,d,h]:[o,h,p,d],f=new XY(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var ZY={kernelName:Bo,backendName:"webgl",kernelFunc:YY},$S=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,c=e.strideHeight,u=e.strideWidth,p=e.dilationHeight,d=e.dilationWidth,h=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 b=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(${c}, ${u});
|
|
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 < ${h}; wR++) {
|
|
int xR = xRCorner + wR * ${p};
|
|
|
|
if (xR < 0 || xR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m}; wC++) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
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;
|
|
${b}
|
|
${y}
|
|
setOutput(result);
|
|
}
|
|
`}},DS=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.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,c=e.strideHeight,u=e.strideWidth,p=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,m=e.filterWidth,f=m,g="int xR; int xC; int xCOffset;";for(let x=0;x<h;x++)for(let N=0;N<m;N++)g+=`
|
|
vec4 xTexelR${x}C${N*2} = vec4(0.);
|
|
vec4 wR${x}C${N} = vec4(0.);
|
|
vec4 xR${x}C${N} = vec4(0.);`;for(let x=0;x<h;x++)for(let N=0;N<f;N++){let T=N*2;if(g+=`
|
|
xR = xRCorner + ${x*p};
|
|
xC = xCCorner + ${T*d};
|
|
`,u===1){if(T<m&&(l%2==1?g+=`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < ${s} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
xTexelR${x}C${T}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${x}C${T} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + 1 - 2;
|
|
if(xR >= 0 && xR < ${s} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
previous.zw = vec2(0.);
|
|
}
|
|
|
|
xR${x}C${T} = vec4(previous.zw, xTexelR${x}C${T}.xy);
|
|
} else {
|
|
xR${x}C${T} = vec4(0, 0, xTexelR${x}C${T}.xy);
|
|
}
|
|
`:g+=`
|
|
if(xR >= 0 && xR < ${s} && xC >= 0 && xC < ${i}) {
|
|
xTexelR${x}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${x}C${T} = vec4(0.);
|
|
}
|
|
|
|
xR${x}C${T} = xTexelR${x}C${T};
|
|
`,T+1<m)){let C=l%2==0?k.nearestLargerEven(d):d;d%2==0&&l%2==1||d%2!=0&&l%2!=1?(g+=`
|
|
xCOffset = xC + ${l%2} + ${C};
|
|
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,d>1&&(g+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${x}C${T} = vec4(0.);
|
|
}
|
|
`),g+=`
|
|
xR${x}C${T+1} = vec4(
|
|
xTexelR${x}C${T}.zw, xTexelR${x}C${T+2}.xy);
|
|
`):g+=`
|
|
xCOffset = xC + ${C};
|
|
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${x}C${T+1} = xTexelR${x}C${T+2};
|
|
`}}else T<m&&(g+=`
|
|
if(xR >= 0 && xR < ${s}) {
|
|
`,l%2==1?(g+=`
|
|
xCOffset = xC + 1 - ${u};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${x}C${T} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${i}) {
|
|
xTexelR${x}C${T+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${x}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${x}C${T} = vec4(
|
|
xTexelR${x}C${T}.zw, xTexelR${x}C${T+2}.zw);
|
|
`,T+1<m&&(g+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + ${u};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR${x}C${T+1} = vec4(xTexelR${x}C${T+2}.xy, final.xy);
|
|
`)):(g+=`
|
|
if(xC >= 0 && xC < ${i}) {
|
|
xTexelR${x}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${x}C${T} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${u};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${x}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${x}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${x}C${T} = vec4(
|
|
xTexelR${x}C${T}.xy, xTexelR${x}C${T+2}.xy);
|
|
`,T+1<m&&(g+=`
|
|
xR${x}C${T+1} = vec4(
|
|
xTexelR${x}C${T}.zw, xTexelR${x}C${T+2}.zw);
|
|
`)),g+="}");T<m&&(g+=`
|
|
vec4 wTexelR${x}C${T} = getW(${x}, ${T}, d1, q);
|
|
wR${x}C${T} = vec4(wTexelR${x}C${T}.xz, wTexelR${x}C${T}.xz);
|
|
`,T+1<m&&(g+=`
|
|
vec4 wTexelR${x}C${T+1} = getW(${x}, ${T+1}, d1, q);
|
|
wR${x}C${T+1} =
|
|
vec4(wTexelR${x}C${T+1}.xz, wTexelR${x}C${T+1}.xz);`))}for(let x=0;x<h;x++)for(let N=0;N<m;N++)g+=`dotProd += xR${x}C${N} * wR${x}C${N};`;let y="",b="";n&&(a?y=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?y=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:y=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,b="result = activation(result);");let v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${y}
|
|
|
|
const ivec2 strides = ivec2(${c}, ${u});
|
|
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;
|
|
int q = 0;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
vec4 dotProd = vec4(0.);
|
|
|
|
${g}
|
|
|
|
vec4 result = dotProd;
|
|
${v}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}};function JY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=a,u=l;u==null&&(u=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=_.computeConv2DInfo(r.shape,s.shape,i,u,o,c,!0),d;return ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?d=new DS(p):d=new $S(p),n.runWebGLProgram(d,[r,s],"float32")}var QY={kernelName:Ps,backendName:"webgl",kernelFunc:JY},e7=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);
|
|
}
|
|
`}},t7=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 n7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,filterShape:u}=a,p=_.computeConv2DInfo(r.shape,u,i,o,l,c,!0),d=new e7(p);return n.runWebGLProgram(d,[r,s],"float32")}var a7={kernelName:Ad,backendName:"webgl",kernelFunc:n7};function r7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,inputShape:u}=a,p=_.computeConv2DInfo(u,s.shape,i,o,l,c,!0),d=new t7(p);return n.runWebGLProgram(d,[r,s],"float32")}var s7={kernelName:Fd,backendName:"webgl",kernelFunc:r7},i7=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 o7(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 i7(s),l=n.runWebGLProgram(o,[i],i.dtype),c=be({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var l7={kernelName:$d,backendName:"webgl",kernelFunc:o7},u7=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:c}=e,{top:u,left:p}=a;this.userCode=`
|
|
const ivec2 strides = ivec2(${r}, ${s});
|
|
const ivec2 pads = ivec2(${u}, ${p});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${i}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${o}; w++) {
|
|
int wIn = wBeg + w * ${c};
|
|
|
|
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 c7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),u,p=new u7(c);u=n.runWebGLProgram(p,[r,s],"float32");let d=be({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),d}var p7={kernelName:dc,backendName:"webgl",kernelFunc:c7},d7="return (x >= 0.0) ? x : (exp(x) - 1.0);",h7=`
|
|
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;
|
|
`,m7=Ze({opSnippet:d7,packedOpSnippet:h7}),f7={kernelName:Wo,backendName:"webgl",kernelFunc:m7},g7="return (b >= 1.0) ? a : a * (b + 1.0);",y7=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,b7=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new kp(y7,a.shape,r.shape):new mu(g7,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},x7={kernelName:Md,backendName:"webgl",kernelFunc:b7},v7=`
|
|
return vec4(equal(a, b));
|
|
`,w7="return float(a == b);",k7=nn({opSnippet:w7,packedOpSnippet:v7,dtype:"bool"}),I7={kernelName:Uo,backendName:"webgl",kernelFunc:k7},N7=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${_.ERF_P};
|
|
float a1 = ${_.ERF_A1};
|
|
float a2 = ${_.ERF_A2};
|
|
float a3 = ${_.ERF_A3};
|
|
float a4 = ${_.ERF_A4};
|
|
float a5 = ${_.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));
|
|
`,T7=Ze({opSnippet:N7}),S7={kernelName:Vo,backendName:"webgl",kernelFunc:T7},RS="return exp(x);",MS=Ze({opSnippet:RS,packedOpSnippet:RS,cpuKernelImpl:T8}),C7={kernelName:Ls,backendName:"webgl",kernelFunc:MS};function Xv(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 _7={kernelName:Go,backendName:"webgl",kernelFunc:Xv},PS="return exp(x) - 1.0;",E7=Ze({opSnippet:PS,packedOpSnippet:PS,cpuKernelImpl:S8}),A7={kernelName:Ho,backendName:"webgl",kernelFunc:E7},OS=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 LS(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,c=new OS("real",l,t),u=new OS("imag",l,t),p=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],d=n.runWebGLProgram(c,p,"float32"),h=n.runWebGLProgram(u,p,"float32"),m=ps({inputs:{real:d,imag:h},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h);let f=be({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function F7(e){let{inputs:t,backend:n}=e,{input:a}=t;return LS(a,!1,n)}var $7={kernelName:Pd,backendName:"webgl",kernelFunc:F7},D7=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 Yv(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 D7(a,r),o=i.getCustomSetupFunc(r);return t.runWebGLProgram(i,[],s,o)}}var R7={kernelName:hc,backendName:"webgl",kernelFunc:Yv},M7=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);
|
|
}
|
|
`}},P7={kernelName:jo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new M7(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},zS="return floor(x);",O7=Ze({opSnippet:zS,packedOpSnippet:zS,cpuKernelImpl:C8}),L7={kernelName:zs,backendName:"webgl",kernelFunc:O7},z7=`
|
|
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;
|
|
}
|
|
`,B7=`
|
|
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);
|
|
`,W7=nn({opSnippet:z7,packedOpSnippet:B7,dtype:"int32"}),V7={kernelName:Bs,backendName:"webgl",kernelFunc:W7},U7=class{constructor(e){this.variableNames=["A"];let t=hn(),[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));
|
|
}
|
|
`}},G7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=hn(),[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;
|
|
}
|
|
`}},j7={kernelName:Yd,backendName:"webgl",kernelFunc:H7},gu;function H7(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=typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap,[c,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,c],d=[u,c,s];(o||i||l)&&(gu==null&&(gu=document.createElement("canvas").getContext("2d")),gu.canvas.width=c,gu.canvas.height=u,gu.drawImage(r,0,0,c,u),r=gu.canvas);let h=n.makeTensorInfo(p,"int32");n.texData.get(h.dataId).usage=Qn.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),r);let m=ee().getBool("WEBGL_PACK")?new G7(d):new U7(d),f=n.runWebGLProgram(m,[h],"int32");return n.disposeData(h.dataId),f}function q7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=a,f=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(r.shape,s.shape,l,p,c,d,!1,f),y,b=[];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=CS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=_S({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let x=i!=null,N=o!=null,T=h==="leakyrelu",C=h?Gm(h,!1):null,F=new SS(g,x,C,N,T),$=[r,s];if(i&&$.push(i),o&&$.push(o),T){let P=n.makeTensorInfo([],"float32",k.createScalarValue(m,"float32"));$.push(P),b.push(P)}y=n.runWebGLProgram(F,$,"float32")}let v=be({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var K7={kernelName:xi,backendName:"webgl",kernelFunc:q7};function X7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=a,m=[],f=u;f==null&&(f=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=_.computeConv2DInfo(r.shape,s.shape,l,f,c,p,!0),y=ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=d?Gm(d,y):null,v=[r,s],x=i!=null,N=o!=null,T=d==="leakyrelu";if(x&&v.push(i),N&&v.push(o),T){let $=n.makeTensorInfo([],"float32",k.createScalarValue(h,"float32"));v.push($),m.push($)}let C;y?C=new DS(g,x,b,N,T):C=new $S(g,x,b,N,T);let F=n.runWebGLProgram(C,v,"float32");return m.forEach($=>n.disposeIntermediateTensorInfo($)),F}var Y7={kernelName:vi,backendName:"webgl",kernelFunc:X7},Z7=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=ft(t.length),r=ft(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 J7(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],[o,l,c,u]=_.prepareAndValidate(a,r),p=be({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),d=be({inputs:{x:a},backend:n,attrs:{shape:[k.sizeFromShape(a.shape)/c,c]}}),h=new Z7(i,u,[l,c]),m=n.runWebGLProgram(h,[d,p],d.dtype),f=be({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),f}var Q7={kernelName:Ko,backendName:"webgl",kernelFunc:J7},tZ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=ft(this.rank),a=eZ(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function eZ(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;r<e.length;r++)r===2?a.push("int(getIndices(resRC.x, resRC.z))"):a.push(`${n[r]}`);return a.join()}function nZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=k.parseAxisParam(i,r.shape)[0],c=_.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=k.sizeFromShape(s.shape),p=[],d=be({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),h=be({inputs:{x:s},backend:n,attrs:{shape:[c.batchSize,u/c.batchSize]}});p.push(d),p.push(h);let m=[c.batchSize,c.outerSize,u/c.batchSize,c.sliceSize];if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.bufferSync(h),v=n.bufferSync(d),x=_8(v,b,m);return p.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(c.outputShape,x.dtype,x.values)}let f=new tZ(d.shape,m),g=n.runWebGLProgram(f,[d,h],d.dtype);p.push(g);let y=be({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return p.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var aZ={kernelName:qo,backendName:"webgl",kernelFunc:nZ},rZ="return float(a > b);",sZ=`
|
|
return vec4(greaterThan(a, b));
|
|
`,iZ=nn({opSnippet:rZ,packedOpSnippet:sZ,cpuKernelImpl:E8,dtype:"bool"}),oZ={kernelName:Xo,backendName:"webgl",kernelFunc:iZ},lZ="return float(a >= b);",uZ=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,cZ=nn({opSnippet:lZ,packedOpSnippet:uZ,dtype:"bool"}),pZ={kernelName:Vs,backendName:"webgl",kernelFunc:cZ};function dZ(e){let{inputs:t,backend:n}=e,{input:a}=t;return LS(a,!0,n)}var hZ={kernelName:Od,backendName:"webgl",kernelFunc:dZ},mZ="return float(!isnan(x) && !isinf(x));",fZ=Ze({opSnippet:mZ,dtype:"bool"}),gZ={kernelName:Yo,backendName:"webgl",kernelFunc:fZ},yZ="return float(isinf(x));",bZ=Ze({opSnippet:yZ,dtype:"bool"}),xZ={kernelName:Zo,backendName:"webgl",kernelFunc:bZ},vZ="return float(isnan(x));",wZ=Ze({opSnippet:vZ,dtype:"bool"}),kZ={kernelName:Jo,backendName:"webgl",kernelFunc:wZ},IZ="return float(a < b);",NZ=`
|
|
return vec4(lessThan(a, b));
|
|
`,TZ=nn({opSnippet:IZ,packedOpSnippet:NZ,cpuKernelImpl:A8,dtype:"bool"}),SZ={kernelName:Qo,backendName:"webgl",kernelFunc:TZ},CZ="return float(a <= b);",_Z=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,EZ=nn({opSnippet:CZ,packedOpSnippet:_Z,dtype:"bool"}),AZ={kernelName:el,backendName:"webgl",kernelFunc:EZ};function FZ(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=F8(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var $Z={kernelName:zd,backendName:"webgl",kernelFunc:FZ},DZ=`if (x < 0.0) return NAN;
|
|
return log(x);`,RZ=`
|
|
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;
|
|
`,MZ=Ze({opSnippet:DZ,packedOpSnippet:RZ,cpuKernelImpl:$8}),PZ={kernelName:Hs,backendName:"webgl",kernelFunc:MZ},OZ="return log(1.0 + x);",LZ=Ze({opSnippet:OZ}),zZ={kernelName:tl,backendName:"webgl",kernelFunc:LZ},BZ="return float(a >= 1.0 && b >= 1.0);",WZ=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,VZ=nn({opSnippet:BZ,packedOpSnippet:WZ,dtype:"bool"}),UZ={kernelName:nl,backendName:"webgl",kernelFunc:VZ},GZ="return float(!(x >= 1.0));",HZ=Ze({opSnippet:GZ}),jZ={kernelName:mc,backendName:"webgl",kernelFunc:HZ},qZ="return float(a >= 1.0 || b >= 1.0);",KZ=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,XZ=nn({opSnippet:qZ,packedOpSnippet:KZ,dtype:"bool"}),YZ={kernelName:fc,backendName:"webgl",kernelFunc:XZ},ZZ=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);
|
|
}
|
|
`}},JZ=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);
|
|
}
|
|
`}},QZ=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,c=ee().getBool("WEBGL_PACK_NORMALIZATION")?new JZ(r.shape,s,i,o,l):new ZZ(r.shape,s,i,o,l);return n.runWebGLProgram(c,[r],r.dtype)},e9={kernelName:gc,backendName:"webgl",kernelFunc:QZ},t9=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);
|
|
}
|
|
`}},n9=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:c,beta:u}=a,p=new t9(r.shape,o,l,c,u);return n.runWebGLProgram(p,[r,s,i],r.dtype)},a9={kernelName:Bd,backendName:"webgl",kernelFunc:n9};function r9(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=Ki(i,e.dtype,"max",a),l=be({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function BS(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),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=n.shouldExecuteOnCPU([r]),h=r;if(p){if(d){let b=n.texData.get(h.dataId).values,v=new Array(o);for(let T=0;T<v.length;T++)v[T]=r.shape[u[T]];let x=Vv(b,r.shape,r.dtype,u,v);h=n.makeTensorInfo(v,r.dtype);let N=n.texData.get(h.dataId);N.values=x}else h=Hm(r,u,n);c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("max",c,o);let[m,f]=_.computeOutAndReduceShapes(h.shape,c),g=m;i&&(g=_.expandShapeToKeepDim(m,l));let y;if(d){let b=n.texData.get(h.dataId).values,v=D8(b,k.sizeFromShape(f),g,r.dtype);y=n.makeTensorInfo(g,r.dtype);let x=n.texData.get(y.dataId);x.values=v}else y=r9(h,f,g,n);return p&&n.disposeIntermediateTensorInfo(h),y}var s9={kernelName:js,backendName:"webgl",kernelFunc:BS},i9=aS+`
|
|
return max(a, b);
|
|
`,o9=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Um+`
|
|
return result;
|
|
`,l9=nn({opSnippet:i9,packedOpSnippet:o9,cpuKernelImpl:R8}),u9={kernelName:qs,backendName:"webgl",kernelFunc:l9};function c9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;vp(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Wn({inputs:{x:r},backend:n});let p=new Ip(u,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var p9={kernelName:Ks,backendName:"webgl",kernelFunc:c9};function d9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,c,l),d=new jv(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var h9={kernelName:yc,backendName:"webgl",kernelFunc:d9},m9=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);
|
|
}
|
|
`}},f9=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,c=e.effectiveFilterWidth,u=o-1-e.padInfo.front,p=l-1-e.padInfo.top,d=c-1-e.padInfo.left,h=o*l*c-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${u}, ${p}, ${d});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${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 < ${c};
|
|
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 = ${h} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${c} +
|
|
wR * ${c} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function g9(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new jv(d,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new f9(d),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var y9={kernelName:Vd,backendName:"webgl",kernelFunc:g9};function b9(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;vp([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=_.computePool2DInfo(o.shape,l,c,1,u,p),h=!0,m=new Ip(d,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new m9(d),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var x9={kernelName:Wd,backendName:"webgl",kernelFunc:b9};function v9(e,t,n,a){let r=new Ip(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new Ip(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var w9={kernelName:Ud,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 c=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(s,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=_.computePool2DInfo(a.shape,r,s,c,i),[p,d]=v9(a,o,u,l);return[p,d]}};function k9(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=Ki(i,"float32","mean",a),l=be({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var I9={kernelName:Xs,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),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=i.shouldExecuteOnCPU([a]),h=[],m=a;if(p){if(d){let v=i.texData.get(m.dataId).values,x=new Array(o);for(let C=0;C<x.length;C++)x[C]=a.shape[u[C]];let N=Vv(v,a.shape,a.dtype,u,x);m=i.makeTensorInfo(x,a.dtype);let T=i.texData.get(m.dataId);T.values=N}else m=Hm(a,u,i);h.push(m),c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("sum",c,o);let[f,g]=_.computeOutAndReduceShapes(m.shape,c),y=f;r&&(y=_.expandShapeToKeepDim(f,l));let b=k9(m,g,y,i);for(let v of h)i.disposeIntermediateTensorInfo(v);return b}};function N9(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),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=Tn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,r.shape.length)),_.assertAxesAreInnerMostDims("min",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=be({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Ki(f,f.dtype,"min",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=be({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var T9={kernelName:Ys,backendName:"webgl",kernelFunc:N9},S9=aS+`
|
|
return min(a, b);
|
|
`,C9=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Um+`
|
|
return result;
|
|
`,_9=nn({opSnippet:S9,packedOpSnippet:C9,cpuKernelImpl:M8}),E9={kernelName:Zs,backendName:"webgl",kernelFunc:_9},A9=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let a=e.length,r=ft(a),s=t.map(c=>c[0]).join(","),i=t.map((c,u)=>c[0]+e[u]).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}));
|
|
}
|
|
`}},F9=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let a=e.length,r=ft(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=mn("rc",a),l=mn("source",a),c=`${o[a-1]} < ${this.outputShape[a-1]}`,u=a===1?"source":`vec2(${l.slice(-2).join()})`,p=n==="reflect"?0:1,d="";if(a===1){let h=`
|
|
${r} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${p};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${p};
|
|
}
|
|
source -= start;
|
|
`;d=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`}else{let h=`
|
|
${r} source = rc;
|
|
${r} lt = ${r}(lessThan(source, start));
|
|
${r} gte = ${r}(greaterThanEqual(source, end));
|
|
${r} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${p}) +
|
|
gte * ((end - 1) * 2 - source + ${p});
|
|
source -= start;
|
|
`;d=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${r} start = ${r}(${s});
|
|
const ${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}},$9=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new F9(a.shape,r,s):new A9(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},D9={kernelName:bc,backendName:"webgl",kernelFunc:$9},R9=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,M9=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Um+`
|
|
return result;
|
|
`,P9=nn({opSnippet:R9,packedOpSnippet:M9}),O9={kernelName:al,backendName:"webgl",kernelFunc:P9},L9=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)}}},z9=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,B9=`
|
|
// 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;
|
|
`,WS=nn({opSnippet:z9,packedOpSnippet:B9,checkOutOfBounds:!0}),W9={kernelName:Os,backendName:"webgl",kernelFunc:WS},VS="return a - b;",US=nn({opSnippet:VS,packedOpSnippet:VS,supportsComplex:!0,cpuKernelImpl:U8}),V9={kernelName:fi,backendName:"webgl",kernelFunc:US};function GS(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=k.parseAxisParam([s],r.shape),o=BS({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=_.expandShapeToKeepDim(o.shape,i),c=be({inputs:{x:o},backend:n,attrs:{shape:l}}),u=US({inputs:{a:r,b:c},backend:n}),p=MS({inputs:{x:u},backend:n}),d=Hv({inputs:{x:p},backend:n,attrs:{axis:i,keepDims:!1}}),h=be({inputs:{x:d},backend:n,attrs:{shape:l}}),m=WS({inputs:{a:p,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),m}var U9={kernelName:hi,backendName:"webgl",kernelFunc:GS};function G9(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:GS({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],p=new L9(c,u,s),d=p.getCustomSetupFunc(i),h=n.runWebGLProgram(p,[l],"int32",d);return o||n.disposeIntermediateTensorInfo(l),h}var H9={kernelName:Gd,backendName:"webgl",kernelFunc:G9},HS="return -x;";function j9(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=O8(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new hu(a.shape,HS):r=new cs(a.shape,HS),n.runWebGLProgram(r,[a],a.dtype)}var q9={kernelName:rl,backendName:"webgl",kernelFunc:j9},K9=Ja.nonMaxSuppressionV3Impl;function X9(e){_.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,c=n.readSync(r.dataId),u=n.readSync(s.dataId),{selectedIndices:p}=K9(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var Y9={kernelName:il,backendName:"webgl",kernelFunc:X9},Z9=Ja.nonMaxSuppressionV4Impl;function J9(e){_.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:c}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),{selectedIndices:d,validOutputs:h}=Z9(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Q9={kernelName:ol,backendName:"webgl",kernelFunc:J9},eJ=Ja.nonMaxSuppressionV5Impl;function tJ(e){_.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:c}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),d=i,h=o,m=l,f=c,{selectedIndices:g,selectedScores:y}=eJ(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var nJ={kernelName:ll,backendName:"webgl",kernelFunc:tJ},aJ=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)));
|
|
}
|
|
`}},rJ=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=k.sizeFromShape(r.shape),c=new aJ(l,s,i,o),u=be({inputs:{x:r},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let d=[...r.shape,s],h=be({inputs:{x:p},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(p),h},sJ={kernelName:Qs,backendName:"webgl",kernelFunc:rJ};function Ym(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=Tp({inputs:{input:a},backend:n}),s=Ym({inputs:{x:r},backend:n}),i=Xm({inputs:{input:a},backend:n}),o=Ym({inputs:{x:i},backend:n}),l=ps({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Yv({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var iJ={kernelName:Sl,backendName:"webgl",kernelFunc:Ym};function jS(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=Tp({inputs:{input:a},backend:n}),s=jS({inputs:{x:r},backend:n}),i=Xm({inputs:{input:a},backend:n}),o=Ym({inputs:{x:i},backend:n}),l=ps({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Yv({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var oJ={kernelName:ul,backendName:"webgl",kernelFunc:jS};function lJ(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Xv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=Xv({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=TS({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var uJ={kernelName:cl,backendName:"webgl",kernelFunc:lJ},cJ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);let a=e.length,r=ft(a),s=t.map(l=>l[0]).join(","),i=t.map((l,c)=>l[0]+e[c]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(float(${n}));
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${r} start = ${r}(${s});
|
|
${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(float(${n}));
|
|
} else {
|
|
${r} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
}
|
|
`}},pJ=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=ft(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=mn("rc",a),l=mn("source",a),c=`${o[a-1]} < ${this.outputShape[a-1]}`,u=a===1?"source":`vec2(${l.slice(-2).join()})`,p=[`${r} rc = outputLoc;`,`${o[a-1]} += 1;
|
|
if(${c}) {
|
|
`,a===1?"":`}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {`,a===1?"":` ${o[a-1]} += 1;
|
|
if(${c}) {`],d=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=a===1?2:4;m<f;m++)h+=`
|
|
${p[m]}
|
|
if (${d}) {
|
|
result[${m}] = float(${n});
|
|
} else {
|
|
${r} source = rc - start;
|
|
result[${m}] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`;h+=a===1?"} ":"}}",this.userCode=`
|
|
const ${r} start = ${r}(${s});
|
|
const ${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},qS=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a,o=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pJ(r.shape,s,i):new cJ(r.shape,s,i);return n.runWebGLProgram(o,[r],r.dtype)},dJ={kernelName:ei,backendName:"webgl",kernelFunc:qS},hJ=`
|
|
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);
|
|
`,mJ=`
|
|
// 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));
|
|
`+Um+`
|
|
return result;
|
|
`,fJ=nn({opSnippet:hJ,packedOpSnippet:mJ}),gJ={kernelName:ti,backendName:"webgl",kernelFunc:fJ};function yJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],c=k.parseAxisParam(s,r.shape),u=c,p=_.getAxesPermutation(u,o),d=r;p!=null&&(d=Tn({inputs:{x:r},backend:n,attrs:{perm:p}}),u=_.getInnerMostAxes(u.length,o),l.push(d)),_.assertAxesAreInnerMostDims("prod",u,o);let h;if(n.shouldExecuteOnCPU([d])){let m=n.texData.get(d.dataId).values,{outVals:f,outShape:g,outDtype:y}=L8(d.shape,d.dtype,m,u);h=n.makeTensorInfo(g,y,f)}else{let[m,f]=_.computeOutAndReduceShapes(d.shape,u),g=k.sizeFromShape(f),y=be({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),b=nh(r.dtype),v=Ki(y,b,"prod",n);h=be({inputs:{x:v},backend:n,attrs:{shape:m}}),l.push(y),l.push(v)}if(i){l.push(h);let m=_.expandShapeToKeepDim(h.shape,c);h=be({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var bJ={kernelName:pl,backendName:"webgl",kernelFunc:yJ},KS=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=z8(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},xJ={kernelName:xc,backendName:"webgl",kernelFunc:KS},vJ="return 1.0 / x;",wJ=Ze({opSnippet:vJ}),kJ={kernelName:dl,backendName:"webgl",kernelFunc:wJ},IJ=Ma+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,NJ=`
|
|
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;
|
|
`,TJ=Ze({opSnippet:IJ,packedOpSnippet:NJ}),SJ={kernelName:ai,backendName:"webgl",kernelFunc:TJ},CJ=Ma+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,_J=`
|
|
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;
|
|
`,EJ=Ze({opSnippet:CJ,packedOpSnippet:_J}),AJ={kernelName:si,backendName:"webgl",kernelFunc:EJ},FJ=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 c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p;r?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
|
|
ivec2 sourceCeilRC = ivec2(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
|
|
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
|
|
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
|
|
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
|
|
|
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracRC.y;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
|
|
float newValue = top + (bottom - top) * fracRC.x;
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},$J=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 c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p;r?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]},
|
|
${c[1]/u[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
|
|
ivec3 sourceCeilRC = ivec3(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${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 DJ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=ee().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new $J(r.shape,l,c,s,i):new FJ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],"float32")}var RJ={kernelName:ri,backendName:"webgl",kernelFunc:DJ},MJ=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],c=o[0]/l[0],u=o[1]/l[1],p=1/c,d=1/u,h=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${c});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${d});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${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 PJ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new MJ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var OJ={kernelName:qd,backendName:"webgl",kernelFunc:PJ},LJ=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 c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p=a?"0.5":"0.0",d;r?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function zJ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=new LJ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],r.dtype)}var BJ={kernelName:vc,backendName:"webgl",kernelFunc:zJ},WJ=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],c=o[0]/l[0],u=o[1]/l[1],p=1/c,d=1/u,h=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${c});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${d});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${o[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${o[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${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 VJ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new WJ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var UJ={kernelName:jd,backendName:"webgl",kernelFunc:VJ},GJ=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=ft(n);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},HJ=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=mn("rc",n),r=`${a[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${a[n-2]} + 1 < ${this.outputShape[n-2]}`,i=ft(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 = ${c(a.slice())};
|
|
if(${r}) {
|
|
result.a = ${u(a.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function o(h){return p(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",p(h)}function c(h){return h[n-2]="("+h[n-2]+" + 1)",p(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",p(h)}function p(h){let m=e.map((y,b)=>d(b,h)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function d(h,m){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${m[h]} - 1`:`${m[h]}`}}};function jJ(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 Wn({inputs:{x:r},backend:n});let l=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new HJ(r.shape,o):new GJ(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var qJ={kernelName:ii,backendName:"webgl",kernelFunc:jJ},KJ=class{constructor(e,t,n,a){this.variableNames=["Image"],this.outputShape=[];let r=e[1],s=e[2],i=Math.sin(t).toFixed(3),o=Math.cos(t).toFixed(3);this.outputShape=e;let[l,c]=_.getImageCenter(a,r,s),u=l.toFixed(3),p=c.toFixed(3),d="";typeof n=="number"?d=`float outputValue = ${n.toFixed(2)};`:d=`
|
|
vec3 fill = vec3(${n.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - ${u}) * ${o} - (float(y) - ${p}) * ${i};
|
|
float coordYFloat = (float(x) - ${u}) * ${i} + (float(y) - ${p}) * ${o};
|
|
int coordX = int(round(coordXFloat + ${u}));
|
|
int coordY = int(round(coordYFloat + ${p}));
|
|
${d}
|
|
if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${r}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},XJ={kernelName:Cl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new KJ(a.shape,r,s,i);return o.runWebGLProgram(l,[a],a.dtype)}},YJ=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,ZJ=Ze({opSnippet:YJ}),JJ={kernelName:oi,backendName:"webgl",kernelFunc:ZJ},QJ="return inversesqrt(x);",eQ=Ze({opSnippet:QJ,cpuKernelImpl:B8}),tQ={kernelName:li,backendName:"webgl",kernelFunc:eQ},XS=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=ft(r.length),l=ft(s.length),c="";n===1?c="i":n===2&&(c="i, j");let u=`getIndices(${c})`,p="";a===1?p="i":a===2&&(p="i, coords[1]");let d=`getUpdates(${p})`,h=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(${u});
|
|
flattenedIndex += index * ${h};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${d};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function nQ(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:c,strides:u,outputSize:p}=_.calculateShapes(s,r,i),d=[p/c,c];if(p===0)return n.makeTensorInfo(i,r.dtype);let h=be({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=be({inputs:{x:s},backend:n,attrs:{shape:[l,c]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new XS(l,o,h.shape.length,m.shape.length,u,d),y=n.runWebGLProgram(g,[m,h,f],m.dtype),b=be({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),b}var aQ={kernelName:ml,backendName:"webgl",kernelFunc:nQ},rQ=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 c=0;c<t.length;c++)l.push(`${i[c]}`),c<e&&o.push(`${i[c]}`);a=o.join(),r=l.join()}let s=ft(n);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${a});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function sQ(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new rQ(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],ua(r.dtype,s.dtype))}var iQ={kernelName:fl,backendName:"webgl",kernelFunc:sQ},oQ=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${_.SELU_SCALEALPHA};
|
|
float scale = ${_.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,lQ=Ze({opSnippet:oQ}),uQ={kernelName:gl,backendName:"webgl",kernelFunc:lQ},cQ="return 1.0 / (1.0 + exp(-1.0 * x));",pQ=Ze({opSnippet:cQ}),dQ={kernelName:ci,backendName:"webgl",kernelFunc:pQ},hQ=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,mQ=Ze({opSnippet:hQ}),fQ={kernelName:xl,backendName:"webgl",kernelFunc:mQ},gQ=lS+`
|
|
return sin(x);
|
|
`,yQ=Ze({opSnippet:gQ}),bQ={kernelName:ui,backendName:"webgl",kernelFunc:yQ},xQ=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,vQ=Ze({opSnippet:xQ}),wQ={kernelName:bl,backendName:"webgl",kernelFunc:vQ},kQ=`
|
|
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;
|
|
`,IQ=Ze({opSnippet:kQ}),NQ={kernelName:vl,backendName:"webgl",kernelFunc:IQ},TQ=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,b)=>y*b),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<r.shape.length;++y)l.push([0,0]);let c=[],u=qS({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=_.getReshaped(u.shape,s,o,!1),d=_.getPermuted(p.length,s.length,!1),h=_.getReshapedPermuted(u.shape,s,o,!1),m=be({inputs:{x:u},backend:n,attrs:{shape:p}}),f=Tn({inputs:{x:m},backend:n,attrs:{perm:d}}),g=be({inputs:{x:f},backend:n,attrs:{shape:h}});return c.push(u),c.push(m),c.push(f),c.forEach(y=>n.disposeIntermediateTensorInfo(y)),g},SQ={kernelName:wc,backendName:"webgl",kernelFunc:TQ};function CQ(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:c,strides:u,outputSize:p}=_.calculateShapes(s,r,o),d=!1,h=new XS(c,l,r.shape.length,s.shape.length,u,[p,1],d),m=n.runWebGLProgram(h,[s,r,i],s.dtype),f=be({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),f}var _Q={kernelName:Kd,backendName:"webgl",kernelFunc:CQ};function EQ(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=_.prepareSplitSize(r,s,o),c=r.shape.length,u=new Array(c).fill(0),p=r.shape.slice();return l.map(d=>{let h=[...p];h[o]=d;let m=Np({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[o]+=d,m})}var AQ={kernelName:wl,backendName:"webgl",kernelFunc:EQ},FQ="return sqrt(x);",$Q=Ze({opSnippet:FQ}),DQ={kernelName:pi,backendName:"webgl",kernelFunc:$Q},RQ="return x * x;",MQ=Ze({opSnippet:RQ}),PQ={kernelName:kc,backendName:"webgl",kernelFunc:MQ},YS="return (a - b) * (a - b);",OQ=nn({opSnippet:YS,packedOpSnippet:YS}),LQ={kernelName:mi,backendName:"webgl",kernelFunc:OQ};function zQ({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Ma+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new cs(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var BQ={kernelName:Vr,backendName:"webgl",kernelFunc:zQ},WQ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=ft(n.length),s=ft(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,c)=>(o++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${o-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
|
|
${r} begin = ${r}(${e});
|
|
${r} strides = ${r}(${t});
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function VQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:d}=a,{nonStrided:h,$begin:m,$strides:f,size:g,newShape:y,outShape:b}=cn.sliceInfo(r.shape,s,i,o,l,c,u,p,d),v=be({inputs:{x:r},backend:n,attrs:{shape:y}}),x;if(h){let T=Np({inputs:{x:v},backend:n,attrs:{begin:m,size:g}});x=be({inputs:{x:T},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(T)}else if(b.some(T=>T===0))x=n.makeTensorInfo(b,r.dtype,[]);else if(n.shouldExecuteOnCPU([v])){let T=n.texData.get(v.dataId).values,C=Le(v.shape,v.dtype,T),F=V8(b,C,f,m);x=n.makeTensorInfo(b,v.dtype,F.values)}else{let T=new WQ(m,f,b);x=n.runWebGLProgram(T,[v],v.dtype)}let N=be({inputs:{x},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),N}var UQ={kernelName:kl,backendName:"webgl",kernelFunc:VQ},GQ="return tan(x);",HQ=Ze({opSnippet:GQ}),jQ={kernelName:Il,backendName:"webgl",kernelFunc:HQ},qQ=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,KQ=Ze({opSnippet:qQ}),XQ={kernelName:gi,backendName:"webgl",kernelFunc:KQ},ZQ=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;let a=ft(this.rank),r=YQ(e);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function YQ(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],a=[];for(let r=0;r<e.length;r++)a.push(`imod(${n[r]}, ${e[r]})`);return a.join()}function ZS(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;if(r.dtype==="string"){let o=n.readSync(r.dataId).map(u=>k.decodeString(u)),l=Le(r.shape,r.dtype,o),c=G8(l,s);return n.makeTensorInfo(c.shape,c.dtype,c.values)}let i=new ZQ(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var JQ={kernelName:Wr,backendName:"webgl",kernelFunc:ZS};function QQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=n.readSync(r.dataId),[l,c]=H8(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var eee={kernelName:Nl,backendName:"webgl",kernelFunc:QQ};function tee(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;vp(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:c}=j8(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var nee={kernelName:Xd,backendName:"webgl",kernelFunc:tee};function aee(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],c=new Array(o-1),u=0;for(let f=0;f<o;f++)f!==s&&(c[u++]=i.shape[f]);let p=[],d=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){d[s]=f;let g=Np({inputs:{x:i},backend:n,attrs:{begin:d,size:h}}),y=be({inputs:{x:g},backend:n,attrs:{shape:c}});m[f]=y,p.push(g)}return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var ree={kernelName:Tl,backendName:"webgl",kernelFunc:aee},see=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",c=Math.floor(n/4)*4,u=n%4,p=`
|
|
sumValue += dot(values, segFilter);
|
|
`,d="";r%n>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`);let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${d}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${s})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${s})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${u===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function iee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],c=0,u=_.getAxesPermutation([c],o),p=r;u!=null&&(p=Tn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(p),c=_.getInnerMostAxes(1,o)[0]);let d=_.segment_util.computeOutShape(p.shape,c,i),h=k.sizeFromShape([p.shape[c]]),m=be({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=nh(r.dtype),g=(x,N,T,C,F)=>{let $=x.shape[0],P=x.shape[1],B=_.segment_util.segOpComputeOptimalWindowSize(P,F),W={windowSize:B,inSize:P,batchSize:$,numSegments:F},G=new see(W,N),q=n.compileAndRun(G,[x,T],C);if(l.push(q),q.shape[1]===F)return q;let j=KS({backend:n,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),X=ZS({inputs:{x:j},backend:n,attrs:{reps:[P/B]}});return l.push(j),l.push(X),g(q,N,X,C,F)},y=g(m,"unsortedSegmentSum",s,f,i),b=be({inputs:{x:y},backend:n,attrs:{shape:d}}),v=b;if(u!=null){l.push(b);let x=_.getUndoAxesPermutation(u);v=Tn({inputs:{x:v},backend:n,attrs:{perm:x}})}return l.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var oee={kernelName:Ic,backendName:"webgl",kernelFunc:iee},lee=[e9,a9,VK,GK,qK,YK,JK,tX,aX,sX,uX,pX,mX,yX,NX,vX,CX,FX,EX,MX,OX,zX,UX,YX,JX,rY,iY,cY,hY,IK,yY,CY,EY,wY,DY,MY,FY,LY,WY,GY,jY,KY,ZY,a7,s7,QY,l7,p7,f7,x7,I7,S7,C7,_7,A7,$7,R7,P7,L7,V7,j7,K7,Y7,Q7,aZ,oZ,pZ,kK,hZ,gY,gZ,xZ,kZ,TK,SZ,AZ,$Z,zZ,PZ,UZ,jZ,YZ,s9,h9,p9,y9,x9,w9,u9,I9,T9,E9,D9,O9,H9,AK,q9,Y9,Q9,nJ,eY,sJ,oJ,uJ,dJ,gJ,CK,bJ,xJ,tY,W9,kJ,AJ,SJ,$K,RJ,OJ,BJ,UJ,qJ,XJ,JJ,tQ,aQ,iQ,uQ,dQ,fQ,bQ,wQ,KX,U9,NQ,SQ,_Q,AQ,DQ,PQ,LQ,BQ,UQ,V9,zK,jQ,XQ,JQ,eee,BK,nee,ree,oee,iJ];for(let e of lee)Tc(e);var uee="3.1.0",cee={"tfjs-core":e1,"tfjs-backend-cpu":WU,"tfjs-backend-webgl":wK,"tfjs-data":CN,"tfjs-layers":ym,"tfjs-converter":wN,tfjs:uee},Vn;(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"})(Vn||(Vn={}));var Sp;(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"})(Sp||(Sp={}));var JS;function pee(e){JS=e.wasm.cwrap(bi,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function dee(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:c,activation:u,leakyreluAlpha:p}=a,d=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let F=n.dataIdMap.get(i.dataId);if(F.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${F.shape.length}.`);m=F.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=Sp[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?r.shape[2]:r.shape[1],b=c?s.shape[1]:s.shape[2],v=r.shape[0],x=n.makeOutput([v,y,b],r.dtype),N=n.dataIdMap.get(x.dataId).id,T=new Uint8Array(new Int32Array(r.shape).buffer),C=new Uint8Array(new Int32Array(s.shape).buffer);return JS(d,T,r.shape.length,h,C,s.shape.length,l,c,g,m,f,p||0,N),x}var hee={kernelName:bi,backendName:"wasm",setupFunc:pee,kernelFunc:dee};function Sn(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),c=s.dataIdMap.get(l.dataId).id;return k.sizeFromShape(l.shape)===0||t(o,c),l}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var mee=Sn(Eo);function fn(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:c,b:u}=l,p=o.dataIdMap.get(c.dataId).id,d=o.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,m=_.assertAndGetBroadcastShape(c.shape,u.shape),f=o.makeOutput(m,h);if(k.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(c.shape).buffer),y=new Uint8Array(new Int32Array(u.shape).buffer),b=o.dataIdMap.get(f.dataId).id,v=()=>a(p,g,c.shape.length,d,y,u.shape.length,Vn[c.dtype],b);if(t&&c.dtype==="float32")return v(),f;let x=_.getBroadcastDims(c.shape,m),N=_.getBroadcastDims(u.shape,m),T=x.every((F,$)=>F===$),C=N.every((F,$)=>F===$);if(T&&C)return v(),f;throw new Error(`Broadcasting along outer dims is not yet supported for ${c.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var fee=!0,gee=fn(zr,fee),QS;function yee(e){QS=e.wasm.cwrap(Ss,null,["array","number","number","number"])}function bee(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 QS(s,r.length,Vn[a.dtype],i),a}var xee={kernelName:Ss,backendName:"wasm",setupFunc:yee,kernelFunc:bee};function Zm(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 vee={kernelName:Us,backendName:"wasm",kernelFunc:Zm},e2;function wee(e){e2=e.wasm.cwrap(yi,null,["number","array","number","number","number","array","number"])}function Jm(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=Iee(t.x.shape,a.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=kee(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=Zm({inputs:t,backend:n});return m.shape=o,m}let c=n.makeOutput(o,l.dtype),u=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(c.dataId).id,d=new Uint8Array(new Int32Array(s).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return e2(u,h,l.shape.length,Vn[l.dtype],p,d,s.length),c}function kee(e,t){let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];return n}function Iee(e,t){let n=[],a=[];for(let r=0;r<e.length;++r)e[r]!==1&&n.push(e[r]),e[t[r]]!==1&&a.push(t[r]);for(let r=0;r<a.length;++r){let s=-1;for(let i=0;i<a.length;++i)a[i]>=r&&(s===-1||a[s]>a[i])&&(s=i);a[s]=r}return[n,a]}var Nee={kernelName:yi,backendName:"wasm",kernelFunc:Jm,setupFunc:wee};function yu(e,t,n){let a=e.shape,r=e.shape.length,s=k.parseAxisParam(t,a),i=s,o=_.getAxesPermutation(i,r),l=null,c=!1;if(o!=null){let u=new Array(r);for(let d=0;d<u.length;d++)u[d]=a[o[d]];i=_.getInnerMostAxes(i.length,r),l=Jm({inputs:{x:e},attrs:{perm:o},backend:n});let p=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==p&&(c=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:c}}var t2;function Tee(e){t2=e.wasm.cwrap(Cs,null,["number","number","number","number","number"])}function See(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r}=a,{x:s}=n,i=t.dataIdMap.get(s.dataId).id,o=i,l=s,{transposed:c,axes:u,inputWasTransposed:p}=yu(s,r,t);if(p){let y=t.dataIdMap.get(c.dataId).id;y!==i&&(l=c,o=y)}let d=l.shape.slice(0,-1),h=t.makeOutput(d,"int32"),m=t.dataIdMap.get(h.dataId).id,f=k.sizeFromShape(h.shape),g=l.shape[u[0]];return t2(o,Vn[l.dtype],f,g,m),p&&t.disposeData(c.dataId),h}var Cee={kernelName:Cs,backendName:"wasm",kernelFunc:See,setupFunc:Tee},n2;function _ee(e){n2=e.wasm.cwrap(_s,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Eee(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:c}=n,u=_.computePool2DInfo(r.shape,i,o,1,l,c),p=u.filterHeight,d=u.filterWidth,h=u.padInfo.top,m=u.padInfo.right,f=u.padInfo.bottom,g=u.padInfo.left,y=u.strideHeight,b=u.strideWidth,v=u.inChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);if(u.dilationWidth!==1||u.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${u.dilationHeight}, ${u.dilationWidth}].`);let x=a.makeOutput(u.outShape,"float32"),N=a.dataIdMap.get(x.dataId).id;return n2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,v,N),x}var Aee={kernelName:_s,backendName:"wasm",setupFunc:_ee,kernelFunc:Eee};function Pa(e){let{inputs:t,attrs:n}=e,{x:a}=t,{shape:r}=n,s=k.sizeFromShape(a.shape),i=k.inferFromImplicitShape(r,s);return k.assert(s===k.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var Fee={kernelName:hl,backendName:"wasm",kernelFunc:Pa},a2;function $ee(e){a2=e.wasm.cwrap(Es,null,["number","array","number","number","array","number","number","number","number"])}function Dee(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,c=s.shape.length,u=i?r.shape[l-2]:r.shape[l-1],p=o?s.shape[c-1]:s.shape[c-2],d=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[c-2]:s.shape[c-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=k.sizeFromShape(m),y=k.sizeFromShape(f),b=g===y||g===1||y===1;k.assert(l>=2&&c>=2&&b,()=>`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 v=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([d,h]);k.assert(u===p,()=>`Error in matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,d]:[g,d,u],N=o?[y,h,p]:[y,p,h],T=Pa({inputs:{x:r},backend:n,attrs:{shape:x}}),C=Pa({inputs:{x:s},backend:n,attrs:{shape:N}}),F=n.dataIdMap.get(T.dataId).id,$=n.dataIdMap.get(C.dataId).id,P=i?T.shape[2]:T.shape[1],B=o?C.shape[1]:C.shape[2],W=Math.max(g,y),G=n.makeOutput([W,P,B],T.dtype),q=n.dataIdMap.get(G.dataId).id,j=new Uint8Array(new Int32Array(T.shape).buffer),X=new Uint8Array(new Int32Array(C.shape).buffer);return a2(F,j,T.shape.length,$,X,C.shape.length,i,o,q),n.disposeData(T.dataId),n.disposeData(C.dataId),G.shape=v,G}var Ree={kernelName:Es,backendName:"wasm",setupFunc:$ee,kernelFunc:Dee};function Qm(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 Mee={kernelName:As,backendName:"wasm",kernelFunc:Qm},Pee=Sn(Fs),r2;function Oee(e){r2=e.wasm.cwrap(Br,null,["number","number","number","number"])}function Lee(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),c=n.dataIdMap.get(l.dataId).id;return r2(o,s,i,c),l}var zee={kernelName:Br,backendName:"wasm",setupFunc:Oee,kernelFunc:Lee};function s2(e){let{inputs:t,backend:n}=e,a=k.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=_.computeOutShape(t.map(h=>h.shape),a),s=t.filter(h=>k.sizeFromShape(h.shape)>0);if(s.length===1)return Zm({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(h=>h.shape);if(_.assertParamsConsistent(o,a),s[0].dtype==="string"){let h=s.map(v=>{let x=k.sizeFromShape(v.shape.slice(a));return Pa({inputs:{x:v},backend:n,attrs:{shape:[-1,x]}})}),m=h.map(v=>({vals:n.readSync(v.dataId),shape:v.shape}));r=_.computeOutShape(h.map(v=>v.shape),1);let f=h[0].shape[0]===1,g=vv(m,r,t[0].dtype,f),y=_.computeOutShape(s.map(v=>v.shape),a);i.shape=y;let b=n.dataIdMap.get(i.dataId);return b.stringBytes=_.fromStringArrayToUint8(g),i}let l=k.sizeFromShape(s[0].shape.slice(0,a)),c=0,u=s.map(h=>{let m=k.sizeFromShape(h.shape.slice(a));return c+=m,m}),p=s.map(h=>n.typedArrayFromHeap(h)),d=n.typedArrayFromHeap(i);for(let h=0;h<l;h++){let m=h*c;for(let f=0;f<p.length;f++){let g=u[f],y=h*g,b=p[f].subarray(y,y+g);d.set(b,m),m+=g}}return i}var Bee={kernelName:Oo,backendName:"wasm",kernelFunc:s2},i2;function Wee(e){i2=e.wasm.cwrap($s,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Vee(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:c,pad:u,dimRoundingMode:p,dataFormat:d}=n,h=_.convertConv2DDataFormat(d),m=_.computeConv2DInfo(r.shape,s.shape,l,c,u,p,!1,h),f=m.filterHeight,g=m.filterWidth,y=m.padInfo.top,b=m.padInfo.right,v=m.padInfo.bottom,x=m.padInfo.left,N=m.dilationHeight,T=m.dilationWidth,C=m.strideHeight,F=m.strideWidth,$=m.inChannels,P=m.outChannels,B=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let W=a.makeOutput(m.outShape,"float32"),G=a.dataIdMap.get(W.dataId).id;return i2(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,y,b,v,x,B,N,T,C,F,$,P,G),W}var Uee={kernelName:$s,backendName:"wasm",setupFunc:Wee,kernelFunc:Vee},o2;function Gee(e){o2=e.wasm.cwrap(Ds,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Hee(e){let{backend:t,inputs:n,attrs:a}=e,{dy:r,filter:s}=n,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,inputShape:u}=a,p=1,d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(u,s.shape,i,p,o,c,!1,d),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:y,inHeight:b,inWidth:v,outChannels:x,outHeight:N,outWidth:T,strideHeight:C,strideWidth:F}=h,$=f-1-h.padInfo.top,P=g-1-h.padInfo.left,B=h.dataFormat==="channelsLast",W=k.computeStrides(h.inShape),G=k.computeStrides(r.shape),[q,j,X]=k.computeStrides(s.shape),K=W[0],ne=B?W[1]:W[2],J=B?W[2]:1,se=B?1:W[1],Q=G[0],oe=B?G[1]:G[2],ae=B?G[2]:1,pe=B?1:G[1],ue=t.makeOutput(h.inShape,"float32"),ge=t.dataIdMap.get(ue.dataId).id,ye=t.dataIdMap.get(r.dataId).id,ke=t.dataIdMap.get(s.dataId).id;return o2(ye,ke,m,f,g,b,v,y,N,T,x,C,F,$,P,q,j,X,K,ne,J,se,Q,oe,ae,pe,ge),ue}var jee={kernelName:Ds,backendName:"wasm",setupFunc:Gee,kernelFunc:Hee},qee=Sn(Rs),Zv;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(Zv||(Zv={}));var l2;function Kee(e){l2=e.wasm.cwrap(zo,null,["number","number","number","number","array","number","number","number","number","number"])}function Xee(e){let{backend:t,inputs:n,attrs:a}=e,{method:r,extrapolationValue:s,cropSize:i}=a,{image:o,boxes:l,boxInd:c}=n,u=l.shape[0],[p,d]=i,h=[u,p,d,o.shape[3]],m=t.dataIdMap.get(o.dataId),f;o.dtype!=="float32"&&(f=Qm({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));let g=m.id,y=t.dataIdMap.get(l.dataId).id,b=t.dataIdMap.get(c.dataId).id,v=t.makeOutput(h,"float32"),x=t.dataIdMap.get(v.dataId).id,N=new Uint8Array(new Int32Array(o.shape).buffer);return l2(g,y,b,u,N,p,d,Zv[r],s,x),f!=null&&t.disposeData(f.dataId),v}var Yee={kernelName:zo,backendName:"wasm",setupFunc:Kee,kernelFunc:Xee},u2;function Zee(e){u2=e.wasm.cwrap(Ms,null,["number","number","number","number","number","number"])}function Jee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;k.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=_.getAxesPermutation([s],l),u=r;c!==null&&(u=Jm({inputs:{x:r},attrs:{perm:c},backend:n}));let p=_.getInnerMostAxes(1,l)[0];_.assertAxesAreInnerMostDims("cumsum",[p],l);let d=n.makeOutput(u.shape,u.dtype),h=u.shape[p],m=n.dataIdMap.get(u.dataId).id,f=n.dataIdMap.get(d.dataId).id;u2(m,i?1:0,o?1:0,h,f,Vn[r.dtype]);let g=d;if(c!==null){let y=_.getUndoAxesPermutation(c);g=Jm({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(u.dataId),n.disposeData(d.dataId)}return g}var Qee={kernelName:Ms,backendName:"wasm",setupFunc:Zee,kernelFunc:Jee},c2;function ete(e){c2=e.wasm.cwrap(Bo,null,["number","number","number","array","number","array","array","number","number"])}function tte(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],c=i==="NHWC"?r.shape[2]:r.shape[3],u=i==="NHWC"?r.shape[3]:r.shape[1],p=l*s,d=c*s,h=u/(s*s),m=i==="NHWC"?[o,p,d,h]:[o,h,p,d],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(r.dataId).id,y=new Uint8Array(new Int32Array(k.computeStrides(r.shape)).buffer),b=new Uint8Array(new Int32Array(m).buffer),v=new Uint8Array(new Int32Array(k.computeStrides(m)).buffer),x=t.dataIdMap.get(f.dataId).id;return c2(g,s,i==="NHWC"?1:0,y,r.shape.length-1,b,v,m.length,x),f}var nte={kernelName:Bo,backendName:"wasm",setupFunc:ete,kernelFunc:tte},p2;function ate(e){p2=e.wasm.cwrap(Ps,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function rte(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:c,pad:u,dimRoundingMode:p}=n,d=c==null?[1,1]:c,h=_.computeConv2DInfo(r.shape,s.shape,l,d,u,p,!0),m=h.filterHeight,f=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,b=h.padInfo.bottom,v=h.padInfo.left,x=h.dilationHeight,N=h.dilationWidth,T=h.strideHeight,C=h.strideWidth,F=h.inChannels,$=h.outChannels,P=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let B=a.makeOutput(h.outShape,"float32"),W=a.dataIdMap.get(B.dataId).id;return p2(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,y,b,v,P,x,N,T,C,F,$,W),B}var ste={kernelName:Ps,backendName:"wasm",setupFunc:ate,kernelFunc:rte},ite=!1,ote=fn(Uo,ite,"bool"),lte=Sn(Ls);function Jv(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),Pa({inputs:{x:r},backend:a,attrs:{shape:o}})}var ute={kernelName:Go,backendName:"wasm",kernelFunc:Jv};function cte(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 pte={kernelName:hc,backendName:"wasm",kernelFunc:cte},d2;function dte(e){d2=e.wasm.cwrap(jo,null,["number","number","number","number","number","number"])}function hte(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,c,u]=a.shape;return d2(s,o,l,c,u,i),r}var mte={kernelName:jo,backendName:"wasm",kernelFunc:hte,setupFunc:dte},fte=Sn(zs),gte=!1,yte=fn(Bs,gte),h2;function bte(e){h2=e.wasm.cwrap(Ws,null,["number","number","number","number","number","number","number"])}function xte(e){let{backend:t,inputs:n,attrs:a}=e,{varianceEpsilon:r}=a,{x:s,mean:i,variance:o,offset:l,scale:c}=n,u=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(i.dataId).id,d=t.dataIdMap.get(o.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,m=c!=null?t.dataIdMap.get(c.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 h2(u,p,d,h,m,r,g),f}var vte={kernelName:Ws,backendName:"wasm",setupFunc:bte,kernelFunc:xte},m2;function wte(e){m2=e.wasm.cwrap(xi,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 kte(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=n,f=_.computeConv2DInfo(r.shape,s.shape,l,u,c,d),g=Sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let y=a.dataIdMap.get(r.dataId).id,b=a.dataIdMap.get(s.dataId).id,v=f.outChannels,x=0;if(i!=null){let ae=a.dataIdMap.get(i.dataId);if(ae.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==v)throw new Error(`FusedConv2D bias shape (${ae.shape}) does not match the number of output channels (${v})`);x=ae.id}let N=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,F=f.padInfo.right,$=f.padInfo.bottom,P=f.padInfo.left,B=f.dilationHeight,W=f.dilationWidth,G=f.strideHeight,q=f.strideWidth,j=f.inChannels,X=f.padInfo.type==="SAME"?1:0,K=f.batchSize,ne=f.inHeight,J=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let se=a.makeOutput(f.outShape,"float32"),Q=a.dataIdMap.get(se.dataId).id,oe=o==null?0:a.dataIdMap.get(o.dataId).id;return m2(y,K,ne,J,b,N,T,x,C,F,$,P,X,B,W,G,q,j,v,g,oe,m||0,Q),se}var Ite={kernelName:xi,backendName:"wasm",setupFunc:wte,kernelFunc:kte},f2;function Nte(e){f2=e.wasm.cwrap(vi,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 Tte(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=n,f=_.computeConv2DInfo(r.shape,s.shape,l,u,c,d,!0),g=Sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=a.dataIdMap.get(r.dataId).id,b=a.dataIdMap.get(s.dataId).id,v=f.outChannels,x=0;if(i!=null){let ae=a.dataIdMap.get(i.dataId);if(ae.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==v)throw new Error(`FusedDepthwiseConv2D bias shape (${ae.shape}) does not match the number of output channels (${v})`);x=ae.id}let N=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,F=f.padInfo.right,$=f.padInfo.bottom,P=f.padInfo.left,B=f.dilationHeight,W=f.dilationWidth,G=f.strideHeight,q=f.strideWidth,j=f.inChannels,X=f.padInfo.type==="SAME"?1:0,K=f.batchSize,ne=f.inHeight,J=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let se=a.makeOutput(f.outShape,"float32"),Q=a.dataIdMap.get(se.dataId).id,oe=o==null?0:a.dataIdMap.get(o.dataId).id;return f2(y,K,ne,J,b,N,T,x,C,F,$,P,X,B,W,G,q,j,v,g,oe,m||0,Q),se}var Ste={kernelName:vi,backendName:"wasm",setupFunc:Nte,kernelFunc:Tte},g2;function Cte(e){g2=e.wasm.cwrap(Ko,null,["number","number","number","number","number","number","array","number"])}function _te(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=by.prepareAndValidate(a,r),c=t.makeOutput(s,a.dtype);if(i===0)return c;let u=r.shape,p=u[u.length-1],d=t.dataIdMap.get(a.dataId).id,h=t.dataIdMap.get(r.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(c.dataId).id;return g2(d,Vn[a.dtype],h,i,p,o,m,f),c}var Ete={kernelName:Ko,backendName:"wasm",setupFunc:Cte,kernelFunc:_te},y2;function Ate(e){y2=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Fte(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],c=_.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=Pa({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),p=k.sizeFromShape(s.shape),d=Pa({inputs:{x:s},attrs:{shape:[c.batchSize,p/c.batchSize]},backend:t}),h=[c.batchSize,c.outerSize,p/c.batchSize,c.sliceSize],m=t.makeOutput(h,r.dtype);if(k.sizeFromShape(r.shape)===0)return m;let f=u.shape.length-1,g=t.dataIdMap.get(u.dataId).id,y=t.dataIdMap.get(d.dataId).id,b=t.dataIdMap.get(m.dataId).id,v=new Uint8Array(new Int32Array(k.computeStrides(u.shape)).buffer),x=new Uint8Array(new Int32Array(k.computeStrides(h)).buffer);return y2(g,Vn[r.dtype],v,f,y,c.batchSize,x,b),t.disposeData(u.dataId),t.disposeData(d.dataId),m.shape=c.outputShape,m}var $te={kernelName:qo,backendName:"wasm",setupFunc:Ate,kernelFunc:Fte},Dte=!1,Rte=fn(Xo,Dte,"bool"),Mte=!1,Pte=fn(Vs,Mte,"bool"),b2;function Ote(e){b2=e.wasm.cwrap(Gs,null,["number","number","number"])}function Lte(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;b2(r,n,i)}return s}var zte={kernelName:Gs,backendName:"wasm",setupFunc:Ote,kernelFunc:Lte},Bte=!1,Wte=fn(Qo,Bte,"bool"),Vte=!1,Ute=fn(el,Vte,"bool"),Gte=Sn(Hs),Hte=!1,jte=fn(nl,Hte,"bool"),x2;function qte(e){x2=e.wasm.cwrap(js,null,["number, number, number"])}function Kte(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:c,axes:u,originalAxes:p,inputWasTransposed:d}=yu(i,r,t);if(d){let b=t.dataIdMap.get(c.dataId).id;l=c,o=b}let h=l.shape.length;_.assertAxesAreInnerMostDims("max",u,h);let[m,f]=_.computeOutAndReduceShapes(l.shape,u),g=k.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(k.sizeFromShape(l.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;x2(o,g,b)}if(d&&t.disposeData(c.dataId),s){let b=_.expandShapeToKeepDim(y.shape,p);y.shape=b}return y}var Xte={kernelName:js,backendName:"wasm",setupFunc:qte,kernelFunc:Kte},Yte=!1,Zte=fn(qs,Yte),v2;function Jte(e){v2=e.wasm.cwrap(Ks,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Qte(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:c}=n,u=_.computePool2DInfo(r.shape,i,o,1,l,c),p=u.filterHeight,d=u.filterWidth,h=u.padInfo.top,m=u.padInfo.right,f=u.padInfo.bottom,g=u.padInfo.left,y=u.dilationHeight,b=u.dilationWidth,v=u.strideHeight,x=u.strideWidth,N=u.inChannels,T=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let C=a.makeOutput(u.outShape,"float32"),F=a.dataIdMap.get(C.dataId).id;return v2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,v,x,N,T,F),C}var ene={kernelName:Ks,backendName:"wasm",setupFunc:Jte,kernelFunc:Qte},w2;function tne(e){w2=e.wasm.cwrap(Xs,null,["number, number, number"])}function nne(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,c=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:h}=yu(i,r,t),m=p;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(c=u,l=x,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("mean",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=k.sizeFromShape(g),b=c;c.dtype!=="float32"&&(b=Qm({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(b.dataId).id);let v=t.makeOutput(f,"float32");if(k.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(v.dataId).id;w2(l,y,x)}if(h&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(v.shape,d);v.shape=x}return c.dtype!=="float32"&&t.disposeData(b.dataId),v}var ane={kernelName:Xs,backendName:"wasm",setupFunc:tne,kernelFunc:nne},k2;function rne(e){k2=e.wasm.cwrap(Ys,null,["number, number, number"])}function sne(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,c=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:h}=yu(i,r,t);if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v)}let m=c.shape.length;_.assertAxesAreInnerMostDims("min",p,m);let[f,g]=_.computeOutAndReduceShapes(c.shape,p),y=k.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(k.sizeFromShape(c.shape)!==0){let v=t.dataIdMap.get(b.dataId).id;k2(l,y,v)}if(h&&t.disposeData(u.dataId),s){let v=_.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var ine={kernelName:Ys,backendName:"wasm",setupFunc:rne,kernelFunc:sne},one=!1,lne=fn(Zs,one),une=!0,cne=fn(Js,une),pne=Sn(rl);function Qv(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 I2;function dne(e){I2=e.wasm.cwrap(il,"number",["number","number","number","number","number"])}function hne(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i}=a,{boxes:o,scores:l}=n,c=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(l.dataId).id,p=I2(c,u,s,r,i),{pSelectedIndices:d,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=Qv(t,p);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",d)}var mne={kernelName:il,backendName:"wasm",setupFunc:dne,kernelFunc:hne},N2;function fne(e){N2=e.wasm.cwrap(ol,"number",["number","number","number","number","number","bool"])}function gne(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=a,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(c.dataId).id,d=N2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=Qv(t,d);t.wasm._free(f);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([],"int32",g);return[y,b]}var yne={kernelName:ol,backendName:"wasm",setupFunc:fne,kernelFunc:gne},T2;function bne(e){T2=e.wasm.cwrap(ll,"number",["number","number","number","number","number","number"])}function xne(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=a,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(c.dataId).id,d=T2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=Qv(t,d);t.wasm._free(g);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([m],"float32",f);return[y,b]}var vne={kernelName:ll,backendName:"wasm",setupFunc:bne,kernelFunc:xne},wne=!1,kne=fn(sl,wne,"bool"),S2;function Ine(e){S2=e.wasm.cwrap(Qs,null,["number","number","number","number","number"])}function Nne(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"),c=n.dataIdMap.get(l.dataId).id,u=n.dataIdMap.get(r.dataId).id;return S2(u,s,i,o,c),l}var Tne={kernelName:Qs,backendName:"wasm",setupFunc:Ine,kernelFunc:Nne};function Sne(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var Cne={kernelName:ul,backendName:"wasm",kernelFunc:Sne};function _ne(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Jv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(l=>{k.assertShapesMatch(s,l.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=t.map(l=>Jv({inputs:{input:l},backend:n,attrs:{dim:r}}));return s2({inputs:o,backend:n,attrs:{axis:r}})}var Ene={kernelName:cl,backendName:"wasm",kernelFunc:_ne},C2;function Ane(e){C2=e.wasm.cwrap(ei,null,["number","array","number","number","array","array","number","number"])}function Fne(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,c=new Uint8Array(new Int32Array(t.shape).buffer),u=a.map(m=>m[0]),p=a.map(m=>m[1]),d=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(p).buffer);return C2(i,c,t.shape.length,Vn[t.dtype],d,h,r,l),o}var $ne={kernelName:ei,backendName:"wasm",kernelFunc:Fne,setupFunc:Ane},Dne=!1,Rne=fn(ti,Dne),_2;function Mne(e){_2=e.wasm.cwrap(ni,null,["number","number","number"])}function Pne(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 _2(s,i,l),o}var One={kernelName:ni,backendName:"wasm",setupFunc:Mne,kernelFunc:Pne},E2;function Lne(e){E2=e.wasm.cwrap(pl,null,["number","number","number","number"])}function zne(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,c=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:h}=yu(i,r,t),m=p;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("prod",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=k.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(k.sizeFromShape(c.shape)!==0){let v=t.dataIdMap.get(b.dataId).id;E2(l,y,Vn[b.dtype],v)}if(h&&t.disposeData(u.dataId),s){let v=_.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var Bne={kernelName:pl,backendName:"wasm",setupFunc:Lne,kernelFunc:zne},Wne=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=Iv(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Vne={kernelName:xc,backendName:"wasm",kernelFunc:Wne},Une=!0,Gne=fn(Os,Une),Hne=Sn(ai),jne=Sn(si),A2;function qne(e){A2=e.wasm.cwrap(ri,null,["number","number","number","number","number","number","number","number","number","number"])}function Kne(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,[u,p,d,h]=r.shape,m=[u,l,c,h],f=t.dataIdMap.get(r.dataId),g;f.dtype!=="float32"&&(g=Qm({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let y=f.id,b=t.makeOutput(m,"float32");if(k.sizeFromShape(r.shape)===0)return b;let v=t.dataIdMap.get(b.dataId).id;return A2(y,u,p,d,h,l,c,s?1:0,i?1:0,v),g!=null&&t.disposeData(g.dataId),b}var Xne={kernelName:ri,backendName:"wasm",setupFunc:qne,kernelFunc:Kne},F2;function Yne(e){F2=e.wasm.cwrap(ii,null,["number","array","number","array","number","number"])}function Zne(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 Zm({inputs:{x:r},backend:n});let o=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(i).buffer),p=new Uint8Array(new Int32Array(r.shape).buffer);F2(l,u,i.length,p,r.shape.length,c);let d=Pa({inputs:{x:o},attrs:{shape:r.shape},backend:n});return n.disposeData(o.dataId),d}var Jne={kernelName:ii,backendName:"wasm",kernelFunc:Zne,setupFunc:Yne},$2;function Qne(e){$2=e.wasm.cwrap(Cl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function eae(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),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[p,d,h,m]=r.shape,[f,g]=_.getImageCenter(o,d,h),y=i===0,b=255,v=typeof i=="number"?[i,i,i,y?0:b]:[...i,b],x=new Uint8Array(new Int32Array(v).buffer);return $2(c,p,d,h,m,s,f,g,x,v.length,u),l}var tae={kernelName:Cl,backendName:"wasm",kernelFunc:eae,setupFunc:Qne},nae=Sn(oi),aae=Sn(li),D2;function rae(e){D2=e.wasm.cwrap(ml,null,["number","number","number","number","number","number","array","number","number"])}function sae(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:c,sliceSize:u,strides:p,outputSize:d}=xy.calculateShapes(s,r,i),h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(p).buffer),g=t.dataIdMap.get(o.dataId).id;return D2(h,m,Vn[s.dtype],l,c,u,f,d,g),o}var iae={kernelName:ml,backendName:"wasm",setupFunc:rae,kernelFunc:sae},R2;function oae(e){R2=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function lae(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,c=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(c.dataId).id,p=a.shape.length,d=r.shape.length,h=p===0||p>1||d===1?1:k.sizeFromShape(r.shape.slice(1));return R2(i,o,l,h,u),c}var uae={kernelName:fl,backendName:"wasm",kernelFunc:lae,setupFunc:oae},M2;function cae(e){M2=e.wasm.cwrap(ci,null,["number","number"])}function pae(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||M2(a,s),r}var dae={kernelName:"Sigmoid",backendName:"wasm",setupFunc:cae,kernelFunc:pae},hae=Sn(ui);function ef(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),c=r.makeOutput(i,t.dtype),u=k.computeStrides(t.shape),p=r.dataIdMap.get(c.dataId);if(o){let m=cn.computeFlatOffset(s,u);return t.dtype==="string"?p.stringBytes=l.slice(m,m+k.sizeFromShape(i)):r.typedArrayFromHeap(c).set(l.subarray(m,m+k.sizeFromShape(i))),c}if(t.dtype==="string"){let m=Dm(l,s,i,t.shape,t.dtype);return p.stringBytes=m,c}let d=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)mae(l,u[0],d,s,i);else if(h===3)fae(l,u[0],u[1],d,s,i);else if(h===4)gae(l,u[0],u[1],u[2],d,s,i);else{let m=Dm(l,s,i,t.shape,t.dtype);d.set(m)}return c}function mae(e,t,n,a,r){let s=0,i=a[0],o=a[1],l=i+r[0];for(let c=i;c<l;c++){let u=c*t+o;n.set(e.subarray(u,u+r[1]),s),s+=r[1]}}function fae(e,t,n,a,r,s){let i=0,o=r[0],l=r[1],c=r[2],u=o+s[0],p=l+s[1];for(let d=o;d<u;d++)for(let h=l;h<p;h++){let m=d*t+h*n+c;a.set(e.subarray(m,m+s[2]),i),i+=s[2]}}function gae(e,t,n,a,r,s,i){let o=0,l=s[0],c=s[1],u=s[2],p=l+i[0],d=c+i[1],h=u+i[2],m=s[3];for(let f=l;f<p;f++)for(let g=c;g<d;g++)for(let y=u;y<h;y++){let b=f*t+g*n+y*a+m;r.set(e.subarray(b,b+i[3]),o),o+=i[3]}}var yae={kernelName:yl,backendName:"wasm",kernelFunc:ef},P2;function bae(e){P2=e.wasm.cwrap(hi,null,["number","number","number","number"])}function xae(e){let{backend:t,inputs:{logits:n},attrs:{dim:a}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),i=t.dataIdMap.get(s.dataId).id,o=n.shape[a],l=k.sizeFromShape(n.shape)/o;return k.sizeFromShape(s.shape)===0||P2(r,i,o,l),s}var vae={kernelName:hi,backendName:"wasm",setupFunc:bae,kernelFunc:xae};function wae(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=k.parseAxisParam(i,r.shape)[0],l=_.prepareSplitSize(r,s,o),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(p=>{let d=[...u];d[o]=p;let h=ef({inputs:{x:r},attrs:{begin:c,size:d},backend:a});return c[o]+=p,h})}var kae={kernelName:wl,backendName:"wasm",kernelFunc:wae},Iae=Sn(pi),Nae=Sn(kc),Tae=!0,Sae=fn(mi,Tae),O2;function Cae(e){O2=e.wasm.cwrap(Vr,null,["number","number","number"])}function _ae(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 O2(i,r,l),o}var Eae={kernelName:Vr,backendName:"wasm",setupFunc:Cae,kernelFunc:_ae},L2;function Aae(e){L2=e.wasm.cwrap(kl,null,["number","array","number","array","array","array","array","array","number","number"])}function Fae(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:c,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:d}=a,h=_.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let m=r.shape.length-s.length,f=_.slice_util.maskToAxes(p),g=r.shape.slice();f.forEach(P=>{s[P]=0,i[P]=1,g.splice(P,0,1)});let y=Pa({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:b,end:v,strides:x}=_.slice_util.getNormalizedAxes(y.shape,h,m,s,i,o,l,c,u);s=b,i=v,o=x;let N=_.slice_util.maskToAxes(d);N.forEach(P=>{i[P]=s[P]+1,o[P]=1});let T=_.slice_util.computeOutShape(s,i,o),C=T.filter((P,B)=>N.indexOf(B)===-1);if(o.every(P=>P===1)){let P=ef({inputs:{x:r},attrs:{begin:s,size:T},backend:t});t.disposeData(y.dataId);let B=Pa({inputs:{x:P},attrs:{shape:C},backend:t});return t.disposeData(P.dataId),B}let F=t.makeOutput(C,"float32");if(!C.some(P=>P===0)){let P=t.dataIdMap.get(y.dataId).id,B=new Uint8Array(new Int32Array(k.computeStrides(y.shape)).buffer),W=new Uint8Array(new Int32Array(s).buffer),G=new Uint8Array(new Int32Array(i).buffer),q=new Uint8Array(new Int32Array(o).buffer),j=new Uint8Array(new Int32Array(C).buffer),X=new Uint8Array(new Int32Array(k.computeStrides(C)).buffer),K=t.dataIdMap.get(F.dataId).id;L2(P,B,y.shape.length,W,G,q,j,X,C.length,K)}t.disposeData(y.dataId);let $=Pa({inputs:{x:F},attrs:{shape:C},backend:t});return t.disposeData(F.dataId),$}var $ae={kernelName:kl,backendName:"wasm",setupFunc:Aae,kernelFunc:Fae},Dae=!0,Rae=fn(fi,Dae),z2;function Mae(e){z2=e.wasm.cwrap(di,null,["number, number, number"])}function Pae(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,c=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:h}=yu(i,r,t),m=p;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("sum",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=k.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(k.sizeFromShape(c.shape)!==0){let v=t.dataIdMap.get(b.dataId).id;z2(l,y,v)}if(h&&t.disposeData(u.dataId),s){let v=_.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var Oae={kernelName:di,backendName:"wasm",setupFunc:Mae,kernelFunc:Pae},Lae=Sn(gi),B2;function zae(e){B2=e.wasm.cwrap(Wr,null,["number","array","number","array","number","number"])}function Bae(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 d=0;d<o.length;d++)o[d]=r.shape[d]*i[d];let l=new Uint8Array(new Int32Array(r.shape).buffer),c=new Uint8Array(new Int32Array(o).buffer),u=n.makeOutput(o,r.dtype),p=n.dataIdMap.get(u.dataId).id;return B2(s,l,r.shape.length,c,o.length,Vn[u.dtype],p),u}var Wae={kernelName:Wr,backendName:"wasm",setupFunc:zae,kernelFunc:Bae},W2;function Vae(e){W2=e.wasm.cwrap(Nl,null,["number","array","number","number","number","bool","number","number"])}var Uae=({inputs:e,backend:t,attrs:n})=>{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 c=t.makeOutput(l,a.dtype),u=t.dataIdMap.get(c.dataId).id,p=t.makeOutput(l,"int32"),d=t.dataIdMap.get(p.dataId).id;return W2(i,o,a.shape.length,Vn[a.dtype],r,s,u,d),[c,p]},Gae={kernelName:Nl,backendName:"wasm",setupFunc:Vae,kernelFunc:Uae};function Hae(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),c=0;for(let h=0;h<o;h++)h!==s&&(l[c++]=r.shape[h]);let u=new Array(i),p=new Array(o).fill(0),d=r.shape.slice();d[s]=1;for(let h=0;h<u.length;h++)p[s]=h,u[h]=ef({inputs:{x:r},attrs:{begin:p,size:d},backend:n});return u.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var jae={kernelName:Tl,backendName:"wasm",kernelFunc:Hae};function qae(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var Kae={kernelName:Sl,backendName:"wasm",kernelFunc:qae},Xae=[mee,gee,xee,Cee,Aee,Ree,Mee,Pee,zee,Bee,Uee,jee,qee,Yee,Qee,nte,ste,ote,lte,ute,pte,mte,fte,yte,hee,vte,Ite,Ste,Ete,$te,Rte,Pte,vee,zte,Wte,Ute,Gte,jte,Xte,Zte,ene,ane,ine,lne,cne,pne,mne,yne,vne,kne,Tne,Cne,Ene,$ne,Rne,One,Bne,Vne,Gne,Hne,jne,Fee,Xne,Jne,tae,aae,nae,iae,uae,dae,hae,yae,vae,kae,Iae,Nae,Sae,Eae,$ae,Rae,Oae,Lae,Wae,Gae,Nee,jae,Kae];for(let e of Xae)Tc(e);var ew=ee();ew.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])));ew.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(ew.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 V2=So(IE()),Yae='var threadInfoStruct=0;var selfThreadId=0;var parentThreadId=0;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:selfThreadId})}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};this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["DYNAMIC_BASE"]=e.data.DYNAMIC_BASE;Module["DYNAMICTOP_PTR"]=e.data.DYNAMICTOP_PTR;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)}Module=WasmBackendModuleThreadedSimd(Module);postMessage({"cmd":"loaded"})}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;threadInfoStruct=e.data.threadInfoStruct;Module["__register_pthread_ptr"](threadInfoStruct,0,0);selfThreadId=e.data.selfThreadId;parentThreadId=e.data.parentThreadId;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["dynCall_ii"](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"){Atomics.store(Module["HEAPU32"],threadInfoStruct+4>>2,ex instanceof Module["ExitStatus"]?ex.status:-2);Atomics.store(Module["HEAPU32"],threadInfoStruct+0>>2,1);Module["_emscripten_futex_wake"](threadInfoStruct+0,2147483647);if(!(ex instanceof Module["ExitStatus"]))throw ex}}}else if(e.data.cmd==="cancel"){if(threadInfoStruct){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(threadInfoStruct){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.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");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()}}}}',Zae=So(NE()),U2=class extends rc{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new gd(this,Ha())}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 c=t;this.dataIdMap.set(e,{id:s,stringBytes:c,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 Jae(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(),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 Qae(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)})})}),{})}function G2(e,t,n){if(tf!=null)return tf;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),Cp!=null&&Cp[a]!=null?Cp[a]:n+a}async function ere(){let[e,t]=await Promise.all([ee().getAsync("WASM_HAS_SIMD_SUPPORT"),ee().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(l,c)=>{if(l.endsWith(".worker.js")){let u=Yae,p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return l.endsWith(".wasm")?G2(e,t,_p!=null?_p:c):c+l},tw&&(r.instantiateWasm=Qae(G2(e,t,_p!=null?_p:"")));let s;t&&e&&tf==null?(s=V2.default(r),s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+V2.default.toString()],{type:"text/javascript"})):s=Zae.default(r);let i=null;s.tfjs={init:s.cwrap("init",null,[]),registerTensor:s.cwrap("register_tensor",null,["number","number","number"]),disposeData:s.cwrap("dispose_data",i,["number"]),dispose:s.cwrap("dispose",i,[])};let o=!1;s.onRuntimeInitialized=()=>{o=!0,Ep=!1,n({wasm:s})},s.onAbort=()=>{o||Ep||(Ep=!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"}))}})}function Jae(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 tre=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],tf=null,_p=null,Cp={},Ep=!1,tw=!1;function nre(e,t=!1){if(Ty("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Ep)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");tf=e,tw=t}function are(e,t=!1){if(Ep)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")_p=e;else{Cp=e;let n=tre.filter(a=>Cp[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.`)}tw=t}var rre="3.1.0",sre=2;uh("wasm",async()=>{let{wasm:e}=await ere();return new U2(e)},sre);var Cw={};hd(Cw,{AnchorPosition:()=>lr,DrawBox:()=>sf,DrawBoxOptions:()=>gw,DrawFaceLandmarks:()=>Sw,DrawFaceLandmarksOptions:()=>Tw,DrawTextField:()=>hs,DrawTextFieldOptions:()=>Dp,drawContour:()=>Sr,drawDetections:()=>gre,drawFaceExpressions:()=>vre,drawFaceLandmarks:()=>wre});function Sr(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:a,y:r},s)=>{let i=t[s];e.moveTo(i.x,i.y),e.lineTo(a,r)}),n){let a=t[t.length-1],r=t[0];if(!a||!r)return;e.moveTo(a.x,a.y),e.lineTo(r.x,r.y)}e.stroke()}var nw={};hd(nw,{computeReshapedDimensions:()=>sw,getCenterPoint:()=>Zi,isDimensions:()=>af,isEven:()=>nf,isFloat:()=>rw,isTensor:()=>Xi,isTensor1D:()=>ire,isTensor2D:()=>aw,isTensor3D:()=>Cr,isTensor4D:()=>ea,isValidNumber:()=>Oa,isValidProbablitiy:()=>bu,range:()=>ir,round:()=>Yi});var gn=class{constructor(t,n){if(!Oa(t)||!Oa(n))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:n})}`);this._width=t,this._height=n}get width(){return this._width}get height(){return this._height}reverse(){return new gn(1/this.width,1/this.height)}};function Xi(e,t){return e instanceof Ae&&e.shape.length===t}function ire(e){return Xi(e,1)}function aw(e){return Xi(e,2)}function Cr(e){return Xi(e,3)}function ea(e){return Xi(e,4)}function rw(e){return e%1!=0}function nf(e){return e%2==0}function Yi(e,t=2){let n=10**t;return Math.floor(e*n)/n}function af(e){return e&&e.width&&e.height}function sw({width:e,height:t},n){let a=n/Math.max(t,e);return new gn(Math.round(e*a),Math.round(t*a))}function Zi(e){return e.reduce((t,n)=>t.add(n),new De(0,0)).div(new De(e.length,e.length))}function ir(e,t,n){return Array(e).fill(0).map((a,r)=>t+r*n)}function Oa(e){return!!e&&e!==Infinity&&e!==-Infinity&&!Number.isNaN(e)||e===0}function bu(e){return Oa(e)&&e>=0&&e<=1}var De=class{constructor(t,n){this._x=t,this._y=n}get x(){return this._x}get y(){return this._y}add(t){return new De(this.x+t.x,this.y+t.y)}sub(t){return new De(this.x-t.x,this.y-t.y)}mul(t){return new De(this.x*t.x,this.y*t.y)}div(t){return new De(this.x/t.x,this.y/t.y)}abs(){return new De(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new De(Math.floor(this.x),Math.floor(this.y))}};var ut=class{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(Oa)}static assertIsValidBox(t,n,a=!1){if(!ut.isRect(t))throw new Error(`${n} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!a&&(t.width<0||t.height<0))throw new Error(`${n} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,n=!0){let a=t||{},r=[a.left,a.top,a.right,a.bottom].every(Oa),s=[a.x,a.y,a.width,a.height].every(Oa);if(!s&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(a)}`);let[i,o,l,c]=s?[a.x,a.y,a.width,a.height]:[a.left,a.top,a.right-a.left,a.bottom-a.top];ut.assertIsValidBox({x:i,y:o,width:l,height:c},"Box.constructor",n),this._x=i,this._y=o,this._width=l,this._height=c}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new De(this.left,this.top)}get topRight(){return new De(this.right,this.top)}get bottomLeft(){return new De(this.left,this.bottom)}get bottomRight(){return new De(this.right,this.bottom)}round(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.round(s));return new ut({x:t,y:n,width:a,height:r})}floor(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.floor(s));return new ut({x:t,y:n,width:a,height:r})}toSquare(){let{x:t,y:n,width:a,height:r}=this,s=Math.abs(a-r);return a<r&&(t-=s/2,a+=s),r<a&&(n-=s/2,r+=s),new ut({x:t,y:n,width:a,height:r})}rescale(t){let n=af(t)?t.width:t,a=af(t)?t.height:t;return new ut({x:this.x*n,y:this.y*a,width:this.width*n,height:this.height*a})}pad(t,n){let[a,r,s,i]=[this.x-t/2,this.y-n/2,this.width+t,this.height+n];return new ut({x:a,y:r,width:s,height:i})}clipAtImageBorders(t,n){let{x:a,y:r,right:s,bottom:i}=this,o=Math.max(a,0),l=Math.max(r,0),c=s-o,u=i-l,p=Math.min(c,t-o),d=Math.min(u,n-l);return new ut({x:o,y:l,width:p,height:d}).floor()}shift(t,n){let{width:a,height:r}=this,s=this.x+t,i=this.y+n;return new ut({x:s,y:i,width:a,height:r})}padAtBorders(t,n){let a=this.width+1,r=this.height+1,s=1,i=1,o=a,l=r,c=this.left,u=this.top,p=this.right,d=this.bottom;return p>n&&(o=-p+n+a,p=n),d>t&&(l=-d+t+r,d=t),c<1&&(l=2-c,c=1),u<1&&(l=2-u,u=1),{dy:i,edy:l,dx:s,edx:o,y:u,ey:d,x:c,ex:p,w:a,h:r}}calibrate(t){return new ut({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()}};var xu=class extends ut{constructor(t,n,a,r,s=!1){super({left:t,top:n,right:a,bottom:r},s)}};var ds=class{constructor(t,n,a,r,s){this._imageDims=new gn(s.width,s.height),this._score=t,this._classScore=n,this._className=a,this._box=new ut(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new ut(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new ds(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var bt=class extends ds{constructor(t,n,a){super(t,t,"",n,a)}forSize(t,n){let{score:a,relativeBox:r,imageDims:s}=super.forSize(t,n);return new bt(a,r,s)}};function iw(e,t,n=!0){let a=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),r=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=a*r;return n?s/(e.area+t.area-s):s/Math.min(e.area,t.area)}function ow(e){let t=e.map(o=>o.x),n=e.map(o=>o.y),a=t.reduce((o,l)=>l<o?l:o,Infinity),r=n.reduce((o,l)=>l<o?l:o,Infinity),s=t.reduce((o,l)=>o<l?l:o,0),i=n.reduce((o,l)=>o<l?l:o,0);return new xu(a,r,s,i)}function lw(e,t,n,a=!0){let r=t.map((i,o)=>({score:i,boxIndex:o})).sort((i,o)=>i.score-o.score).map(i=>i.boxIndex),s=[];for(;r.length>0;){let i=r.pop();s.push(i);let o=r,l=[];for(let c=0;c<o.length;c++){let u=o[c],p=e[i],d=e[u];l.push(iw(p,d,a))}r=r.filter((c,u)=>l[u]<=n)}return s}function La(e,t){return D(()=>{let[n,a,r]=t,s=wn([...e.shape.slice(0,3),1],n,"float32"),i=wn([...e.shape.slice(0,3),1],a,"float32"),o=wn([...e.shape.slice(0,3),1],r,"float32"),l=Qe([s,i,o],3);return fe(e,l)})}function uw(e,t=!1){return D(()=>{let[n,a]=e.shape.slice(1);if(n===a)return e;let r=Math.abs(n-a),s=Math.round(r*(t?.5:1)),i=n>a?2:1,o=d=>{let h=e.shape.slice();return h[i]=d,wn(h,0,"float32")},l=o(s),c=r-l.shape[i],p=[t&&c?o(c):null,e,l].filter(d=>!!d).map(d=>ce(d,"float32"));return Qe(p,i)})}function ore(e){let t=e.slice();for(let n=t.length-1;n>0;n--){let a=Math.floor(Math.random()*(n+1)),r=t[n];t[n]=t[a],t[a]=r}return t}function Ap(e){return 1/(1+Math.exp(-e))}function lre(e){return Math.log(e/(1-e))}var vu=class extends ut{constructor(t,n,a,r,s=!1){super({x:t,y:n,width:a,height:r},s)}};var ure=.5,cre=.43,pre=.45,ta=class{constructor(t,n,a=new De(0,0)){let{width:r,height:s}=n;this._imgDims=new gn(r,s),this._shift=a,this._positions=t.map(i=>i.mul(new De(r,s)).add(a))}get shift(){return new De(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(t=>t.sub(this._shift).div(new De(this.imageWidth,this.imageHeight)))}forSize(t,n){return new this.constructor(this.relativePositions,{width:t,height:n})}shiftBy(t,n){return new this.constructor(this.relativePositions,this._imgDims,new De(t,n))}shiftByPoint(t){return this.shiftBy(t.x,t.y)}align(t,n={}){if(t){let s=t instanceof bt?t.box.floor():new ut(t);return this.shiftBy(s.x,s.y).align(null,n)}let{useDlibAlignment:a,minBoxPadding:r}={useDlibAlignment:!1,minBoxPadding:.2,...n};return a?this.alignDlib():this.alignMinBbox(r)}alignDlib(){let t=this.getRefPointsForAlignment(),[n,a,r]=t,s=p=>r.sub(p).magnitude(),i=(s(n)+s(a))/2,o=Math.floor(i/pre),l=Zi(t),c=Math.floor(Math.max(0,l.x-ure*o)),u=Math.floor(Math.max(0,l.y-cre*o));return new vu(c,u,Math.min(o,this.imageWidth+c),Math.min(o,this.imageHeight+u))}alignMinBbox(t){let n=ow(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var H2=class extends ta{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],Zi([t[3],t[4]])]}};var wu=class extends ta{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Zi)}};var Fp=class{constructor(t,n){this._label=t,this._distance=n}get label(){return this._label}get distance(){return this._distance}toString(t=!0){return`${this.label}${t?` (${Yi(this.distance)})`:""}`}};var $p=class extends ut{static assertIsValidLabeledBox(t,n){if(ut.assertIsValidBox(t,n),!Oa(t.label))throw new Error(`${n} - expected property label (${t.label}) to be a number`)}constructor(t,n){super(t);this._label=n}get label(){return this._label}};var _r=class{constructor(t,n){if(typeof t!="string")throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(n)||n.some(a=>!(a instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=n}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(t=>Array.from(t))}}static fromJSON(t){let n=t.descriptors.map(a=>new Float32Array(a));return new _r(t.label,n)}};var j2=class extends $p{static assertIsValidPredictedBox(t,n){if($p.assertIsValidLabeledBox(t,n),!bu(t.score)||!bu(t.classScore))throw new Error(`${n} - expected properties score (${t.score}) and (${t.classScore}) to be a number between [0, 1]`)}constructor(t,n,a,r){super(t,n);this._score=a,this._classScore=r}get score(){return this._score}get classScore(){return this._classScore}};function or(e){return e.detection instanceof bt}function Ji(e,t){return{...e,...{detection:t}}}function cw(){let e=window.fetch;if(!e)throw new Error("fetch - missing fetch implementation for browser environment");return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function rf(e){let t="";if(!e)try{e=require("fs")}catch(a){t=a.toString()}return{readFile:e?a=>new Promise((r,s)=>{e.readFile(a,(i,o)=>i?s(i):r(o))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function pw(){let e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=()=>{if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},a=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},r=global.fetch,s=rf();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:a,fetch:r,...s}}function dw(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var hw=aE(K2()),Jt;function mre(){if(!Jt)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Jt}function mw(e){Jt=e}function fw(){return dw()?mw(cw()):hw.isNodejs()?mw(pw()):null}function fre(e){if(Jt||fw(),!Jt)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=Jt.Canvas,Image:n=Jt.Image}=e;Jt.Canvas=t,Jt.Image=n,Jt.createCanvasElement=e.createCanvasElement||(()=>new t),Jt.createImageElement=e.createImageElement||(()=>new n),Jt.ImageData=e.ImageData||Jt.ImageData,Jt.Video=e.Video||Jt.Video,Jt.fetch=e.fetch||Jt.fetch,Jt.readFile=e.readFile||Jt.readFile}var st={getEnv:mre,setEnv:mw,initialize:fw,createBrowserEnv:cw,createFileSystem:rf,createNodejsEnv:pw,monkeyPatch:fre,isBrowser:dw,isNodejs:hw.isNodejs};fw();function Qi(e){return!st.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Cn(e){let{Canvas:t,CanvasRenderingContext2D:n}=st.getEnv();if(e instanceof n)return e;let a=Qi(e);if(!(a instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let r=a.getContext("2d");if(!r)throw new Error("resolveContext2d - canvas 2d context is null");return r}var lr;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(lr||(lr={}));var Dp=class{constructor(t={}){let{anchorPosition:n,backgroundColor:a,fontColor:r,fontSize:s,fontStyle:i,padding:o}=t;this.anchorPosition=n||lr.TOP_LEFT,this.backgroundColor=a||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=s||14,this.fontStyle=i||"Georgia",this.padding=o||4}},hs=class{constructor(t,n,a={}){this.text=typeof t=="string"?[t]:t instanceof hs?t.text:t,this.anchor=n,this.options=new Dp(a)}measureWidth(t){let{padding:n}=this.options;return this.text.map(a=>t.measureText(a).width).reduce((a,r)=>a<r?r:a,0)+2*n}measureHeight(){let{fontSize:t,padding:n}=this.options;return this.text.length*t+2*n}getUpperLeft(t,n){let{anchorPosition:a}=this.options,r=a===lr.BOTTOM_RIGHT||a===lr.TOP_RIGHT,s=a===lr.BOTTOM_LEFT||a===lr.BOTTOM_RIGHT,i=this.measureWidth(t),o=this.measureHeight(),l=r?this.anchor.x-i:this.anchor.x,c=s?this.anchor.y-o:this.anchor.y;if(n){let{width:u,height:p}=n,d=Math.max(Math.min(l,u-i),0),h=Math.max(Math.min(c,p-o),0);return{x:d,y:h}}return{x:l,y:c}}draw(t){let n=Qi(t),a=Cn(n),{backgroundColor:r,fontColor:s,fontSize:i,fontStyle:o,padding:l}=this.options;a.font=`${i}px ${o}`;let c=this.measureWidth(a),u=this.measureHeight();a.fillStyle=r;let p=this.getUpperLeft(a,n);a.fillRect(p.x,p.y,c,u),a.fillStyle=s,this.text.forEach((d,h)=>{let m=l+p.x,f=l+p.y+(h+1)*i;a.fillText(d,m,f)})}};var gw=class{constructor(t={}){let{boxColor:n,lineWidth:a,label:r,drawLabelOptions:s}=t;this.boxColor=n||"rgba(0, 0, 255, 1)",this.lineWidth=a||2,this.label=r;let i={anchorPosition:lr.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Dp({...i,...s})}},sf=class{constructor(t,n={}){this.box=new ut(t),this.options=new gw(n)}draw(t){let n=Cn(t),{boxColor:a,lineWidth:r}=this.options,{x:s,y:i,width:o,height:l}=this.box;n.strokeStyle=a,n.lineWidth=r,n.strokeRect(s,i,o,l);let{label:c}=this.options;c&&new hs([c],{x:s-r/2,y:i},this.options.drawLabelOptions).draw(t)}};function gre(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof bt?a.score:or(a)?a.detection.score:void 0,s=a instanceof bt?a.box:or(a)?a.detection.box:new ut(a),i=r?`${Yi(r)}`:void 0;new sf(s,{label:i}).draw(e)})}function Rp(e){let{Image:t,Video:n}=st.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function yw(e){return new Promise((t,n)=>{if(e instanceof st.getEnv().Canvas||Rp(e))return t(null);function a(s){!s.currentTarget||(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),n(s))}function r(s){!s.currentTarget||(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),t(s))}e.addEventListener("load",r),e.addEventListener("error",a)})}function bw(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToImage - expected buf to be of type: Blob"));let a=new FileReader;a.onload=()=>{typeof a.result!="string"&&n(new Error("bufferToImage - expected reader.result to be a string, in onload"));let r=st.getEnv().createImageElement();r.onload=()=>t(r),r.onerror=n,r.src=a.result},a.onerror=n,a.readAsDataURL(e)})}function eo(e){let{Image:t,Video:n}=st.getEnv();return e instanceof t?new gn(e.naturalWidth,e.naturalHeight):e instanceof n?new gn(e.videoWidth,e.videoHeight):new gn(e.width,e.height)}function to({width:e,height:t}){let{createCanvasElement:n}=st.getEnv(),a=n();return a.width=e,a.height=t,a}function Mp(e,t){let{ImageData:n}=st.getEnv();if(!(e instanceof n)&&!Rp(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:a,height:r}=t||eo(e),s=to({width:a,height:r});return e instanceof n?Cn(s).putImageData(e,0,0):Cn(s).drawImage(e,0,0,a,r),s}async function xw(e,t){let n=t||st.getEnv().createCanvasElement(),[a,r,s]=e.shape.slice(ea(e)?1:0),i=D(()=>e.as3D(a,r,s).toInt());return await Ni.toPixels(i,n),i.dispose(),n}function of(e){let{Image:t,Canvas:n,Video:a}=st.getEnv();return e instanceof t||e instanceof n||e instanceof a}function vw(e,t,n=!1){let{Image:a,Canvas:r}=st.getEnv();if(!(e instanceof a||e instanceof r))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return to({width:1,height:1});let s=eo(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,c=to({width:t,height:t}),u=e instanceof r?e:Mp(e),p=Math.abs(o-l)/2,d=n&&o<l?p:0,h=n&&l<o?p:0;return u.width>0&&u.height>0&&Cn(c).drawImage(u,d,h,o,l),c}var Er=class{constructor(t,n=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];if(!Array.isArray(t))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${t}`);this._treatAsBatchInput=n,this._batchSize=t.length,t.forEach((a,r)=>{if(Cr(a)){this._imageTensors[r]=a,this._inputDimensions[r]=a.shape;return}if(ea(a)){let i=a.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=a,this._inputDimensions[r]=a.shape.slice(1);return}let s=a instanceof st.getEnv().Canvas?a:Mp(a);this._canvases[r]=s,this._inputDimensions[r]=[s.height,s.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return ir(this.batchSize,0,1).map((t,n)=>this.getReshapedInputDimensions(n))}getInput(t){return this.canvases[t]||this.imageTensors[t]}getInputDimensions(t){return this._inputDimensions[t]}getInputHeight(t){return this._inputDimensions[t][0]}getInputWidth(t){return this._inputDimensions[t][1]}getReshapedInputDimensions(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let n=this.getInputWidth(t),a=this.getInputHeight(t);return sw({width:n,height:a},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,D(()=>{let a=ir(this.batchSize,0,1).map(s=>{let i=this.getInput(s);if(i instanceof Ae){let o=ea(i)?i:i.expandDims();return o=uw(o,n),(o.shape[1]!==t||o.shape[2]!==t)&&(o=Za.resizeBilinear(o,[t,t])),o.as3D(t,t,3)}if(i instanceof st.getEnv().Canvas)return Ni.fromPixels(vw(i,t,n));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)});return $t(a.map(s=>ce(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function gt(e){if(e instanceof Er)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");let n=r=>Array.isArray(e)?` at input index ${r}:`:"",a=t.map(Qi);return a.forEach((r,s)=>{if(!of(r)&&!Cr(r)&&!ea(r))throw typeof t[s]=="string"?new Error(`toNetInput -${n(s)} string passed, but could not resolve HTMLElement for element id ${t[s]}`):new Error(`toNetInput -${n(s)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(ea(r)){let i=r.shape[0];if(i!==1)throw new Error(`toNetInput -${n(s)} tf.Tensor4D with batchSize ${i} passed, but not supported in input array`)}}),await Promise.all(a.map(r=>of(r)&&yw(r))),new Er(a,Array.isArray(e))}async function ku(e,t){let{Canvas:n}=st.getEnv(),a=e;if(!(e instanceof n)){let i=await gt(e);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let o=i.getInput(0);a=o instanceof n?o:await xw(o)}let r=Cn(a);return t.map(i=>i instanceof bt?i.forSize(a.width,a.height).box.floor():i).map(i=>i.clipAtImageBorders(a.width,a.height)).map(({x:i,y:o,width:l,height:c})=>{let u=to({width:l,height:c});return l>0&&c>0&&Cn(u).putImageData(r.getImageData(i,o,l,c),0,0),u})}async function Iu(e,t){if(!Cr(e)&&!ea(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(ea(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return D(()=>{let[n,a,r]=e.shape.slice(ea(e)?1:0);return t.map(o=>o instanceof bt?o.forSize(a,n).box:o).map(o=>o.clipAtImageBorders(a,n)).map(({x:o,y:l,width:c,height:u})=>Ul(e.as3D(n,a,r),[l,o,0],[u,c,r]))})}async function no(e,t){let{fetch:n}=st.getEnv(),a=await n(e,t);if(!(a.status<400))throw new Error(`failed to fetch: (${a.status}) ${a.statusText}, from url: ${a.url}`);return a}async function yre(e){let t=await no(e),n=await t.blob();if(!n.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${n.type}, for url: ${t.url}`);return bw(n)}async function ww(e){return(await no(e)).json()}async function bre(e){return new Float32Array(await(await no(e)).arrayBuffer())}function lf(e,t){let n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};let a=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(a,"");let r=e.split("/").filter(o=>o),s=e.endsWith(".json")?r[r.length-1]:n,i=a+(e.endsWith(".json")?r.slice(0,r.length-1):r).join("/");return i=e.startsWith("/")?`/${i}`:i,{modelBaseUri:i,manifestUri:i==="/"?`/${s}`:`${i}/${s}`}}async function kw(e,t){let{manifestUri:n,modelBaseUri:a}=lf(e,t),r=await ww(n);return Ht.loadWeights(r,a)}function xre(e,t,n=!1){let{width:a,height:r}=n?eo(t):t;return e.width=a,e.height=r,{width:a,height:r}}var an=class{constructor(t){this._params=void 0;this._paramMappings=[];this._name=t}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(t){let{obj:n,objProp:a}=this.traversePropertyPath(t);return n[a]}reassignParamFromPath(t,n){let{obj:a,objProp:r}=this.traversePropertyPath(t);a[r].dispose(),a[r]=n}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof Ur)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof Ur))}variable(){this.getFrozenParams().forEach(({path:t,tensor:n})=>{this.reassignParamFromPath(t,n.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:n})=>{let a=qn(n.dataSync());n.dispose(),this.reassignParamFromPath(t,a)})}dispose(t=!0){this.getParamList().forEach(n=>{if(t&&n.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${n.path}`);n.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:t})=>Array.from(t.dataSync())).reduce((t,n)=>t.concat(n)))}async load(t){if(t instanceof Float32Array){this.extractWeights(t);return}await this.loadFromUri(t)}async loadFromUri(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);let n=await kw(t,this.getDefaultModelName());this.loadFromWeightMap(n)}async loadFromDisk(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);let{readFile:n}=st.getEnv(),{manifestUri:a,modelBaseUri:r}=lf(t,this.getDefaultModelName()),s=c=>Promise.all(c.map(u=>n(u).then(p=>p.buffer))),i=Ht.weightsLoaderFactory(s),o=JSON.parse((await n(a)).toString()),l=await i(o,r);this.loadFromWeightMap(l)}loadFromWeightMap(t){let{paramMappings:n,params:a}=this.extractParamsFromWeightMap(t);this._paramMappings=n,this._params=a}extractWeights(t){let{paramMappings:n,params:a}=this.extractParams(t);this._paramMappings=n,this._params=a}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let n=t.split("/").reduce((s,i)=>{if(!s.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${t}`);return{obj:s.nextObj,objProp:i,nextObj:s.nextObj[i]}},{nextObj:this.params}),{obj:a,objProp:r}=n;if(!a||!r||!(a[r]instanceof Ae))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:a,objProp:r}}};function _n(e,t,n){return D(()=>{let a=Fi(e,t.depthwise_filter,t.pointwise_filter,n,"same");return a=Z(a,t.bias),a})}function uf(e,t,n=!1){return D(()=>{let a=Ye(n?Z(At(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):_n(e,t.conv0,[2,2])),r=_n(a,t.conv1,[1,1]),s=Ye(Z(a,r)),i=_n(s,t.conv2,[1,1]);return Ye(Z(a,Z(r,i)))})}function Pp(e,t,n=!1,a=!0){return D(()=>{let r=Ye(n?Z(At(e,t.conv0.filters,a?[2,2]:[1,1],"same"),t.conv0.bias):_n(e,t.conv0,a?[2,2]:[1,1])),s=_n(r,t.conv1,[1,1]),i=Ye(Z(r,s)),o=_n(i,t.conv2,[1,1]),l=Ye(Z(r,Z(s,o))),c=_n(l,t.conv3,[1,1]);return Ye(Z(r,Z(s,Z(o,c))))})}function ao(e,t,n="same",a=!1){return D(()=>{let r=Z(At(e,t.filters,[1,1],n),t.bias);return a?Ye(r):r})}function yn(e,t){Object.keys(e).forEach(n=>{t.some(a=>a.originalPath===n)||e[n].dispose()})}function Nu(e,t){return(n,a,r,s)=>{let i=Ca(e(n*a*r*r),[r,r,n,a]),o=tt(e(a));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function cf(e,t){return(n,a,r)=>{let s=Sa(e(n*a),[n,a]),i=tt(e(a));return t.push({paramPath:`${r}/weights`},{paramPath:`${r}/bias`}),{weights:s,bias:i}}}var pf=class{constructor(t,n,a){this.depthwise_filter=t;this.pointwise_filter=n;this.bias=a}};function Tu(e,t){return(n,a,r)=>{let s=Ca(e(3*3*n),[3,3,n,1]),i=Ca(e(n*a),[1,1,n,a]),o=tt(e(a));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new pf(s,i,o)}}function Su(e){return t=>{let n=e(`${t}/depthwise_filter`,4),a=e(`${t}/pointwise_filter`,4),r=e(`${t}/bias`,1);return new pf(n,a,r)}}function Un(e,t){return(n,a,r)=>{let s=e[n];if(!Xi(s,a))throw new Error(`expected weightMap[${n}] to be a Tensor${a}D, instead have ${s}`);return t.push({originalPath:n,paramPath:r||n}),s}}function bn(e){let t=e;function n(r){let s=t.slice(0,r);return t=t.slice(r),s}function a(){return t}return{extractWeights:n,getRemainingWeights:a}}function df(e,t){let n=Nu(e,t),a=Tu(e,t);function r(i,o,l,c=!1){let u=c?n(i,o,3,`${l}/conv0`):a(i,o,`${l}/conv0`),p=a(o,o,`${l}/conv1`),d=a(o,o,`${l}/conv2`);return{conv0:u,conv1:p,conv2:d}}function s(i,o,l,c=!1){let{conv0:u,conv1:p,conv2:d}=r(i,o,l,c),h=a(o,o,`${l}/conv3`);return{conv0:u,conv1:p,conv2:d,conv3:h}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:s}}function X2(e){let t=[],{extractWeights:n,getRemainingWeights:a}=bn(e),{extractDenseBlock4Params:r}=df(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2"),l=r(128,256,"dense3");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o,dense3:l}}}function hf(e){return t=>{let n=e(`${t}/filters`,4),a=e(`${t}/bias`,1);return{filters:n,bias:a}}}function mf(e,t){let n=Un(e,t),a=hf(n),r=Su(n);function s(o,l=!1){let c=l?a(`${o}/conv0`):r(`${o}/conv0`),u=r(`${o}/conv1`),p=r(`${o}/conv2`);return{conv0:c,conv1:u,conv2:p}}function i(o,l=!1){let c=l?a(`${o}/conv0`):r(`${o}/conv0`),u=r(`${o}/conv1`),p=r(`${o}/conv2`),d=r(`${o}/conv3`);return{conv0:c,conv1:u,conv2:p,conv3:d}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:i}}function Y2(e){let t=[],{extractDenseBlock4Params:n}=mf(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return yn(e,t),{params:a,paramMappings:t}}var Op=class extends an{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return D(()=>{let a=ce(t.toBatchTensor(112,!0),"float32"),s=La(a,[122.782,117.001,104.298]).div(de(255)),i=Pp(s,n.dense0,!0);return i=Pp(i,n.dense1),i=Pp(i,n.dense2),i=Pp(i,n.dense3),i=Xn(i,[7,7],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await gt(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return Y2(t)}extractParams(t){return X2(t)}};function Lp(e,t){return D(()=>Z(ze(e,t.weights),t.bias))}function Z2(e,t,n){let a=[],{extractWeights:r,getRemainingWeights:s}=bn(e),o=cf(r,a)(t,n,"fc");if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:a,params:{fc:o}}}function J2(e){let t=[],n=Un(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:a("fc")};return yn(e,t),{params:r,paramMappings:t}}function ff(e){let t={},n={};return Object.keys(e).forEach(a=>{let r=a.startsWith("fc")?n:t;r[a]=e[a]}),{featureExtractorMap:t,classifierMap:n}}var zp=class extends an{constructor(t,n){super(t);this._faceFeatureExtractor=n}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){let{params:n}=this;if(!n)throw new Error(`${this._name} - load model before inference`);return D(()=>{let a=t instanceof Er?this.faceFeatureExtractor.forwardInput(t):t;return Lp(a.as2D(a.shape[0],-1),n.fc)})}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:a}=this.extractClassifierParams(t);this._params=n,this._paramMappings=a}extractClassifierParams(t){return Z2(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=ff(t);return this.faceFeatureExtractor.loadFromWeightMap(n),J2(a)}extractParams(t){let n=this.getClassifierChannelsIn(),a=this.getClassifierChannelsOut(),r=a*n+a,s=t.slice(0,t.length-r),i=t.slice(t.length-r);return this.faceFeatureExtractor.extractWeights(s),this.extractClassifierParams(i)}};var Iw=["neutral","happy","sad","angry","fearful","disgusted","surprised"],ms=class{constructor(t){if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);Iw.forEach((n,a)=>{this[n]=t[a]})}asSortedArray(){return Iw.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var gf=class extends zp{constructor(t=new Op){super("FaceExpressionNet",t)}forwardInput(t){return D(()=>Ta(this.runNet(t)))}async forward(t){return this.forwardInput(await gt(t))}async predictExpressions(t){let n=await gt(t),a=await this.forwardInput(n),r=await Promise.all(dt(a).map(async i=>{let o=await i.data();return i.dispose(),o}));a.dispose();let s=r.map(i=>new ms(i));return n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function Nw(e){return e.expressions instanceof ms}function yf(e,t){return{...e,...{expressions:t}}}function vre(e,t,n=.1,a){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof ms?s:Nw(s)?s.expressions:void 0;if(!i)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let l=i.asSortedArray().filter(p=>p.probability>n),c=or(s)?s.detection.box.bottomLeft:a||new De(0,0);new hs(l.map(p=>`${p.expression} (${Yi(p.probability)})`),c).draw(e)})}function ro(e){return or(e)&&e.landmarks instanceof ta&&e.unshiftedLandmarks instanceof ta&&e.alignedRect instanceof bt}function Cu(e,t){let{box:n}=e.detection,a=t.shiftBy(n.x,n.y),r=a.align(),{imageDims:s}=e.detection,i=new bt(e.detection.score,r.rescale(s.reverse()),s);return{...e,...{landmarks:a,unshiftedLandmarks:t,alignedRect:i}}}var Tw=class{constructor(t={}){let{drawLines:n=!0,drawPoints:a=!0,lineWidth:r,lineColor:s,pointSize:i,pointColor:o}=t;this.drawLines=n,this.drawPoints=a,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=s||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}},Sw=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new Tw(n)}draw(t){let n=Cn(t),{drawLines:a,drawPoints:r,lineWidth:s,lineColor:i,pointSize:o,pointColor:l}=this.options;if(a&&this.faceLandmarks instanceof wu&&(n.strokeStyle=i,n.lineWidth=s,Sr(n,this.faceLandmarks.getJawOutline()),Sr(n,this.faceLandmarks.getLeftEyeBrow()),Sr(n,this.faceLandmarks.getRightEyeBrow()),Sr(n,this.faceLandmarks.getNose()),Sr(n,this.faceLandmarks.getLeftEye(),!0),Sr(n,this.faceLandmarks.getRightEye(),!0),Sr(n,this.faceLandmarks.getMouth(),!0)),r){n.strokeStyle=l,n.fillStyle=l;let c=u=>{n.beginPath(),n.arc(u.x,u.y,o,0,2*Math.PI),n.fill()};this.faceLandmarks.positions.forEach(c)}}};function wre(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof ta?a:ro(a)?a.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Sw(r).draw(e)})}var Q2="0.13.1";function kre(e,t){let n=Nu(e,t),a=Tu(e,t);function r(i,o,l){let c=a(i,o,`${l}/separable_conv0`),u=a(o,o,`${l}/separable_conv1`),p=n(i,o,1,`${l}/expansion_conv`);return{separable_conv0:c,separable_conv1:u,expansion_conv:p}}function s(i,o){let l=a(i,i,`${o}/separable_conv0`),c=a(i,i,`${o}/separable_conv1`),u=a(i,i,`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:u}}return{extractConvParams:n,extractSeparableConvParams:a,extractReductionBlockParams:r,extractMainBlockParams:s}}function eC(e,t){let n=[],{extractWeights:a,getRemainingWeights:r}=bn(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=kre(a,n),c=s(3,32,3,"entry_flow/conv_in"),u=o(32,64,"entry_flow/reduction_block_0"),p=o(64,128,"entry_flow/reduction_block_1"),d={conv_in:c,reduction_block_0:u,reduction_block_1:p},h={};ir(t,0,1).forEach(y=>{h[`main_block_${y}`]=l(128,`middle_flow/main_block_${y}`)});let m=o(128,256,"exit_flow/reduction_block"),f=i(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{entry_flow:d,middle_flow:h,exit_flow:g}}}function Ire(e,t){let n=Un(e,t),a=hf(n),r=Su(n);function s(o){let l=r(`${o}/separable_conv0`),c=r(`${o}/separable_conv1`),u=a(`${o}/expansion_conv`);return{separable_conv0:l,separable_conv1:c,expansion_conv:u}}function i(o){let l=r(`${o}/separable_conv0`),c=r(`${o}/separable_conv1`),u=r(`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:u}}return{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}}function tC(e,t){let n=[],{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}=Ire(e,n),o=a("entry_flow/conv_in"),l=s("entry_flow/reduction_block_0"),c=s("entry_flow/reduction_block_1"),u={conv_in:o,reduction_block_0:l,reduction_block_1:c},p={};ir(t,0,1).forEach(f=>{p[`main_block_${f}`]=i(`middle_flow/main_block_${f}`)});let d=s("exit_flow/reduction_block"),h=r("exit_flow/separable_conv"),m={reduction_block:d,separable_conv:h};return yn(e,n),{params:{entry_flow:u,middle_flow:p,exit_flow:m},paramMappings:n}}function nC(e,t,n){return Z(At(e,t.filters,n,"same"),t.bias)}function _w(e,t,n=!0){let a=n?Ye(e):e;return a=_n(a,t.separable_conv0,[1,1]),a=_n(Ye(a),t.separable_conv1,[1,1]),a=Ft(a,[3,3],[2,2],"same"),a=Z(a,nC(e,t.expansion_conv,[2,2])),a}function Nre(e,t){let n=_n(Ye(e),t.separable_conv0,[1,1]);return n=_n(Ye(n),t.separable_conv1,[1,1]),n=_n(Ye(n),t.separable_conv2,[1,1]),n=Z(n,e),n}var Ew=class extends an{constructor(t){super("TinyXception");this._numMainBlocks=t}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyXception - load model before inference");return D(()=>{let a=ce(t.toBatchTensor(112,!0),"float32"),s=La(a,[122.782,117.001,104.298]).div(de(256)),i=Ye(nC(s,n.entry_flow.conv_in,[2,2]));return i=_w(i,n.entry_flow.reduction_block_0,!1),i=_w(i,n.entry_flow.reduction_block_1),ir(this._numMainBlocks,0,1).forEach(o=>{i=Nre(i,n.middle_flow[`main_block_${o}`])}),i=_w(i,n.exit_flow.reduction_block),i=Ye(_n(i,n.exit_flow.separable_conv,[1,1])),i})}async forward(t){return this.forwardInput(await gt(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return tC(t,this._numMainBlocks)}extractParams(t){return eC(t,this._numMainBlocks)}};function aC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=bn(e),r=cf(n,t),s=r(512,1,"fc/age"),i=r(512,2,"fc/gender");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{fc:{age:s,gender:i}}}}function rC(e){let t=[],n=Un(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:{age:a("fc/age"),gender:a("fc/gender")}};return yn(e,t),{params:r,paramMappings:t}}var Ar;(function(e){e.FEMALE="female",e.MALE="male"})(Ar||(Ar={}));var bf=class extends an{constructor(t=new Ew(2)){super("AgeGenderNet");this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(t){let{params:n}=this;if(!n)throw new Error(`${this._name} - load model before inference`);return D(()=>{let a=t instanceof Er?this.faceFeatureExtractor.forwardInput(t):t,r=Xn(a,[7,7],[2,2],"valid").as2D(a.shape[0],-1),s=Lp(r,n.fc.age).as1D(),i=Lp(r,n.fc.gender);return{age:s,gender:i}})}forwardInput(t){return D(()=>{let{age:n,gender:a}=this.runNet(t);return{age:n,gender:Ta(a)}})}async forward(t){return this.forwardInput(await gt(t))}async predictAgeAndGender(t){let n=await gt(t),a=await this.forwardInput(n),r=dt(a.age),s=dt(a.gender),i=r.map((l,c)=>({ageTensor:l,genderTensor:s[c]})),o=await Promise.all(i.map(async({ageTensor:l,genderTensor:c})=>{let u=(await l.data())[0],p=(await c.data())[0],d=p>.5,h=d?Ar.MALE:Ar.FEMALE,m=d?p:1-p;return l.dispose(),c.dispose(),{age:u,gender:h,genderProbability:m}}));return a.age.dispose(),a.gender.dispose(),n.isBatchInput?o:o[0]}getDefaultModelName(){return"age_gender_model"}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:a}=this.extractClassifierParams(t);this._params=n,this._paramMappings=a}extractClassifierParams(t){return aC(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=ff(t);return this.faceFeatureExtractor.loadFromWeightMap(n),rC(a)}extractParams(t){let n=512*1+1+(512*2+2),a=t.slice(0,t.length-n),r=t.slice(t.length-n);return this.faceFeatureExtractor.extractWeights(a),this.extractClassifierParams(r)}};var Bp=class extends zp{postProcess(t,n,a){let r=a.map(({width:i,height:o})=>{let l=n/Math.max(o,i);return{width:i*l,height:o*l}}),s=r.length;return D(()=>{let i=(p,d)=>$t([wn([68],p,"float32"),wn([68],d,"float32")],1).as2D(1,136).as1D(),o=(p,d)=>{let{width:h,height:m}=r[p];return d(h,m)?Math.abs(h-m)/2:0},l=p=>o(p,(d,h)=>d<h),c=p=>o(p,(d,h)=>h<d);return t.mul(wn([s,136],n,"float32")).sub($t(Array.from(Array(s),(p,d)=>i(l(d),c(d))))).div($t(Array.from(Array(s),(p,d)=>i(r[d].width,r[d].height))))})}forwardInput(t){return D(()=>{let n=this.runNet(t);return this.postProcess(n,t.inputSize,t.inputDimensions.map(([a,r])=>({height:a,width:r})))})}async forward(t){return this.forwardInput(await gt(t))}async detectLandmarks(t){let n=await gt(t),a=D(()=>dt(this.forwardInput(n))),r=await Promise.all(a.map(async(s,i)=>{let o=Array.from(await s.data()),l=o.filter((u,p)=>nf(p)),c=o.filter((u,p)=>!nf(p));return new wu(Array(68).fill(0).map((u,p)=>new De(l[p],c[p])),{height:n.getInputHeight(i),width:n.getInputWidth(i)})}));return a.forEach(s=>s.dispose()),n.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}};var _u=class extends Bp{constructor(t=new Op){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function sC(e){let t=[],{extractDenseBlock3Params:n}=mf(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return yn(e,t),{params:a,paramMappings:t}}function iC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=bn(e),{extractDenseBlock3Params:r}=df(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o}}}var Aw=class extends an{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return D(()=>{let a=ce(t.toBatchTensor(112,!0),"float32"),s=La(a,[122.782,117.001,104.298]).div(de(255)),i=uf(s,n.dense0,!0);return i=uf(i,n.dense1),i=uf(i,n.dense2),i=Xn(i,[14,14],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await gt(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return sC(t)}extractParams(t){return iC(t)}};var xf=class extends Bp{constructor(t=new Aw){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var oC=class extends _u{};function lC(e,t){return Z(L(e,t.weights),t.biases)}function Fw(e,t,n,a,r="same"){let{filters:s,bias:i}=t.conv,o=At(e,s,n,r);return o=Z(o,i),o=lC(o,t.scale),a?Ye(o):o}function uC(e,t){return Fw(e,t,[1,1],!0)}function $w(e,t){return Fw(e,t,[1,1],!1)}function vf(e,t){return Fw(e,t,[2,2],!0,"valid")}function Tre(e,t){function n(o,l,c){let u=e(o),p=u.length/(l*c*c);if(rw(p))throw new Error(`depth has to be an integer: ${p}, weights.length: ${u.length}, numFilters: ${l}, filterSize: ${c}`);return D(()=>Ue(Ca(u,[l,p,c,c]),[2,3,1,0]))}function a(o,l,c,u){let p=n(o,l,c),d=tt(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/bias`}),{filters:p,bias:d}}function r(o,l){let c=tt(e(o)),u=tt(e(o));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:c,biases:u}}function s(o,l,c,u){let p=a(o,l,c,`${u}/conv`),d=r(l,`${u}/scale`);return{conv:p,scale:d}}function i(o,l,c,u,p=!1){let d=s((p?.5:1)*o,l,c,`${u}/conv1`),h=s(o,l,c,`${u}/conv2`);return{conv1:d,conv2:h}}return{extractConvLayerParams:s,extractResidualLayerParams:i}}function cC(e){let{extractWeights:t,getRemainingWeights:n}=bn(e),a=[],{extractConvLayerParams:r,extractResidualLayerParams:s}=Tre(t,a),i=r(4704,32,7,"conv32_down"),o=s(9216,32,3,"conv32_1"),l=s(9216,32,3,"conv32_2"),c=s(9216,32,3,"conv32_3"),u=s(36864,64,3,"conv64_down",!0),p=s(36864,64,3,"conv64_1"),d=s(36864,64,3,"conv64_2"),h=s(36864,64,3,"conv64_3"),m=s(147456,128,3,"conv128_down",!0),f=s(147456,128,3,"conv128_1"),g=s(147456,128,3,"conv128_2"),y=s(589824,256,3,"conv256_down",!0),b=s(589824,256,3,"conv256_1"),v=s(589824,256,3,"conv256_2"),x=s(589824,256,3,"conv256_down_out"),N=D(()=>Ue(Sa(t(256*128),[128,256]),[1,0]));if(a.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{conv32_down:i,conv32_1:o,conv32_2:l,conv32_3:c,conv64_down:u,conv64_1:p,conv64_2:d,conv64_3:h,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:y,conv256_1:b,conv256_2:v,conv256_down_out:x,fc:N},paramMappings:a}}function Sre(e,t){let n=Un(e,t);function a(i){let o=n(`${i}/scale/weights`,1),l=n(`${i}/scale/biases`,1);return{weights:o,biases:l}}function r(i){let o=n(`${i}/conv/filters`,4),l=n(`${i}/conv/bias`,1),c=a(i);return{conv:{filters:o,bias:l},scale:c}}function s(i){return{conv1:r(`${i}/conv1`),conv2:r(`${i}/conv2`)}}return{extractConvLayerParams:r,extractResidualLayerParams:s}}function pC(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Sre(e,t),r=n("conv32_down"),s=a("conv32_1"),i=a("conv32_2"),o=a("conv32_3"),l=a("conv64_down"),c=a("conv64_1"),u=a("conv64_2"),p=a("conv64_3"),d=a("conv128_down"),h=a("conv128_1"),m=a("conv128_2"),f=a("conv256_down"),g=a("conv256_1"),y=a("conv256_2"),b=a("conv256_down_out"),{fc:v}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!aw(v))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${v}`);let x={conv32_down:r,conv32_1:s,conv32_2:i,conv32_3:o,conv64_down:l,conv64_1:c,conv64_2:u,conv64_3:p,conv128_down:d,conv128_1:h,conv128_2:m,conv256_down:f,conv256_1:g,conv256_2:y,conv256_down_out:b,fc:v};return yn(e,t),{params:x,paramMappings:t}}function za(e,t){let n=uC(e,t.conv1);return n=$w(n,t.conv2),n=Z(n,e),n=Ye(n),n}function Wp(e,t){let n=vf(e,t.conv1);n=$w(n,t.conv2);let a=Xn(e,2,2,"valid"),r=vt(a.shape),s=a.shape[3]!==n.shape[3];if(a.shape[1]!==n.shape[1]||a.shape[2]!==n.shape[2]){let o=[...n.shape];o[1]=1;let l=vt(o);n=Qe([n,l],1);let c=[...n.shape];c[2]=1;let u=vt(c);n=Qe([n,u],2)}return a=s?Qe([a,r],3):a,n=Z(a,n),n=Ye(n),n}var Eu=class extends an{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return D(()=>{let a=ce(t.toBatchTensor(150,!0),"float32"),s=La(a,[122.782,117.001,104.298]).div(de(256)),i=vf(s,n.conv32_down);i=Ft(i,3,2,"valid"),i=za(i,n.conv32_1),i=za(i,n.conv32_2),i=za(i,n.conv32_3),i=Wp(i,n.conv64_down),i=za(i,n.conv64_1),i=za(i,n.conv64_2),i=za(i,n.conv64_3),i=Wp(i,n.conv128_down),i=za(i,n.conv128_1),i=za(i,n.conv128_2),i=Wp(i,n.conv256_down),i=za(i,n.conv256_1),i=za(i,n.conv256_2),i=Wp(i,n.conv256_down_out);let o=i.mean([1,2]);return ze(o,n.fc)})}async forward(t){return this.forwardInput(await gt(t))}async computeFaceDescriptor(t){var s;if((s=t==null?void 0:t.shape)==null?void 0:s.some(i=>i<=0))return new Float32Array(128);let n=await gt(t),a=D(()=>dt(this.forwardInput(n))),r=await Promise.all(a.map(i=>i.data()));return a.forEach(i=>i.dispose()),n.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(t){return pC(t)}extractParams(t){return cC(t)}};function Cre(e){let t=new Eu;return t.extractWeights(e),t}function wf(e,t){return{...e,...{descriptor:t}}}function _re(e){return typeof e.age=="number"}function kf(e,t){return{...e,...{age:t}}}function Ere(e){return(e.gender===Ar.MALE||e.gender===Ar.FEMALE)&&bu(e.genderProbability)}function If(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function Are(e,t){function n(l,c){let u=Ca(e(3*3*l),[3,3,l,1]),p=tt(e(l)),d=tt(e(l)),h=tt(e(l)),m=tt(e(l));return t.push({paramPath:`${c}/filters`},{paramPath:`${c}/batch_norm_scale`},{paramPath:`${c}/batch_norm_offset`},{paramPath:`${c}/batch_norm_mean`},{paramPath:`${c}/batch_norm_variance`}),{filters:u,batch_norm_scale:p,batch_norm_offset:d,batch_norm_mean:h,batch_norm_variance:m}}function a(l,c,u,p,d){let h=Ca(e(l*c*u*u),[u,u,l,c]),m=tt(e(c));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/${d?"batch_norm_offset":"bias"}`}),{filters:h,bias:m}}function r(l,c,u,p){let{filters:d,bias:h}=a(l,c,u,p,!0);return{filters:d,batch_norm_offset:h}}function s(l,c,u){let p=n(l,`${u}/depthwise_conv`),d=r(l,c,1,`${u}/pointwise_conv`);return{depthwise_conv:p,pointwise_conv:d}}function i(){let l=r(3,32,3,"mobilenetv1/conv_0"),c=s(32,64,"mobilenetv1/conv_1"),u=s(64,128,"mobilenetv1/conv_2"),p=s(128,128,"mobilenetv1/conv_3"),d=s(128,256,"mobilenetv1/conv_4"),h=s(256,256,"mobilenetv1/conv_5"),m=s(256,512,"mobilenetv1/conv_6"),f=s(512,512,"mobilenetv1/conv_7"),g=s(512,512,"mobilenetv1/conv_8"),y=s(512,512,"mobilenetv1/conv_9"),b=s(512,512,"mobilenetv1/conv_10"),v=s(512,512,"mobilenetv1/conv_11"),x=s(512,1024,"mobilenetv1/conv_12"),N=s(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:c,conv_2:u,conv_3:p,conv_4:d,conv_5:h,conv_6:m,conv_7:f,conv_8:g,conv_9:y,conv_10:b,conv_11:v,conv_12:x,conv_13:N}}function o(){let l=r(1024,256,1,"prediction_layer/conv_0"),c=r(256,512,3,"prediction_layer/conv_1"),u=r(512,128,1,"prediction_layer/conv_2"),p=r(128,256,3,"prediction_layer/conv_3"),d=r(256,128,1,"prediction_layer/conv_4"),h=r(128,256,3,"prediction_layer/conv_5"),m=r(256,64,1,"prediction_layer/conv_6"),f=r(64,128,3,"prediction_layer/conv_7"),g=a(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),y=a(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),b=a(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),v=a(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),x=a(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),N=a(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),T=a(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),C=a(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),F=a(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),$=a(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),P=a(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),B=a(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:l,conv_1:c,conv_2:u,conv_3:p,conv_4:d,conv_5:h,conv_6:m,conv_7:f,box_predictor_0:{box_encoding_predictor:g,class_predictor:y},box_predictor_1:{box_encoding_predictor:b,class_predictor:v},box_predictor_2:{box_encoding_predictor:x,class_predictor:N},box_predictor_3:{box_encoding_predictor:T,class_predictor:C},box_predictor_4:{box_encoding_predictor:F,class_predictor:$},box_predictor_5:{box_encoding_predictor:P,class_predictor:B}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function dC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=bn(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:s}=Are(n,t),i=r(),o=s(),c={extra_dim:ih(n(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{params:{mobilenetv1:i,prediction_layer:o,output_layer:c},paramMappings:t}}function Fre(e,t){let n=Un(e,t);function a(c,u,p){let d=n(`${c}/Conv2d_${u}_pointwise/weights`,4,`${p}/filters`),h=n(`${c}/Conv2d_${u}_pointwise/convolution_bn_offset`,1,`${p}/batch_norm_offset`);return{filters:d,batch_norm_offset:h}}function r(c){let u=`mobilenetv1/conv_${c}`,p=`MobilenetV1/Conv2d_${c}_depthwise`,d=`${u}/depthwise_conv`,h=`${u}/pointwise_conv`,m=n(`${p}/depthwise_weights`,4,`${d}/filters`),f=n(`${p}/BatchNorm/gamma`,1,`${d}/batch_norm_scale`),g=n(`${p}/BatchNorm/beta`,1,`${d}/batch_norm_offset`),y=n(`${p}/BatchNorm/moving_mean`,1,`${d}/batch_norm_mean`),b=n(`${p}/BatchNorm/moving_variance`,1,`${d}/batch_norm_variance`);return{depthwise_conv:{filters:m,batch_norm_scale:f,batch_norm_offset:g,batch_norm_mean:y,batch_norm_variance:b},pointwise_conv:a("MobilenetV1",c,h)}}function s(){return{conv_0:a("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:r(1),conv_2:r(2),conv_3:r(3),conv_4:r(4),conv_5:r(5),conv_6:r(6),conv_7:r(7),conv_8:r(8),conv_9:r(9),conv_10:r(10),conv_11:r(11),conv_12:r(12),conv_13:r(13)}}function i(c,u){let p=n(`${c}/weights`,4,`${u}/filters`),d=n(`${c}/biases`,1,`${u}/bias`);return{filters:p,bias:d}}function o(c){let u=i(`Prediction/BoxPredictor_${c}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${c}/box_encoding_predictor`),p=i(`Prediction/BoxPredictor_${c}/ClassPredictor`,`prediction_layer/box_predictor_${c}/class_predictor`);return{box_encoding_predictor:u,class_predictor:p}}function l(){return{conv_0:a("Prediction",0,"prediction_layer/conv_0"),conv_1:a("Prediction",1,"prediction_layer/conv_1"),conv_2:a("Prediction",2,"prediction_layer/conv_2"),conv_3:a("Prediction",3,"prediction_layer/conv_3"),conv_4:a("Prediction",4,"prediction_layer/conv_4"),conv_5:a("Prediction",5,"prediction_layer/conv_5"),conv_6:a("Prediction",6,"prediction_layer/conv_6"),conv_7:a("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:o(0),box_predictor_1:o(1),box_predictor_2:o(2),box_predictor_3:o(3),box_predictor_4:o(4),box_predictor_5:o(5)}}return{extractMobilenetV1Params:s,extractPredictionLayerParams:l}}function hC(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=Fre(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Cr(r))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${r}`);let s={mobilenetv1:n(),prediction_layer:a(),output_layer:{extra_dim:r}};return yn(e,t),{params:s,paramMappings:t}}function xa(e,t,n){return D(()=>{let a=At(e,t.filters,n,"same");return a=Z(a,t.batch_norm_offset),qt(a,0,6)})}var $re=.0010000000474974513;function Dre(e,t,n){return D(()=>{let a=Yr(e,t.filters,n,"same");return a=gr(a,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,$re),qt(a,0,6)})}function Rre(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function mC(e,t){return D(()=>{let n,a=xa(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((s,i)=>{let o=i+1,l=Rre(o);a=Dre(a,s.depthwise_conv,l),a=xa(a,s.pointwise_conv,[1,1]),o===11&&(n=a)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:a,conv11:n}})}function Mre(e,t,n){let a=e.arraySync(),r=Math.min(a[t][0],a[t][2]),s=Math.min(a[t][1],a[t][3]),i=Math.max(a[t][0],a[t][2]),o=Math.max(a[t][1],a[t][3]),l=Math.min(a[n][0],a[n][2]),c=Math.min(a[n][1],a[n][3]),u=Math.max(a[n][0],a[n][2]),p=Math.max(a[n][1],a[n][3]),d=(i-r)*(o-s),h=(u-l)*(p-c);if(d<=0||h<=0)return 0;let m=Math.max(r,l),f=Math.max(s,c),g=Math.min(i,u),y=Math.min(o,p),b=Math.max(g-m,0)*Math.max(y-f,0);return b/(d+h-b)}function fC(e,t,n,a,r){let s=e.shape[0],i=Math.min(n,s),o=t.map((u,p)=>({score:u,boxIndex:p})).filter(u=>u.score>r).sort((u,p)=>p.score-u.score),l=u=>u<=a?1:0,c=[];return o.forEach(u=>{if(c.length>=i)return;let p=u.score;for(let d=c.length-1;d>=0;--d){let h=Mre(e,u.boxIndex,c[d]);if(h!==0&&(u.score*=l(h),u.score<=r))break}p===u.score&&c.push(u.boxIndex)}),c}function Pre(e){let t=dt(Ue(e,[1,0])),n=[fe(t[2],t[0]),fe(t[3],t[1])],a=[Z(t[0],ve(n[0],de(2))),Z(t[1],ve(n[1],de(2)))];return{sizes:n,centers:a}}function Ore(e,t){let{sizes:n,centers:a}=Pre(e),r=dt(Ue(t,[1,0])),s=ve(L(pn(ve(r[2],de(5))),n[0]),de(2)),i=Z(L(ve(r[0],de(10)),n[0]),a[0]),o=ve(L(pn(ve(r[3],de(5))),n[1]),de(2)),l=Z(L(ve(r[1],de(10)),n[1]),a[1]);return Ue($t([fe(i,s),fe(l,o),Z(i,s),Z(l,o)]),[1,0])}function gC(e,t,n){return D(()=>{let a=e.shape[0],r=Ore(H(qa(n.extra_dim,[a,1,1]),[-1,4]),H(e,[-1,4]));r=H(r,[a,r.shape[0]/a,4]);let s=ca(We(t,[0,0,1],[-1,-1,-1])),i=We(s,[0,0,0],[-1,-1,1]);i=H(i,[a,i.shape[1]]);let o=dt(r),l=dt(i);return{boxes:o,scores:l}})}function so(e,t){return D(()=>{let n=e.shape[0],a=H(ao(e,t.box_encoding_predictor),[n,-1,1,4]),r=H(ao(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:a,classPrediction:r}})}function yC(e,t,n){return D(()=>{let a=xa(e,n.conv_0,[1,1]),r=xa(a,n.conv_1,[2,2]),s=xa(r,n.conv_2,[1,1]),i=xa(s,n.conv_3,[2,2]),o=xa(i,n.conv_4,[1,1]),l=xa(o,n.conv_5,[2,2]),c=xa(l,n.conv_6,[1,1]),u=xa(c,n.conv_7,[2,2]),p=so(t,n.box_predictor_0),d=so(e,n.box_predictor_1),h=so(r,n.box_predictor_2),m=so(i,n.box_predictor_3),f=so(l,n.box_predictor_4),g=so(u,n.box_predictor_5),y=Qe([p.boxPredictionEncoding,d.boxPredictionEncoding,h.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),b=Qe([p.classPrediction,d.classPrediction,h.classPrediction,m.classPrediction,f.classPrediction,g.classPrediction],1);return{boxPredictions:y,classPredictions:b}})}var va=class{constructor({minConfidence:t,maxResults:n}={}){this._name="SsdMobilenetv1Options";if(this._minConfidence=t||.5,this._maxResults=n||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}};var io=class extends an{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return D(()=>{let a=ce(t.toBatchTensor(512,!1),"float32"),r=fe(L(a,de(.007843137718737125)),de(1)),s=mC(r,n.mobilenetv1),{boxPredictions:i,classPredictions:o}=yC(s.out,s.conv11,n.prediction_layer);return gC(i,o,n.output_layer)})}async forward(t){return this.forwardInput(await gt(t))}async locateFaces(t,n={}){let{maxResults:a,minConfidence:r}=new va(n),s=await gt(t),{boxes:i,scores:o}=this.forwardInput(s),l=i[0],c=o[0];for(let v=1;v<i.length;v++)i[v].dispose(),o[v].dispose();let u=Array.from(await c.data()),d=fC(l,u,a,.5,r),h=s.getReshapedInputDimensions(0),m=s.inputSize,f=m/h.width,g=m/h.height,y=l.arraySync(),b=d.map(v=>{let[x,N]=[Math.max(0,y[v][0]),Math.min(1,y[v][2])].map(F=>F*g),[T,C]=[Math.max(0,y[v][1]),Math.min(1,y[v][3])].map(F=>F*f);return new bt(u[v],new vu(T,x,C-T,N-x),{height:s.getInputHeight(0),width:s.getInputWidth(0)})});return l.dispose(),c.dispose(),b}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return hC(t)}extractParams(t){return dC(t)}};function bC(e){let t=new io;return t.extractWeights(e),t}function Lre(e){return bC(e)}var xC=class extends io{};var vC=.4,wC=[new De(.738768,.874946),new De(2.42204,2.65704),new De(4.30971,7.04493),new De(10.246,4.59428),new De(12.6868,11.8741)],kC=[new De(1.603231,2.094468),new De(6.041143,7.080126),new De(2.882459,3.518061),new De(4.266906,5.178857),new De(9.041765,10.66308)],IC=[117.001,114.697,97.404],NC="tiny_yolov2_model",TC="tiny_yolov2_separable_conv_model";var Nf=e=>typeof e=="number";function Dw(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!Nf(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>Nf(t.x)&&Nf(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(Nf)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Au(e){return D(()=>{let t=L(e,de(.10000000149011612));return Z(Ye(fe(e,t)),t)})}function Fr(e,t){return D(()=>{let n=Zn(e,[[0,0],[1,1],[1,1],[0,0]]);return n=At(n,t.conv.filters,[1,1],"valid"),n=fe(n,t.bn.sub),n=L(n,t.bn.truediv),n=Z(n,t.conv.bias),Au(n)})}function $r(e,t){return D(()=>{let n=Zn(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Fi(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=Z(n,t.bias),Au(n)})}function zre(e,t){let n=Nu(e,t);function a(i,o){let l=tt(e(i)),c=tt(e(i));return t.push({paramPath:`${o}/sub`},{paramPath:`${o}/truediv`}),{sub:l,truediv:c}}function r(i,o,l){let c=n(i,o,3,`${l}/conv`),u=a(o,`${l}/bn`);return{conv:c,bn:u}}let s=Tu(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}}function SC(e,t,n,a){let{extractWeights:r,getRemainingWeights:s}=bn(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=zre(r,i),u;if(t.withSeparableConvs){let[p,d,h,m,f,g,y,b,v]=a,x=t.isFirstLayerConv2d?o(p,d,3,"conv0"):c(p,d,"conv0"),N=c(d,h,"conv1"),T=c(h,m,"conv2"),C=c(m,f,"conv3"),F=c(f,g,"conv4"),$=c(g,y,"conv5"),P=b?c(y,b,"conv6"):void 0,B=v?c(b,v,"conv7"):void 0,W=o(v||b||y,5*n,1,"conv8");u={conv0:x,conv1:N,conv2:T,conv3:C,conv4:F,conv5:$,conv6:P,conv7:B,conv8:W}}else{let[p,d,h,m,f,g,y,b,v]=a,x=l(p,d,"conv0"),N=l(d,h,"conv1"),T=l(h,m,"conv2"),C=l(m,f,"conv3"),F=l(f,g,"conv4"),$=l(g,y,"conv5"),P=l(y,b,"conv6"),B=l(b,v,"conv7"),W=o(v,5*n,1,"conv8");u={conv0:x,conv1:N,conv2:T,conv3:C,conv4:F,conv5:$,conv6:P,conv7:B,conv8:W}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:u,paramMappings:i}}function Bre(e,t){let n=Un(e,t);function a(o){let l=n(`${o}/sub`,1),c=n(`${o}/truediv`,1);return{sub:l,truediv:c}}function r(o){let l=n(`${o}/filters`,4),c=n(`${o}/bias`,1);return{filters:l,bias:c}}function s(o){let l=r(`${o}/conv`),c=a(`${o}/bn`);return{conv:l,bn:c}}let i=Su(n);return{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function CC(e,t){let n=[],{extractConvParams:a,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}=Bre(e,n),i;if(t.withSeparableConvs){let o=t.filterSizes&&t.filterSizes.length||9;i={conv0:t.isFirstLayerConv2d?a("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:o>7?s("conv6"):void 0,conv7:o>8?s("conv7"):void 0,conv8:a("conv8")}}else i={conv0:r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:r("conv6"),conv7:r("conv7"),conv8:a("conv8")};return yn(e,n),{params:i,paramMappings:n}}var ur=class{constructor({inputSize:t,scoreThreshold:n}={}){this._name="TinyYolov2Options";if(this._inputSize=t||416,this._scoreThreshold=n||.5,typeof this._inputSize!="number"||this._inputSize%32!=0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}};var Rw=class extends an{constructor(t){super("TinyYolov2");Dw(t),this._config=t}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(t,n){let a=Fr(t,n.conv0);return a=Ft(a,[2,2],[2,2],"same"),a=Fr(a,n.conv1),a=Ft(a,[2,2],[2,2],"same"),a=Fr(a,n.conv2),a=Ft(a,[2,2],[2,2],"same"),a=Fr(a,n.conv3),a=Ft(a,[2,2],[2,2],"same"),a=Fr(a,n.conv4),a=Ft(a,[2,2],[2,2],"same"),a=Fr(a,n.conv5),a=Ft(a,[2,2],[1,1],"same"),a=Fr(a,n.conv6),a=Fr(a,n.conv7),ao(a,n.conv8,"valid",!1)}runMobilenet(t,n){let a=this.config.isFirstLayerConv2d?Au(ao(t,n.conv0,"valid",!1)):$r(t,n.conv0);return a=Ft(a,[2,2],[2,2],"same"),a=$r(a,n.conv1),a=Ft(a,[2,2],[2,2],"same"),a=$r(a,n.conv2),a=Ft(a,[2,2],[2,2],"same"),a=$r(a,n.conv3),a=Ft(a,[2,2],[2,2],"same"),a=$r(a,n.conv4),a=Ft(a,[2,2],[2,2],"same"),a=$r(a,n.conv5),a=Ft(a,[2,2],[1,1],"same"),a=n.conv6?$r(a,n.conv6):a,a=n.conv7?$r(a,n.conv7):a,ao(a,n.conv8,"valid",!1)}forwardInput(t,n){let{params:a}=this;if(!a)throw new Error("TinyYolov2 - load model before inference");return D(()=>{let r=ce(t.toBatchTensor(n,!1),"float32");return r=this.config.meanRgb?La(r,this.config.meanRgb):r,r=r.div(de(256)),this.config.withSeparableConvs?this.runMobilenet(r,a):this.runTinyYolov2(r,a)})}async forward(t,n){return this.forwardInput(await gt(t),n)}async detect(t,n={}){let{inputSize:a,scoreThreshold:r}=new ur(n),s=await gt(t),i=await this.forwardInput(s,a),o=D(()=>dt(i)[0].expandDims()),l={width:s.getInputWidth(0),height:s.getInputHeight(0)},c=await this.extractBoxes(o,s.getReshapedInputDimensions(0),r);i.dispose(),o.dispose();let u=c.map(g=>g.box),p=c.map(g=>g.score),d=c.map(g=>g.classScore),h=c.map(g=>this.config.classes[g.label]);return lw(u.map(g=>g.rescale(a)),p,this.config.iouThreshold,!0).map(g=>new ds(p[g],d[g],h[g],u[g],l))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return CC(t,this.config)}extractParams(t){let n=this.config.filterSizes||Rw.DEFAULT_FILTER_SIZES,a=n?n.length:void 0;if(a!==7&&a!==8&&a!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${a} filterSizes in config`);return SC(t,this.config,this.boxEncodingSize,n)}async extractBoxes(t,n,a){let{width:r,height:s}=n,i=Math.max(r,s),o=i/r,l=i/s,c=t.shape[1],u=this.config.anchors.length,[p,d,h]=D(()=>{let y=t.reshape([c,c,u,this.boxEncodingSize]),b=y.slice([0,0,0,0],[c,c,u,4]),v=y.slice([0,0,0,4],[c,c,u,1]),x=this.withClassScores?Ta(y.slice([0,0,0,5],[c,c,u,this.config.classes.length]),3):de(0);return[b,v,x]}),m=[],f=await d.array(),g=await p.array();for(let y=0;y<c;y++)for(let b=0;b<c;b++)for(let v=0;v<u;v++){let x=Ap(f[y][b][v][0]);if(!a||x>a){let N=(b+Ap(g[y][b][v][0]))/c*o,T=(y+Ap(g[y][b][v][1]))/c*l,C=Math.exp(g[y][b][v][2])*this.config.anchors[v].x/c*o,F=Math.exp(g[y][b][v][3])*this.config.anchors[v].y/c*l,$=N-C/2,P=T-F/2,B={row:y,col:b,anchor:v},{classScore:W,label:G}=this.withClassScores?await this.extractPredictedClass(h,B):{classScore:1,label:0};m.push({box:new xu($,P,$+C,P+F),score:x,classScore:x*W,label:G,...B})}}return p.dispose(),d.dispose(),h.dispose(),m}async extractPredictedClass(t,n){let{row:a,col:r,anchor:s}=n,i=await t.array();return Array(this.config.classes.length).fill(0).map((o,l)=>i[a][r][s][l]).map((o,l)=>({classScore:o,label:l})).reduce((o,l)=>o.classScore>l.classScore?o:l)}},Fu=Rw;Fu.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var $u=class extends Fu{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:vC,classes:["face"],...t?{anchors:kC,meanRgb:IC}:{anchors:wC,withClassScores:!0}};super(n)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new bt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?TC:NC}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function Wre(e,t=!0){let n=new $u(t);return n.extractWeights(e),n}var Tf=class extends ur{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var wa=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function oo(e,t,n,a,r=({alignedRect:s})=>s){let s=e.map(l=>ro(l)?r(l):l.detection),i=a||(t instanceof Ae?await Iu(t,s):await ku(t,s)),o=await n(i);return i.forEach(l=>l instanceof Ae&&l.dispose()),o}async function Du(e,t,n,a,r){return oo([e],t,async s=>n(s[0]),a,r)}var _C=.4,EC=[new De(1.603231,2.094468),new De(6.041143,7.080126),new De(2.882459,3.518061),new De(4.266906,5.178857),new De(9.041765,10.66308)],AC=[117.001,114.697,97.404];var Ru=class extends Fu{constructor(){let t={withSeparableConvs:!0,iouThreshold:_C,classes:["face"],anchors:EC,meanRgb:AC,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(t)}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new bt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var nt={ssdMobilenetv1:new io,tinyFaceDetector:new Ru,tinyYolov2:new $u,faceLandmark68Net:new _u,faceLandmark68TinyNet:new xf,faceRecognitionNet:new Eu,faceExpressionNet:new gf,ageGenderNet:new bf},FC=(e,t)=>nt.ssdMobilenetv1.locateFaces(e,t),Vre=(e,t)=>nt.tinyFaceDetector.locateFaces(e,t),Ure=(e,t)=>nt.tinyYolov2.locateFaces(e,t),$C=e=>nt.faceLandmark68Net.detectLandmarks(e),Gre=e=>nt.faceLandmark68TinyNet.detectLandmarks(e),Hre=e=>nt.faceRecognitionNet.computeFaceDescriptor(e),jre=e=>nt.faceExpressionNet.predictExpressions(e),qre=e=>nt.ageGenderNet.predictAgeAndGender(e),DC=e=>nt.ssdMobilenetv1.load(e),Kre=e=>nt.tinyFaceDetector.load(e),Xre=e=>nt.tinyYolov2.load(e),Yre=e=>nt.faceLandmark68Net.load(e),Zre=e=>nt.faceLandmark68TinyNet.load(e),Jre=e=>nt.faceRecognitionNet.load(e),Qre=e=>nt.faceExpressionNet.load(e),ese=e=>nt.ageGenderNet.load(e),tse=DC,nse=FC,ase=$C;var Mw=class extends wa{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},Ou=class extends Mw{async run(){let t=await this.parentTask,n=await oo(t,this.input,async a=>Promise.all(a.map(r=>nt.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return t.map((a,r)=>yf(a,n[r]))}withAgeAndGender(){return new Mu(this,this.input)}},Lu=class extends Mw{async run(){let t=await this.parentTask;if(!t)return;let n=await Du(t,this.input,a=>nt.faceExpressionNet.predictExpressions(a),this.extractedFaces);return yf(t,n)}withAgeAndGender(){return new Pu(this,this.input)}},co=class extends Ou{withAgeAndGender(){return new lo(this,this.input)}withFaceDescriptors(){return new fs(this,this.input)}},po=class extends Lu{withAgeAndGender(){return new uo(this,this.input)}withFaceDescriptor(){return new gs(this,this.input)}};var Pw=class extends wa{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},Mu=class extends Pw{async run(){let t=await this.parentTask,n=await oo(t,this.input,async a=>Promise.all(a.map(r=>nt.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return t.map((a,r)=>{let{age:s,gender:i,genderProbability:o}=n[r];return kf(If(a,i,o),s)})}withFaceExpressions(){return new Ou(this,this.input)}},Pu=class extends Pw{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:a,genderProbability:r}=await Du(t,this.input,s=>nt.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return kf(If(t,a,r),n)}withFaceExpressions(){return new Lu(this,this.input)}},lo=class extends Mu{withFaceExpressions(){return new co(this,this.input)}withFaceDescriptors(){return new fs(this,this.input)}},uo=class extends Pu{withFaceExpressions(){return new po(this,this.input)}withFaceDescriptor(){return new gs(this,this.input)}};var Sf=class extends wa{constructor(t,n){super();this.parentTask=t;this.input=n}},fs=class extends Sf{async run(){let t=await this.parentTask;return(await oo(t,this.input,a=>Promise.all(a.map(r=>nt.faceRecognitionNet.computeFaceDescriptor(r))),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}))).map((a,r)=>wf(t[r],a))}withFaceExpressions(){return new co(this,this.input)}withAgeAndGender(){return new lo(this,this.input)}},gs=class extends Sf{async run(){let t=await this.parentTask;if(!t)return;let n=await Du(t,this.input,a=>nt.faceRecognitionNet.computeFaceDescriptor(a),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}));return wf(t,n)}withFaceExpressions(){return new po(this,this.input)}withAgeAndGender(){return new uo(this,this.input)}};var Cf=class extends wa{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.useTinyLandmarkNet=a}get landmarkNet(){return this.useTinyLandmarkNet?nt.faceLandmark68TinyNet:nt.faceLandmark68Net}},_f=class extends Cf{async run(){let t=await this.parentTask,n=t.map(s=>s.detection),a=this.input instanceof Ae?await Iu(this.input,n):await ku(this.input,n),r=await Promise.all(a.map(s=>this.landmarkNet.detectLandmarks(s)));return a.forEach(s=>s instanceof Ae&&s.dispose()),t.map((s,i)=>Cu(s,r[i]))}withFaceExpressions(){return new co(this,this.input)}withAgeAndGender(){return new lo(this,this.input)}withFaceDescriptors(){return new fs(this,this.input)}},Ef=class extends Cf{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,a=this.input instanceof Ae?await Iu(this.input,[n]):await ku(this.input,[n]),r=await this.landmarkNet.detectLandmarks(a[0]);return a.forEach(s=>s instanceof Ae&&s.dispose()),Cu(t,r)}withFaceExpressions(){return new po(this,this.input)}withAgeAndGender(){return new uo(this,this.input)}withFaceDescriptor(){return new gs(this,this.input)}};var Af=class extends wa{constructor(t,n=new va){super();this.input=t;this.options=n}},Vp=class extends Af{async run(){let{input:t,options:n}=this,a=n instanceof Tf?r=>nt.tinyFaceDetector.locateFaces(r,n):n instanceof va?r=>nt.ssdMobilenetv1.locateFaces(r,n):n instanceof ur?r=>nt.tinyYolov2.locateFaces(r,n):null;if(!a)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return a(t)}runAndExtendWithFaceDetections(){return new Promise(async t=>{let n=await this.run();t(n.map(a=>Ji({},a)))})}withFaceLandmarks(t=!1){return new _f(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new Ou(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Mu(this.runAndExtendWithFaceDetections(),this.input)}},Ff=class extends Af{async run(){let t=await new Vp(this.input,this.options),n=t[0];return t.forEach(a=>{a.score>n.score&&(n=a)}),n}runAndExtendWithFaceDetection(){return new Promise(async t=>{let n=await this.run();t(n?Ji({},n):void 0)})}withFaceLandmarks(t=!1){return new Ef(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new Lu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Pu(this.runAndExtendWithFaceDetection(),this.input)}};function rse(e,t=new va){return new Ff(e,t)}function $f(e,t=new va){return new Vp(e,t)}async function RC(e,t){return $f(e,new va(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function sse(e,t={}){return $f(e,new ur(t)).withFaceLandmarks().withFaceDescriptors()}var ise=RC;function Ow(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");let n=Array.from(e),a=Array.from(t);return Math.sqrt(n.map((r,s)=>r-a[s]).reduce((r,s)=>r+s**2,0))}var Df=class{constructor(t,n=.6){this._distanceThreshold=n;let a=Array.isArray(t)?t:[t];if(!a.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1,s=()=>`person ${r++}`;this._labeledDescriptors=a.map(i=>{if(i instanceof _r)return i;if(i instanceof Float32Array)return new _r(s(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new _r(s(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(t,n){return n.map(a=>Ow(a,t)).reduce((a,r)=>a+r,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:a})=>new Fp(a,this.computeMeanDistance(t,n))).reduce((n,a)=>n.distance<a.distance?n:a)}findBestMatch(t){let n=this.matchDescriptor(t);return n.distance<this.distanceThreshold?n:new Fp("unknown",n.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(a=>_r.fromJSON(a));return new Df(n,t.distanceThreshold)}};function ose(e){let t=new Ru;return t.extractWeights(e),t}function MC(e,t){let{width:n,height:a}=new gn(t.width,t.height);if(n<=0||a<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:a})}`);if(Array.isArray(e))return e.map(r=>MC(r,{width:n,height:a}));if(ro(e)){let r=e.detection.forSize(n,a),s=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return Cu(Ji(e,r),s)}return or(e)?Ji(e,e.detection.forSize(n,a)):e instanceof ta||e instanceof bt?e.forSize(n,a):e}var lse=typeof process!="undefined",use=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",cse={faceapi:Q2,node:lse,browser:use};export{bf as AgeGenderNet,xu as BoundingBox,ut as Box,wa as ComposableTask,fs as ComputeAllFaceDescriptorsTask,Sf as ComputeFaceDescriptorsTaskBase,gs as ComputeSingleFaceDescriptorTask,_f as DetectAllFaceLandmarksTask,Vp as DetectAllFacesTask,Cf as DetectFaceLandmarksTaskBase,Af as DetectFacesTaskBase,Ef as DetectSingleFaceLandmarksTask,Ff as DetectSingleFaceTask,gn as Dimensions,Iw as FACE_EXPRESSION_LABELS,bt as FaceDetection,xC as FaceDetectionNet,gf as FaceExpressionNet,ms as FaceExpressions,_u as FaceLandmark68Net,xf as FaceLandmark68TinyNet,oC as FaceLandmarkNet,ta as FaceLandmarks,H2 as FaceLandmarks5,wu as FaceLandmarks68,Fp as FaceMatch,Df as FaceMatcher,Eu as FaceRecognitionNet,Ar as Gender,$p as LabeledBox,_r as LabeledFaceDescriptors,Er as NetInput,an as NeuralNetwork,ds as ObjectDetection,De as Point,j2 as PredictedBox,vu as Rect,io as SsdMobilenetv1,va as SsdMobilenetv1Options,Ru as TinyFaceDetector,Tf as TinyFaceDetectorOptions,$u as TinyYolov2,ur as TinyYolov2Options,ise as allFaces,RC as allFacesSsdMobilenetv1,sse as allFacesTinyYolov2,yw as awaitMediaLoaded,bw as bufferToImage,Hre as computeFaceDescriptor,to as createCanvas,Mp as createCanvasFromMedia,Lre as createFaceDetectionNet,Cre as createFaceRecognitionNet,bC as createSsdMobilenetv1,ose as createTinyFaceDetector,Wre as createTinyYolov2,$f as detectAllFaces,$C as detectFaceLandmarks,Gre as detectFaceLandmarksTiny,ase as detectLandmarks,rse as detectSingleFace,Cw as draw,st as env,Ow as euclideanDistance,kf as extendWithAge,wf as extendWithFaceDescriptor,Ji as extendWithFaceDetection,yf as extendWithFaceExpressions,Cu as extendWithFaceLandmarks,If as extendWithGender,Iu as extractFaceTensors,ku as extractFaces,yre as fetchImage,ww as fetchJson,bre as fetchNetWeights,no as fetchOrThrow,Cn as getContext2dOrThrow,eo as getMediaDimensions,xw as imageTensorToCanvas,vw as imageToSquare,lre as inverseSigmoid,iw as iou,of as isMediaElement,Rp as isMediaLoaded,_re as isWithAge,or as isWithFaceDetection,Nw as isWithFaceExpressions,ro as isWithFaceLandmarks,Ere as isWithGender,ese as loadAgeGenderModel,tse as loadFaceDetectionModel,Qre as loadFaceExpressionModel,Yre as loadFaceLandmarkModel,Zre as loadFaceLandmarkTinyModel,Jre as loadFaceRecognitionModel,DC as loadSsdMobilenetv1Model,Kre as loadTinyFaceDetectorModel,Xre as loadTinyYolov2Model,kw as loadWeightMap,nse as locateFaces,xre as matchDimensions,ow as minBbox,nt as nets,lw as nonMaxSuppression,La as normalize,uw as padToSquare,qre as predictAgeAndGender,jre as recognizeFaceExpressions,MC as resizeResults,Qi as resolveInput,ore as shuffleArray,Ap as sigmoid,FC as ssdMobilenetv1,Ug as tf,Vre as tinyFaceDetector,Ure as tinyYolov2,gt as toNetInput,nw as utils,Dw as validateConfig,cse as version};
|
|
/**
|
|
* @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 See the LICENSE file. */
|
|
//# sourceMappingURL=face-api.esm.js.map
|