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 faceapi=(()=>{var PE=Object.create,Ed=Object.defineProperty,OE=Object.getPrototypeOf,LE=Object.prototype.hasOwnProperty,zE=Object.getOwnPropertyNames,BE=Object.getOwnPropertyDescriptor;var Xw=e=>Ed(e,"__esModule",{value:!0});var WE=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),cc=(e,t)=>{Xw(e);for(var n in t)Ed(e,n,{get:t[n],enumerable:!0})},VE=(e,t,n)=>{if(Xw(e),t&&typeof t=="object"||typeof t=="function")for(let a of zE(t))!LE.call(e,a)&&a!=="default"&&Ed(e,a,{get:()=>t[a],enumerable:!(n=BE(t,a))||n.enumerable});return e},UE=e=>e&&e.__esModule?e:VE(Ed(e!=null?PE(OE(e)):{},"default",{value:e,enumerable:!0}),e);var hC=WE((hse,dC)=>{cc(hse,{isNodejs:()=>mse});function mse(){return typeof global=="object"&&!0&&typeof dC!="undefined"&&typeof process!="undefined"&&!!process.version}});var Rse={};cc(Rse,{AgeGenderNet:()=>jp,BoundingBox:()=>ao,Box:()=>lt,ComposableTask:()=>ia,ComputeAllFaceDescriptorsTask:()=>Or,ComputeFaceDescriptorsTaskBase:()=>ed,ComputeSingleFaceDescriptorTask:()=>Lr,DetectAllFaceLandmarksTask:()=>nd,DetectAllFacesTask:()=>Gu,DetectFaceLandmarksTaskBase:()=>td,DetectFacesTaskBase:()=>rd,DetectSingleFaceLandmarksTask:()=>ad,DetectSingleFaceTask:()=>sd,Dimensions:()=>un,FACE_EXPRESSION_LABELS:()=>Wf,FaceDetection:()=>bt,FaceDetectionNet:()=>Aw,FaceExpressionNet:()=>Gp,FaceExpressions:()=>Mr,FaceLandmark68Net:()=>po,FaceLandmark68TinyNet:()=>Kp,FaceLandmarkNet:()=>Sw,FaceLandmarks:()=>Gn,FaceLandmarks5:()=>dw,FaceLandmarks68:()=>so,FaceMatch:()=>Au,FaceMatcher:()=>od,FaceRecognitionNet:()=>ho,Gender:()=>dr,LabeledBox:()=>Fu,LabeledFaceDescriptors:()=>ur,NetInput:()=>pr,NeuralNetwork:()=>tn,ObjectDetection:()=>Dr,Point:()=>De,PredictedBox:()=>hw,Rect:()=>ro,SsdMobilenetv1:()=>Ns,SsdMobilenetv1Options:()=>sa,TinyFaceDetector:()=>yo,TinyFaceDetectorOptions:()=>Qp,TinyYolov2:()=>fo,TinyYolov2Options:()=>Ua,allFaces:()=>x_,allFacesSsdMobilenetv1:()=>Ow,allFacesTinyYolov2:()=>b_,awaitMediaLoaded:()=>Cf,bufferToImage:()=>_f,computeFaceDescriptor:()=>r_,createCanvas:()=>io,createCanvasFromMedia:()=>Du,createFaceDetectionNet:()=>VC,createFaceRecognitionNet:()=>DC,createSsdMobilenetv1:()=>Ew,createTinyFaceDetector:()=>v_,createTinyYolov2:()=>JC,detectAllFaces:()=>id,detectFaceLandmarks:()=>Dw,detectFaceLandmarksTiny:()=>a_,detectLandmarks:()=>g_,detectSingleFace:()=>y_,draw:()=>Uf,env:()=>st,euclideanDistance:()=>qf,extendWithAge:()=>Jp,extendWithFaceDescriptor:()=>Yp,extendWithFaceDetection:()=>bs,extendWithFaceExpressions:()=>Hp,extendWithFaceLandmarks:()=>co,extendWithGender:()=>Zp,extractFaceTensors:()=>lo,extractFaces:()=>oo,fetchImage:()=>mC,fetchJson:()=>Ff,fetchNetWeights:()=>fC,fetchOrThrow:()=>ks,getContext2dOrThrow:()=>bn,getMediaDimensions:()=>ws,imageTensorToCanvas:()=>Ef,imageToSquare:()=>Af,inverseSigmoid:()=>pC,iou:()=>wf,isMediaElement:()=>zp,isMediaLoaded:()=>$u,isWithAge:()=>MC,isWithFaceDetection:()=>Wa,isWithFaceExpressions:()=>Vf,isWithFaceLandmarks:()=>Is,isWithGender:()=>RC,loadAgeGenderModel:()=>h_,loadFaceDetectionModel:()=>m_,loadFaceExpressionModel:()=>d_,loadFaceLandmarkModel:()=>u_,loadFaceLandmarkTinyModel:()=>c_,loadFaceRecognitionModel:()=>p_,loadSsdMobilenetv1Model:()=>Mw,loadTinyFaceDetectorModel:()=>o_,loadTinyYolov2Model:()=>l_,loadWeightMap:()=>Df,locateFaces:()=>f_,matchDimensions:()=>gC,minBbox:()=>kf,nets:()=>et,nonMaxSuppression:()=>If,normalize:()=>ka,padToSquare:()=>Nf,predictAgeAndGender:()=>i_,recognizeFaceExpressions:()=>s_,resizeResults:()=>Lw,resolveInput:()=>xs,shuffleArray:()=>cC,sigmoid:()=>Eu,ssdMobilenetv1:()=>$w,tf:()=>Ad,tinyFaceDetector:()=>t_,tinyYolov2:()=>n_,toNetInput:()=>yt,utils:()=>bf,validateConfig:()=>jf,version:()=>w_});var Ad={};cc(Ad,{Abs:()=>Lo,Acos:()=>zo,Acosh:()=>Bo,AdadeltaOptimizer:()=>nm,AdagradOptimizer:()=>am,AdamOptimizer:()=>rm,AdamaxOptimizer:()=>sm,Add:()=>Hr,AddN:()=>Ms,All:()=>Od,Any:()=>Ld,ArgMax:()=>Rs,ArgMin:()=>fc,Asin:()=>Wo,Asinh:()=>Vo,Atan:()=>Uo,Atan2:()=>Ho,Atanh:()=>Go,AvgPool:()=>Ps,AvgPool3D:()=>gc,AvgPool3DGrad:()=>Bd,AvgPoolGrad:()=>zd,BackendWasm:()=>lC,BatchMatMul:()=>Os,BatchToSpaceND:()=>yc,Bincount:()=>Wd,BroadcastTo:()=>h0,Callback:()=>lN,CallbackList:()=>iI,Cast:()=>Ls,Ceil:()=>jo,ClipByValue:()=>jr,Complex:()=>Vd,ComplexAbs:()=>bc,Concat:()=>qo,Conv2D:()=>zs,Conv2DBackpropFilter:()=>Ud,Conv2DBackpropInput:()=>Bs,Conv3D:()=>xc,Conv3DBackpropFilterV2:()=>Gd,Conv3DBackpropInputV2:()=>Hd,Cos:()=>Ws,Cosh:()=>Ko,CropAndResize:()=>Xo,Cumsum:()=>Vs,CustomCallback:()=>lI,DataStorage:()=>Dd,DenseBincount:()=>jd,DepthToSpace:()=>Yo,DepthwiseConv2dNative:()=>Us,DepthwiseConv2dNativeBackpropFilter:()=>qd,DepthwiseConv2dNativeBackpropInput:()=>Kd,Diag:()=>Xd,Dilation2D:()=>vc,Dilation2DBackpropFilter:()=>Jd,Dilation2DBackpropInput:()=>Yd,ENV:()=>iy,EarlyStopping:()=>cN,Elu:()=>Jo,EluGrad:()=>Zd,Environment:()=>c0,Equal:()=>Qo,Erf:()=>Zo,Exp:()=>Hs,ExpandDims:()=>el,Expm1:()=>tl,FFT:()=>Qd,Fill:()=>wc,FlipLeftRight:()=>nl,Floor:()=>js,FloorDiv:()=>qs,FromPixels:()=>hh,FusedBatchNorm:()=>Ks,FusedConv2D:()=>Ti,FusedDepthwiseConv2D:()=>Si,GatherNd:()=>rl,GatherV2:()=>al,GraphModel:()=>zN,Greater:()=>sl,GreaterEqual:()=>Xs,History:()=>oI,IFFT:()=>eh,Identity:()=>il,Imag:()=>th,InputSpec:()=>Jt,IsFinite:()=>ol,IsInf:()=>ll,IsNan:()=>ul,KernelBackend:()=>dc,LRN:()=>Nc,LRNGrad:()=>ah,LayerVariable:()=>tI,LayersModel:()=>Cr,LeakyRelu:()=>Ys,Less:()=>cl,LessEqual:()=>pl,LinSpace:()=>nh,Log:()=>Js,Log1p:()=>dl,LogSoftmax:()=>m0,LogicalAnd:()=>hl,LogicalNot:()=>kc,LogicalOr:()=>Ic,Max:()=>Zs,MaxPool:()=>ei,MaxPool3D:()=>Tc,MaxPool3DGrad:()=>sh,MaxPoolGrad:()=>rh,MaxPoolWithArgmax:()=>ih,Maximum:()=>Qs,Mean:()=>ti,Min:()=>ni,Minimum:()=>ai,MirrorPad:()=>Sc,Mod:()=>ml,MomentumOptimizer:()=>im,Multinomial:()=>oh,Multiply:()=>ri,Neg:()=>fl,NonMaxSuppressionV3:()=>yl,NonMaxSuppressionV4:()=>bl,NonMaxSuppressionV5:()=>xl,NotEqual:()=>gl,OP_SCOPE_SUFFIX:()=>T0,OneHot:()=>si,OnesLike:()=>vl,Optimizer:()=>Nr,Pack:()=>wl,PadV2:()=>ii,Pool:()=>AA,Pow:()=>oi,Prelu:()=>li,Prod:()=>kl,RMSPropOptimizer:()=>om,RNN:()=>rr,Range:()=>Cc,Rank:()=>my,Real:()=>lh,RealDiv:()=>Gs,Reciprocal:()=>Il,Reduction:()=>mn,Relu:()=>ui,Relu6:()=>pi,Reshape:()=>Nl,ResizeBilinear:()=>ci,ResizeBilinearGrad:()=>ch,ResizeNearestNeighbor:()=>_c,ResizeNearestNeighborGrad:()=>uh,Reverse:()=>di,RotateWithOffset:()=>Ll,Round:()=>hi,Rsqrt:()=>mi,SGDOptimizer:()=>ap,ScatterNd:()=>Tl,Select:()=>Sl,Selu:()=>Cl,Sequential:()=>lu,Sigmoid:()=>gi,Sign:()=>Al,Sin:()=>fi,Sinh:()=>El,Slice:()=>_l,Softmax:()=>xi,Softplus:()=>Fl,SpaceToBatchND:()=>Ec,SparseToDense:()=>ph,SplitV:()=>$l,Sqrt:()=>yi,Square:()=>Ac,SquaredDifference:()=>vi,Step:()=>Kr,StridedSlice:()=>Dl,Sub:()=>wi,Sum:()=>bi,SymbolicTensor:()=>Ma,Tan:()=>Ml,Tanh:()=>ki,Tensor:()=>z,TensorBuffer:()=>zt,Tile:()=>qr,TopK:()=>Rl,Transpose:()=>Ii,Unique:()=>dh,Unpack:()=>Pl,UnsortedSegmentSum:()=>Fc,Variable:()=>Xr,ZerosLike:()=>Ol,_FusedMatMul:()=>Ni,abs:()=>Bt,acos:()=>Oy,acosh:()=>Ly,add:()=>Z,addN:()=>o1,addStrict:()=>H1,all:()=>Ch,any:()=>Wc,argMax:()=>Vc,argMin:()=>zy,asin:()=>By,asinh:()=>Wy,atan:()=>Vy,atan2:()=>Uy,atanh:()=>Gy,avgPool:()=>Jn,avgPool3d:()=>qy,backend:()=>i1,backend_util:()=>E,basicLSTMCell:()=>sD,batchNorm:()=>xr,batchNorm2d:()=>p1,batchNorm3d:()=>d1,batchNorm4d:()=>h1,batchToSpaceND:()=>Gc,bincount:()=>m1,booleanMaskAsync:()=>uP,broadcastTo:()=>Hc,browser:()=>Ai,buffer:()=>Le,callbacks:()=>mV,cast:()=>pe,ceil:()=>Ky,clipByValue:()=>Xt,clone:()=>Qr,complex:()=>Yr,concat:()=>Qe,concat1d:()=>f1,concat2d:()=>g1,concat3d:()=>y1,concat4d:()=>b1,constraints:()=>_k,conv1d:()=>Eh,conv2d:()=>Ft,conv2dTranspose:()=>Ah,conv3d:()=>Yy,conv3dTranspose:()=>CD,copyRegisteredKernels:()=>DA,cos:()=>jc,cosh:()=>Fh,cosineWindow:()=>wb,cumsum:()=>$h,customGrad:()=>Ya,data:()=>WN,denseBincount:()=>v1,deprecationWarn:()=>Rt,depthToSpace:()=>Jy,depthwiseConv2d:()=>vr,deregisterOp:()=>gV,device_util:()=>xh,diag:()=>RD,dilation2d:()=>Zy,disableDeprecationWarnings:()=>y$,dispose:()=>Fe,disposeVariables:()=>b$,div:()=>we,divNoNan:()=>Qy,divStrict:()=>j1,dot:()=>w1,dropout:()=>ak,elu:()=>Kl,enableDebugMode:()=>g$,enableProdMode:()=>f$,enclosingPowerOfTwo:()=>rk,engine:()=>ts,env:()=>te,equal:()=>wr,equalStrict:()=>z1,erf:()=>eb,exp:()=>hn,expandDims:()=>Zn,expm1:()=>tb,eye:()=>nb,fft:()=>ep,fill:()=>In,findBackend:()=>T$,findBackendFactory:()=>S$,floor:()=>Xl,floorDiv:()=>Sh,fused:()=>is,gather:()=>Di,gatherND:()=>nk,gather_util:()=>Ay,getBackend:()=>I$,getGradient:()=>cy,getKernel:()=>uy,getKernelsForBackend:()=>mh,grad:()=>cM,grads:()=>pM,greater:()=>Qn,greaterEqual:()=>kr,greaterEqualStrict:()=>B1,greaterStrict:()=>W1,ifft:()=>eu,imag:()=>Dh,image:()=>Qa,inTopKAsync:()=>RP,initializers:()=>Rk,input:()=>Kk,io:()=>qt,irfft:()=>Kh,isFinite:()=>k1,isInf:()=>I1,isNaN:()=>N1,keep:()=>Kt,kernel_impls:()=>er,layers:()=>qk,leakyRelu:()=>qc,less:()=>Kc,lessEqual:()=>as,lessEqualStrict:()=>V1,lessStrict:()=>U1,linalg:()=>gk,linspace:()=>T1,loadGraphModel:()=>gU,loadLayersModel:()=>M4,localResponseNormalization:()=>ab,log:()=>Dn,log1p:()=>Mh,logSigmoid:()=>C1,logSoftmax:()=>Ph,logSumExp:()=>ib,logicalAnd:()=>fa,logicalNot:()=>Xc,logicalOr:()=>Oh,logicalXor:()=>F1,losses:()=>YO,matMul:()=>ze,math:()=>W0,max:()=>ea,maxPool:()=>$t,maxPool3d:()=>ob,maxPoolWithArgmax:()=>$1,maximum:()=>Ca,maximumStrict:()=>q1,mean:()=>Ct,memory:()=>Nh,metrics:()=>sN,min:()=>Jl,minimum:()=>Ri,minimumStrict:()=>K1,mirrorPad:()=>lb,mod:()=>Lh,modStrict:()=>X1,model:()=>$4,models:()=>iN,moments:()=>zh,movingAverage:()=>CP,mul:()=>L,mulStrict:()=>Y1,multiRNNCell:()=>BM,multinomial:()=>D1,neg:()=>St,nextFrame:()=>lm,norm:()=>Jh,notEqual:()=>rs,notEqualStrict:()=>G1,oneHot:()=>Gl,ones:()=>Ja,onesLike:()=>Mn,op:()=>R,outerProduct:()=>HM,pad:()=>ta,pad1d:()=>KM,pad2d:()=>YM,pad3d:()=>ZM,pad4d:()=>eR,pool:()=>M1,pow:()=>Za,powStrict:()=>J1,prelu:()=>Jc,print:()=>R0,prod:()=>Bh,profile:()=>x$,rand:()=>uR,randomGamma:()=>hR,randomNormal:()=>R1,randomUniform:()=>Zl,range:()=>Wh,ready:()=>k$,real:()=>Zc,reciprocal:()=>pb,registerBackend:()=>Th,registerCallbackConstructor:()=>R4,registerGradient:()=>f0,registerKernel:()=>Dc,registerOp:()=>fV,regularizers:()=>oN,relu:()=>Ye,relu6:()=>Vh,removeBackend:()=>N$,reshape:()=>q,reverse:()=>Rn,reverse1d:()=>kR,reverse2d:()=>NR,reverse3d:()=>SR,reverse4d:()=>_R,rfft:()=>tp,round:()=>db,rsqrt:()=>Uh,scalar:()=>he,scatterND:()=>tk,scatter_util:()=>Fy,selu:()=>Gh,separableConv2d:()=>Pi,sequential:()=>D4,serialization:()=>re,setBackend:()=>w$,setPlatform:()=>C$,setWasmPath:()=>sse,setWasmPaths:()=>ise,setdiff1dAsync:()=>P1,sigmoid:()=>ma,sign:()=>hb,signal:()=>XO,sin:()=>Hh,sinh:()=>jh,slice:()=>We,slice1d:()=>qh,slice2d:()=>mb,slice3d:()=>Ql,slice4d:()=>Qc,slice_util:()=>dn,softmax:()=>_a,softplus:()=>Yl,spaceToBatchND:()=>Yc,sparseToDense:()=>vb,spectral:()=>KO,split:()=>Pn,sqrt:()=>an,square:()=>ct,squaredDifference:()=>np,squaredDifferenceStrict:()=>Z1,squeeze:()=>ss,stack:()=>Dt,step:()=>tu,stridedSlice:()=>fb,sub:()=>ge,subStrict:()=>Q1,sum:()=>Ce,sumOutType:()=>bh,tan:()=>gb,tanh:()=>ql,tensor:()=>Xn,tensor1d:()=>nt,tensor2d:()=>Ea,tensor3d:()=>kh,tensor4d:()=>Aa,tensor5d:()=>eP,tensor6d:()=>tP,tensor_util:()=>Sa,test_util:()=>n1,tidy:()=>D,tile:()=>Xa,time:()=>v$,topk:()=>yb,train:()=>Li,transpose:()=>Ue,truncatedNormal:()=>Xh,unique:()=>Yh,unregisterGradient:()=>$A,unregisterKernel:()=>FA,unsortedSegmentSum:()=>bb,unstack:()=>ht,upcastType:()=>ha,util:()=>k,valueAndGrad:()=>dM,valueAndGrads:()=>hM,variable:()=>O1,variableGrads:()=>S1,version:()=>mte,version_converter:()=>BN,version_core:()=>s1,version_layers:()=>$m,version_wasm:()=>ose,where:()=>kn,whereAsync:()=>xb,zeros:()=>xt,zerosLike:()=>Ge});var GE=Object.create,Fd=Object.defineProperty,HE=Object.getPrototypeOf,jE=Object.prototype.hasOwnProperty,qE=Object.getOwnPropertyNames,KE=Object.getOwnPropertyDescriptor,Yw=e=>Fd(e,"__esModule",{value:!0}),pn=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Oe=(e,t)=>{Yw(e);for(var n in t)Fd(e,n,{get:t[n],enumerable:!0})},XE=(e,t,n)=>{if(Yw(e),t&&typeof t=="object"||typeof t=="function")for(let a of qE(t))!jE.call(e,a)&&a!=="default"&&Fd(e,a,{get:()=>t[a],enumerable:!(n=KE(t,a))||n.enumerable});return e},Ro=e=>e&&e.__esModule?e:XE(Fd(e!=null?GE(HE(e)):{},"default",{value:e,enumerable:!0}),e),YE=pn(()=>{}),JE=pn((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)}),ZE=pn((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)}),QE=pn((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)}),eA=pn((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)}),tA=pn((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)}),nA=pn((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)}),aA=pn(()=>{}),rA=pn((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 $=[];T=T==!0?{entropy:!0}:T||{};var F=b(y(T.entropy?[N,x(n)]:N==null?v():N,3),$),O=new f($),W=function(){for(var V=O.g(i),H=c,K=0;V<u;)V=(V+K)*s,H*=s,K=O.g(1);for(;V>=p;)V/=2,H/=2,K>>>=1;return(V+K)/H};return W.int32=function(){return O.g(4)|0},W.quick=function(){return O.g(4)/4294967296},W.double=W,b(x(O.S),n),(T.pass||C||function(V,H,K,j){return j&&(j.S&&g(j,O),V.state=function(){return g(O,{})}),K?(a[l]=V,H):V})(W,F,"global"in T?T.global:this==a,T.state)}a["seed"+l]=m;function f(N){var T,C=N.length,$=this,F=0,O=$.i=$.j=0,W=$.S=[];for(C||(N=[C++]);F<s;)W[F]=F++;for(F=0;F<s;F++)W[F]=W[O=d&O+N[F%C]+(T=W[F])],W[O]=T;($.g=function(V){for(var H,K=0,j=$.i,Y=$.j,J=$.S;V--;)H=J[j=d&j+1],K=K*s+J[d&(J[j]=J[Y=d&Y+H])+(J[Y]=H)];return $.i=j,$.j=Y,K})(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=[],$=typeof N,F;if(T&&$=="object")for(F in N)try{C.push(y(N[F],T-1))}catch(O){}return C.length?C:$=="string"?N:N+"\0"}function b(N,T){for(var C=N+"",$,F=0;F<C.length;)T[d&F]=d&($^=T[d&F]*19)+C.charCodeAt(F++);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($){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=aA()}catch(N){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)}),$d=pn((e,t)=>{var n=JE(),a=ZE(),r=QE(),s=eA(),i=tA(),o=nA(),l=rA();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),sA=pn(()=>{}),pc=pn(()=>{}),iA=pn(()=>{}),oA=pn(()=>{}),lA=pn((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 ee.buffer!=Ze&&Fn(ee.buffer),En}function i(){return ee.buffer!=Ze&&Fn(ee.buffer),nn}function o(){return ee.buffer!=Ze&&Fn(ee.buffer),wn}function l(){return ee.buffer!=Ze&&Fn(ee.buffer),cn}function c(){return ee.buffer!=Ze&&Fn(ee.buffer),Ga}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&&(Ze=u.buffer,ua=u.DYNAMIC_BASE,Ta=u.DYNAMICTOP_PTR);var N="";function T(w){return u.locateFile?u.locateFile(w,N):N+w}var C,$,F,O,W,V;if(b){y?N=pc().dirname(N)+"/":N=__dirname+"/",C=function(w,S){return W||(W=require("fs")),V||(V=pc()),w=V.normalize(w),W.readFileSync(w,S?null:"utf8")},F=function(w){var S=C(w,!0);return S.buffer||(S=new Uint8Array(S)),be(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 qw))throw w}),process.on("unhandledRejection",mr),f=function(w){process.exit(w)},u.inspect=function(){return"[Emscripten Module object]"};var H;try{H=iA()}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=H.Worker}else v?(typeof read!="undefined"&&(C=function(w){return read(w)}),F=function(w){var S;return typeof readbuffer=="function"?new Uint8Array(readbuffer(w)):(S=read(w,"binary"),be(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 W||(W=require("fs")),V||(V=pc()),w=V.normalize(w),W.readFileSync(w,S?null:"utf8")},F=function(w){var S=C(w,!0);return S.buffer||(S=new Uint8Array(S)),be(S.buffer),S}):(C=function(w){var S=new XMLHttpRequest;return S.open("GET",w,!1),S.send(null),S.responseText},y&&(F=function(w){var S=new XMLHttpRequest;return S.open("GET",w,!1),S.responseType="arraybuffer",S.send(null),new Uint8Array(S.response)}),$=function(w,S,M){var G=new XMLHttpRequest;G.open("GET",w,!0),G.responseType="arraybuffer",G.onload=function(){if(G.status==200||G.status==0&&G.response){S(G.response);return}M()},G.onerror=M,G.send(null)}),O=function(w){document.title=w});b&&typeof performance=="undefined"&&(performance=oA().performance);var K=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 Y=Atomics.load,J=Atomics.store,ne=Atomics.compareExchange,Q;u.wasmBinary&&(Q=u.wasmBinary);var ie;u.noExitRuntime&&(ie=u.noExitRuntime),typeof WebAssembly!="object"&&j("no native wasm support detected");var ee,le=new WebAssembly.Table({initial:169,maximum:169+0,element:"anyfunc"}),se,ce=0,de=0,fe=!1,xe=0;function be(w,S){w||mr("Assertion failed: "+S)}function Se(w){var S=u["_"+w];return be(S,"Cannot call unknown function "+w+", make sure it is exported"),S}function _e(w,S,M,G,me){var ue={string:function(Kn){var Vr=0;if(Kn!=null&&Kn!==0){var uc=(Kn.length<<2)+1;Vr=Fo(uc),ut(Kn,Vr,uc)}return Vr},array:function(Kn){var Vr=Fo(Kn.length);return pt(Kn,Vr),Vr}};function oe(Kn){return S==="string"?Ve(Kn):S==="boolean"?Boolean(Kn):Kn}var ke=Se(w),tt=[],Ot=0;if(G)for(var on=0;on<G.length;on++){var Do=ue[M[on]];Do?(Ot===0&&(Ot=ic()),tt[on]=Do(G[on])):tt[on]=G[on]}var lc=ke.apply(null,tt);return lc=oe(lc),Ot!==0&&$o(Ot),lc}function Me(w,S,M,G){M=M||[];var me=M.every(function(oe){return oe==="number"}),ue=S!=="string";return ue&&me&&!G?Se(w):function(){return _e(w,S,M,arguments,G)}}function Ke(w,S,M){for(var G=S+M,me="";!(S>=G);){var ue=w[S++];if(!ue)return me;if(!(ue&128)){me+=String.fromCharCode(ue);continue}var oe=w[S++]&63;if((ue&224)==192){me+=String.fromCharCode((ue&31)<<6|oe);continue}var ke=w[S++]&63;if((ue&240)==224?ue=(ue&15)<<12|oe<<6|ke:ue=(ue&7)<<18|oe<<12|ke<<6|w[S++]&63,ue<65536)me+=String.fromCharCode(ue);else{var tt=ue-65536;me+=String.fromCharCode(55296|tt>>10,56320|tt&1023)}}return me}function Ve(w,S){return w?Ke(i(),w,S):""}function it(w,S,M,G){if(!(G>0))return 0;for(var me=M,ue=M+G-1,oe=0;oe<w.length;++oe){var ke=w.charCodeAt(oe);if(ke>=55296&&ke<=57343){var tt=w.charCodeAt(++oe);ke=65536+((ke&1023)<<10)|tt&1023}if(ke<=127){if(M>=ue)break;S[M++]=ke}else if(ke<=2047){if(M+1>=ue)break;S[M++]=192|ke>>6,S[M++]=128|ke&63}else if(ke<=65535){if(M+2>=ue)break;S[M++]=224|ke>>12,S[M++]=128|ke>>6&63,S[M++]=128|ke&63}else{if(M+3>=ue)break;S[M++]=240|ke>>18,S[M++]=128|ke>>12&63,S[M++]=128|ke>>6&63,S[M++]=128|ke&63}}return S[M]=0,M-me}function ut(w,S,M){return it(w,i(),S,M)}function He(w){for(var S=0,M=0;M<w.length;++M){var G=w.charCodeAt(M);G>=55296&&G<=57343&&(G=65536+((G&1023)<<10)|w.charCodeAt(++M)&1023),G<=127?++S:G<=2047?S+=2:G<=65535?S+=3:S+=4}return S}function pt(w,S){s().set(w,S)}var dt=65536;function jn(w,S){return w%S>0&&(w+=S-w%S),w}var Ze,En,nn,An,oa,wn,cn,la,Ga;function Fn(w){Ze=w,u.HEAP8=En=new Int8Array(w),u.HEAP16=An=new Int16Array(w),u.HEAP32=wn=new Int32Array(w),u.HEAPU8=nn=new Uint8Array(w),u.HEAPU16=oa=new Uint16Array(w),u.HEAPU32=cn=new Uint32Array(w),u.HEAPF32=la=new Float32Array(w),u.HEAPF64=Ga=new Float64Array(w)}var ko=5256464,Hu=ko,Na=13584,ua=5256464,Ta=12656,Io=u.INITIAL_MEMORY||16777216;if(x)ee=u.wasmMemory,Ze=u.buffer;else if(u.wasmMemory)ee=u.wasmMemory;else if(ee=new WebAssembly.Memory({initial:Io/dt,maximum:2147483648/dt,shared:!0}),!(ee.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");ee&&(Ze=ee.buffer),Io=Ze.byteLength,Fn(Ze),x||(o()[Ta>>2]=ua);function No(w){for(;w.length>0;){var S=w.shift();if(typeof S=="function"){S(u);continue}var M=S.func;typeof M=="number"?S.arg===void 0?u.dynCall_v(M):u.dynCall_vi(M,S.arg):M(S.arg===void 0?null:S.arg)}}var Ts=[],ju=[],Kf=[],qu=[],ld=[],Ku=!1;x&&(Ku=!0);function ca(){if(!x){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)Jf(u.preRun.shift());No(Ts)}}function ud(){Ku=!0,No(ju)}function Xf(){x||No(Kf)}function Yf(){if(!x){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Ss(u.postRun.shift());No(ld)}}function Jf(w){Ts.unshift(w)}function Ss(w){ld.unshift(w)}var To=Math.ceil,Zf=Math.floor,hr=0,Xu=null,Cs=null;function Qf(w){be(!x,"addRunDependency cannot be used in a pthread worker"),hr++,u.monitorRunDependencies&&u.monitorRunDependencies(hr)}function eg(w){if(hr--,u.monitorRunDependencies&&u.monitorRunDependencies(hr),hr==0&&(Xu!==null&&(clearInterval(Xu),Xu=null),Cs)){var S=Cs;Cs=null,S()}}u.preloadedImages={},u.preloadedAudios={};function mr(w){throw u.onAbort&&u.onAbort(w),x&&console.error("Pthread aborting at "+new Error().stack),w+="",K(w),j(w),fe=!0,xe=1,w="abort("+w+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(w)}function Yu(w,S){return String.prototype.startsWith?w.startsWith(S):w.indexOf(S)===0}var tg="data:application/octet-stream;base64,";function cd(w){return Yu(w,tg)}var ng="file://";function pd(w){return Yu(w,ng)}var pa="tfjs-backend-wasm-threaded-simd.wasm";cd(pa)||(pa=T(pa));function dd(){try{if(Q)return new Uint8Array(Q);if(F)return F(pa);throw"both async and sync fetching of the wasm failed"}catch(w){mr(w)}}function ag(){return!Q&&(g||y)&&typeof fetch=="function"&&!pd(pa)?fetch(pa,{credentials:"same-origin"}).then(function(w){if(!w.ok)throw"failed to load wasm binary file at '"+pa+"'";return w.arrayBuffer()}).catch(function(){return dd()}):new Promise(function(w,S){w(dd())})}function rg(){var w={a:Xg};function S(oe,ke){var tt=oe.exports;if(u.asm=tt,se=ke,!x){var Ot=ye.unusedWorkers.length;ye.unusedWorkers.forEach(function(on){ye.loadWasmModuleToWorker(on,function(){--Ot||eg("wasm-instantiate")})})}}x||Qf("wasm-instantiate");function M(oe){S(oe.instance,oe.module)}function G(oe){return ag().then(function(ke){return WebAssembly.instantiate(ke,w)}).then(oe,function(ke){j("failed to asynchronously prepare wasm: "+ke),mr(ke)})}function me(){if(!Q&&typeof WebAssembly.instantiateStreaming=="function"&&!cd(pa)&&!pd(pa)&&typeof fetch=="function")fetch(pa,{credentials:"same-origin"}).then(function(oe){var ke=WebAssembly.instantiateStreaming(oe,w);return ke.then(M,function(tt){j("wasm streaming compile failed: "+tt),j("falling back to ArrayBuffer instantiation"),G(M)})});else return G(M)}if(u.instantiateWasm)try{var ue=u.instantiateWasm(w,S);return ue}catch(oe){return j("Module.instantiateWasm callback failed with error: "+oe),!1}return me(),{}}var sg={};function ig(){ye.initRuntime()}x||ju.push({func:function(){Qu()}});var hd=0,md=0,fd=0;function So(w,S,M){w=w|0,S=S|0,M=M|0,hd=w,fd=S,md=M}u.__register_pthread_ptr=So;var Ju={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},Co=13568;function _o(w,S){if(w<=0||w>s().length||w&!0||S<0)return-28;if(S==0)return 0;S>=2147483647&&(S=Infinity);var M=Atomics.load(o(),Co>>2),G=0;if(M==w){var me=Atomics.compareExchange(o(),Co>>2,M,0);if(me==M&&(--S,G=1,S<=0))return 1}var ue=Atomics.notify(o(),w>>2,S);if(ue>=0)return ue+G;throw"Atomics.notify returned an unexpected value "+ue}u._emscripten_futex_wake=_o;function og(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=ye.pthreads[w];S.worker.terminate(),ye.freeThreadData(S),ye.runningWorkers.splice(ye.runningWorkers.indexOf(S.worker),1),S.worker.pthread=void 0}function lg(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=ye.pthreads[w];S.worker.postMessage({cmd:"cancel"})}function ug(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=ye.pthreads[w];if(S){var M=S.worker;ye.returnWorkerToPool(M)}}var ye={MAIN_THREAD_ID:1,mainThreadInfo:{schedPolicy:0,schedPrio:0},unusedWorkers:[],runningWorkers:[],initRuntime:function(){So(ye.mainThreadBlock,!y,1),Uw(ye.mainThreadBlock)},initMainThreadBlock:function(){for(var w=8,S=0;S<w;++S)ye.allocateUnusedWorker();ye.mainThreadBlock=12816;for(var S=0;S<232/4;++S)l()[ye.mainThreadBlock/4+S]=0;o()[ye.mainThreadBlock+12>>2]=ye.mainThreadBlock;var M=ye.mainThreadBlock+156;o()[M>>2]=M;for(var G=13056,S=0;S<128;++S)l()[G/4+S]=0;Atomics.store(l(),ye.mainThreadBlock+104>>2,G),Atomics.store(l(),ye.mainThreadBlock+40>>2,ye.mainThreadBlock),Atomics.store(l(),ye.mainThreadBlock+44>>2,42)},initWorker:function(){},pthreads:{},exitHandlers:null,setThreadStatus:function(){},runExitHandlers:function(){if(ye.exitHandlers!==null){for(;ye.exitHandlers.length>0;)ye.exitHandlers.pop()();ye.exitHandlers=null}x&&ce&&Vw()},threadExit:function(w){var S=Ha();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),ye.runExitHandlers(),_o(S+0,2147483647),So(0,0,0),ce=0,x&&postMessage({cmd:"exit"}))},threadCancel:function(){ye.runExitHandlers(),Atomics.store(l(),ce+4>>2,-1),Atomics.store(l(),ce+0>>2,1),_o(ce+0,2147483647),ce=de=0,So(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var w in ye.pthreads){var S=ye.pthreads[w];S&&S.worker&&ye.returnWorkerToPool(S.worker)}ye.pthreads={};for(var M=0;M<ye.unusedWorkers.length;++M){var G=ye.unusedWorkers[M];G.terminate()}ye.unusedWorkers=[];for(var M=0;M<ye.runningWorkers.length;++M){var G=ye.runningWorkers[M],S=G.pthread;ye.freeThreadData(S),G.terminate()}ye.runningWorkers=[]},freeThreadData:function(w){if(w){if(w.threadInfoStruct){var S=o()[w.threadInfoStruct+104>>2];o()[w.threadInfoStruct+104>>2]=0,sc(S),sc(w.threadInfoStruct)}w.threadInfoStruct=0,w.allocatedOwnStack&&w.stackBase&&sc(w.stackBase),w.stackBase=0,w.worker&&(w.worker.pthread=null)}},returnWorkerToPool:function(w){delete ye.pthreads[w.pthread.thread],ye.unusedWorkers.push(w),ye.runningWorkers.splice(ye.runningWorkers.indexOf(w),1),ye.freeThreadData(w.pthread),w.pthread=void 0},receiveObjectTransfer:function(w){},loadWasmModuleToWorker:function(w,S){w.onmessage=function(M){var G=M.data,me=G.cmd;if(w.pthread&&(ye.currentProxiedOperationCallerThread=w.pthread.threadInfoStruct),G.targetThread&&G.targetThread!=Ha()){var ue=ye.pthreads[G.targetThread];ue?ue.worker.postMessage(M.data,G.transferList):console.error('Internal error! Worker sent a message "'+me+'" to target pthread '+G.targetThread+", but that thread no longer exists!"),ye.currentProxiedOperationCallerThread=void 0;return}if(me==="processQueuedMainThreadWork")Zg();else if(me==="spawnThread")wd(M.data);else if(me==="cleanupThread")ug(G.thread);else if(me==="killThread")og(G.thread);else if(me==="cancelThread")lg(G.thread);else if(me==="loaded")w.loaded=!0,S&&S(w),w.runPthread&&(w.runPthread(),delete w.runPthread);else if(me==="print")K("Thread "+G.threadId+": "+G.text);else if(me==="printErr")j("Thread "+G.threadId+": "+G.text);else if(me==="alert")alert("Thread "+G.threadId+": "+G.text);else if(me==="exit"){var oe=w.pthread&&Atomics.load(l(),w.pthread.thread+68>>2);oe&&ye.returnWorkerToPool(w)}else me==="cancelDone"?ye.returnWorkerToPool(w):me==="objectTransfer"?ye.receiveObjectTransfer(M.data):M.data.target==="setimmediate"?w.postMessage(M.data):j("worker sent an unknown command "+me);ye.currentProxiedOperationCallerThread=void 0},w.onerror=function(M){j("pthread sent an error! "+M.filename+":"+M.lineno+": "+M.message)},b&&(w.on("message",function(M){w.onmessage({data:M})}),w.on("error",function(M){w.onerror(M)}),w.on("exit",function(M){console.log("worker exited - TODO: update the worker queue?")})),w.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||a,wasmMemory:ee,wasmModule:se,DYNAMIC_BASE:ua,DYNAMICTOP_PTR:Ta})},allocateUnusedWorker:function(){var w=T("tfjs-backend-wasm-threaded-simd.worker.js");ye.unusedWorkers.push(new Worker(w))},getNewWorker:function(){return ye.unusedWorkers.length==0&&(ye.allocateUnusedWorker(),ye.loadWasmModuleToWorker(ye.unusedWorkers[0])),ye.unusedWorkers.length>0?ye.unusedWorkers.pop():null},busySpinWait:function(w){for(var S=performance.now()+w;performance.now()<S;);}};function cg(w,S){ko=Hu=w,Na=S,$o(w)}u.establishStackSpace=cg;function pg(){return ie}u.getNoExitRuntime=pg;function dg(w,S,M,G){mr("Assertion failed: "+Ve(w)+", at: "+[S?Ve(S):"unknown filename",M,G?Ve(G):"unknown function"])}function hg(w,S){var M=_main(w,S)}var _s;b?_s=function(){var w=process.hrtime();return w[0]*1e3+w[1]/1e6}:x?_s=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?_s=dateNow:_s=function(){return performance.now()};function mg(w){return o()[zw()>>2]=w,w}function fg(w,S){if(x)return zr(1,1,w,S);qu.unshift({func:w,arg:S})}function gg(w,S){if(w==S)postMessage({cmd:"processQueuedMainThreadWork"});else if(x)postMessage({targetThread:w,cmd:"processThreadQueue"});else{var M=ye.pthreads[w],G=M&&M.worker;if(!G)return;G.postMessage({cmd:"processThreadQueue"})}return 1}function yg(){mr()}function bg(w,S){w=w|0,S=S|0}function xg(w,S,M){if(w<=0||w>s().length||w&!0)return-28;if(y){var G=Atomics.wait(o(),w>>2,S,M);if(G==="timed-out")return-73;if(G==="not-equal")return-6;if(G==="ok")return 0;throw"Atomics.wait returned an unexpected value "+G}else{var me=Atomics.load(o(),w>>2);if(S!=me)return-6;var ue=performance.now(),oe=ue+M;Atomics.store(o(),Co>>2,w);for(var ke=w;w==ke;){if(ue=performance.now(),ue>oe)return-73;Zg(),w=Atomics.load(o(),Co>>2)}return 0}}function vg(){return fd|0}function wg(){return md|0}function kg(w,S,M){i().copyWithin(w,S,S+M)}function Ig(){return navigator.hardwareConcurrency}function zr(w,S){for(var M=arguments.length-2,G=ic(),me=Fo(M*8),ue=me>>3,oe=0;oe<M;oe++)c()[ue+oe]=arguments[2+oe];var ke=Hw(w,M,me,S);return $o(G),ke}var Es=[];function Eo(w,S){Eo.array||(Eo.array=[]);var M=Eo.array;M.length=0;for(var G;G=i()[w++];)G===100||G===102?(S=S+7&~7,M.push(c()[S>>3]),S+=8):(S=S+3&~3,M.push(o()[S>>2]),S+=4);return M}function Ng(w,S,M){Es.length=S;for(var G=M>>3,me=0;me<S;me++)Es[me]=c()[G+me];var ue=w<0,oe=ue?sg[-w-1]:Kg[w];if(ue){var ke=Es[1],tt=Es[2],Ot=Eo(ke,tt);return oe.apply(null,Ot)}return oe.apply(null,Es)}function Tg(){return i().length}function Sg(w){try{return ee.grow(w-Ze.byteLength+65535>>>16),Fn(ee.buffer),1}catch(S){}}function Cg(w){w=w>>>0;var S=Tg();if(w<=S)return!1;var M=65536,G=2147483648;if(w>G)return!1;for(var me=16777216,ue=1;ue<=4;ue*=2){var oe=S*(1+.2/ue);oe=Math.min(oe,w+100663296);var ke=Math.min(G,jn(Math.max(me,w,oe),M)),tt=Sg(ke);if(tt)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||(qu.push(Pe.removeAllEventListeners),Pe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(w,S,M){function G(oe,ke){if(oe.length!=ke.length)return!1;for(var tt in oe)if(oe[tt]!=ke[tt])return!1;return!0}for(var me in Pe.deferredCalls){var ue=Pe.deferredCalls[me];if(ue.targetFunction==w&&G(ue.argsList,M))return}Pe.deferredCalls.push({targetFunction:w,precedence:S,argsList:M}),Pe.deferredCalls.sort(function(oe,ke){return oe.precedence<ke.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 M=0;M<Pe.eventHandlers.length;++M)Pe.eventHandlers[M].target==w&&(!S||S==Pe.eventHandlers[M].eventTypeString)&&Pe._removeHandler(M--)},_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(G){++Pe.inEventHandler,Pe.currentEventHandler=w,Pe.runDeferredCalls(),w.handlerFunc(G),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 M=0;M<Pe.eventHandlers.length;++M)Pe.eventHandlers[M].target==w.target&&Pe.eventHandlers[M].eventTypeString==w.eventTypeString&&Pe._removeHandler(M--)},queueEventHandlerOnThread_iiii:function(w,S,M,G,me){var ue=ic(),oe=Fo(12);o()[oe>>2]=M,o()[oe+4>>2]=G,o()[oe+8>>2]=me,Qg(w,637534208,S,G,oe),$o(ue)},getTargetThreadForEventCallback:function(w){switch(w){case 1:return 0;case 2:return ye.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 _g(w){var S=He(w)+1,M=rc(S);return ut(w,M,S),M}function Eg(w,S,M,G){var me=ic(),ue=Fo(12),oe=0;S&&(oe=_g(S)),o()[ue>>2]=oe,o()[ue+4>>2]=M,o()[ue+8>>2]=G,Qg(w,657457152,0,oe,ue),$o(me)}function Ag(w,S,M,G){S=S?Ve(S):"",Eg(w,S,M,G)}function Fg(w){return w>2?Ve(w):w}var $g=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Dg(w){w=Fg(w);var S=$g[w]||(typeof document!="undefined"?document.querySelector(w):void 0);return S}function Zu(w){return Dg(w)}function gd(w,S,M){var G=Zu(w);if(!G)return-4;if(G.canvasSharedPtr&&(o()[G.canvasSharedPtr>>2]=S,o()[G.canvasSharedPtr+4>>2]=M),G.offscreenCanvas||!G.controlTransferredOffscreen){G.offscreenCanvas&&(G=G.offscreenCanvas);var me=!1;if(G.GLctxObject&&G.GLctxObject.GLctx){var ue=G.GLctxObject.GLctx.getParameter(2978);me=ue[0]===0&&ue[1]===0&&ue[2]===G.width&&ue[3]===G.height}G.width=S,G.height=M,me&&G.GLctxObject.GLctx.viewport(0,0,S,M)}else if(G.canvasSharedPtr){var oe=o()[G.canvasSharedPtr+8>>2];return Ag(oe,w,S,M),1}else return-4;return 0}function yd(w,S,M){return x?zr(2,1,w,S,M):gd(w,S,M)}function Mg(w,S,M){var G=Zu(w);return G?gd(w,S,M):yd(w,S,M)}function Rg(w){w=w|0}function Pg(w,S){w=w|0,S=S|0}function Og(w){var S=w.getExtension("ANGLE_instanced_arrays");if(S)return w.vertexAttribDivisor=function(M,G){S.vertexAttribDivisorANGLE(M,G)},w.drawArraysInstanced=function(M,G,me,ue){S.drawArraysInstancedANGLE(M,G,me,ue)},w.drawElementsInstanced=function(M,G,me,ue,oe){S.drawElementsInstancedANGLE(M,G,me,ue,oe)},1}function Lg(w){var S=w.getExtension("OES_vertex_array_object");if(S)return w.createVertexArray=function(){return S.createVertexArrayOES()},w.deleteVertexArray=function(M){S.deleteVertexArrayOES(M)},w.bindVertexArray=function(M){S.bindVertexArrayOES(M)},w.isVertexArray=function(M){return S.isVertexArrayOES(M)},1}function zg(w){var S=w.getExtension("WEBGL_draw_buffers");if(S)return w.drawBuffers=function(M,G){S.drawBuffersWEBGL(M,G)},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 M=new Int32Array(Be.MINI_TEMP_BUFFER_SIZE),S=0;S<Be.MINI_TEMP_BUFFER_SIZE;S++)Be.miniTempBufferIntViews[S]=M.subarray(0,S+1)},recordError:function(w){Be.lastError||(Be.lastError=w)},getNewId:function(w){for(var S=Be.counter++,M=w.length;M<S;M++)w[M]=null;return S},MINI_TEMP_BUFFER_SIZE:256,miniTempBufferFloatViews:[0],miniTempBufferIntViews:[0],getSource:function(w,S,M,G){for(var me="",ue=0;ue<S;++ue){var oe=G?o()[G+ue*4>>2]:-1;me+=Ve(o()[M+ue*4>>2],oe<0?void 0:oe)}return me},createContext:function(w,S){var M=w.getContext("webgl",S);if(!M)return 0;var G=Be.registerContext(M,S);return G},registerContext:function(w,S){var M=rc(8);o()[M+4>>2]=Ha();var G={handle:M,attributes:S,version:S.majorVersion,GLctx:w};return w.canvas&&(w.canvas.GLctxObject=G),Be.contexts[M]=G,(typeof S.enableExtensionsByDefault=="undefined"||S.enableExtensionsByDefault)&&Be.initExtensions(G),M},makeContextCurrent:function(w){return Be.currentContext=Be.contexts[w],u.ctx=Br=Be.currentContext&&Be.currentContext.GLctx,!(w&&!Br)},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),sc(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;Og(S),Lg(S),zg(S),S.disjointTimerQueryExt=S.getExtension("EXT_disjoint_timer_query");var M=["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"],G=S.getSupportedExtensions()||[];G.forEach(function(me){M.indexOf(me)!=-1&&S.getExtension(me)})}},populateUniformTable:function(w){for(var S=Be.programs[w],M=Be.programInfos[w]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},G=M.uniforms,me=Br.getProgramParameter(S,35718),ue=0;ue<me;++ue){var oe=Br.getActiveUniform(S,ue),ke=oe.name;M.maxUniformLength=Math.max(M.maxUniformLength,ke.length+1),ke.slice(-1)=="]"&&(ke=ke.slice(0,ke.lastIndexOf("[")));var tt=Br.getUniformLocation(S,ke);if(tt){var Ot=Be.getNewId(Be.uniforms);G[ke]=[oe.size,Ot],Be.uniforms[Ot]=tt;for(var on=1;on<oe.size;++on){var Do=ke+"["+on+"]";tt=Br.getUniformLocation(S,Do),Ot=Be.getNewId(Be.uniforms),Be.uniforms[Ot]=tt}}}}},Bg=["default","low-power","high-performance"];function Wg(w,S){var M={},G=S>>2;M.alpha=!!o()[G+(0>>2)],M.depth=!!o()[G+(4>>2)],M.stencil=!!o()[G+(8>>2)],M.antialias=!!o()[G+(12>>2)],M.premultipliedAlpha=!!o()[G+(16>>2)],M.preserveDrawingBuffer=!!o()[G+(20>>2)];var me=o()[G+(24>>2)];M.powerPreference=Bg[me],M.failIfMajorPerformanceCaveat=!!o()[G+(28>>2)],M.majorVersion=o()[G+(32>>2)],M.minorVersion=o()[G+(36>>2)],M.enableExtensionsByDefault=o()[G+(40>>2)],M.explicitSwapControl=o()[G+(44>>2)],M.proxyContextToMainThread=o()[G+(48>>2)],M.renderViaOffscreenBackBuffer=o()[G+(52>>2)];var ue=Zu(w);if(!ue)return-4;if(M.explicitSwapControl)return-1;var oe=Be.createContext(ue,M);return oe}function Vg(w,S){return Wg(w,S)}var As={splitPath:function(w){var S=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return S.exec(w).slice(1)},normalizeArray:function(w,S){for(var M=0,G=w.length-1;G>=0;G--){var me=w[G];me==="."?w.splice(G,1):me===".."?(w.splice(G,1),M++):M&&(w.splice(G,1),M--)}if(S)for(;M;M--)w.unshift("..");return w},normalize:function(w){var S=w.charAt(0)==="/",M=w.substr(-1)==="/";return w=As.normalizeArray(w.split("/").filter(function(G){return!!G}),!S).join("/"),!w&&!S&&(w="."),w&&M&&(w+="/"),(S?"/":"")+w},dirname:function(w){var S=As.splitPath(w),M=S[0],G=S[1];return!M&&!G?".":(G&&(G=G.substr(0,G.length-1)),M+G)},basename:function(w){if(w==="/")return"/";var S=w.lastIndexOf("/");return S===-1?w:w.substr(S+1)},extname:function(w){return As.splitPath(w)[3]},join:function(){var w=Array.prototype.slice.call(arguments,0);return As.normalize(w.join("/"))},join2:function(w,S){return As.normalize(w+"/"+S)}},Ao={mappings:{},buffers:[null,[],[]],printChar:function(w,S){var M=Ao.buffers[w];S===0||S===10?((w===1?K:j)(Ke(M,0)),M.length=0):M.push(S)},varargs:void 0,get:function(){Ao.varargs+=4;var w=o()[Ao.varargs-4>>2];return w},getStr:function(w){var S=Ve(w);return S},get64:function(w,S){return w}};function bd(w){return x?zr(3,1,w):0}function xd(w,S,M,G,me){if(x)return zr(4,1,w,S,M,G,me)}function vd(w,S,M,G){if(x)return zr(5,1,w,S,M,G);for(var me=0,ue=0;ue<M;ue++){for(var oe=o()[S+ue*8>>2],ke=o()[S+(ue*8+4)>>2],tt=0;tt<ke;tt++)Ao.printChar(w,i()[oe+tt]);me+=ke}return o()[G>>2]=me,0}function Ug(w){var S=ye.exitHandlers.pop();w&&S()}function Gg(w,S){ye.exitHandlers===null&&(ye.exitHandlers=[]),ye.exitHandlers.push(function(){jw(w,S)})}function wd(w){if(x)throw"Internal Error! _spawn_thread() can only ever be called from main application thread!";var S=ye.getNewWorker();if(S.pthread!==void 0)throw"Internal error!";if(!w.pthread_ptr)throw"Internal error, no pthread ptr!";ye.runningWorkers.push(S);for(var M=rc(128*4),G=0;G<128;++G)o()[M+G*4>>2]=0;var me=w.stackBase+w.stackSize,ue=ye.pthreads[w.pthread_ptr]={worker:S,stackBase:w.stackBase,stackSize:w.stackSize,allocatedOwnStack:w.allocatedOwnStack,thread:w.pthread_ptr,threadInfoStruct:w.pthread_ptr},oe=ue.threadInfoStruct>>2;Atomics.store(l(),oe+(0>>2),0),Atomics.store(l(),oe+(4>>2),0),Atomics.store(l(),oe+(8>>2),0),Atomics.store(l(),oe+(68>>2),w.detached),Atomics.store(l(),oe+(104>>2),M),Atomics.store(l(),oe+(48>>2),0),Atomics.store(l(),oe+(40>>2),ue.threadInfoStruct),Atomics.store(l(),oe+(44>>2),42),Atomics.store(l(),oe+(108>>2),w.stackSize),Atomics.store(l(),oe+(84>>2),w.stackSize),Atomics.store(l(),oe+(80>>2),me),Atomics.store(l(),oe+(108+8>>2),me),Atomics.store(l(),oe+(108+12>>2),w.detached),Atomics.store(l(),oe+(108+20>>2),w.schedPolicy),Atomics.store(l(),oe+(108+24>>2),w.schedPrio);var ke=Bw(),tt=ke+40;Atomics.store(l(),oe+(176>>2),tt),S.pthread=ue;var Ot={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(){Ot.time=performance.now(),S.postMessage(Ot,w.transferList)},S.loaded&&(S.runPthread(),delete S.runPthread)}function Hg(w,S,M){if(!S&&!M)return Ju.EINVAL;if(!w)return j("pthread_getschedparam called with a null thread pointer!"),Ju.ESRCH;var G=o()[w+12>>2];if(G!==w)return j("pthread_getschedparam attempted on thread "+w+", which does not point to a valid thread, or does not exist anymore!"),Ju.ESRCH;var me=Atomics.load(l(),w+108+20>>2),ue=Atomics.load(l(),w+108+24>>2);return S&&(o()[S>>2]=me),M&&(o()[M>>2]=ue),0}function Ha(){return hd|0}u._pthread_self=Ha;function jg(w,S,M,G){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 me=[],ue=0;if(x&&(me.length===0||ue))return Gw(687865856,w,S,M,G);if(ue)return ue;var oe=0,ke=0,tt=0,Ot=0,on=0;if(S){oe=o()[S>>2],oe+=81920,ke=o()[S+8>>2],tt=o()[S+12>>2]!==0;var Do=o()[S+16>>2]===0;if(Do){var lc=o()[S+20>>2],Kn=o()[S+24>>2],Vr=ye.currentProxiedOperationCallerThread?ye.currentProxiedOperationCallerThread:Ha();Hg(Vr,S+20,S+24),Ot=o()[S+20>>2],on=o()[S+24>>2],o()[S+20>>2]=lc,o()[S+24>>2]=Kn}else Ot=o()[S+20>>2],on=o()[S+24>>2]}else oe=2097152;var uc=ke==0;uc?ke=Ww(16,oe):(ke-=oe,be(ke>0));for(var Mo=rc(232),ty=0;ty<232>>2;++ty)l()[(Mo>>2)+ty]=0;o()[w>>2]=Mo,o()[Mo+12>>2]=Mo;var Kw=Mo+156;o()[Kw>>2]=Kw;var ny={stackBase:ke,stackSize:oe,allocatedOwnStack:uc,schedPolicy:Ot,schedPrio:on,detached:tt,startRoutine:M,pthread_ptr:Mo,parent_pthread_ptr:Ha(),arg:G,transferList:me};return x?(ny.cmd="spawnThread",postMessage(ny,me)):wd(ny),0}function qg(w){return w=+w,w>=0?+Zf(w+.5):+To(w-.5)}function kd(w){if(x)return zr(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 mg(28),-1}x?ye.initWorker():ye.initMainThreadBlock();var Br;Be.init();var Kg=[null,fg,yd,bd,xd,vd,kd],Xg={e:dg,r:hg,w:gg,a:yg,l:bg,d:xg,c:_o,h:_s,g:vg,x:wg,q:kg,B:Ig,t:Ng,A:Cg,u:Mg,k:Rg,s:Pg,v:Vg,m:bd,o:xd,i:vd,p:ig,memory:ee||u.wasmMemory,y:Ug,z:Gg,j:jg,b:Ha,f:qg,n:kd,table:le},Id=rg();u.asm=Id;var Qu=u.___wasm_call_ctors=function(){return(Qu=u.___wasm_call_ctors=u.asm.C).apply(null,arguments)},ec=u._init=function(){return(ec=u._init=u.asm.D).apply(null,arguments)},Nd=u._register_tensor=function(){return(Nd=u._register_tensor=u.asm.E).apply(null,arguments)},Fs=u._dispose_data=function(){return(Fs=u._dispose_data=u.asm.F).apply(null,arguments)},tc=u._dispose=function(){return(tc=u._dispose=u.asm.G).apply(null,arguments)},Yg=u._Abs=function(){return(Yg=u._Abs=u.asm.H).apply(null,arguments)},Jg=u._Add=function(){return(Jg=u._Add=u.asm.I).apply(null,arguments)},nc=u._AddN=function(){return(nc=u._AddN=u.asm.J).apply(null,arguments)},Td=u._ArgMax=function(){return(Td=u._ArgMax=u.asm.K).apply(null,arguments)},Sd=u._AvgPool=function(){return(Sd=u._AvgPool=u.asm.L).apply(null,arguments)},U=u._BatchMatMul=function(){return(U=u._BatchMatMul=u.asm.M).apply(null,arguments)},ae=u._ClipByValue=function(){return(ae=u._ClipByValue=u.asm.N).apply(null,arguments)},Ne=u._Conv2D=function(){return(Ne=u._Conv2D=u.asm.O).apply(null,arguments)},Ee=u._Conv2DBackpropInput=function(){return(Ee=u._Conv2DBackpropInput=u.asm.P).apply(null,arguments)},at=u._Cos=function(){return(at=u._Cos=u.asm.Q).apply(null,arguments)},Et=u._CropAndResize=function(){return(Et=u._CropAndResize=u.asm.R).apply(null,arguments)},Xe=u._Cumsum=function(){return(Xe=u._Cumsum=u.asm.S).apply(null,arguments)},je=u._DepthToSpace=function(){return(je=u._DepthToSpace=u.asm.T).apply(null,arguments)},Ht=u._DepthwiseConv2dNative=function(){return(Ht=u._DepthwiseConv2dNative=u.asm.U).apply(null,arguments)},fr=u._Equal=function(){return(fr=u._Equal=u.asm.V).apply(null,arguments)},gr=u._Exp=function(){return(gr=u._Exp=u.asm.W).apply(null,arguments)},Cd=u._FlipLeftRight=function(){return(Cd=u._FlipLeftRight=u.asm.X).apply(null,arguments)},ac=u._Floor=function(){return(ac=u._Floor=u.asm.Y).apply(null,arguments)},qn=u._FloorDiv=function(){return(qn=u._FloorDiv=u.asm.Z).apply(null,arguments)},Wr=u._FusedBatchNorm=function(){return(Wr=u._FusedBatchNorm=u.asm._).apply(null,arguments)},_d=u._FusedConv2D=function(){return(_d=u._FusedConv2D=u.asm.$).apply(null,arguments)},k_=u._FusedDepthwiseConv2D=function(){return(k_=u._FusedDepthwiseConv2D=u.asm.aa).apply(null,arguments)},I_=u._Gather=function(){return(I_=u._Gather=u.asm.ba).apply(null,arguments)},N_=u._GatherNd=function(){return(N_=u._GatherNd=u.asm.ca).apply(null,arguments)},T_=u._Greater=function(){return(T_=u._Greater=u.asm.da).apply(null,arguments)},S_=u._GreaterEqual=function(){return(S_=u._GreaterEqual=u.asm.ea).apply(null,arguments)},C_=u._LeakyRelu=function(){return(C_=u._LeakyRelu=u.asm.fa).apply(null,arguments)},__=u._Less=function(){return(__=u._Less=u.asm.ga).apply(null,arguments)},E_=u._LessEqual=function(){return(E_=u._LessEqual=u.asm.ha).apply(null,arguments)},A_=u._Log=function(){return(A_=u._Log=u.asm.ia).apply(null,arguments)},F_=u._LogicalAnd=function(){return(F_=u._LogicalAnd=u.asm.ja).apply(null,arguments)},$_=u._Max=function(){return($_=u._Max=u.asm.ka).apply(null,arguments)},D_=u._MaxPool=function(){return(D_=u._MaxPool=u.asm.la).apply(null,arguments)},M_=u._Maximum=function(){return(M_=u._Maximum=u.asm.ma).apply(null,arguments)},R_=u._Mean=function(){return(R_=u._Mean=u.asm.na).apply(null,arguments)},P_=u._Min=function(){return(P_=u._Min=u.asm.oa).apply(null,arguments)},O_=u._Minimum=function(){return(O_=u._Minimum=u.asm.pa).apply(null,arguments)},L_=u._Multiply=function(){return(L_=u._Multiply=u.asm.qa).apply(null,arguments)},z_=u._Neg=function(){return(z_=u._Neg=u.asm.ra).apply(null,arguments)},B_=u._NonMaxSuppressionV3=function(){return(B_=u._NonMaxSuppressionV3=u.asm.sa).apply(null,arguments)},W_=u._NonMaxSuppressionV4=function(){return(W_=u._NonMaxSuppressionV4=u.asm.ta).apply(null,arguments)},V_=u._NonMaxSuppressionV5=function(){return(V_=u._NonMaxSuppressionV5=u.asm.ua).apply(null,arguments)},U_=u._NotEqual=function(){return(U_=u._NotEqual=u.asm.va).apply(null,arguments)},G_=u._OneHot=function(){return(G_=u._OneHot=u.asm.wa).apply(null,arguments)},H_=u._PadV2=function(){return(H_=u._PadV2=u.asm.xa).apply(null,arguments)},j_=u._Pow=function(){return(j_=u._Pow=u.asm.ya).apply(null,arguments)},q_=u._Prelu=function(){return(q_=u._Prelu=u.asm.za).apply(null,arguments)},K_=u._Prod=function(){return(K_=u._Prod=u.asm.Aa).apply(null,arguments)},X_=u._RealDiv=function(){return(X_=u._RealDiv=u.asm.Ba).apply(null,arguments)},Y_=u._Relu=function(){return(Y_=u._Relu=u.asm.Ca).apply(null,arguments)},J_=u._Relu6=function(){return(J_=u._Relu6=u.asm.Da).apply(null,arguments)},Z_=u._ResizeBilinear=function(){return(Z_=u._ResizeBilinear=u.asm.Ea).apply(null,arguments)},Q_=u._Reverse=function(){return(Q_=u._Reverse=u.asm.Fa).apply(null,arguments)},eE=u._RotateWithOffset=function(){return(eE=u._RotateWithOffset=u.asm.Ga).apply(null,arguments)},tE=u._Round=function(){return(tE=u._Round=u.asm.Ha).apply(null,arguments)},nE=u._Rsqrt=function(){return(nE=u._Rsqrt=u.asm.Ia).apply(null,arguments)},aE=u._ScatterNd=function(){return(aE=u._ScatterNd=u.asm.Ja).apply(null,arguments)},rE=u._SelectV2=function(){return(rE=u._SelectV2=u.asm.Ka).apply(null,arguments)},sE=u._Sigmoid=function(){return(sE=u._Sigmoid=u.asm.La).apply(null,arguments)},iE=u._Sin=function(){return(iE=u._Sin=u.asm.Ma).apply(null,arguments)},oE=u._Softmax=function(){return(oE=u._Softmax=u.asm.Na).apply(null,arguments)},lE=u._Sqrt=function(){return(lE=u._Sqrt=u.asm.Oa).apply(null,arguments)},uE=u._Square=function(){return(uE=u._Square=u.asm.Pa).apply(null,arguments)},cE=u._SquaredDifference=function(){return(cE=u._SquaredDifference=u.asm.Qa).apply(null,arguments)},pE=u._Step=function(){return(pE=u._Step=u.asm.Ra).apply(null,arguments)},dE=u._StridedSlice=function(){return(dE=u._StridedSlice=u.asm.Sa).apply(null,arguments)},hE=u._Sub=function(){return(hE=u._Sub=u.asm.Ta).apply(null,arguments)},mE=u._Sum=function(){return(mE=u._Sum=u.asm.Ua).apply(null,arguments)},fE=u._Tanh=function(){return(fE=u._Tanh=u.asm.Va).apply(null,arguments)},gE=u._Tile=function(){return(gE=u._Tile=u.asm.Wa).apply(null,arguments)},yE=u._TopK=function(){return(yE=u._TopK=u.asm.Xa).apply(null,arguments)},bE=u._Transpose=function(){return(bE=u._Transpose=u.asm.Ya).apply(null,arguments)},xE=u.__FusedMatMul=function(){return(xE=u.__FusedMatMul=u.asm.Za).apply(null,arguments)},rc=u._malloc=function(){return(rc=u._malloc=u.asm._a).apply(null,arguments)},sc=u._free=function(){return(sc=u._free=u.asm.$a).apply(null,arguments)},zw=u.___errno_location=function(){return(zw=u.___errno_location=u.asm.ab).apply(null,arguments)},Bw=u._emscripten_get_global_libc=function(){return(Bw=u._emscripten_get_global_libc=u.asm.bb).apply(null,arguments)},vE=u.___em_js__initPthreadsJS=function(){return(vE=u.___em_js__initPthreadsJS=u.asm.cb).apply(null,arguments)},Ww=u._memalign=function(){return(Ww=u._memalign=u.asm.db).apply(null,arguments)},Vw=u.___pthread_tsd_run_dtors=function(){return(Vw=u.___pthread_tsd_run_dtors=u.asm.eb).apply(null,arguments)},Zg=u._emscripten_main_thread_process_queued_calls=function(){return(Zg=u._emscripten_main_thread_process_queued_calls=u.asm.fb).apply(null,arguments)},wE=u._emscripten_current_thread_process_queued_calls=function(){return(wE=u._emscripten_current_thread_process_queued_calls=u.asm.gb).apply(null,arguments)},Uw=u._emscripten_register_main_browser_thread_id=function(){return(Uw=u._emscripten_register_main_browser_thread_id=u.asm.hb).apply(null,arguments)},kE=u._emscripten_main_browser_thread_id=function(){return(kE=u._emscripten_main_browser_thread_id=u.asm.ib).apply(null,arguments)},IE=u._emscripten_async_run_in_main_thread=function(){return(IE=u._emscripten_async_run_in_main_thread=u.asm.jb).apply(null,arguments)},NE=u._emscripten_sync_run_in_main_thread=function(){return(NE=u._emscripten_sync_run_in_main_thread=u.asm.kb).apply(null,arguments)},TE=u._emscripten_sync_run_in_main_thread_0=function(){return(TE=u._emscripten_sync_run_in_main_thread_0=u.asm.lb).apply(null,arguments)},SE=u._emscripten_sync_run_in_main_thread_1=function(){return(SE=u._emscripten_sync_run_in_main_thread_1=u.asm.mb).apply(null,arguments)},CE=u._emscripten_sync_run_in_main_thread_2=function(){return(CE=u._emscripten_sync_run_in_main_thread_2=u.asm.nb).apply(null,arguments)},_E=u._emscripten_sync_run_in_main_thread_xprintf_varargs=function(){return(_E=u._emscripten_sync_run_in_main_thread_xprintf_varargs=u.asm.ob).apply(null,arguments)},EE=u._emscripten_sync_run_in_main_thread_3=function(){return(EE=u._emscripten_sync_run_in_main_thread_3=u.asm.pb).apply(null,arguments)},Gw=u._emscripten_sync_run_in_main_thread_4=function(){return(Gw=u._emscripten_sync_run_in_main_thread_4=u.asm.qb).apply(null,arguments)},AE=u._emscripten_sync_run_in_main_thread_5=function(){return(AE=u._emscripten_sync_run_in_main_thread_5=u.asm.rb).apply(null,arguments)},FE=u._emscripten_sync_run_in_main_thread_6=function(){return(FE=u._emscripten_sync_run_in_main_thread_6=u.asm.sb).apply(null,arguments)},$E=u._emscripten_sync_run_in_main_thread_7=function(){return($E=u._emscripten_sync_run_in_main_thread_7=u.asm.tb).apply(null,arguments)},Hw=u._emscripten_run_in_main_runtime_thread_js=function(){return(Hw=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},Qg=u._emscripten_async_queue_on_thread_=function(){return(Qg=u._emscripten_async_queue_on_thread_=u.asm.vb).apply(null,arguments)},DE=u._emscripten_tls_init=function(){return(DE=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},ic=u.stackSave=function(){return(ic=u.stackSave=u.asm.xb).apply(null,arguments)},Fo=u.stackAlloc=function(){return(Fo=u.stackAlloc=u.asm.yb).apply(null,arguments)},$o=u.stackRestore=function(){return($o=u.stackRestore=u.asm.zb).apply(null,arguments)},jw=u.dynCall_vi=function(){return(jw=u.dynCall_vi=u.asm.Ab).apply(null,arguments)},ME=u.dynCall_v=function(){return(ME=u.dynCall_v=u.asm.Bb).apply(null,arguments)},RE=u.dynCall_ii=function(){return(RE=u.dynCall_ii=u.asm.Cb).apply(null,arguments)};u.asm=Id,u.cwrap=Me,u.PThread=ye,u.PThread=ye,u._pthread_self=Ha,u.wasmMemory=ee,u.ExitStatus=qw;var oc;u.then=function(w){if(oc)w(u);else{var S=u.onRuntimeInitialized;u.onRuntimeInitialized=function(){S&&S(),w(u)}}return u};function qw(w){this.name="ExitStatus",this.message="Program terminated with exit("+w+")",this.status=w}Cs=function w(){oc||ey(),oc||(Cs=w)};function ey(w){if(w=w||h,hr>0||(ca(),hr>0))return;function S(){oc||(oc=!0,u.calledRun=!0,!fe&&(ud(),Xf(),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Yf()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),S()},1)):S()}if(u.run=ey,u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return x||(ie=!0),x||ey(),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)}),uA=pn((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(U,ae){throw ae},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(U){return s.locateFile?s.locateFile(U,f):f+U}var y,b,v,x,N,T;h?(d?f=pc().dirname(f)+"/":f=__dirname+"/",y=function(U,ae){return N||(N=require("fs")),T||(T=pc()),U=T.normalize(U),N.readFileSync(U,ae?null:"utf8")},v=function(U){var ae=y(U,!0);return ae.buffer||(ae=new Uint8Array(ae)),j(ae.buffer),ae},process.argv.length>1&&(c=process.argv[1].replace(/\\/g,"/")),l=process.argv.slice(2),process.on("uncaughtException",function(U){if(!(U instanceof tc))throw U}),process.on("unhandledRejection",Ts),u=function(U){process.exit(U)},s.inspect=function(){return"[Emscripten Module object]"}):m?(typeof read!="undefined"&&(y=function(U){return read(U)}),v=function(U){var ae;return typeof readbuffer=="function"?new Uint8Array(readbuffer(U)):(ae=read(U,"binary"),j(typeof ae=="object"),ae)},typeof scriptArgs!="undefined"?l=scriptArgs:typeof arguments!="undefined"&&(l=arguments),typeof quit=="function"&&(u=function(U){quit(U)}),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(U){var ae=new XMLHttpRequest;return ae.open("GET",U,!1),ae.send(null),ae.responseText},d&&(v=function(U){var ae=new XMLHttpRequest;return ae.open("GET",U,!1),ae.responseType="arraybuffer",ae.send(null),new Uint8Array(ae.response)}),b=function(U,ae,Ne){var Ee=new XMLHttpRequest;Ee.open("GET",U,!0),Ee.responseType="arraybuffer",Ee.onload=function(){if(Ee.status==200||Ee.status==0&&Ee.response){ae(Ee.response);return}Ne()},Ee.onerror=Ne,Ee.send(null)},x=function(U){document.title=U});var C=s.print||console.log.bind(console),$=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 F;s.wasmBinary&&(F=s.wasmBinary);var O;s.noExitRuntime&&(O=s.noExitRuntime),typeof WebAssembly!="object"&&$("no native wasm support detected");var W,V=new WebAssembly.Table({initial:151,maximum:151+0,element:"anyfunc"}),H=!1,K=0;function j(U,ae){U||Ts("Assertion failed: "+ae)}function Y(U){var ae=s["_"+U];return j(ae,"Cannot call unknown function "+U+", make sure it is exported"),ae}function J(U,ae,Ne,Ee,at){var Et={string:function(qn){var Wr=0;if(qn!=null&&qn!==0){var _d=(qn.length<<2)+1;Wr=ec(_d),se(qn,Wr,_d)}return Wr},array:function(qn){var Wr=ec(qn.length);return ce(qn,Wr),Wr}};function Xe(qn){return ae==="string"?ee(qn):ae==="boolean"?Boolean(qn):qn}var je=Y(U),Ht=[],fr=0;if(Ee)for(var gr=0;gr<Ee.length;gr++){var Cd=Et[Ne[gr]];Cd?(fr===0&&(fr=Qu()),Ht[gr]=Cd(Ee[gr])):Ht[gr]=Ee[gr]}var ac=je.apply(null,Ht);return ac=Xe(ac),fr!==0&&Nd(fr),ac}function ne(U,ae,Ne,Ee){Ne=Ne||[];var at=Ne.every(function(Xe){return Xe==="number"}),Et=ae!=="string";return Et&&at&&!Ee?Y(U):function(){return J(U,ae,Ne,arguments,Ee)}}var Q=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ie(U,ae,Ne){for(var Ee=ae+Ne,at=ae;U[at]&&!(at>=Ee);)++at;if(at-ae>16&&U.subarray&&Q)return Q.decode(U.subarray(ae,at));for(var Et="";ae<at;){var Xe=U[ae++];if(!(Xe&128)){Et+=String.fromCharCode(Xe);continue}var je=U[ae++]&63;if((Xe&224)==192){Et+=String.fromCharCode((Xe&31)<<6|je);continue}var Ht=U[ae++]&63;if((Xe&240)==224?Xe=(Xe&15)<<12|je<<6|Ht:Xe=(Xe&7)<<18|je<<12|Ht<<6|U[ae++]&63,Xe<65536)Et+=String.fromCharCode(Xe);else{var fr=Xe-65536;Et+=String.fromCharCode(55296|fr>>10,56320|fr&1023)}}return Et}function ee(U,ae){return U?ie(xe,U,ae):""}function le(U,ae,Ne,Ee){if(!(Ee>0))return 0;for(var at=Ne,Et=Ne+Ee-1,Xe=0;Xe<U.length;++Xe){var je=U.charCodeAt(Xe);if(je>=55296&&je<=57343){var Ht=U.charCodeAt(++Xe);je=65536+((je&1023)<<10)|Ht&1023}if(je<=127){if(Ne>=Et)break;ae[Ne++]=je}else if(je<=2047){if(Ne+1>=Et)break;ae[Ne++]=192|je>>6,ae[Ne++]=128|je&63}else if(je<=65535){if(Ne+2>=Et)break;ae[Ne++]=224|je>>12,ae[Ne++]=128|je>>6&63,ae[Ne++]=128|je&63}else{if(Ne+3>=Et)break;ae[Ne++]=240|je>>18,ae[Ne++]=128|je>>12&63,ae[Ne++]=128|je>>6&63,ae[Ne++]=128|je&63}}return ae[Ne]=0,Ne-at}function se(U,ae,Ne){return le(U,xe,ae,Ne)}function ce(U,ae){fe.set(U,ae)}var de,fe,xe,be,Se,_e,Me,Ke,Ve;function it(U){de=U,s.HEAP8=fe=new Int8Array(U),s.HEAP16=be=new Int16Array(U),s.HEAP32=_e=new Int32Array(U),s.HEAPU8=xe=new Uint8Array(U),s.HEAPU16=Se=new Uint16Array(U),s.HEAPU32=Me=new Uint32Array(U),s.HEAPF32=Ke=new Float32Array(U),s.HEAPF64=Ve=new Float64Array(U)}var ut=s.INITIAL_MEMORY||16777216;function He(U){for(;U.length>0;){var ae=U.shift();if(typeof ae=="function"){ae(s);continue}var Ne=ae.func;typeof Ne=="number"?ae.arg===void 0?s.dynCall_v(Ne):s.dynCall_vi(Ne,ae.arg):Ne(ae.arg===void 0?null:ae.arg)}}var pt=[],dt=[],jn=[],Ze=[],En=!1,nn=!1;function An(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)Ga(s.preRun.shift());He(pt)}function oa(){En=!0,He(dt)}function wn(){He(jn)}function cn(){nn=!0}function la(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Fn(s.postRun.shift());He(Ze)}function Ga(U){pt.unshift(U)}function Fn(U){Ze.unshift(U)}var ko=Math.ceil,Hu=Math.floor,Na=0,ua=null,Ta=null;function Io(U){Na++,s.monitorRunDependencies&&s.monitorRunDependencies(Na)}function No(U){if(Na--,s.monitorRunDependencies&&s.monitorRunDependencies(Na),Na==0&&(ua!==null&&(clearInterval(ua),ua=null),Ta)){var ae=Ta;Ta=null,ae()}}s.preloadedImages={},s.preloadedAudios={};function Ts(U){throw s.onAbort&&s.onAbort(U),U+="",C(U),$(U),H=!0,K=1,U="abort("+U+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(U)}function ju(U,ae){return String.prototype.startsWith?U.startsWith(ae):U.indexOf(ae)===0}var Kf="data:application/octet-stream;base64,";function qu(U){return ju(U,Kf)}var ld="file://";function Ku(U){return ju(U,ld)}var ca="tfjs-backend-wasm.wasm";qu(ca)||(ca=g(ca));function ud(){try{if(F)return new Uint8Array(F);if(v)return v(ca);throw"both async and sync fetching of the wasm failed"}catch(U){Ts(U)}}function Xf(){return!F&&(p||d)&&typeof fetch=="function"&&!Ku(ca)?fetch(ca,{credentials:"same-origin"}).then(function(U){if(!U.ok)throw"failed to load wasm binary file at '"+ca+"'";return U.arrayBuffer()}).catch(function(){return ud()}):new Promise(function(U,ae){U(ud())})}function Yf(){var U={env:mr,wasi_snapshot_preview1:mr};function ae(Xe,je){var Ht=Xe.exports;s.asm=Ht,W=Ht.memory,it(W.buffer),No("wasm-instantiate")}Io("wasm-instantiate");function Ne(Xe){ae(Xe.instance)}function Ee(Xe){return Xf().then(function(je){return WebAssembly.instantiate(je,U)}).then(Xe,function(je){$("failed to asynchronously prepare wasm: "+je),Ts(je)})}function at(){if(!F&&typeof WebAssembly.instantiateStreaming=="function"&&!qu(ca)&&!Ku(ca)&&typeof fetch=="function")fetch(ca,{credentials:"same-origin"}).then(function(Xe){var je=WebAssembly.instantiateStreaming(Xe,U);return je.then(Ne,function(Ht){$("wasm streaming compile failed: "+Ht),$("falling back to ArrayBuffer instantiation"),Ee(Ne)})});else return Ee(Ne)}if(s.instantiateWasm)try{var Et=s.instantiateWasm(U,ae);return Et}catch(Xe){return $("Module.instantiateWasm callback failed with error: "+Xe),!1}return at(),{}}dt.push();function Jf(U){it(W.buffer)}var Ss={splitPath:function(U){var ae=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return ae.exec(U).slice(1)},normalizeArray:function(U,ae){for(var Ne=0,Ee=U.length-1;Ee>=0;Ee--){var at=U[Ee];at==="."?U.splice(Ee,1):at===".."?(U.splice(Ee,1),Ne++):Ne&&(U.splice(Ee,1),Ne--)}if(ae)for(;Ne;Ne--)U.unshift("..");return U},normalize:function(U){var ae=U.charAt(0)==="/",Ne=U.substr(-1)==="/";return U=Ss.normalizeArray(U.split("/").filter(function(Ee){return!!Ee}),!ae).join("/"),!U&&!ae&&(U="."),U&&Ne&&(U+="/"),(ae?"/":"")+U},dirname:function(U){var ae=Ss.splitPath(U),Ne=ae[0],Ee=ae[1];return!Ne&&!Ee?".":(Ee&&(Ee=Ee.substr(0,Ee.length-1)),Ne+Ee)},basename:function(U){if(U==="/")return"/";var ae=U.lastIndexOf("/");return ae===-1?U:U.substr(ae+1)},extname:function(U){return Ss.splitPath(U)[3]},join:function(){var U=Array.prototype.slice.call(arguments,0);return Ss.normalize(U.join("/"))},join2:function(U,ae){return Ss.normalize(U+"/"+ae)}},To={mappings:{},buffers:[null,[],[]],printChar:function(U,ae){var Ne=To.buffers[U];ae===0||ae===10?((U===1?C:$)(ie(Ne,0)),Ne.length=0):Ne.push(ae)},varargs:void 0,get:function(){To.varargs+=4;var U=_e[To.varargs-4>>2];return U},getStr:function(U){var ae=ee(U);return ae},get64:function(U,ae){return U}};function Zf(U){return 0}function hr(U,ae,Ne,Ee,at){}function Xu(U,ae,Ne,Ee){for(var at=0,Et=0;Et<Ne;Et++){for(var Xe=_e[ae+Et*8>>2],je=_e[ae+(Et*8+4)>>2],Ht=0;Ht<je;Ht++)To.printChar(U,xe[Xe+Ht]);at+=je}return _e[Ee>>2]=at,0}function Cs(U){Td(U)}function Qf(U){Cs(U)}function eg(U){return U=+U,U>=0?+Hu(U+.5):+ko(U-.5)}var mr={emscripten_notify_memory_growth:Jf,fd_close:Zf,fd_seek:hr,fd_write:Xu,proc_exit:Qf,roundf:eg},Yu=Yf();s.asm=Yu;var tg=s._init=function(){return(tg=s._init=s.asm.init).apply(null,arguments)},cd=s._register_tensor=function(){return(cd=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},ng=s._dispose_data=function(){return(ng=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},pd=s._dispose=function(){return(pd=s._dispose=s.asm.dispose).apply(null,arguments)},pa=s._Abs=function(){return(pa=s._Abs=s.asm.Abs).apply(null,arguments)},dd=s._Add=function(){return(dd=s._Add=s.asm.Add).apply(null,arguments)},ag=s._AddN=function(){return(ag=s._AddN=s.asm.AddN).apply(null,arguments)},rg=s._ArgMax=function(){return(rg=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},sg=s._AvgPool=function(){return(sg=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},ig=s._BatchMatMul=function(){return(ig=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},hd=s._ClipByValue=function(){return(hd=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},md=s._Conv2D=function(){return(md=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},fd=s._Conv2DBackpropInput=function(){return(fd=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},So=s._Cos=function(){return(So=s._Cos=s.asm.Cos).apply(null,arguments)},Ju=s._CropAndResize=function(){return(Ju=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},Co=s._Cumsum=function(){return(Co=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},_o=s._DepthToSpace=function(){return(_o=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},og=s._DepthwiseConv2dNative=function(){return(og=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},lg=s._Equal=function(){return(lg=s._Equal=s.asm.Equal).apply(null,arguments)},ug=s._Exp=function(){return(ug=s._Exp=s.asm.Exp).apply(null,arguments)},ye=s._FlipLeftRight=function(){return(ye=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},cg=s._Floor=function(){return(cg=s._Floor=s.asm.Floor).apply(null,arguments)},pg=s._FloorDiv=function(){return(pg=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},dg=s._FusedBatchNorm=function(){return(dg=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},hg=s._FusedConv2D=function(){return(hg=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},_s=s._FusedDepthwiseConv2D=function(){return(_s=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},mg=s._Gather=function(){return(mg=s._Gather=s.asm.Gather).apply(null,arguments)},fg=s._GatherNd=function(){return(fg=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},gg=s._Greater=function(){return(gg=s._Greater=s.asm.Greater).apply(null,arguments)},yg=s._GreaterEqual=function(){return(yg=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},bg=s._LeakyRelu=function(){return(bg=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},xg=s._Less=function(){return(xg=s._Less=s.asm.Less).apply(null,arguments)},vg=s._LessEqual=function(){return(vg=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},wg=s._Log=function(){return(wg=s._Log=s.asm.Log).apply(null,arguments)},kg=s._LogicalAnd=function(){return(kg=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},Ig=s._Max=function(){return(Ig=s._Max=s.asm.Max).apply(null,arguments)},zr=s._MaxPool=function(){return(zr=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Es=s._Maximum=function(){return(Es=s._Maximum=s.asm.Maximum).apply(null,arguments)},Eo=s._Mean=function(){return(Eo=s._Mean=s.asm.Mean).apply(null,arguments)},Ng=s._Min=function(){return(Ng=s._Min=s.asm.Min).apply(null,arguments)},Tg=s._Minimum=function(){return(Tg=s._Minimum=s.asm.Minimum).apply(null,arguments)},Sg=s._Multiply=function(){return(Sg=s._Multiply=s.asm.Multiply).apply(null,arguments)},Cg=s._Neg=function(){return(Cg=s._Neg=s.asm.Neg).apply(null,arguments)},Pe=s._NonMaxSuppressionV3=function(){return(Pe=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},_g=s._NonMaxSuppressionV4=function(){return(_g=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},Eg=s._NonMaxSuppressionV5=function(){return(Eg=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Ag=s._NotEqual=function(){return(Ag=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},Fg=s._OneHot=function(){return(Fg=s._OneHot=s.asm.OneHot).apply(null,arguments)},$g=s._PadV2=function(){return($g=s._PadV2=s.asm.PadV2).apply(null,arguments)},Dg=s._Pow=function(){return(Dg=s._Pow=s.asm.Pow).apply(null,arguments)},Zu=s._Prelu=function(){return(Zu=s._Prelu=s.asm.Prelu).apply(null,arguments)},gd=s._Prod=function(){return(gd=s._Prod=s.asm.Prod).apply(null,arguments)},yd=s._RealDiv=function(){return(yd=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},Mg=s._Relu=function(){return(Mg=s._Relu=s.asm.Relu).apply(null,arguments)},Rg=s._Relu6=function(){return(Rg=s._Relu6=s.asm.Relu6).apply(null,arguments)},Pg=s._ResizeBilinear=function(){return(Pg=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},Og=s._Reverse=function(){return(Og=s._Reverse=s.asm.Reverse).apply(null,arguments)},Lg=s._RotateWithOffset=function(){return(Lg=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},zg=s._Round=function(){return(zg=s._Round=s.asm.Round).apply(null,arguments)},Be=s._Rsqrt=function(){return(Be=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},Bg=s._ScatterNd=function(){return(Bg=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},Wg=s._SelectV2=function(){return(Wg=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},Vg=s._Sigmoid=function(){return(Vg=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},As=s._Sin=function(){return(As=s._Sin=s.asm.Sin).apply(null,arguments)},Ao=s._Softmax=function(){return(Ao=s._Softmax=s.asm.Softmax).apply(null,arguments)},bd=s._Sqrt=function(){return(bd=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},xd=s._Square=function(){return(xd=s._Square=s.asm.Square).apply(null,arguments)},vd=s._SquaredDifference=function(){return(vd=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},Ug=s._Step=function(){return(Ug=s._Step=s.asm.Step).apply(null,arguments)},Gg=s._StridedSlice=function(){return(Gg=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},wd=s._Sub=function(){return(wd=s._Sub=s.asm.Sub).apply(null,arguments)},Hg=s._Sum=function(){return(Hg=s._Sum=s.asm.Sum).apply(null,arguments)},Ha=s._Tanh=function(){return(Ha=s._Tanh=s.asm.Tanh).apply(null,arguments)},jg=s._Tile=function(){return(jg=s._Tile=s.asm.Tile).apply(null,arguments)},qg=s._TopK=function(){return(qg=s._TopK=s.asm.TopK).apply(null,arguments)},kd=s._Transpose=function(){return(kd=s._Transpose=s.asm.Transpose).apply(null,arguments)},Br=s.__FusedMatMul=function(){return(Br=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},Kg=s._malloc=function(){return(Kg=s._malloc=s.asm.malloc).apply(null,arguments)},Xg=s._free=function(){return(Xg=s._free=s.asm.free).apply(null,arguments)},Id=s.__start=function(){return(Id=s.__start=s.asm._start).apply(null,arguments)},Qu=s.stackSave=function(){return(Qu=s.stackSave=s.asm.stackSave).apply(null,arguments)},ec=s.stackAlloc=function(){return(ec=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},Nd=s.stackRestore=function(){return(Nd=s.stackRestore=s.asm.stackRestore).apply(null,arguments)};s.asm=Yu,s.cwrap=ne;var Fs;s.then=function(U){if(Fs)U(s);else{var ae=s.onRuntimeInitialized;s.onRuntimeInitialized=function(){ae&&ae(),U(s)}}return s};function tc(U){this.name="ExitStatus",this.message="Program terminated with exit("+U+")",this.status=U}var Yg=!1;Ta=function U(){Fs||nc(),Fs||(Ta=U)};function Jg(U){var ae=s.__start;try{ae();var Ne=0;Td(Ne,!0)}catch(at){if(at instanceof tc)return;if(at=="unwind"){O=!0;return}else{var Ee=at;at&&typeof at=="object"&&at.stack&&(Ee=[at,at.stack]),$("exception thrown: "+Ee),u(1,at)}}finally{Yg=!0}}function nc(U){if(U=U||l,Na>0||(An(),Na>0))return;function ae(){Fs||(Fs=!0,s.calledRun=!0,!H&&(oa(),wn(),s.onRuntimeInitialized&&s.onRuntimeInitialized(),Sd&&Jg(U),la()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),ae()},1)):ae()}s.run=nc;function Td(U,ae){ae&&O&&U===0||(O||(H=!0,K=U,cn(),s.onExit&&s.onExit(U)),u(U,new tc(U)))}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();var Sd=!0;return s.noInitialRun&&(Sd=!1),O=!0,nc(),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)}),cA=1e-7,pA=1e-4,Dd=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}},dc=class{decComplexRef(e){}time(e){return X("time")}read(e){return X("read")}readSync(e){return X("readSync")}numDataIds(){return X("numDataIds")}disposeData(e){return X("disposeData")}write(e,t,n){return X("write")}move(e,t,n,a){return X("move")}memory(){return X("memory")}floatPrecision(){return X("floatPrecision")}epsilon(){return this.floatPrecision()===32?cA:pA}batchMatMul(e,t,n,a){return X("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:a,bias:r,activation:s,preluActivationWeights:i}){return X("fusedBatchMatMul")}slice(e,t,n){return X("slice")}stridedSlice(e,t,n,a){return X("stridedSlice")}unstack(e,t){return X("unstack")}reverse(e,t){return X("reverse")}concat(e,t){return X("concat")}neg(e){return X("neg")}add(e,t){return X("add")}addN(e){return X("addN")}subtract(e,t){return X("subtract")}multiply(e,t){return X("multiply")}realDivide(e,t){return X("realDivide")}floorDiv(e,t){return X("floorDiv")}sum(e,t){return X("sum")}prod(e,t){return X("prod")}unsortedSegmentSum(e,t,n){return X("unsortedSegmentSum")}argMin(e,t){return X("argMin")}argMax(e,t){return X("argMax")}equal(e,t){return X("equal")}notEqual(e,t){return X("notEqual")}less(e,t){return X("less")}lessEqual(e,t){return X("lessEqual")}greater(e,t){return X("greater")}greaterEqual(e,t){return X("greaterEqual")}logicalNot(e){return X("logicalNot")}logicalAnd(e,t){return X("logicalAnd")}logicalOr(e,t){return X("logicalOr")}where(e){return X("where")}select(e,t,n){return X("select")}topk(e,t,n){return X("topk")}min(e,t){return X("min")}minimum(e,t){return X("minimum")}mod(e,t){return X("mod")}max(e,t){return X("max")}maximum(e,t){return X("maximum")}all(e,t){return X("all")}any(e,t){return X("any")}squaredDifference(e,t){return X("squaredDifference")}ceil(e){return X("ceil")}floor(e){return X("floor")}round(e){return X("round")}sign(e){return X("sign")}isNaN(e){return X("isNaN")}isInf(e){return X("isInf")}isFinite(e){return X("isFinite")}pow(e,t){return X("pow")}exp(e){return X("exp")}expm1(e){return X("expm1")}softmax(e,t){return X("softmax")}log(e){return X("log")}log1p(e){return X("log1p")}sqrt(e){return X("sqrt")}rsqrt(e){return X("rsqrt")}square(e){return X("square")}reciprocal(e){return X("reciprocal")}relu(e){return X("relu")}relu6(e){return X("relu6")}prelu(e,t){return X("prelu")}elu(e){return X("elu")}eluDer(e,t){return X("eluDer")}selu(e){return X("selu")}int(e){return X("int")}clip(e,t,n){return X("clip")}abs(e){return X("abs")}complexAbs(e){return X("complexAbs")}sigmoid(e){return X("sigmoid")}softplus(e){return X("softplus")}sin(e){return X("sin")}cos(e){return X("cos")}tan(e){return X("tan")}asin(e){return X("asin")}acos(e){return X("acos")}atan(e){return X("atan")}atan2(e,t){return X("atan2")}sinh(e){return X("sinh")}cosh(e){return X("cosh")}tanh(e){return X("tanh")}asinh(e){return X("asinh")}acosh(e){return X("acosh")}atanh(e){return X("atanh")}erf(e){return X("erf")}step(e,t){return X("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:a,activation:r,preluActivationWeights:s}){return X("fusedConv2d")}conv2d(e,t,n){return X("conv2d")}conv2dDerInput(e,t,n){return X("conv2dDerInput")}conv2dDerFilter(e,t,n){return X("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:a,activation:r,preluActivationWeights:s}){return X("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return X("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return X("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return X("depthwiseConv2DDerFilter")}conv3d(e,t,n){return X("conv3d")}conv3dDerInput(e,t,n){return X("conv3dDerInput")}conv3dDerFilter(e,t,n){return X("conv3dDerFilter")}maxPool(e,t){return X("maxPool")}maxPoolBackprop(e,t,n,a){return X("maxPoolBackprop")}avgPool(e,t){return X("avgPool")}avgPoolBackprop(e,t,n){return X("avgPoolBackprop")}avgPool3d(e,t){return X("avgPool3d")}avgPool3dBackprop(e,t,n){return X("avgPool3dBackprop")}maxPool3d(e,t){return X("maxPool3d")}maxPool3dBackprop(e,t,n,a){return X("maxPool3dBackprop")}reshape(e,t){return X("reshape")}cast(e,t){return X("cast")}tile(e,t){return X("tile")}pad(e,t,n){return X("pad")}transpose(e,t){return X("transpose")}gather(e,t,n,a=0){return X("gather")}gatherND(e,t){return X("gatherND")}scatterND(e,t,n){return X("scatterND")}batchToSpaceND(e,t,n){return X("batchToSpaceND")}spaceToBatchND(e,t,n){return X("spaceToBatchND")}resizeBilinear(e,t,n,a,r){return X("resizeBilinear")}resizeBilinearBackprop(e,t,n){return X("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,a,r){return X("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return X("resizeNearestNeighborBackprop")}batchNorm(e,t,n,a,r,s){return X("batchNorm")}localResponseNormalization4D(e,t,n,a,r){return X("localResponseNormalization4D")}LRNGrad(e,t,n,a,r,s,i){return X("LRNGrad")}multinomial(e,t,n,a){return X("multinomial")}oneHot(e,t,n,a){return X("oneHot")}cumsum(e,t,n,a){return X("cumsum")}nonMaxSuppression(e,t,n,a,r){return X("nonMaxSuppression")}fft(e){return X("fft")}ifft(e){return X("ifft")}complex(e,t){return X("complex")}real(e){return X("real")}imag(e){return X("imag")}cropAndResize(e,t,n,a,r,s){return X("cropAndResize")}depthToSpace(e,t,n){return X("depthToSpace")}split(e,t,n){return X("split")}sparseToDense(e,t,n,a){return X("sparseToDense")}diag(e){return X("diag")}fill(e,t,n){return X("fill")}onesLike(e){return X("onesLike")}zerosLike(e){return X("zerosLike")}linspace(e,t,n){return X("linspace")}dispose(){return X("dispose")}};function X(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 Jw(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 hc(e,t,n){return Math.max(e,Math.min(t,n))}function dA(e){return e%2==0?e:e+1}function hA(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function mA(e,t){let n=Math.random();return t*n+(1-n)*e}function fA(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 rt(e,t,n=""){A(yr(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function $s(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ds(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||ln(e)&&!n)for(let a=0;a<e.length;++a)Ds(e[a],t,n);else t.push(e);return t}function Lt(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 gA(e){return e.length===0}function yr(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 jt(e){return e%1==0}function yA(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 bA(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function xA(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Jw(t),t}function mc(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function vA(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 wA(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 da(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=>jt(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function Zw(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:da(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 Qw(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 e0(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 t0(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 n0(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function a0(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function ln(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function r0(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 s0(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Ur(e){return typeof e=="string"||e instanceof String}function i0(e){return typeof e=="boolean"}function o0(e){return typeof e=="number"}function Md(e){return Array.isArray(e)?Md(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":o0(e)?"float32":Ur(e)?"string":i0(e)?"bool":"float32"}function Gr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Rd(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Po(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 l0(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]=l0(e+o*i,s,n)}return a}function Oo(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 l0(0,e,t)}function ay(e,t){let n=Pd(e,t);for(let a=0;a<n.length;a++)n[a]=1;return n}function Pd(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 kA(e,t){let n=e.reduce((a,r)=>a*r,1);if(t==null||t==="float32")return Oo(e,new Float32Array(n));if(t==="int32")return Oo(e,new Int32Array(n));if(t==="bool")return Oo(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ry(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function IA(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 NA(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 sy(e){return e&&e.then&&typeof e.then=="function"}var u0="tfjsflags",c0=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(sy(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=TA(this.global.location.search);u0 in e&&e[u0].split(",").forEach(t=>{let[n,a]=t.split(":");this.urlFlags[n]=SA(n,a)})}};function TA(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(CA(t,a[0],a[1]),a.join("="))),t}function CA(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function SA(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 te(){return iy}var iy=null;function _A(e){iy=e}var oy;function p0(){if(oy==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");oy=e}return oy}function EA(){let e=p0();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function d0(e,t){let n=EA();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var Lo="Abs",zo="Acos",Bo="Acosh",Hr="Add",Ms="AddN",Od="All",Ld="Any",Rs="ArgMax",fc="ArgMin",Wo="Asin",Vo="Asinh",Uo="Atan",Go="Atanh",Ho="Atan2",Ps="AvgPool",zd="AvgPoolGrad",gc="AvgPool3D",Bd="AvgPool3DGrad",Os="BatchMatMul",yc="BatchToSpaceND",Wd="Bincount",h0="BroadcastTo",Ls="Cast",jo="Ceil",jr="ClipByValue",Vd="Complex",bc="ComplexAbs",qo="Concat",zs="Conv2D",Ud="Conv2DBackpropFilter",Bs="Conv2DBackpropInput",xc="Conv3D",Gd="Conv3DBackpropFilterV2",Hd="Conv3DBackpropInputV2",Ws="Cos",Ko="Cosh",Vs="Cumsum",Xo="CropAndResize",jd="DenseBincount",Yo="DepthToSpace",Us="DepthwiseConv2dNative",qd="DepthwiseConv2dNativeBackpropFilter",Kd="DepthwiseConv2dNativeBackpropInput",Xd="Diag",vc="Dilation2D",Yd="Dilation2DBackpropInput",Jd="Dilation2DBackpropFilter",Gs="RealDiv",Jo="Elu",Zd="EluGrad",Zo="Erf",Qo="Equal",Hs="Exp",el="ExpandDims",tl="Expm1",Qd="FFT",wc="Fill",nl="FlipLeftRight",js="Floor",qs="FloorDiv",Ks="FusedBatchNorm",al="GatherV2",rl="GatherNd",sl="Greater",Xs="GreaterEqual",il="Identity",eh="IFFT",th="Imag",ol="IsFinite",ll="IsInf",ul="IsNan",Ys="LeakyRelu",cl="Less",pl="LessEqual",nh="LinSpace",Js="Log",dl="Log1p",hl="LogicalAnd",kc="LogicalNot",Ic="LogicalOr",m0="LogSoftmax",Nc="LRN",ah="LRNGrad",Zs="Max",Qs="Maximum",ei="MaxPool",rh="MaxPoolGrad",Tc="MaxPool3D",sh="MaxPool3DGrad",ih="MaxPoolWithArgmax",ti="Mean",ni="Min",ai="Minimum",Sc="MirrorPad",ml="Mod",oh="Multinomial",ri="Multiply",fl="Neg",gl="NotEqual",yl="NonMaxSuppressionV3",bl="NonMaxSuppressionV4",xl="NonMaxSuppressionV5",vl="OnesLike",si="OneHot",wl="Pack",ii="PadV2",AA="Pool",oi="Pow",li="Prelu",kl="Prod",Cc="Range",lh="Real",Il="Reciprocal",ui="Relu",Nl="Reshape",_c="ResizeNearestNeighbor",uh="ResizeNearestNeighborGrad",ci="ResizeBilinear",ch="ResizeBilinearGrad",pi="Relu6",di="Reverse",hi="Round",mi="Rsqrt",Tl="ScatterNd",Sl="Select",Cl="Selu",_l="Slice",fi="Sin",El="Sinh",Al="Sign",gi="Sigmoid",Fl="Softplus",yi="Sqrt",bi="Sum",Ec="SpaceToBatchND",$l="SplitV",xi="Softmax",vi="SquaredDifference",Ac="Square",wi="Sub",ph="SparseToDense",Dl="StridedSlice",Ml="Tan",ki="Tanh",qr="Tile",Rl="TopK",Ii="Transpose",dh="Unique",Pl="Unpack",Fc="UnsortedSegmentSum",Ol="ZerosLike",Kr="Step",hh="FromPixels",Ll="RotateWithOffset",Ni="_FusedMatMul",Ti="FusedConv2D",Si="FusedDepthwiseConv2D",zl=d0("kernelRegistry",()=>new Map),$c=d0("gradRegistry",()=>new Map);function uy(e,t){let n=ly(e,t);return zl.get(n)}function cy(e){return $c.get(e)}function mh(e){let t=zl.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 Dc(e){let{kernelName:t,backendName:n}=e,a=ly(t,n);zl.has(a)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),zl.set(a,e)}function f0(e){let{kernelName:t}=e;$c.has(t)&&te().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),$c.set(t,e)}function FA(e,t){let n=ly(e,t);if(!zl.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);zl.delete(n)}function $A(e){if(!$c.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);$c.delete(e)}function DA(e,t){mh(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});Dc(a)})}function ly(e,t){return`${t}_${e}`}var k={};Oe(k,{arraysEqual:()=>yr,assert:()=>A,assertNonNegativeIntegerDimensions:()=>ry,assertNonNull:()=>$s,assertShapesMatch:()=>rt,bytesFromStringArray:()=>s0,bytesPerElement:()=>r0,checkConversionForErrors:()=>t0,clamp:()=>hc,computeStrides:()=>Po,createScalarValue:()=>MA,createShuffledIndices:()=>xA,decodeString:()=>gh,distSquared:()=>fA,encodeString:()=>Mc,fetch:()=>RA,flatten:()=>Ds,getArrayFromDType:()=>e0,getTypedArrayFromDType:()=>Qw,hasEncodingLoss:()=>a0,indexToLoc:()=>NA,inferDtype:()=>Md,inferFromImplicitShape:()=>wA,isBoolean:()=>i0,isFunction:()=>Gr,isInt:()=>jt,isNumber:()=>o0,isPromise:()=>sy,isScalarShape:()=>gA,isString:()=>Ur,isTypedArray:()=>ln,isValidDtype:()=>n0,locToIndex:()=>IA,makeOnesTypedArray:()=>ay,makeZerosNestedTypedArray:()=>kA,makeZerosTypedArray:()=>Pd,nearestDivisor:()=>Rd,nearestLargerEven:()=>dA,now:()=>py,parseAxisParam:()=>da,randUniform:()=>mA,repeatedTry:()=>vA,rightPad:()=>mc,shuffle:()=>Jw,sizeFromShape:()=>Lt,sizeToSquarishShape:()=>bA,squeezeShape:()=>Zw,sum:()=>hA,tanh:()=>yA,toNestedArray:()=>Oo,toTypedArray:()=>fh});function MA(e,t){return t==="string"?Mc(e):fh([e],t)}function PA(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function fh(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ds(e)),te().getBool("DEBUG")&&t0(e,t),PA(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 py(){return te().platform.now()}function RA(e,t){return te().platform.fetch(e,t)}function Mc(e,t="utf-8"){return t=t||"utf-8",te().platform.encode(e,t)}function gh(e,t="utf-8"){return t=t||"utf-8",te().platform.decode(e,t)}var zA=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new LA)}profileKernel(e,t,n){let a,r=()=>{a=n()},s=this.backendTimer.time(r);if(te().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let i=0;i<a.length;i++){let o=a[i];o.data().then(l=>{OA(l,o.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(i=>i.kernelMs),extraInfo:s.then(i=>i.getExtraProfileInfo!=null?i.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 OA(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 LA=class{logKernelProfile(e,t,n,a,r,s){let i=typeof a=="number"?mc(`${a}ms`,9):a.error,o=mc(e,25),l=t.rank,c=t.size,u=mc(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 BA(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 WA(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(!yr(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 g0=20,Rc=3,dy=7;function UA(e,t,n,a){let r=Po(t),s=VA(e,t,n,r),i=t.length,o=yh(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 VA(e,t,n,a){let r=Lt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Oc(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],Pc(l[u+p],0,n).length)}return i}function Pc(e,t,n){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(dy))} + ${parseFloat(e[1].toFixed(dy))}j`:Ur(e)?a=`'${e}'`:n==="bool"?a=y0(e):a=parseFloat(e.toFixed(dy)).toString(),mc(a,t)}function y0(e){return e===0?"false":"true"}function yh(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=Oc(e);return[Pc(f[0],0,n)]}return n==="bool"?[y0(e[0])]:[e[0].toString()]}if(l===1){if(o>g0){let g=Rc*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o-Rc)*i,o*i));return n==="complex64"&&(y=Oc(y),b=Oc(b)),["["+y.map((v,x)=>Pc(v,r[x],n)).join(", ")+", ..., "+b.map((v,x)=>Pc(v,r[o-Rc+x],n)).join(", ")+"]"]}let f=n==="complex64"?Oc(e):Array.from(e);return["["+f.map((g,y)=>Pc(g,r[y],n)).join(", ")+"]"]}let c=t.slice(1),u=a.slice(1),p=a[0]*i,d=[];if(o>g0){for(let f=0;f<Rc;f++){let g=f*p,y=g+p;d.push(...yh(e.slice(g,y),c,n,u,r,!1))}d.push("...");for(let f=o-Rc;f<o;f++){let g=f*p,y=g+p;d.push(...yh(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(...yh(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 Oc(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var zt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Lt(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||e0(t,this.size),this.strides=Po(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 ja().makeTensor(this.values,this.shape,this.dtype)}},ja=null,Bl=null,GA=null;function HA(e){ja=e}function jA(e){Bl=e}function qA(e){GA=e}var z=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Lt(e),this.strides=Po(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 Bl.buffer(this.shape,this.dtype,e)}bufferSync(){return Bl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Oo(this.shape,e)}arraySync(){return Oo(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=ja().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>gh(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=ja().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>gh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await ja().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(ja().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bl.print(this,e)}clone(){return this.throwIfDisposed(),Bl.clone(this)}toString(e=!1){let t=this.dataSync();return UA(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ja().makeVariable(this,e,t,n)}};Object.defineProperty(z,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});var Xr=class extends z{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(!yr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ja().disposeTensor(this),this.dataId=e.dataId,ja().incRef(this,null)}dispose(){ja().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Xr,Symbol.hasInstance,{value:e=>e instanceof z&&e.assign!=null&&e.assign instanceof Function});var Sa={};Oe(Sa,{assertTypesMatch:()=>b0,getTensorsInContainer:()=>hy,isTensorInList:()=>KA,makeTypesMatch:()=>Tt});var my;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(my||(my={}));var fy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(fy||(fy={}));var gy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(gy||(gy={}));var yy;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(yy||(yy={}));var by;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(by||(by={}));var XA={float32:yy,int32:fy,bool:gy,complex64:by};function ha(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return XA[e][t]}function bh(e){return ha(e,"int32")}function Tt(e,t){if(e.dtype===t.dtype)return[e,t];let n=ha(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function b0(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function KA(e,t){return t.some(n=>n.id===e.id)}function hy(e){let t=[],n=new Set;return x0(e,t,n),t}function x0(e,t,n){if(e==null)return;if(e instanceof z){t.push(e);return}if(!YA(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),x0(s,t,n))}}function YA(e){return Array.isArray(e)||typeof e=="object"}var v0=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()}},Lc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new v0}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 zA(this.backendInstance),!0}setupRegisteredKernels(){mh(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){mh(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 dc)&&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);a.disposeData(t),n.backend=e,e.move(t,r,n.shape,n.dtype),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 Lc.nextTensorId++}nextVariableId(){return Lc.nextVariableId++}clone(e){let t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return P.runKernelFunc(c=>c.cast(s,i),o,null,Ls,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n,a,r){let s=null,i=null;return this.runKernelFunc(s,t,i,e,n,a,r)}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,t,n,a,r,s,i){let o,l=[],c=this.isTapeOn();a==null&&(a=this.state.activeScope!=null?this.state.activeScope.name:"");let u=this.state.numBytes,p=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let d;this.backendName==null&&this.backend;let h=uy(a,this.backendName),m;if(h!=null)d=()=>{let g=this.backend.numDataIds();m=h.kernelFunc({inputs:t,attrs:r,backend:this.backend});let y=Array.isArray(m)?m:[m];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(a,g,y);let b=y.map(v=>{if(v.rank!=null)return v;let{dataId:x,shape:N,dtype:T}=v;return this.makeTensorFromDataId(x,N,T)});if(c){let v=this.getTensorsForGradient(a,t,b);if(v==null){i==null&&(i=[]);let x=b.filter((N,T)=>i[T]);v=(s||[]).slice().concat(x)}l=this.saveTensorsForBackwardMode(v)}return b};else{if(e==null)throw new Error(`Error running ${a}: Neither modular kernel nor forward func passed`);let g=y=>{!c||(l=y.map(b=>this.keep(this.clone(b))))};d=()=>{let y=this.backend.numDataIds();m=this.tidy(()=>e(this.backend,g));let b=Array.isArray(m)?m:[m];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(a,y,b),b}}let f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?o=d():(f=this.profiler.profileKernel(a,t,()=>d()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),o=f.outputs)}),c&&this.addTapeNode(a,t,o,n,l,r),this.state.profiling&&this.state.activeProfile.kernels.push({name:a,bytesAdded:this.state.numBytes-u,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-p,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(g=>t[g]!=null?t[g].shape:null),outputShapes:o.map(g=>g.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(m)?o:o[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=cy(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 null}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"&&Ur(e[0])&&(r=e.map(o=>Mc(o)));let s=a.write(r,t,n),i=new z(t,n,s,this.nextTensorId());if(this.incRef(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=s0(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r=new z(t,n,e,this.nextTensorId());return this.incRef(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 Xr(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}incRef(e,t){let n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;let a=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(a=e.size*r0(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:a,refCount:0}),this.state.numBytes+=a}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Xr||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;let t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):(t.backend.decComplexRef(e.dataId),this.state.tensorInfo.get(e.dataId).refCount--)}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=cy(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((c,u)=>{if(c==null){let p=n[u],d=Pd(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=hy(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 z,()=>"The result y returned by f() must be a tensor.");let s=BA(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?JA(r.shape):n,WA(i,s,l=>this.tidy(l),ZA);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(Gr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(r=>r instanceof z),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};return t.forEach((r,s)=>{a[s]=r}),this.runKernelFunc((r,s)=>(n=e(...t,s),A(n.value instanceof z,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(Gr(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a,(r,s)=>{let i=n.gradFunc(r,s),o=Array.isArray(i)?i:[i];A(o.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(o.every(c=>c instanceof z),()=>"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 l={};return o.forEach((c,u)=>{l[u]=()=>c}),l})}}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=py(),n=await this.backend.time(e);return n.wallMs=py()-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 v0;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}};Lc.nextTensorId=0;Lc.nextVariableId=0;function JA(e){let t=ay(Lt(e),"float32");return P.makeTensor(t,e,"float32")}function w0(){let e=p0();if(e._tfengine==null){let t=new c0(e);e._tfengine=new Lc(t)}return _A(e._tfengine.ENV),HA(()=>e._tfengine),e._tfengine}var P=w0();function ZA(e,t){let n={a:e,b:t};return P.runKernel(Hr,n)}var xh={};Oe(xh,{isBrowser:()=>k0,isMobile:()=>QA});function eF(){return typeof navigator!="undefined"&&navigator!=null}function QA(){if(eF()){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 k0(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var qa=te();qa.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});qa.registerFlag("IS_BROWSER",()=>k0());qa.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");qa.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));qa.registerFlag("PROD",()=>!1);qa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>qa.getBool("DEBUG"));qa.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);qa.registerFlag("IS_TEST",()=>!1);qa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);function Ka(e,t){let n=e;if(ln(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||ln(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&te().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&I0(e,a,[]),a}function I0(e,t,n){if(n=n||[],!Array.isArray(e)&&!ln(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)I0(e[r],a,n.concat(r))}function N0(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,t,n,a="numeric"){if(e instanceof z)return N0(a,e.dtype,t,n),e;let r=Md(e);if(r!=="string"&&["bool","int32","float32"].indexOf(a)>=0&&(r=a),N0(a,r,t,n),e==null||!ln(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=Ka(e,r);!ln(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?fh(e,r):Ds(e,[],!0);return P.makeTensor(i,s,r)}function zc(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)=>_(r,`${t}[${s}]`,n,a))}var T0="__op";function R(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+T0;let r=(...s)=>{P.startScope(n);try{let i=a(...s);return sy(i)&&console.error("Cannot return a Promise inside of tidy."),P.endScope(i),i}catch(i){throw P.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function tF(e,t){let n=_(e,"real","complex"),a=_(t,"imag","complex");rt(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 P.runKernel(Vd,r)}var Yr=R({complex_:tF});function Jr(e,t,n,a){if(a==null&&(a=Md(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!ln(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){ry(t);let r=Lt(t),s=Lt(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!==Lt(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!ln(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?fh(e,a):Ds(e,[],!0),P.makeTensor(e,t,a)}function Xn(e,t,n){let a=Ka(e,n);return Jr(e,t,a,n)}var xy={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},vh=4;async function aF(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)+vh*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+=vh,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:nF(s),specs:n}}function S0(e,t){let n={},a,r=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,c=Lt(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=xy[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=rF()),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=Lt(s.shape);u=[];for(let d=0;d<p;d++){let h=new Uint32Array(e.slice(r,r+vh))[0];r+=vh;let m=new Uint8Array(e.slice(r,r+h));u.push(m),r+=h}}else{let p=xy[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=Xn(h,l,"float32"),g=Xn(m,l,"float32");n[i]=Yr(f,g),f.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=c*p}o!=="complex64"&&(n[i]=Xn(u,l,o))}return n}function nF(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 vy=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function C0(e){return vy?Buffer.byteLength(e):new Blob([e]).size}function sF(e){if(vy)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 iF(e){if(vy){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 wy(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 _0(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 Bc(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:C0(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:C0(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function oF(){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 lF(){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 uF(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function rF(){let e=oF(),t=lF(),n=uF();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 At=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return At.instance==null&&(At.instance=new At),At.instance}static registerSaveRouter(e){At.getInstance().saveRouters.push(e)}static registerLoadRouter(e){At.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return At.getHandlers(e,"save")}static getLoadHandlers(e,t){return At.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?At.getInstance().loadRouters:At.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},cF=e=>At.registerSaveRouter(e),pF=e=>At.registerLoadRouter(e),dF=e=>At.getSaveHandlers(e),hF=(e,t)=>At.getLoadHandlers(e,t),ky="tensorflowjs",Iy=1,Ci="models_store",Zr="model_info_store";function E0(){if(!te().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 Ny(e){let t=e.result;t.createObjectStore(Ci,{keyPath:"modelPath"}),t.createObjectStore(Zr,{keyPath:"modelPath"})}var _i=class{constructor(e){if(this.indexedDB=E0(),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(ky,Iy);r.onupgradeneeded=()=>Ny(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(Ci,"readonly"),o=i.objectStore(Ci).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=Bc(t),o=s.transaction(Zr,"readwrite"),l=o.objectStore(Zr),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),u;c.onsuccess=()=>{u=s.transaction(Ci,"readwrite");let p=u.objectStore(Ci).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});p.onsuccess=()=>n({modelArtifactsInfo:i}),p.onerror=d=>{l=o.objectStore(Zr);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)})}};_i.URL_SCHEME="indexeddb://";var A0=e=>te().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(_i.URL_SCHEME)?mF(e.slice(_i.URL_SCHEME.length)):null;At.registerSaveRouter(A0);At.registerLoadRouter(A0);function mF(e){return new _i(e)}function fF(e){return e.startsWith(_i.URL_SCHEME)?e.slice(_i.URL_SCHEME.length):e}var gF=class{constructor(){this.indexedDB=E0()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(ky,Iy);n.onupgradeneeded=()=>Ny(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(Zr,"readonly"),s=r.objectStore(Zr).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=fF(e),new Promise((t,n)=>{let a=this.indexedDB.open(ky,Iy);a.onupgradeneeded=()=>Ny(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(Zr,"readwrite"),i=s.objectStore(Zr),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(Ci,"readwrite");let p=l.objectStore(Ci).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)})}},br="/",Wl="tensorflowjs_models",F0="info",yF="model_topology",bF="weight_specs",xF="weight_data",vF="model_metadata";function $0(e){return{info:[Wl,e,F0].join(br),topology:[Wl,e,yF].join(br),weightSpecs:[Wl,e,bF].join(br),weightData:[Wl,e,xF].join(br),modelMetadata:[Wl,e,vF].join(br)}}function wF(e){let t=e.split(br);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(br)}function kF(e){return e.startsWith(Ei.URL_SCHEME)?e.slice(Ei.URL_SCHEME.length):e}var Ei=class{constructor(e){if(!te().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=$0(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=Bc(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,sF(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=iF(s),t}};Ei.URL_SCHEME="localstorage://";var D0=e=>te().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ei.URL_SCHEME)?IF(e.slice(Ei.URL_SCHEME.length)):null;At.registerSaveRouter(D0);At.registerLoadRouter(D0);function IF(e){return new Ei(e)}var NF=class{constructor(){A(te().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=Wl+br,n=br+F0;for(let a=0;a<this.LS.length;++a){let r=this.LS.key(a);if(r.startsWith(t)&&r.endsWith(n)){let s=wF(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=kF(e);let t=$0(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}},Vl="://",Yn=class{constructor(){this.managers={}}static getInstance(){return Yn.instance==null&&(Yn.instance=new Yn),Yn.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Vl)&&(e=e.slice(0,e.indexOf(Vl))),A(e.length>0,()=>"scheme must not be an empty string.");let n=Yn.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 wh(e){if(e.indexOf(Vl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Yn.getSchemes().join(",")}`);return{scheme:e.split(Vl)[0],path:e.split(Vl)[1]}}async function M0(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=At.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=At.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=wh(e).scheme,l=wh(e).path,c=o===wh(e).scheme,u=await r.load();n&&c&&await Yn.getManager(o).removeModel(l);let p=await i.save(u);return n&&!c&&await Yn.getManager(o).removeModel(l),p.modelArtifactsInfo}async function TF(){let e=Yn.getSchemes(),t={};for(let n of e){let a=await Yn.getManager(n).listModels();for(let r in a){let s=n+Vl+r;t[s]=a[r]}}return t}async function SF(e){let t=wh(e);return Yn.getManager(t.scheme).removeModel(t.path)}async function CF(e,t){return M0(e,t,!1)}async function _F(e,t){return M0(e,t,!0)}var EF=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(te().get("IS_BROWSER")){te().setPlatform("browser",new EF);try{Yn.registerManager(Ei.URL_SCHEME,new NF)}catch(e){}try{Yn.registerManager(_i.URL_SCHEME,new gF)}catch(e){}}var AF={importFetch:()=>YE()},Ty,FF=class{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return te().global.fetch!=null?te().global.fetch(e,t):(Ty==null&&(Ty=AF.importFetch()),Ty(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)}};te().get("IS_NODE")&&te().setPlatform("node",new FF);function Le(e,t="float32",n){return t=t||"float32",ry(e),new zt(e,t,n)}function $F(e,t){let n=_(e,"x","cast");if(!n0(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 P.runKernel(Ls,a,r)}var pe=R({cast_:$F});function DF(e){let t={x:_(e,"x","clone","string_or_numeric")};return P.runKernel(il,t)}var Qr=R({clone_:DF});function R0(e,t=!1){console.log(e.toString(t))}w0();var MF={buffer:Le,cast:pe,clone:Qr,print:R0};jA(MF);var qt={};Oe(qt,{browserFiles:()=>RF,browserHTTPRequest:()=>OF,concatenateArrayBuffers:()=>wy,copyModel:()=>CF,decodeWeights:()=>S0,encodeWeights:()=>aF,fromMemory:()=>LF,getLoadHandlers:()=>hF,getModelArtifactsInfoForJSON:()=>Bc,getSaveHandlers:()=>dF,http:()=>Cy,isHTTPScheme:()=>Sy,listModels:()=>TF,loadWeights:()=>PF,moveModel:()=>_F,registerLoadRouter:()=>pF,registerSaveRouter:()=>cF,removeModel:()=>SF,weightsLoaderFactory:()=>P0,withSaveHandler:()=>zF});var BF="model",WF=".json",VF=".weights.bin";function O0(e){return new Promise(t=>setTimeout(t)).then(e)}var Ul=class{constructor(e){if(!te().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ul.URL_SCHEME)&&(e=e.slice(Ul.URL_SCHEME.length)),(e==null||e.length===0)&&(e=BF),this.modelTopologyFileName=e+WF,this.weightDataFileName=e+VF}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 O0(()=>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 O0(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Bc(e)}}}};Ul.URL_SCHEME="downloads://";var UF=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:wy(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=>_0(s.name)),r={};for(let s of e)s.paths.forEach(i=>{let o=_0(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}},HF=e=>te().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ul.URL_SCHEME)?GF(e.slice(Ul.URL_SCHEME.length)):null;At.registerSaveRouter(HF);function GF(e="model"){return new Ul(e)}function RF(e){return new UF(e)}function L0(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 z0(e,t){t==null&&(t={});let n=t.fetchFunc==null?te().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 L0(a,t.onProgress,r,s)).map(c=>c.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await L0(i,t.onProgress,o,l)}async function PF(e,t="",n,a){return P0(r=>z0(r,{requestInit:a}))(e,t,n)}function P0(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=xy[y]*Lt(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=S0(x,[v.manifestEntry]);for(let T in N)p[T]=N[T]}),d+=m}),p}}var jF="application/octet-stream",qF="application/json",_y=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(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=te().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:qF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:jF}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Bc(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]=KF(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 z0(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,wy(l)]}};_y.URL_SCHEME_REGEX=/^https?:\/\//;function KF(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function Sy(e){return e.match(_y.URL_SCHEME_REGEX)!=null}var B0=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>Sy(a)):n=Sy(e),n)return Cy(e,t)}return null};At.registerSaveRouter(B0);At.registerLoadRouter(B0);function Cy(e,t){return new _y(e,t)}function OF(e,t){return Cy(e,t)}var Ey=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},XF=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function LF(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Ey(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 Ey({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 Ey({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function zF(e){return new XF(e)}var W0={};Oe(W0,{confusionMatrix:()=>YF});function JF(e,t,n=!1,a=!1){let r=_(e,"a","matMul"),s=_(t,"b","matMul");[r,s]=Tt(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return P.runKernel(Os,i,o)}var ze=R({matMul_:JF});function ZF(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,"indices","oneHot","int32")},s={depth:t,onValue:n,offValue:a};return P.runKernel(si,r,s)}var Gl=R({oneHot_:ZF});function QF(e,t){let n=_(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 P.runKernel(Ii,a,r)}var Ue=R({transpose_:QF});function e$(e,t,n){let a=_(e,"labels","confusionMatrix"),r=_(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=Gl(pe(a,"int32"),n),i=Gl(pe(r,"int32"),n),o=Ue(s),l=ze(o,i);return pe(l,"int32")}var YF=R({confusionMatrix_:e$}),Ai={};Oe(Ai,{fromPixels:()=>n$,toPixels:()=>t$});function kh(e,t,n){if($s(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=Ka(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 Jr(e,t,a,n)}var Hl;function a$(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(uy(hh,P.backendName)!=null){let d={pixels:e},h={numChannels:t};return P.runKernel(hh,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)&&(Hl==null&&(Hl=document.createElement("canvas").getContext("2d")),Hl.canvas.width=l,Hl.canvas.height=c,Hl.drawImage(e,0,0,l,c),u=Hl.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 kh(p,[c,l,t],"int32")}async function t$(e,t){let n=_(e,"img","toPixels");if(!(e instanceof z)){let c=n;n=pe(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 n$=R({fromPixels_:a$}),Ay={};Oe(Ay,{prepareAndValidate:()=>V0});function V0(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(Lt(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=[...Po(e.shape).map(p=>p/c),1].slice(0,s);return[l,i,c,u]}var Fy={};Oe(Fy,{calculateShapes:()=>U0,validateInput:()=>Dy,validateUpdateShape:()=>$y});function $y(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 Dy(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}`)}$y(n,t,e)}function U0(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=Lt(t.shape)/o,c=[...Po(n.slice(0,r)),1],u=Lt(n);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:c,outputSize:u}}var dn={};Oe(dn,{assertParamsValid:()=>r$,computeFlatOffset:()=>i$,computeOutShape:()=>G0,getNormalizedAxes:()=>j0,isSliceContinous:()=>s$,maskToAxes:()=>Ih,parseSliceParams:()=>Z0,sliceInfo:()=>o$,startForAxis:()=>Y0,startIndicesWithElidedDims:()=>q0,stopForAxis:()=>J0,stopIndicesWithElidedDims:()=>K0,stridesForAxis:()=>X0,stridesWithElidedDims:()=>H0});function r$(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 Ih(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function G0(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 H0(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 Q0(e,t,n){return n<=e?n:n-(t-1)}function e1(e,t){let n=[];for(let a=0;a<e;a++)n.push(t+a);return n}function j0(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=q0(i,h,m,a,e),p=K0(o,h,m,r,e),d=H0(s,h,m,e)}else for(let h=0;h<c;h++)u[h]=Y0(i,a,s,e,h,l),p[h]=J0(o,r,s,e,h,l),d[h]=X0(s,h,l);return{begin:u,end:p,strides:d}}function q0(e,t,n,a,r){let s=[...r],i=e1(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=Q0(t,n,o),c=a[l];e&1<<l&&(c=0),s[o]=c}return s}function K0(e,t,n,a,r){let s=[...r],i=e1(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=Q0(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]=hc(0,s[o],r[o])}return s}function X0(e,t,n){let a=e[t];return(n&1<<t||a==null)&&(a=1),a}function Y0(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=hc(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=hc(0,i,l):i=hc(-1,i,l-1),i}function s$(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 i$(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 Z0(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 o$(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=Ih(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=Ih(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}=j0(f,d,h,c,u,p,r,s,i);c=g,u=y,p=b;let v=Ih(l);v.forEach(T=>{u[T]=c[T]+1,p[T]=1});let x=G0(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:()=>t1,SerializationMap:()=>Fi,registerClass:()=>es});var t1=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Fi=class{constructor(){this.classNameMap={}}static getMap(){return Fi.instance==null&&(Fi.instance=new Fi),Fi.instance}static register(e){Fi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function es(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."),Fi.register(e)}var n1={};Oe(n1,{TEST_EPSILON_FLOAT16:()=>a1,encodeStrings:()=>r1,expectArrayBuffersEqual:()=>h$,expectArraysClose:()=>l$,expectArraysEqual:()=>c$,expectNumbersClose:()=>p$,expectPromiseToFail:()=>u$,expectValuesInRange:()=>d$,testEpsilon:()=>My});var m$=.001,a1=.1;function l$(e,t,n){return n==null&&(n=My()),Ry(e,t,(a,r)=>Py(a,r,n))}function My(){return P.backend.floatPrecision()===32?m$:a1}function Ry(e,t,n){let a=!0;if((ln(e)||ln(t))&&(a=!1),ln(e)&&ln(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=Ka(e),o=Ka(t);if(!yr(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=ln(e)?e:Ds(e),s=ln(t)?t:Ds(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 u$(e,t){e().then(()=>t.fail(),()=>t())}function c$(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ur(e)||Ur(e[0])||Ur(t)||Ur(t[0])?Ry(e,n,(a,r)=>a==r):Ry(e,t,(a,r)=>Py(a,r,0))}function p$(e,t,n){if(n==null&&(n=My()),!Py(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Py(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function d$(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 h$(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function r1(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?r1(n):e[t]=Mc(n)}return e}var s1="2.8.5";function f$(){te().set("PROD",!0)}function g$(){te().set("DEBUG",!0)}function y$(){te().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Rt(e){te().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}qA(Rt);function b$(){P.disposeVariables()}function ts(){return P}function Nh(){return P.memory()}function x$(e){return P.profile(e)}function D(e,t){return P.tidy(e,t)}function Fe(e){hy(e).forEach(t=>t.dispose())}function Kt(e){return P.keep(e)}function v$(e){return P.time(e)}function w$(e){return P.setBackend(e)}function k$(){return P.ready()}function I$(){return P.backendName}function N$(e){P.removeBackend(e)}function T$(e){return P.findBackend(e)}function S$(e){return P.findBackendFactory(e)}function Th(e,t,n=1){return P.registerBackend(e,t,n)}function i1(){return P.backend}function C$(e,t){te().setPlatform(e,t)}function _$(e,t){let n=_(e,"a","add"),a=_(t,"b","add");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(Hr,r)}var Z=R({add_:_$});function E$(e,t){let n=_(e,"a","floorDiv"),a=_(t,"b","floorDiv");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(qs,r)}var Sh=R({floorDiv_:E$});function A$(e,t){let n=_(e,"a","div"),a=_(t,"b","div");if([n,a]=Tt(n,a),n.dtype==="int32"&&a.dtype==="int32")return Sh(n,a);let r={a:n,b:a},s={};return P.runKernel(Gs,r,s)}var we=R({div_:A$});function F$(e,t){let n=_(e,"a","mul"),a=_(t,"b","mul");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(ri,r)}var L=R({mul_:F$});function $$(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return P.runKernel(bc,n)}else{let n={x:t};return P.runKernel(Lo,n)}}var Bt=R({abs_:$$});function D$(e){let t={x:_(e,"x","acos")};return P.runKernel(zo,t)}var Oy=R({acos_:D$});function M$(e){let t={x:_(e,"x","acosh")};return P.runKernel(Bo,t)}var Ly=R({acosh_:M$});function R$(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)=>_(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(!yr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return P.runKernel(Ms,a)}var o1=R({addN_:R$});function P$(e,t=null,n=!1){let a={x:_(e,"x","all","bool")},r={axis:t,keepDims:n};return P.runKernel(Od,a,r)}var Ch=R({all_:P$});function O$(e,t=null,n=!1){let a={x:_(e,"x","any","bool")},r={axis:t,keepDims:n};return P.runKernel(Ld,a,r)}var Wc=R({any_:O$});function L$(e,t=0){let n={x:_(e,"x","argMax")},a={axis:t};return P.runKernel(Rs,n,a)}var Vc=R({argMax_:L$});function z$(e,t=0){let n={x:_(e,"x","argMin")},a={axis:t};return P.runKernel(fc,n,a)}var zy=R({argMin_:z$});function B$(e){let t={x:_(e,"x","asin")};return P.runKernel(Wo,t)}var By=R({asin_:B$});function W$(e){let t={x:_(e,"x","asinh")};return P.runKernel(Vo,t)}var Wy=R({asinh_:W$});function V$(e){let t={x:_(e,"x","atan")};return P.runKernel(Uo,t)}var Vy=R({atan_:V$});function U$(e,t){let n=_(e,"a","atan2"),a=_(t,"b","atan2");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(Ho,r)}var Uy=R({atan2_:U$});function G$(e){let t={x:_(e,"x","atanh")};return P.runKernel(Go,t)}var Gy=R({atanh_:G$});function H$(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=l1(r);return Uc(e,o,n,s,a,null,null,l)}function u1(e,t,n,a,r,s,i="channelsLast"){let[o,l]=_h(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 Uc(e,c,n,a,r,s,!1,i)}function j$(e,t,n,a,r,s,i="NDHWC"){let[o,l,c]=Hy(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 c1(e,u,n,a,r,!1,p,s)}function Uc(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]=_h(n),[y,b]=_h(a),v=jl(d,y),x=jl(h,b),{padInfo:N,outHeight:T,outWidth:C}=q$(r,c,u,f,g,v,x,s,o),$=i?m*p:m,F;return o==="channelsFirst"?F=[l,$,T,C]:o==="channelsLast"&&(F=[l,T,C,$]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:p,outHeight:T,outWidth:C,outChannels:$,padInfo:N,strideHeight:f,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:v,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:e,outShape:F,filterShape:t}}function c1(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]=Hy(n),[x,N,T]=Hy(a),C=jl(h,x),$=jl(m,N),F=jl(f,T),{padInfo:O,outDepth:W,outHeight:V,outWidth:H}=K$(r,c,u,p,y,b,v,C,$,F,o),K=s?g*d:g,j;return i==="channelsFirst"?j=[l,K,W,V,H]:i==="channelsLast"&&(j=[l,W,V,H,K]),{batchSize:l,dataFormat:i,inDepth:c,inHeight:u,inWidth:p,inChannels:d,outDepth:W,outHeight:V,outWidth:H,outChannels:K,padInfo:O,strideDepth:y,strideHeight:b,strideWidth:v,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:$,effectiveFilterWidth:F,dilationDepth:x,dilationHeight:N,dilationWidth:T,inShape:e,outShape:j,filterShape:t}}function X$(e,t,n,a,r){a==null&&(a=jy(e,t,n));let s=e[0],i=e[1],o=$i((s-t+2*a)/n+1,r),l=$i((i-t+2*a)/n+1,r);return[o,l]}function Y$(e,t,n,a,r,s){r==null&&(r=jy(e,t,a));let i=e[0],o=e[1],l=e[2],c=$i((i-t+2*r)/a+1,s),u=$i((o-t+2*r)/a+1,s),p=$i((l-t+2*r)/a+1,s);return[c,u,p,n]}function jy(e,t,n,a=1){let r=jl(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function _h(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Hy(e){return typeof e=="number"?[e,e,e]:e}function jl(e,t){return t<=1?e:e+(e-1)*(t-1)}function q$(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=X$([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=$i((t-s+d+h)/a+1,o),p=$i((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:p}}function K$(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=Y$([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 $i(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 ns(e){let[t,n,a]=_h(e);return t===1&&n===1&&a===1}function $n(e,t){return ns(e)||ns(t)}function l1(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function J$(e,t){let n={x:_(e,"x","reshape","string_or_numeric")},a={shape:t};return P.runKernel(Nl,n,a)}var q=R({reshape_:J$});function Z$(e,t,n,a,r){let s=_(e,"x","avgPool","float32"),i=1;A($n(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=q(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(jt(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=P.runKernel(Ps,c,u);return p=pe(p,s.dtype),l?q(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Jn=R({avgPool_:Z$});function Q$(e,t,n,a,r,s="NDHWC",i){i==null?i=[1,1,1]:Rt("dilations is deprecated, this field will be gone in v3.0.0.");let o=_(e,"x","avgPool3d","float32"),l=o,c=!1;o.rank===4&&(c=!0,l=q(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),A($n(n,i),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&A(jt(a),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:l},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s,dilations:i},d=P.runKernel(gc,u,p);return d=pe(d,l.dtype),c?q(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var qy=R({avgPool3d_:Q$});function eD(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=zc(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 P.runKernel(qo,a,r)}var Qe=R({concat_:eD});function tD(e){let t={x:_(e,"x","sigmoid")};return P.runKernel(gi,t)}var ma=R({sigmoid_:tD});function nD(e,t,n){let a=_(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 P.runKernel(_l,r,s)}var We=R({slice_:nD});function aD(e){let t={x:_(e,"x","tanh")};return P.runKernel(ki,t)}var ql=R({tanh_:aD});function rD(e,t,n,a,r,s){let i=_(e,"forgetBias","basicLSTMCell"),o=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),c=_(a,"data","basicLSTMCell"),u=_(r,"c","basicLSTMCell"),p=_(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(ma(b),ql(v)),L(u,ma(Z(i,x)))),C=L(ql(T),ma(N));return[T,C]}var sD=R({basicLSTMCell_:rD});function iD(e,t,n){let a=_(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 P.runKernel(yc,s,i)}var Gc=R({batchToSpaceND_:iD});function oD(e){let t;return e.rank===0||e.rank===1?t=q(e,[1,1,1,e.size]):e.rank===2?t=q(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=q(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function lD(e,t,n,a,r,s){s==null&&(s=.001);let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;a!=null&&(u=_(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:oD(i),scale:c,offset:u,mean:o,variance:l},d={varianceEpsilon:s},h=P.runKernel(Ks,p,d);return q(h,i.shape)}var xr=R({batchNorm_:lD});function uD(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return a!=null&&(u=_(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}.`),xr(i,o,l,u,c,s)}var p1=R({batchNorm2d_:uD});function cD(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return a!=null&&(u=_(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}.`),xr(i,o,l,u,c,s)}var d1=R({batchNorm3d_:cD});function pD(e,t,n,a,r,s){let i=_(e,"x","batchNorm"),o=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return a!=null&&(u=_(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}.`),xr(i,o,l,u,c,s)}var h1=R({batchNorm4d_:pD});function dD(e,t,n){let a=_(e,"x","bincount"),r=_(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 P.runKernel(Wd,s,i)}var m1=R({bincount_:dD});function hD(e,t){let n=_(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=q(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 P.runKernel(qr,i,o)}var Hc=R({broadcastTo_:hD});function mD(e){let t={x:_(e,"x","ceil")};return P.runKernel(jo,t)}var Ky=R({ceil_:mD});function fD(e,t,n){let a=_(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 P.runKernel(jr,r,s)}var Xt=R({clipByValue_:fD});function gD(e){return Qe(e,0)}var f1=R({concat1d_:gD});function yD(e,t){return Qe(e,t)}var g1=R({concat2d_:yD});function bD(e,t){return Qe(e,t)}var y1=R({concat3d_:bD});function xD(e,t){return Qe(e,t)}var b1=R({concat4d_:xD});function vD(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","conv2d"),l=_(t,"filter","conv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=q(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(jt(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($n(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=P.runKernel(zs,d,h);return u?q(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ft=R({conv2d_:vD});function wD(e,t,n,a,r="NWC",s=1,i){let o=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),c=o,u=!1;o.rank===2&&(u=!0,c=q(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(jt(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($n(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=q(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=q(c,[c.shape[0],1,c.shape[1],c.shape[2]]),h=Ft(d,p,[1,n],a,"NHWC",[1,s],i);return u?q(h,[h.shape[2],h.shape[3]]):q(h,[h.shape[0],h.shape[2],h.shape[3]])}var Eh=R({conv1d_:wD});function kD(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=q(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(jt(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=P.runKernel(Bs,d,h);return c?q(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Xy=R({conv2DBackpropInput_:kD});function ID(e,t,n,a,r,s){let i=_(e,"x","conv2dTranspose"),o=_(t,"filter","conv2dTranspose");return Xy(n,i,o,a,r,"NHWC",s)}var Ah=R({conv2dTranspose_:ID});function ND(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=_(e,"x","conv3d"),o=_(t,"filter","conv3d"),l=i,c=!1;i.rank===4&&(c=!0,l=q(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($n(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=P.runKernel(xc,u,p);return c?q(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Yy=R({conv3d_:ND});function TD(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=q(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=P.runKernel(Hd,u,p);return o?q(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var x1=R({conv3DBackpropInput_:TD});function SD(e,t,n,a,r){let s=_(e,"x","conv3dTranspose"),i=_(t,"filter","conv3dTranspose");return x1(n,s,i,a,r)}var CD=R({conv3dTranspose_:SD});function _D(e){let t={x:_(e,"x","cos")};return P.runKernel(Ws,t)}var jc=R({cos_:_D});function ED(e){let t={x:_(e,"x","cosh")};return P.runKernel(Ko,t)}var Fh=R({cosh_:ED});function AD(e,t=0,n=!1,a=!1){let r={x:_(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return P.runKernel(Vs,r,s)}var $h=R({cumsum_:AD});function FD(e,t,n,a=!1){let r=_(e,"x","denseBincount"),s=_(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 P.runKernel(jd,i,o)}var v1=R({denseBincount_:FD});function $D(e,t,n="NHWC"){let a=_(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 P.runKernel(Yo,o,l)}var Jy=R({depthToSpace_:$D});function DD(e,t,n,a,r="NHWC",s=[1,1],i){let o=_(e,"x","depthwiseConv2d"),l=_(t,"filter","depthwiseConv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=q(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(jt(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=P.runKernel(Us,p,d);return u?q(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var vr=R({depthwiseConv2d_:DD});function MD(e){let t={x:_(e,"x","diag")};return P.runKernel(Xd,t)}var RD=R({diag_:MD});function PD(e,t,n,a,r=[1,1],s="NHWC"){let i=_(e,"x","dilation2d"),o=_(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=q(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=P.runKernel(vc,u,p);return c?q(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Zy=R({dilation2d_:PD});function OD(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 Wt(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 wt(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 LD(e,t){let n=_(e,"a","equal"),a=_(t,"b","equal");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Qo,r)}var wr=R({equal_:LD});function zD(e,t,n){let a=_(t,"a","where"),r=_(n,"b","where"),s=_(e,"condition","where","bool"),i=wt(a.shape,r.shape),o=Hc(a,i),l=Hc(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&&rt(s.shape,l.shape,"Error in where: ");let c={condition:s,t:o,e:l};return P.runKernel(Sl,c)}var kn=R({where_:zD});function BD(e){let t={x:_(e,"x","zerosLike")};return P.runKernel(Ol,t)}var Ge=R({zerosLike_:BD});function WD(e,t){let n=_(e,"a","div"),a=_(t,"b","div");[n,a]=Tt(n,a);let r=we(n,a),s=Ge(r),i=wr(a,s);return kn(i,s,r)}var Qy=R({divNoNan_:WD});function VD(e,t){let n=_(e,"t1","dot"),a=_(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=q(n,[1,-1]),o=q(a,[-1,1]),l=ze(i,o);return q(l,[])}else if(n.rank===1&&a.rank===2){let i=q(n,[1,-1]),o=q(a,[a.shape[0],a.shape[1]]),l=ze(i,o);return q(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=q(a,[-1,1]),o=ze(n,i);return q(o,[o.size])}else{let i=q(a,[a.shape[0],a.shape[1]]);return ze(n,i)}}var w1=R({dot_:VD});function UD(e){let t={x:_(e,"x","elu")};return P.runKernel(Jo,t)}var Kl=R({elu_:UD});function GD(e){let t=_(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=pe(t,"float32"));let n={x:t};return P.runKernel(Zo,n)}var eb=R({erf_:GD});function HD(e){let t={x:_(e,"x","exp")};return P.runKernel(Hs,t)}var hn=R({exp_:HD});function jD(e,t=0){let n=_(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 P.runKernel(el,a,r)}var Zn=R({expandDims_:jD});function qD(e){let t={x:_(e,"x","expm1")};return P.runKernel(tl,t)}var tb=R({expm1_:qD});function KD(e,t){let n=_(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 P.runKernel(qr,a,r)}var Xa=R({tile_:KD});function XD(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=q(r.toTensor(),[e,t]);if(n==null)return i;if(n.length===1)return Xa(Zn(i,0),[n[0],1,1]);if(n.length===2)return Xa(Zn(Zn(i,0),0),[n[0],n[1],1,1]);if(n.length===3)return Xa(Zn(Zn(Zn(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 nb=R({eye_:XD});function In(e,t,n){let a={shape:e,value:t,dtype:n};return P.runKernel(wc,{},a)}function YD(e){let t={x:_(e,"x","floor")};return P.runKernel(js,t)}var Xl=R({floor_:YD});function JD(e,t,n=0,a=0){let r=_(e,"x","gather"),s=_(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:n,batchDims:a};return P.runKernel(al,i,o)}var Di=R({gather_:JD});function ZD(e,t){let n=_(e,"a","greater"),a=_(t,"b","greater");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(sl,r)}var Qn=R({greater_:ZD});function QD(e,t){let n=_(e,"a","greaterEqual"),a=_(t,"b","greaterEqual");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Xs,r)}var kr=R({greaterEqual_:QD});function eM(e){let t={input:_(e,"input","imag")};return P.runKernel(th,t)}var Dh=R({imag_:eM});function tM(e){let t={x:_(e,"x","isFinite")};return P.runKernel(ol,t)}var k1=R({isFinite_:tM});function nM(e){let t={x:_(e,"x","isInf")};return P.runKernel(ll,t)}var I1=R({isInf_:nM});function aM(e){let t={x:_(e,"x","isNaN")};return P.runKernel(ul,t)}var N1=R({isNaN_:aM});function rM(e,t=.2){let n={x:_(e,"x","leakyRelu")},a={alpha:t};return P.runKernel(Ys,n,a)}var qc=R({leakyRelu_:rM});function sM(e,t){let n=_(e,"a","less"),a=_(t,"b","less");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(cl,r)}var Kc=R({less_:sM});function iM(e,t){let n=_(e,"a","lessEqual"),a=_(t,"b","lessEqual");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(pl,r)}var as=R({lessEqual_:iM});function T1(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 P.runKernel(nh,{},a)}function oM(e,t=5,n=1,a=1,r=.5){let s=_(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(jt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=q(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=P.runKernel(Nc,l,c);return o?q(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var ab=R({localResponseNormalization_:oM});function lM(e){let t={x:_(e,"x","log")};return P.runKernel(Js,t)}var Dn=R({log_:lM});function uM(e){let t={x:_(e,"x","log1p")};return P.runKernel(dl,t)}var Mh=R({log1p_:uM});function cM(e){return A(Gr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(a),[a],r);return r!=null&&rt(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Rh(i),i[0]})}}function pM(e){return A(Gr(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=zc(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(...a),a,r);return r!=null&&rt(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rh(i),i})}}function dM(e){return A(Gr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof z,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof z,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=P.gradients(()=>e(t),[t],n);return Rh(a),{grad:a[0],value:r}}}function hM(e){return A(Gr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(r=>r instanceof z),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof z,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=P.gradients(()=>e(...t),t,n);return n!=null&&rt(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rh(a.grads),a}}function S1(e,t){A(Gr(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(c=>c instanceof Xr),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in P.registeredVariables)t.push(P.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}=P.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 Ya(e){return P.customGrad(e)}function Rh(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 mM(e){let t={x:_(e,"x","neg")};return P.runKernel(fl,t)}var St=R({neg_:mM});function fM(e){let t={x:_(e,"x","softplus")};return P.runKernel(Fl,t)}var Yl=R({softplus_:fM});function gM(e){let t=_(e,"x","logSigmoid");return Ya(n=>({value:St(Yl(St(n))),gradFunc:a=>L(a,ma(St(n)))}))(t)}var C1=R({logSigmoid_:gM});function yM(e,t=null,n=!1){let a={x:_(e,"x","max")},r={reductionIndices:t,keepDims:n};return P.runKernel(Zs,a,r)}var ea=R({max_:yM});function bM(e,t){let n=_(e,"a","sub"),a=_(t,"b","sub");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(wi,r)}var ge=R({sub_:bM});function xM(e,t=null,n=!1){let a=_(e,"x","sum");a.dtype==="bool"&&(a=pe(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return P.runKernel(bi,r,s)}var Ce=R({sum_:xM});function vM(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Ya((a,r)=>{let s=!0,i=ea(a,t,!0),o=ge(a,i),l=ge(pe(o,"float32"),Dn(Ce(hn(o),t,s)));return r([l]),{value:l,gradFunc:(c,u)=>{let[p]=u,d=!0,h=hn(p);return ge(c,L(Ce(c,t,d),h))}}})(n)}var Ph=R({logSoftmax_:vM});function rb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function _1(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 E1(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 Mi(e,t){let n=t.map(a=>1);return _1(e,n,t)}function wM(e,t,n){A(rb(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function A1(e,t){if(rb(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 sb(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function kM(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function IM(e,t=null,n=!1){let a=_(e,"x","logSumExp"),r=da(t,a.shape),s=ea(a,r,!0),i=ge(a,s),o=hn(i),l=Ce(o,r),c=Dn(l),u=Z(q(s,c.shape),c);if(n){let p=Mi(u.shape,r);return q(u,p)}return u}var ib=R({logSumExp_:IM});function NM(e,t){let n=_(e,"a","logicalAnd","bool"),a=_(t,"b","logicalAnd","bool");wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(hl,r)}var fa=R({logicalAnd_:NM});function TM(e){let t={x:_(e,"x","logicalNot","bool")};return P.runKernel(kc,t)}var Xc=R({logicalNot_:TM});function SM(e,t){let n=_(e,"a","logicalOr","bool"),a=_(t,"b","logicalOr","bool");wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Ic,r)}var Oh=R({logicalOr_:SM});function CM(e,t){let n=_(e,"a","logicalXor","bool"),a=_(t,"b","logicalXor","bool");return wt(n.shape,a.shape),fa(Oh(e,t),Xc(fa(e,t)))}var F1=R({logicalXor_:CM});function _M(e,t,n,a,r){let s=_(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=q(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($n(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&A(jt(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=P.runKernel(ei,c,u);return l?q(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var $t=R({maxPool_:_M});function EM(e,t=[1,1,1],n,a,r,s="NDHWC",i){i==null?i=[1,1,1]:Rt("dilations is deprecated, this field will be gone in v3.0.0.");let o=_(e,"x","maxPool3d"),l=o,c=!1;o.rank===4&&(c=!0,l=q(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),A($n(n,i),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&A(jt(a),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:l},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s,dilations:i},d=P.runKernel(Tc,u,p);return c?q(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var ob=R({maxPool3d_:EM});function AM(e,t,n,a,r=!1){let s={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=P.runKernel(ih,s,i);return{result:o[0],indexes:o[1]}}var $1=R({maxPoolWithArgmax_:AM});function FM(e,t){let n=_(e,"a","maximum"),a=_(t,"b","maximum");[n,a]=Tt(n,a),n.dtype==="bool"&&(n=pe(n,"int32"),a=pe(a,"int32")),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Qs,r)}var Ca=R({maximum_:FM});function $M(e,t=null,n=!1){let a={x:_(e,"x","mean")},r={axis:t,keepDims:n};return P.runKernel(ti,a,r)}var Ct=R({mean_:$M});function DM(e,t=null,n=!1){let a={x:_(e,"x","min")},r={axis:t,keepDims:n};return P.runKernel(ni,a,r)}var Jl=R({min_:DM});function MM(e,t){let n=_(e,"a","minimum"),a=_(t,"b","minimum");[n,a]=Tt(n,a),n.dtype==="bool"&&(n=pe(n,"int32"),a=pe(a,"int32")),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(ai,r)}var Ri=R({minimum_:MM});function RM(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=_(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 P.runKernel(Sc,i,s)}var lb=R({mirrorPad_:RM});function PM(e,t){let n=_(e,"a","mod"),a=_(t,"b","mod");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(ml,r)}var Lh=R({mod_:PM});function OM(e){let t=_(e,"x","square"),n={};return P.runKernel("Square",{x:t},n)}var ct=R({square_:OM});function LM(e,t=null,n=!1){e=_(e,"x","moments");let a=da(t,e.shape),r=Ct(e,a,n),s=r.shape;n||(s=Mi(r.shape,a));let i=ct(ge(pe(e,"float32"),q(r,s))),o=Ct(i,a,n);return{mean:r,variance:o}}var zh=R({moments_:LM});function zM(e,t,n,a){let r=_(t,"data","multiRNNCell"),s=zc(n,"c","multiRNNCell"),i=zc(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 BM=R({multiRNNCell_:zM});function WM(e,t,n,a=!1){let r=_(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?q(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},c=P.runKernel(oh,o,l);return i===1?q(c,[c.size]):c}var D1=R({multinomial_:WM});function VM(e,t){let n=_(e,"a","notEqual"),a=_(t,"b","notEqual");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(gl,r)}var rs=R({notEqual_:VM});function xt(e,t="float32"){if(t==="complex64"){let a=xt(e,"float32"),r=xt(e,"float32");return Yr(a,r)}let n=Pd(Lt(e),t);return P.makeTensor(n,e,t)}function Ja(e,t="float32"){if(t==="complex64"){let a=Ja(e,"float32"),r=xt(e,"float32");return Yr(a,r)}let n=ay(Lt(e),t);return P.makeTensor(n,e,t)}function UM(e){let t={x:_(e,"x","onesLike")};return P.runKernel(vl,t)}var Mn=R({onesLike_:UM});function GM(e,t){let n=_(e,"v1","outerProduct"),a=_(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=q(n,[-1,1]),s=q(a,[1,-1]);return ze(r,s)}var HM=R({outerProduct_:GM});function jM(e,t,n=0){let a=_(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 P.runKernel(ii,s,r)}var ta=R({pad_:jM});function qM(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ta(e,[t],n)}var KM=R({pad1d_:qM});function XM(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."),ta(e,t,n)}var YM=R({pad2d_:XM});function JM(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."),ta(e,t,n)}var ZM=R({pad3d_:JM});function QM(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."),ta(e,t,n)}var eR=R({pad4d_:QM});function tR(e,t,n){let a=_(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 P.runKernel(Ec,r,s)}var Yc=R({spaceToBatchND_:tR});function rR(e,t,n,a,r,s){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let i=_(e,"x","maxPool"),o=i,l=!1;i.rank===3&&(l=!0,o=q(i,[1,i.shape[0],i.shape[1],i.shape[2]])),A($n(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let c=u1(o.shape,t,s,r,a),u=[c.dilationHeight,c.dilationWidth],p;a==="same"?p=aR([c.filterHeight,c.filterWidth],u):p=[[0,0],[0,0]];let d=u[0]===1&&u[1]===1,[h,m]=nR([c.inHeight,c.inWidth],u,p),f=d?a:"valid",g=d?o:Yc(o,u,h),y=(n==="avg"?()=>Jn(g,t,s,f):()=>$t(g,t,s,f))(),b=d?y:Gc(y,u,m);return l?q(b,[b.shape[1],b.shape[2],b.shape[3]]):b}function nR(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 aR(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 M1=R({pool_:rR});function sR(e,t){let n=_(e,"base","pow"),a=_(t,"exp","pow");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(oi,r)}var Za=R({pow_:sR});function iR(e,t){let n=_(e,"x","prelu"),a=_(t,"alpha","prelu"),r={x:n,alpha:a};return P.runKernel(li,r)}var Jc=R({prelu_:iR});function oR(e,t=null,n=!1){let a=_(e,"x","prod");a.dtype==="bool"&&(a=pe(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return P.runKernel(kl,r,s)}var Bh=R({prod_:oR});function lR(e,t,n){let a=Lt(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 P.makeTensor(r,e,n)}var uR=R({rand_:lR}),ub=Ro($d()),cb=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=ub.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=ub.alea(r.toString()),this.randn=new cb(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)}},pR=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=ub.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function dR(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 hR=R({randomGamma_:dR});function mR(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error(`Unsupported data type ${a}`);let s=new cb(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 R1=R({randomNormal_:mR});function fR(e,t=0,n=1,a="float32",r){let s=Le(e,a),i=new pR(t,n,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Zl=R({randomUniform_:fR});function Wh(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 P.runKernel(Cc,{},r)}function gR(e){let t={input:_(e,"input","real")};return P.runKernel(lh,t)}var Zc=R({real_:gR});function yR(e){let t={x:_(e,"x","reciprocal")};return P.runKernel(Il,t)}var pb=R({reciprocal_:yR});function bR(e){let t={x:_(e,"x","relu")};return P.runKernel(ui,t)}var Ye=R({relu_:bR});function xR(e){let t={x:_(e,"x","relu6")};return P.runKernel(pi,t)}var Vh=R({relu6_:xR});function vR(e,t){let n={x:_(e,"x","reverse")},a={dims:t};return P.runKernel(di,n,a)}var Rn=R({reverse_:vR});function wR(e){let t=_(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Rn(t,0)}var kR=R({reverse1d_:wR});function IR(e,t){let n=_(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Rn(n,t)}var NR=R({reverse2d_:IR});function TR(e,t){let n=_(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Rn(n,t)}var SR=R({reverse3d_:TR});function CR(e,t){let n=_(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Rn(n,t)}var _R=R({reverse4d_:CR});function ER(e){let t={x:_(e,"x","round")};return P.runKernel(hi,t)}var db=R({round_:ER});function AR(e){let t={x:_(e,"x","rsqrt")};return P.runKernel(mi,t)}var Uh=R({rsqrt_:AR});function he(e,t){if((ln(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"&&ln(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Jr(e,[],[],t)}function FR(e){let t={x:_(e,"x","selu")};return P.runKernel(Cl,t)}var Gh=R({selu_:FR});function $R(e,t,n,a,r,s=[1,1],i="NHWC"){let o=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),c=_(n,"pointwiseFilter","separableConv2d"),u=o,p=!1;if(o.rank===3&&(p=!0,u=q(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=vr(u,l,a,r,i,s),f=Ft(m,c,1,"valid",i);return p?q(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Pi=R({separableConv2d_:$R});async function DR(e,t){let n=_(e,"x","setdiff1d"),a=_(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 zt([o],n.dtype),c=new zt([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 P1=DR;function MR(e){let t={x:_(e,"x","sign")};return P.runKernel(Al,t)}var hb=R({sign_:MR});function RR(e){let t={x:_(e,"x","sin")};return P.runKernel(fi,t)}var Hh=R({sin_:RR});function PR(e){let t={x:_(e,"x","sinh")};return P.runKernel(El,t)}var jh=R({sinh_:PR});function OR(e,t,n){let a=_(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 qh=R({slice1d_:OR});function LR(e,t,n){let a=_(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 mb=R({slice2d_:LR});function zR(e,t,n){let a=_(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 Ql=R({slice3d_:zR});function BR(e,t,n){let a=_(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 Qc=R({slice4d_:BR});function WR(e,t=-1){let n=_(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let a={logits:n},r={dim:t};return P.runKernel(xi,a,r)}var _a=R({softmax_:WR});function VR(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return P.runKernel(Qd,t)}var ep=R({fft_:VR});function UR(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return P.runKernel(eh,t)}var eu=R({ifft_:UR});function GR(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=q(e,[n,t]);a=eu(r)}else{let r=[n,2*(t-1)],s=q(Zc(e),[n,t]),i=q(Dh(e),[n,t]),o=Rn(We(s,[0,1],[n,t-2]),1),l=L(Rn(We(i,[0,1],[n,t-2]),1),he(-1)),c=Qe([s,o],1),u=Qe([i,l],1),p=q(Yr(c,u),[r[0],r[1]]);a=eu(p)}if(a=Zc(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=q(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var Kh=R({irfft_:GR});function HR(e,t,n=0){let a={x:_(e,"x","split")},r={numOrSizeSplits:t,axis:n};return P.runKernel($l,a,r)}var Pn=R({split_:HR});function jR(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,xt(m)],e.shape.length-1),n=t}else r=e;let s=Ge(r),i=q(Yr(r,s),[a,n]),o=ep(i),l=Math.floor(n/2)+1,c=Zc(o),u=Dh(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,q(Yr(p[0],d[0]),h)}var tp=R({rfft_:jR});function qR(e){let t={x:_(e,"x","sqrt")};return P.runKernel(yi,t)}var an=R({sqrt_:qR});function KR(e,t){let n=_(e,"a","squaredDifference"),a=_(t,"b","squaredDifference");[n,a]=Tt(n,a),wt(n.shape,a.shape);let r={a:n,b:a},s={};return P.runKernel(vi,r,s)}var np=R({squaredDifference_:KR});function XR(e,t){let n=_(e,"x","squeeze");return q(n,Zw(n.shape,t).newShape)}var ss=R({squeeze_:XR});function YR(e,t=0){let n=zc(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 P.runKernel(wl,a,r)}var Dt=R({stack_:YR});function JR(e,t=0){let n={x:_(e,"x","step")},a={alpha:t};return P.runKernel(Kr,n,a)}var tu=R({step_:JR});function ZR(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let c={x:_(e,"x","stridedSlice")},u={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return P.runKernel(Dl,c,u)}var fb=R({stridedSlice_:ZR});function QR(e){let t={x:_(e,"x","tan")};return P.runKernel(Ml,t)}var gb=R({tan_:QR});function nt(e,t){$s(e);let n=Ka(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Jr(e,null,n,t)}function Ea(e,t,n){if($s(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=Ka(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 Jr(e,t,a,n)}function Aa(e,t,n){if($s(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=Ka(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 Jr(e,t,a,n)}function eP(e,t,n){if($s(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=Ka(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 Jr(e,t,a,n)}function tP(e,t,n){if($s(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=Ka(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,Jr(e,t,a,n)}function nP(e,t=1,n=!0){let a=_(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let 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]=P.runKernel(Rl,s,i);return{values:o,indices:l}}var yb=R({topk_:nP});function aP(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new cb(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 Xh=R({truncatedNormal_:aP});function rP(e,t=0){let n=_(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]=P.runKernel(dh,a,r);return{values:s,indices:i}}var Yh=R({unique_:rP});function sP(e,t,n){let a=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");A(jt(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return P.runKernel(Fc,s,i)}var bb=R({unsortedSegmentSum_:sP});function iP(e,t=0){let n=_(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 P.runKernel(Pl,a,r)}var ht=R({unstack_:iP});function O1(e,t=!0,n,a){return P.makeVariable(e,t,n,a)}function L1(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 oP(e){let t=_(e,"condition","whereAsync","bool"),n=await t.data(),a=L1(t.shape,n);return e!==t&&t.dispose(),a}var xb=oP;async function lP(e,t,n){let a=_(e,"tensor","boolMask"),r=_(t,"mask","boolMask","bool"),s=n==null?0:n,i=r.rank,o=a.shape;A(i>0,()=>"mask cannot be scalar"),rt(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=q(a,c),p=q(r,[-1]),d=await xb(p),h=ss(d,[1]),m=Di(u,h,s);return e!==a&&a.dispose(),t!==r&&r.dispose(),h.dispose(),u.dispose(),p.dispose(),d.dispose(),m}var uP=lP;function cP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","notEqualStrict"),a=_(t,"b","notEqualStrict");return rt(n.shape,a.shape,"Error in notEqualStrict: "),rs(n,a)}function pP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","lessStrict"),a=_(t,"b","lessStrict");return rt(n.shape,a.shape,"Error in lessStrict: "),Kc(n,a)}function dP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","equalStrict"),a=_(t,"b","equalStrict");return rt(n.shape,a.shape,"Error in equalStrict: "),wr(n,a)}function hP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","lessEqualStrict"),a=_(t,"b","lessEqualStrict");return rt(n.shape,a.shape,"Error in lessEqualStrict: "),as(n,a)}function mP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","greaterStrict"),a=_(t,"b","greaterStrict");return rt(n.shape,a.shape,"Error in greaterStrict: "),Qn(n,a)}function fP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","greaterEqualStrict"),a=_(t,"b","greaterEqualStrict");return rt(n.shape,a.shape,"Error in greaterEqualStrict: "),kr(n,a)}var z1=R({equalStrict_:dP}),B1=R({greaterEqualStrict_:fP}),W1=R({greaterStrict_:mP}),V1=R({lessEqualStrict_:hP}),U1=R({lessStrict_:pP}),G1=R({notEqualStrict_:cP});function gP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","addStrict"),a=_(t,"b","addStrict");return rt(n.shape,a.shape,"Error in addStrict: "),Z(n,a)}function yP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","subStrict"),a=_(t,"b","subStrict");return rt(n.shape,a.shape,"Error in subStrict: "),ge(n,a)}function bP(e,t){return Rt("strict variants of ops have been deprecated and will be removed in future"),rt(e.shape,t.shape,"Error in powStrict: "),Za(e,t)}function xP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","mul"),a=_(t,"b","mul");return rt(n.shape,a.shape,"Error in multiplyStrict: "),L(n,a)}function vP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","div"),a=_(t,"b","div");return rt(n.shape,a.shape,"Error in divideStrict: "),we(n,a)}function wP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","modStrict"),a=_(t,"b","modStrict");return rt(n.shape,a.shape,"Error in modStrict: "),Lh(n,a)}function kP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","minimumStrict"),a=_(t,"b","minimumStrict");return rt(n.shape,a.shape,"Error in minimumStrict: "),Ri(n,a)}function IP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","maximumStrict"),a=_(t,"b","maximumStrict");return rt(n.shape,a.shape,"Error in maximumStrict: "),Ca(n,a)}function NP(e,t){Rt("strict variants of ops have been deprecated and will be removed in future");let n=_(e,"a","squaredDifferenceStrict"),a=_(t,"b","squaredDifferenceStrict");return rt(n.shape,a.shape,"Error in squaredDifferenceStrict: "),np(n,a)}var H1=R({addStrict_:gP}),j1=R({divStrict_:vP}),q1=R({maximumStrict_:IP}),K1=R({minimumStrict_:kP}),X1=R({modStrict_:wP}),Y1=R({mulStrict_:xP}),J1=R({powStrict_:bP}),Z1=R({squaredDifferenceStrict_:NP}),Q1=R({subStrict_:yP});function TP(e,t="euclidean",n=null,a=!1){e=_(e,"x","norm");let r=ek(e,t,n),s=r.shape;if(a){let i=da(n,e.shape);s=Mi(r.shape,i)}return q(r,s)}function ek(e,t,n=null){if(e.rank===0)return Bt(e);if(e.rank!==1&&n===null)return ek(q(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return Ce(Bt(e),n);if(t===Infinity)return ea(Bt(e),n);if(t===-Infinity)return Jl(Bt(e),n);if(t==="euclidean"||t===2)return an(Ce(Za(Bt(e),he(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return ea(Ce(Bt(e),n[0]),n[1]-1);if(t===Infinity)return ea(Ce(Bt(e),n[1]),n[0]);if(t===-Infinity)return Jl(Ce(Bt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return an(Ce(ct(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var Jh=R({norm_:TP});function SP(e,t,n,a,r=!0){let s=_(e,"v","movingAverage"),i=_(t,"x","movingAverage"),o=_(n,"decay","movingAverage");b0(s,i),A(yr(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=he(1),c=ge(l,o),u=L(ge(i,s),c);if(r){A(a!=null,()=>"When using zeroDebias: true, step is required.");let p=_(a,"step","movingAverage");u=we(u,ge(l,Za(o,p)))}return Z(s,u)}var CP=R({movingAverage_:SP});function _P(e,t,n){let a=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");Dy(r,a,n);let s={indices:a,updates:r},i={shape:n};return P.runKernel(Tl,s,i)}var tk=R({scatterND_:_P});function EP(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 AP(e,t,n,a=0){let r=_(e,"sparseIndices","sparseToDense","int32"),s=_(t,"sparseValues","sparseToDense"),i=_(a,"defaultValue","sparseToDense",s.dtype);EP(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return P.runKernel(ph,o,l)}var vb=R({sparseToDense_:AP});function FP(e,t){let n=_(t,"indices","gatherND","int32"),a={params:_(e,"x","gatherND"),indices:n};return P.runKernel(rl,a)}var nk=R({gatherND_:FP});function $P(e,t){if(t==null)return e.shape.slice();if(yr(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 DP(e,t,n,a){let r=_(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 z?r.clone():r;let s=$P(r,n),i=1-t,o=we(Xl(Z(Zl(s,0,1,"float32",a),i)),i);return L(r,o)}var ak=R({dropout_:DP});function rk(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function wb(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 nt(r,"float32")}async function MP(e,t,n=1){let a=_(e,"predictions","inTopK"),r=_(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}`),rt(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=Qw("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(),Xn(u,r.shape,"bool")}var RP=MP,is={};Oe(is,{conv2d:()=>PP,depthwiseConv2d:()=>OP,matMul:()=>LP});function zP(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=q(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=q(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(jt(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 P.runKernel(Ud,p,d)}var kb=R({conv2DBackpropFilter_:zP});function Zh(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,tu(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Qh(e,t){let n=t,a=Wt(e.shape,t.shape);return a.length>0&&(n=Ce(n,a)),q(n,e.shape)}function em(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Ye(e);if(t==="elu")return Kl(e);if(t==="relu6")return Vh(e);if(t==="prelu")return Jc(e,n);if(t==="leakyrelu")return qc(e,a);throw new Error(`Unknown fused activation ${t}.`)}var tm=(e,t)=>!(e>0)||t==="linear";function BP({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",tm(P.state.gradientDepth,l)===!1){let N=Ft(e,t,n,a,r,s,i);return o!=null&&(N=Z(N,o)),em(N,l,c,u)}let p=_(e,"x","conv2d"),d=_(t,"filter","conv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=q(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(jt(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($n(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=Uc(h.shape,d.shape,n,s,a,i),g;o!=null&&(g=_(o,"bias","fused conv2d"),[g]=Tt(g,p),wt(f.outShape,g.shape));let y;c!=null&&(y=_(c,"prelu weights","fused conv2d"));let b=(N,T)=>{let[C,$,F,O]=T,W=Zh(N,F,l);A(ns(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let V=Xy($.shape,W,C,n,a),H=kb($,W,C.shape,n,a),K=[V,H];if(O!=null){let j=Qh(O,W);K.push(j)}return K},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?Ya((N,T,C)=>{let $=P.runKernel(Ti,v,x);return C([T,N,$]),m&&($=q($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d):Ya((N,T,C,$)=>{let F=P.runKernel(Ti,v,x);return $([T,N,F,C]),m&&(F=q(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}})(h,d,g)}var PP=R({fusedConv2d_:BP});function WP(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=q(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=q(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 P.runKernel(qd,c,u)}var sk=R({depthwiseConv2dNativeBackpropFilter_:WP});function VP(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=q(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=P.runKernel(Kd,c,u);return l?q(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var ik=R({depthwiseConv2dNativeBackpropInput_:VP});function UP({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(tm(P.state.gradientDepth,l)===!1){let N=vr(e,t,n,a,r,s,i);return o!=null&&(N=Z(N,o)),em(N,l,c,u)}let p=_(e,"x","depthwiseConv2d"),d=_(t,"filter","depthwiseConv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=q(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($n(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&A(jt(a),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${a}.`);let f=Uc(h.shape,d.shape,n,s,a,i,!0),g;o!=null&&(g=_(o,"bias","fused conv2d"),[g]=Tt(g,p),wt(f.outShape,g.shape));let y;c!=null&&(y=_(c,"prelu weights","fused depthwiseConv2d"));let b=(N,T)=>{A(ns(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,$,F,O]=T,W=Zh(N,F,l),V=ik($.shape,W,C,n,a,s,i),H=sk($,W,C.shape,n,a,s,i);if(O!=null){let K=Qh(g,W);return[V,H,K]}return[V,H]},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?Ya((N,T,C)=>{let $=P.runKernel(Si,v,x);return C([T,N,$]),m&&($=q($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d):Ya((N,T,C,$)=>{let F=P.runKernel(Si,v,x);return $([T,N,F,C]),m&&(F=q(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}})(h,d,g)}var OP=R({fusedDepthwiseConv2d_:UP});function GP({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(tm(P.state.gradientDepth,s)===!1){let O=ze(e,t,n,a);return r!=null&&(O=Z(O,r)),em(O,s,i,o)}let l=_(e,"a","fused matMul"),c=_(t,"b","fused matMul");[l,c]=Tt(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=Lt(m),y=Lt(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(yr(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?q(l,[g,u,d]):q(l,[g,d,u]),x=a?q(c,[y,h,p]):q(c,[y,p,h]),N;r!=null&&(N=_(r,"bias","fused matMul"),[N]=Tt(N,l),wt(b,N.shape));let T;i!=null&&(T=_(i,"prelu weights","fused matMul"));let C=(O,W)=>{let[V,H,K,j]=W,Y=Zh(q(O,K.shape),K,s),J,ne;if(!n&&!a?(J=ze(Y,H,!1,!0),ne=ze(V,Y,!0,!1)):!n&&a?(J=ze(Y,H,!1,!1),ne=ze(Y,V,!0,!1)):n&&!a?(J=ze(H,Y,!1,!0),ne=ze(V,Y,!1,!1)):(J=ze(H,Y,!0,!0),ne=ze(Y,V,!0,!0)),r!=null){let Q=Qh(j,Y);return[J,ne,Q]}else return[J,ne]},$={a:v,b:x,bias:N,preluActivationWeights:T},F={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?Ya((O,W,V)=>{let H=P.runKernel(Ni,$,F);return V([O,W,H]),{value:q(H,b),gradFunc:C}})(v,x):Ya((O,W,V,H)=>{let K=P.runKernel(Ni,$,F);return H([O,W,K,V]),{value:q(K,b),gradFunc:C}})(v,x,N)}var LP=R({fusedMatMul_:GP});function HP(e){return wb(e,.54,.46)}var jP=R({hammingWindow_:HP});function qP(e){return wb(e,.5,.5)}var ok=R({hannWindow_:qP});function KP(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),In([o],r)]);i.push(l),s+=n}return i.length===0?Ea([],[0,t]):q(Qe(i),[i.length,t])}var lk=R({frame_:KP});function XP(e,t,n,a,r=ok){a==null&&(a=rk(t));let s=lk(e,t,n),i=L(s,r(t)),o=[];for(let l=0;l<s.shape[0];l++)o.push(tp(We(i,[l,0],[1,t]),a));return Qe(o)}var YP=R({stft_:XP});function JP(e,t,n,a,r="bilinear",s=0){let i=_(e,"image","cropAndResize"),o=_(t,"boxes","cropAndResize","float32"),l=_(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 P.runKernel(Xo,u,p)}var ZP=R({cropAndResize_:JP});function QP(e){let t=_(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 P.runKernel(nl,n,{})}var eO=R({flipLeftRight_:QP});function tO(e,t,n=0,a=.5){let r=_(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 P.runKernel(Ll,s,i)}var nO=R({rotateWithOffset_:tO});function nu(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 aO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),o=nu(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return P.runKernel(yl,{boxes:s,scores:i},l)}var rO=R({nonMaxSuppression_:aO});function iO(e,t,n){let a=sO(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function sO(e,t,n){return lO(e,t,n||oO)}function oO(e,t){return e>t?1:e<t?-1:0}function lO(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 uk(e,t,n,a,r){return Ib(e,t,n,a,r,0)}function ck(e,t,n,a,r,s){return Ib(e,t,n,a,r,0,!1,s,!0)}function pk(e,t,n,a,r,s){return Ib(e,t,n,a,r,s,!0)}function Ib(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(dk);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=uO(e,b,p[N]);if(T>=a){x=!0;break}if(g.score=g.score*cO(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&&iO(c,g,dk))}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 uO(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 cO(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function dk(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function pO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),o=nu(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}=uk(c,u,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),nt(p,"int32")}var dO=pO;function hO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=nu(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=P.runKernel(xl,c,u);return{selectedIndices:p[0],selectedScores:p[1]}}var mO=R({nonMaxSuppressionWithScore_:hO});async function fO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=nu(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}=pk(u,p,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:nt(d,"int32"),selectedScores:nt(h)}}var gO=fO;function yO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),l=nu(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=P.runKernel(bl,d,h);return{selectedIndices:m[0],validOutputs:m[1]}}var bO=R({nonMaxSuppressionPadded_:yO});async function xO(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),l=nu(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}=ck(d,h,c,u,p,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:nt(m,"int32"),validOutputs:he(f,"int32")}}var vO=xO;function wO(e,t,n=!1,a=!1){let r=_(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=q(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=P.runKernel(ci,o,l);return i?q(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var hk=R({resizeBilinear_:wO});function kO(e,t,n=!1,a=!1){let r=_(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=q(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=P.runKernel(_c,o,l);return i?q(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var mk=R({resizeNearestNeighbor_:kO});function IO(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,"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=q(Wh(0,s,1,"int32"),[-1,1]),l=Wh(0,i,1,"int32"),c=ge(o,l),u=fa(as(c,he(+t,"int32")),kr(c,he(-n,"int32"))),p=xt([s,i],a.dtype);return q(Dt(ht(q(a,[-1,s,i])).map(d=>kn(u,d,p))),r)}var NO=R({bandPart_:IO});function TO(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=>ss(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(P.tidy(()=>{let s=a[r];if(r>0)for(let i=0;i<r;++i){let o=L(Ce(L(n[i],s)),n[i]);s=ge(s,o)}return we(s,Jh(s,"euclidean"))}));return t?Dt(n,0):n}var SO=R({gramSchmidt_:TO});function CO(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 fk(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),a=ht(q(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[c,u]=fk(l,t);r.push(c),s.push(u)});let i=q(Dt(r,0),e.shape),o=q(Dt(s,0),e.shape);return[i,o]}}function fk(e,t=!1){return P.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=nb(n),s=Qr(e),i=Ea([[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]=P.tidy(()=>{let h=We(s,[c,c],[n-c,1]),m=Jh(h),f=We(s,[c,c],[1,1]),g=kn(Qn(f,0),Ea([[-1]]),Ea([[1]])),y=ge(f,L(g,m)),b=we(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=St(we(ze(g,y),m)),x=We(s,[c,0],[n-c,a]),N=L(v,o),T=Ue(o);if(c===0)s=ge(x,ze(N,ze(T,x)));else{let F=ge(x,ze(N,ze(T,x)));s=Qe([We(s,[0,0],[c,a]),F],0)}let C=Ue(N),$=We(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=ge($,ze(ze($,o),C));else{let F=ge($,ze(ze($,o),C));r=Qe([We(r,[0,0],[n,c]),F],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 _O=R({qr_:CO}),mn;(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"})(mn||(mn={}));function EO(e,t,n=mn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let s=r==null?a:L(a,r);if(n===mn.NONE)return s;if(n===mn.SUM)return Ce(s);if(n===mn.MEAN){if(r==null)return Ct(s);{let i=a.size/r.size,o=we(Ce(s),Ce(r));return i>1?we(o,he(i)):o}}if(n===mn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return we(Ce(s),he(a.size));{let i=L(r,Ja(a.shape)),o=pe(Ce(rs(i,he(0))),"float32");return we(Ce(s),o)}}throw Error(`Unknown reduction: ${n}`)}var Ir=R({computeWeightedLoss_:EO});function AO(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),s=_(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=_(n,"weights","absoluteDifference")),rt(r.shape,s.shape,"Error in absoluteDifference: ");let o=Bt(ge(r,s));return Ir(o,i,a)}var FO=R({absoluteDifference_:AO});function $O(e,t,n,a,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","cosineDistance"),i=_(t,"predictions","cosineDistance"),o=null;a!=null&&(o=_(a,"weights","cosineDistance")),rt(s.shape,i.shape,"Error in cosineDistance: ");let l=he(1),c=ge(l,Ce(L(s,i),n,!0));return Ir(c,o,r)}var DO=R({cosineDistance_:$O});function MO(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),s=_(t,"predictions","hingeLoss"),i=null;n!=null&&(i=_(n,"weights","hingeLoss")),rt(r.shape,s.shape,"Error in hingeLoss: ");let o=he(1);r=ge(L(he(2),r),o);let l=Ye(ge(o,L(r,s)));return Ir(l,i,a)}var RO=R({hingeLoss_:MO});function PO(e,t,n,a=1,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","huberLoss"),i=_(t,"predictions","huberLoss"),o=null;n!=null&&(o=_(n,"weights","huberLoss")),rt(s.shape,i.shape,"Error in huberLoss: ");let l=he(a),c=Bt(ge(i,s)),u=Ri(c,l),p=ge(c,u),d=Z(L(he(.5),ct(u)),L(l,p));return Ir(d,o,r)}var OO=R({huberLoss_:PO});function LO(e,t,n,a=1e-7,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"labels","logLoss"),i=_(t,"predictions","logLoss"),o=null;n!=null&&(o=_(n,"weights","logLoss")),rt(s.shape,i.shape,"Error in logLoss: ");let l=he(1),c=he(a),u=St(L(s,Dn(Z(i,c)))),p=L(ge(l,s),Dn(Z(ge(l,i),c))),d=ge(u,p);return Ir(d,o,r)}var zO=R({logLoss_:LO});function BO(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),s=_(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=_(n,"weights","meanSquaredError")),rt(r.shape,s.shape,"Error in meanSquaredError: ");let o=np(r,s);return Ir(o,i,a)}var WO=R({meanSquaredError_:BO});function VO(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),a=_(t,"logits","sigmoidCrossEntropyWithLogits");rt(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Ye(a),s=L(a,n),i=Mh(hn(St(Bt(a))));return Z(ge(r,s),i)}function UO(e,t,n,a=0,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"multiClassLabels","sigmoidCrossEntropy"),i=_(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","sigmoidCrossEntropy")),rt(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let c=he(a),u=he(1),p=he(.5);s=Z(L(s,ge(u,c)),L(p,c))}let l=VO(s,i);return Ir(l,o,r)}var GO=R({sigmoidCrossEntropy_:UO});function HO(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 Ya((a,r,s)=>{let i=ib(r,[n],!0),o=ge(pe(r,"float32"),i);s([a,o]);let l=St(L(o,a));return{value:Ce(l,[n]),gradFunc:(c,u)=>{let[p,d]=u,h=Mi(c.shape,[n]);return[L(q(c,h),ge(pe(p,"float32"),hn(d))),L(q(c,h),ge(hn(d),pe(p,"float32")))]}}})(e,t)}function jO(e,t,n,a=0,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"onehotLabels","softmaxCrossEntropy"),i=_(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=_(n,"weights","softmaxCrossEntropy")),rt(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let c=he(a),u=he(1),p=he(s.shape[1]);s=Z(L(s,ge(u,c)),we(c,p))}let l=HO(s,i);return Ir(l,o,r)}var qO=R({softmaxCrossEntropy_:jO}),KO={fft:ep,ifft:eu,rfft:tp,irfft:Kh},XO={hammingWindow:jP,hannWindow:ok,frame:lk,stft:YP},Qa={flipLeftRight:eO,resizeNearestNeighbor:mk,resizeBilinear:hk,rotateWithOffset:nO,cropAndResize:ZP,nonMaxSuppression:rO,nonMaxSuppressionAsync:dO,nonMaxSuppressionWithScore:mO,nonMaxSuppressionWithScoreAsync:gO,nonMaxSuppressionPadded:bO,nonMaxSuppressionPaddedAsync:vO},gk={bandPart:NO,gramSchmidt:SO,qr:_O},YO={absoluteDifference:FO,computeWeightedLoss:Ir,cosineDistance:DO,hingeLoss:RO,huberLoss:OO,logLoss:zO,meanSquaredError:WO,sigmoidCrossEntropy:GO,softmaxCrossEntropy:qO},Nr=class extends t1{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 S1(e,t)}dispose(){this.iterations_!=null&&Fe(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:he(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(Nr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var nm=class extends Nr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.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(ct(s),1-this.rho)),c=L(we(an(Z(o,this.epsilon)),an(Z(i,this.epsilon))),s),u=Z(L(o,this.rho),L(ct(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)}};nm.className="Adadelta";es(nm);var am=class extends Nr{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=P.registeredVariables[t];if(this.accumulatedGrads[n]==null){let i=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:D(()=>In(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,ct(r));s.assign(i);let o=Z(L(we(r,an(Z(i,P.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)}};am.className="Adagrad";es(am);var rm=class extends Nr{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=he(t).variable(),this.accBeta2=he(n).variable()}),a==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=ge(1,this.accBeta1),a=ge(1,this.accBeta2);t.forEach((r,s)=>{let i=P.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(ct(l),1-this.beta2)),h=we(p,n),m=we(d,a);c.assign(p),u.assign(d);let f=Z(L(we(h,Z(an(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(Za(this.beta1,this.iterations_+1)),this.accBeta2.assign(Za(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)}};rm.className="Adam";es(rm);var sm=class extends Nr{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=he(0).variable(),this.accBeta1=he(t).variable()}),a==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=ge(1,this.accBeta1),a=we(-this.learningRate,Z(L(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=P.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=Bt(l),m=Ca(d,h);c.assign(p),u.assign(m);let f=Z(L(we(a,n),we(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)}};sm.className="Adamax";es(sm);var ap=class extends Nr{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=P.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=Kt(he(-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)}};ap.className="SGD";es(ap);var im=class extends ap{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=he(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.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)}};im.className="Momentum";es(im);var om=class extends Nr{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=P.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=P.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(ct(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=we(L(s,this.learningRate),an(ge(l,Z(ct(u),this.epsilon)))),d=Z(L(o,this.momentum),p);i.assign(l),c.assign(u),o.assign(d);let h=ge(a,d);a.assign(h)}else{let c=Z(L(i,this.decay),L(ct(s),1-this.decay)),u=Z(L(o,this.momentum),we(L(s,this.learningRate),an(Z(c,this.epsilon))));i.assign(c),o.assign(u);let p=ge(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)}};om.className="RMSProp";es(om);var Oi=class{static sgd(e){return new ap(e)}static momentum(e,t,n=!1){return new im(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new om(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new rm(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new nm(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new sm(e,t,n,a,r)}static adagrad(e,t=.1){return new am(e,t)}},Li={sgd:Oi.sgd,momentum:Oi.momentum,adadelta:Oi.adadelta,adagrad:Oi.adagrad,rmsprop:Oi.rmsprop,adamax:Oi.adamax,adam:Oi.adam},JO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function lm(){return new Promise(e=>JO(()=>e()))}var E={};Oe(E,{ERF_A1:()=>lL,ERF_A2:()=>uL,ERF_A3:()=>cL,ERF_A4:()=>pL,ERF_A5:()=>dL,ERF_P:()=>oL,PARALLELIZE_THRESHOLD:()=>Nb,SELU_SCALE:()=>bk,SELU_SCALEALPHA:()=>yk,applyActivation:()=>em,assertAndGetBroadcastShape:()=>wt,assertAxesAreInnerMostDims:()=>wM,assertParamsConsistent:()=>ZO,assignToTypedArray:()=>vL,axesAreInnerMostDims:()=>rb,calculateShapes:()=>U0,castTensor:()=>NL,combineLocations:()=>_1,complexWithEvenIndex:()=>yL,complexWithOddIndex:()=>bL,computeConv2DInfo:()=>Uc,computeConv3DInfo:()=>c1,computeDefaultPad:()=>jy,computeDilation2DInfo:()=>H$,computeOptimalWindowSize:()=>eL,computeOutAndReduceShapes:()=>E1,computeOutShape:()=>QO,computePool2DInfo:()=>u1,computePool3DInfo:()=>j$,convertConv2DDataFormat:()=>l1,eitherStridesOrDilationsAreOne:()=>$n,expandShapeToKeepDim:()=>Mi,exponent:()=>kL,exponents:()=>wL,fromStringArrayToUint8:()=>CL,fromUint8ToStringArray:()=>SL,getAxesPermutation:()=>A1,getBroadcastDims:()=>OD,getComplexWithIndex:()=>xL,getFusedBiasGradient:()=>Qh,getFusedDyActivation:()=>Zh,getImageCenter:()=>tL,getInnerMostAxes:()=>kM,getPermuted:()=>aL,getReductionAxes:()=>Wt,getReshaped:()=>nL,getReshapedPermuted:()=>rL,getSliceBeginCoords:()=>sL,getSliceSize:()=>iL,getUndoAxesPermutation:()=>sb,log:()=>mL,mergeRealAndImagArrays:()=>fL,prepareAndValidate:()=>V0,prepareSplitSize:()=>IL,reshapeTensor:()=>TL,segment_util:()=>xk,shouldFuse:()=>tm,slice_util:()=>dn,splitRealAndImagArrays:()=>gL,tupleValuesAreOne:()=>ns,upcastType:()=>ha,validateInput:()=>Dy,validateUpdateShape:()=>$y,warn:()=>hL});function ZO(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 QO(e,t){let n=e[0].slice();for(let a=1;a<e.length;a++)n[t]+=e[a][t];return n}var Nb=30;function eL(e){return e<=Nb?e:Rd(e,Math.floor(Math.sqrt(e)))}function tL(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function nL(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 aL(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 rL(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 sL(e,t){let n=[0];for(let a=0;a<t;++a)n.push(e[a][0]);return n}function iL(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 yk=1.7580993408473768,bk=1.0507009873554805,oL=.3275911,lL=.254829592,uL=-.284496736,cL=1.421413741,pL=-1.453152027,dL=1.061405429;function hL(...e){te().getBool("IS_TEST")||console.warn(...e)}function mL(...e){te().getBool("IS_TEST")||console.log(...e)}function fL(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 gL(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 yL(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 bL(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 xL(e,t){let n=e[t*2],a=e[t*2+1];return{real:n,imag:a}}function vL(e,t,n,a){e[a*2]=t,e[a*2+1]=n}function wL(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 kL(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 IL(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 xk={};Oe(xk,{collectGatherOpShapeInfo:()=>AL,computeOutShape:()=>EL,segOpComputeOptimalWindowSize:()=>_L});function _L(e,t){let n=!1,a;for(e<=Nb?(a=e,n=!0):a=Rd(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=Rd(e,a+1);return a}function EL(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 AL(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 NL(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();let a=xt(e.shape),r=pe(e,"float32"),s=n.complex(r,a);return a.dispose(),r.dispose(),s}if(!a0(e.dtype,t))return P.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){let a=n.real(e),r=pe(a,t);return a.dispose(),r}if(t==="int32")return n.int(e);if(t==="bool"){let a=he(0,e.dtype),r=n.notEqual(e,a);return a.dispose(),r}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function TL(e,t){return P.makeTensorFromDataId(e.dataId,t,e.dtype)}function SL(e){try{return e.map(t=>gh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function CL(e){return e.map(t=>Mc(t))}var er={};Oe(er,{nonMaxSuppressionV3Impl:()=>uk,nonMaxSuppressionV4Impl:()=>ck,nonMaxSuppressionV5Impl:()=>pk,whereImpl:()=>L1});var vk={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,tu(pe(n,"float32"),-1))}}},FL={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ct(pe(n,"float32")),r=an(ge(he(1),a));return St(we(e,r))}}}},$L={kernelName:Bo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=an(ge(ct(pe(n,"float32")),1));return we(e,a)}}}},DL={kernelName:Hr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=e,i=Wt(n.shape,r);return i.length>0&&(s=Ce(s,i)),q(s,n.shape)},b:()=>{let s=e,i=Wt(a.shape,r);return i.length>0&&(s=Ce(s,i)),q(s,a.shape)}}}},ML={kernelName:Ms,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},RL={kernelName:Rs,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},PL={kernelName:fc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},OL={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,an(ge(he(1),ct(pe(n,"float32")))))}}},LL={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=an(Z(he(1),ct(pe(n,"float32"))));return we(e,a)}}}},zL={kernelName:Ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=Z(ct(n),ct(a)),i=L(e,we(a,s)),o=Wt(n.shape,r);return o.length>0&&(i=Ce(i,o)),q(i,n.shape)},b:()=>{let s=Z(ct(n),ct(a)),i=St(L(e,we(n,s))),o=Wt(a.shape,r);return o.length>0&&(i=Ce(i,o)),q(i,a.shape)}}}},BL={kernelName:Uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,Z(ct(pe(n,"float32")),1))}}},WL={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,ge(he(1),ct(pe(n,"float32"))))}}};function VL(e,t,n,a,r=[1,1,1],s,i){let o=_(e,"dy","avgPool3dGrad"),l=_(t,"input","avgPool3dGrad"),c=o,u=l,p=!1;l.rank===4&&(p=!0,c=q(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=q(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),A(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),A(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),A($n(a,r),()=>`Error in avgPool3dGrad: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`),i!=null&&A(jt(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let d={dy:c,input:u},h={filterSize:n,strides:a,dilations:r,pad:s,dimRoundingMode:i},m=P.runKernel(Bd,d,h);return p?q(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var UL=R({avgPool3dGrad_:VL}),GL={kernelName:gc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,dilations:i,pad:o,dimRoundingMode:l}=n,c=i==null?[1,1,1]:i;return{x:()=>UL(e,a,r,s,c,o,l)}}};function HL(e,t,n,a,r){let s=_(e,"dy","avgPoolGrad"),i=_(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=q(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=q(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=P.runKernel(zd,u,p);return c?q(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jL=R({avgPoolGrad_:HL}),qL={kernelName:Ps,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>jL(e,a,r,s,i)}}},KL={kernelName:Os,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)}}},XL={kernelName:yc,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>Yc(e,a,r)}}},YL={kernelName:h0,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:()=>Ce(e,o,!0)}}},JL={kernelName:Ls,gradFunc:e=>({x:()=>e.clone()})},ZL={kernelName:jo,gradFunc:e=>({x:()=>Ge(e)})},QL={kernelName:jr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>kn(fa(kr(a,r),as(a,s)),e,Ge(e))}}},e3={kernelName:bc,inputsToSave:["x"],gradFunc:vk.gradFunc},t3={kernelName:qo,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=da(r,t[0].shape)[0],i=a.map(o=>o[s]);return Pn(e,i,s).map(o=>()=>o)}},n3={kernelName:zs,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return A(ns(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Xy(a.shape,e,r,i,o,l),filter:()=>kb(a,e,r.shape,i,o,l)}}},a3={kernelName:Bs,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Ft(e,r,s,i,o,1,l),filter:()=>kb(e,a,r.shape,s,i,o,l)}}};function r3(e,t,n,a,r){let s=e;e.rank===4&&(s=q(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=q(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 P.runKernel(Gd,o,l)}var s3=R({conv3DBackpropFilter_:r3}),i3={kernelName:xc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;A(ns(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:()=>x1(i.shape,e,o,r,s),filter:()=>s3(i,e,o.shape,r,s)}}},o3={kernelName:Ws,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(St(Hh(pe(n,"float32"))),e)}}},l3={kernelName:Ko,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(jh(pe(n,"float32")),e)}}},u3={kernelName:Vs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=A1([r],a.rank),l=$h(e,r,s,!i);return o!=null&&(l=Ue(l,o)),l}}}},c3={kernelName:Us,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;A(ns(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($n(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),i!=null&&A(jt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`),{x:()=>ik(l.shape,e,c,r,s,a,i),filter:()=>sk(l,e,c.shape,r,s,a,i)}}},p3={kernelName:vc,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:()=>P.runKernel(Yd,s,n),filter:()=>P.runKernel(Jd,i,n)}}},d3={kernelName:Jo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>P.runKernel(Zd,a)}}},h3={kernelName:Zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(hn(St(ct(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,a)}}},m3={kernelName:Hs,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},f3={kernelName:el,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>q(e,n.shape)}}},g3={kernelName:tl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,hn(n))}}},y3={kernelName:js,gradFunc:e=>({x:()=>Ge(e)})},b3={kernelName:qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=we(e,pe(a,"float32")),i=Wt(n.shape,r);return i.length>0?q(Ce(s,i),n.shape):s},b:()=>{let s=L(e,pe(n,"float32")),i=Wt(a.shape,r);i.length>0&&(s=q(Ce(s,i),a.shape));let o=ct(a);return St(we(s,pe(o,"float32")))}}}},x3={kernelName:Ks,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?he(1):o,c=Wt(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=ge(r,s),d=L(e,l),h=Uh(Z(i,he(a))),m=L(L(L(h,h),h),he(-.5));return{x:()=>s.rank===1?q(L(L(e,Xa(q(h,[1,1,1,s.shape[0]]),u)),l),r.shape):q(L(L(e,h),l),r.shape),mean:()=>{let f=L(L(h,he(-1)),d);return s.rank===1&&(f=Ce(f,c)),q(f,s.shape)},variance:()=>{let f=L(L(m,p),d);return s.rank===1&&(f=Ce(f,c)),q(f,s.shape)},scale:()=>{let f=L(p,h),g=L(e,f);return s.rank===1&&(g=Ce(g,c)),q(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=Ce(f,c)),q(f,s.shape)}}}},v3={kernelName:al,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=da(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=wk(0,u),m=wk(u+1,u+1+d),f=kk([c,[l],p]),g=q(e,f),y=q(r,[l]),b=kk([[u],h,m]),v=Ue(g,b),x=bb(v,y,a.shape[i]),N=sb(b);return x=Ue(x,N),x},indices:()=>r}}};function wk(e,t){let n=[];for(let a=e;a<t;++a)n.push(a);return n}function kk(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 w3={kernelName:Xs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>Ge(n),b:()=>Ge(a)}}},k3={kernelName:il,gradFunc:e=>({x:()=>pe(e,"float32")})},I3={kernelName:ol,gradFunc:e=>({x:()=>Ge(e)})},N3={kernelName:ll,gradFunc:e=>({x:()=>Ge(e)})},T3={kernelName:ul,gradFunc:e=>({x:()=>Ge(e)})},S3={kernelName:Ys,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=Qn(a,0);return{x:()=>kn(s,e,L(e,r))}}},C3={kernelName:dl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,Z(n,1))}}},_3={kernelName:Js,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,pe(n,"float32"))}}},E3={kernelName:m0,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=!0,i=hn(a);return ge(e,L(Ce(e,r,s),i))}}}};function A3(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 P.runKernel(ah,o,l)}var F3=R({localResponseNormalizationBackprop_:A3}),$3={kernelName:Nc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>F3(a,r,e,s,i,o,l)}}};function Ik(e,t,n,a){return t.rank<n.rank&&(t=q(t,Mi(t.shape,a))),e.rank<n.rank&&(e=q(e,Mi(e.shape,a))),{x:()=>L(e,pe(wr(n,t),e.dtype))}}var Nk={kernelName:Zs,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=da(r,s.shape),l=Ik(e,i,s,o);return{x:()=>l.x()}}},D3={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,pe(kr(n,a),"float32")),b:()=>L(e,pe(Kc(n,a),"float32"))}}};function M3(e,t,n,a,r,s=[1,1,1],i,o){let l=_(e,"dy","maxPool3dGrad"),c=_(t,"input","maxPool3dGrad"),u=_(n,"output","maxPool3dGrad"),p=l,d=c,h=u,m=!1;c.rank===4&&(m=!0,p=q(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=q(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),h=q(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),A(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),A(h.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${h.rank}.`),A($n(r,s),()=>`Error in maxPool3dGrad: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),o!=null&&A(jt(i),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);let f={dy:p,input:d,output:h},g={filterSize:a,strides:r,dilations:s,pad:i,dimRoundingMode:o},y=P.runKernel(sh,f,g);return m?q(y,[y.shape[1],y.shape[2],y.shape[3],y.shape[4]]):y}var R3=R({maxPool3dGrad_:M3}),P3={kernelName:Tc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,dilations:o,pad:l,dimRoundingMode:c}=n,u=o==null?[1,1,1]:o;return{x:()=>R3(e,a,r,s,i,u,l,c)}}};function O3(e,t,n,a,r,s,i){let o=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),c=_(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(jt(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 P.runKernel(rh,u,p)}var L3=R({maxPoolGrad_:O3}),z3={kernelName:ei,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>L3(e,a,r,s,i,o)}}},B3={kernelName:ti,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=da(r,a.shape),i=E1(a.shape,s)[1],o=Lt(i);return{x:()=>{let l=a.shape.slice();s.forEach(u=>{l[u]=1});let c=q(e,l);return we(L(c,Ja(a.shape,"float32")),o)}}}},W3={kernelName:ni,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=da(r,s.shape),l=Ik(e,i,s,o);return{x:()=>l.x()}}},V3={kernelName:ai,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,pe(as(n,a),"float32")),b:()=>L(e,pe(Qn(n,a),"float32"))}}},U3={kernelName:Sc,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)}}},G3={kernelName:ml,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=Wt(n.shape,r);return s.length>0?q(Ce(e,s),n.shape):e},b:()=>{let s=L(e,St(Xl(we(n,a)))),i=Wt(a.shape,r);return i.length>0?q(Ce(s,i),a.shape):s}}}},H3={kernelName:ri,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=L(e,pe(a,"float32")),i=Wt(n.shape,r);return i.length>0?q(Ce(s,i),n.shape):s},b:()=>{let s=L(e,pe(n,"float32")),i=Wt(a.shape,r);return i.length>0?q(Ce(s,i),a.shape):s}}}},j3={kernelName:fl,gradFunc:e=>({x:()=>St(e)})},q3={kernelName:si,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>xt(n.shape,"float32")}}},K3={kernelName:vl,gradFunc:e=>({x:()=>Ge(e)})},X3={kernelName:wl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return ht(e,a).map(r=>()=>r)}},Tk={kernelName:ii,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)}}},Y3={kernelName:oi,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=wt(s.shape,i.shape);return{a:()=>{let l=pe(i,"float32"),c=L(e,L(l,Za(s,ge(l,he(1))))),u=Wt(s.shape,o);return u.length>0&&(c=Ce(c,u)),q(c,s.shape)},b:()=>{let l=Qn(s,0),c=kn(l,Dn(s),Ge(s)),u=L(e,L(r,c)),p=Wt(i.shape,o);return p.length>0&&(u=Ce(u,p)),q(u,i.shape)}}}},J3={kernelName:li,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=Qn(n,0);return{x:()=>kn(r,e,L(e,a)),alpha:()=>{let s=kn(r,Ge(e),L(e,n)),i=Wt(a.shape,e.shape);return i.length>0&&(s=Ce(s,i)),q(s,a.shape)}}}},Z3={kernelName:Gs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=we(e,pe(a,"float32")),i=Wt(n.shape,r);return i.length>0?q(Ce(s,i),n.shape):s},b:()=>{let s=L(e,pe(n,"float32")),i=Wt(a.shape,r);i.length>0&&(s=q(Ce(s,i),a.shape));let o=ct(a);return St(we(s,pe(o,"float32")))}}}},Q3={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,St(ct(n)))}}},ez={kernelName:pi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(as(n,6),tu(n));return{x:()=>L(e,pe(a,"float32"))}}},tz={kernelName:ui,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,pe(tu(n),"float32"))}}},nz={kernelName:Nl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>q(e,n.shape)}}},az={kernelName:ci,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>P.runKernel(ch,r,n)}}},rz={kernelName:_c,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>P.runKernel(uh,r,n)}}},sz={kernelName:di,gradFunc:(e,t,n)=>{let{dims:a}=n,r=da(a,e.shape);return{x:()=>Rn(e,r)}}},iz={kernelName:hi,gradFunc:e=>({x:()=>Ge(e)})},oz={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>St(we(e,L(Za(n,1.5),2)))}}},lz={kernelName:Sl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>pe(Ge(n),"float32"),t:()=>L(e,pe(n,e.dtype)),e:()=>L(e,pe(Xc(n),e.dtype))}}},uz={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Qn(n,he(0)),r=he(yk),s=he(bk),i=L(e,s),o=L(L(e,r),hn(pe(n,"float32")));return kn(a,i,o)}}}},cz={kernelName:gi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,ge(he(1),n)))}}},pz={kernelName:Al,gradFunc:e=>({x:()=>Ge(e)})},dz={kernelName:fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(jc(pe(n,"float32")),e)}}},hz={kernelName:El,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Fh(pe(n,"float32")),e)}}},mz={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=Z0(a,r,s),c=[];for(let u=0;u<e.rank;u++)c.push([o[u],i[u]-o[u]-l[u]]);return{x:()=>ta(e,c)}}},fz={kernelName:xi,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=L(e,a);return{logits:()=>ge(i,L(Ce(i,[r],s),a))}}},gz={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ma(n))}}},Sk={kernelName:Ec,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>Gc(e,a,r)}}},Ck={kernelName:$l,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>Qe(e,a)}}},yz={kernelName:yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,L(an(pe(n,"float32")),2))}}},bz={kernelName:Ac,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(pe(n,"float32"),2))}}},xz={kernelName:vi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=he(2);return{a:()=>L(e,L(r,ge(n,a))),b:()=>L(e,L(r,ge(a,n)))}}},vz={kernelName:Kr,gradFunc:e=>({x:()=>Ge(e)})},wz={kernelName:wi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=wt(n.shape,a.shape);return{a:()=>{let s=e,i=Wt(n.shape,r);return i.length>0&&(s=Ce(s,i)),q(s,n.shape)},b:()=>{let s=e,i=Wt(a.shape,r);return i.length>0&&(s=Ce(s,i)),q(St(s),a.shape)}}}},kz={kernelName:bi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;da(s,a.shape).forEach(l=>{r[l]=1});let i=q(e,r),o=L(i,Ja(a.shape,"float32"));return{x:()=>o}}},Iz={kernelName:Ml,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>we(e,ct(jc(n)))}}},Nz={kernelName:ki,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(ge(he(1),ct(n)),e)}}},Tz={kernelName:qr,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}}}},Sz={kernelName:Ii,gradFunc:(e,t,n)=>{let a=n,{perm:r}=a,s=sb(r);return{x:()=>Ue(e,s)}}},Cz={kernelName:Pl,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>Dt(e,r)}}},Ez={kernelName:Fc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>_z(e,n)}}};function _z(e,t){let n=Ca(t,Ge(t)),a=Di(e,n),r=kr(t,he(0,"int32")),s=a.rank-r.rank;for(let o=0;o<s;++o)r=Zn(r,o+1);r=fa(r,Ja(a.shape,"bool"));let i=Ge(a);return kn(r,a,i)}var Az={kernelName:Ol,gradFunc:e=>({x:()=>Ge(e)})},Fz=[vk,FL,$L,DL,ML,RL,PL,OL,LL,zL,BL,WL,GL,qL,KL,XL,YL,JL,ZL,QL,e3,t3,a3,n3,i3,o3,l3,u3,c3,p3,Z3,d3,h3,m3,f3,g3,b3,y3,x3,v3,w3,k3,I3,N3,T3,S3,C3,_3,E3,$3,Nk,Nk,D3,P3,z3,B3,W3,V3,U3,G3,H3,j3,q3,K3,X3,Tk,Tk,Y3,J3,Q3,ez,tz,nz,az,rz,sz,iz,oz,lz,uz,cz,pz,dz,hz,mz,fz,gz,Sk,Sk,Ck,Ck,yz,xz,bz,vz,wz,kz,Iz,Nz,Tz,Sz,Cz,Ez,Az];for(let e of Fz)f0(e);z.prototype.abs=function(){return this.throwIfDisposed(),Bt(this)};z.prototype.acos=function(){return this.throwIfDisposed(),Oy(this)};z.prototype.acosh=function(){return this.throwIfDisposed(),Ly(this)};z.prototype.addStrict=function(e){return this.throwIfDisposed(),H1(this,e)};z.prototype.add=function(e){return this.throwIfDisposed(),Z(this,e)};z.prototype.all=function(e,t){return this.throwIfDisposed(),Ch(this,e,t)};z.prototype.any=function(e,t){return this.throwIfDisposed(),Wc(this,e,t)};z.prototype.argMax=function(e){return this.throwIfDisposed(),Vc(this,e)};z.prototype.argMin=function(e){return this.throwIfDisposed(),zy(this,e)};z.prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),q(this,[])};z.prototype.asType=function(e){return this.throwIfDisposed(),pe(this,e)};z.prototype.as1D=function(){return this.throwIfDisposed(),q(this,[this.size])};z.prototype.as2D=function(e,t){return this.throwIfDisposed(),q(this,[e,t])};z.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),q(this,[e,t,n])};z.prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),q(this,[e,t,n,a])};z.prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),q(this,[e,t,n,a,r])};z.prototype.asin=function(){return this.throwIfDisposed(),By(this)};z.prototype.asinh=function(){return this.throwIfDisposed(),Wy(this)};z.prototype.atan=function(){return this.throwIfDisposed(),Vy(this)};z.prototype.atan2=function(e){return this.throwIfDisposed(),Uy(this,e)};z.prototype.atanh=function(){return this.throwIfDisposed(),Gy(this)};z.prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),Jn(this,e,t,n,a)};z.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Gc(this,e,t)};z.prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),xr(this,e,t,n,a,r)};z.prototype.broadcastTo=function(e){return this.throwIfDisposed(),Hc(this,e)};z.prototype.cast=function(e){return this.throwIfDisposed(),pe(this,e)};z.prototype.ceil=function(){return this.throwIfDisposed(),Ky(this)};z.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Xt(this,e,t)};z.prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof z&&(e=[e]),Qe([this,...e],t)};z.prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Eh(this,e,t,n,a,r,s)};z.prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),Ah(this,e,t,n,a,r)};z.prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Ft(this,e,t,n,a,r,s)};z.prototype.cos=function(){return this.throwIfDisposed(),jc(this)};z.prototype.cosh=function(){return this.throwIfDisposed(),Fh(this)};z.prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),$h(this,e,t,n)};z.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Jy(this,e,t)};z.prototype.depthwiseConv2D=function(e,t,n,a,r,s){return Rt("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),vr(this,e,t,n,a,r,s)};z.prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),vr(this,e,t,n,a,r,s)};z.prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),Zy(this,e,t,n,a,r)};z.prototype.divNoNan=function(e){return this.throwIfDisposed(),Qy(this,e)};z.prototype.divStrict=function(e){return this.throwIfDisposed(),j1(this,e)};z.prototype.div=function(e){return this.throwIfDisposed(),we(this,e)};z.prototype.dot=function(e){return this.throwIfDisposed(),w1(this,e)};z.prototype.elu=function(){return this.throwIfDisposed(),Kl(this)};z.prototype.equalStrict=function(e){return this.throwIfDisposed(),z1(this,e)};z.prototype.equal=function(e){return this.throwIfDisposed(),wr(this,e)};z.prototype.erf=function(){return this.throwIfDisposed(),eb(this)};z.prototype.exp=function(){return this.throwIfDisposed(),hn(this)};z.prototype.expandDims=function(e){return this.throwIfDisposed(),Zn(this,e)};z.prototype.expm1=function(){return this.throwIfDisposed(),tb(this)};z.prototype.fft=function(){return this.throwIfDisposed(),ep(this)};z.prototype.flatten=function(){return this.throwIfDisposed(),q(this,[this.size])};z.prototype.floor=function(){return this.throwIfDisposed(),Xl(this)};z.prototype.floorDiv=function(e){return this.throwIfDisposed(),Sh(this,e)};z.prototype.gather=function(e,t){return this.throwIfDisposed(),Di(this,e,t)};z.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),B1(this,e)};z.prototype.greaterEqual=function(e){return this.throwIfDisposed(),kr(this,e)};z.prototype.greaterStrict=function(e){return this.throwIfDisposed(),W1(this,e)};z.prototype.greater=function(e){return this.throwIfDisposed(),Qn(this,e)};z.prototype.ifft=function(){return this.throwIfDisposed(),eu(this)};z.prototype.irfft=function(){return this.throwIfDisposed(),Kh(this)};z.prototype.isFinite=function(){return this.throwIfDisposed(),k1(this)};z.prototype.isInf=function(){return this.throwIfDisposed(),I1(this)};z.prototype.isNaN=function(){return this.throwIfDisposed(),N1(this)};z.prototype.leakyRelu=function(e){return this.throwIfDisposed(),qc(this,e)};z.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),V1(this,e)};z.prototype.lessEqual=function(e){return this.throwIfDisposed(),as(this,e)};z.prototype.lessStrict=function(e){return this.throwIfDisposed(),U1(this,e)};z.prototype.less=function(e){return this.throwIfDisposed(),Kc(this,e)};z.prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),ab(this,e,t,n,a)};z.prototype.logSigmoid=function(){return this.throwIfDisposed(),C1(this)};z.prototype.logSoftmax=function(e){return this.throwIfDisposed(),Ph(this,e)};z.prototype.logSumExp=function(e,t){return this.throwIfDisposed(),ib(this,e,t)};z.prototype.log=function(){return this.throwIfDisposed(),Dn(this)};z.prototype.log1p=function(){return this.throwIfDisposed(),Mh(this)};z.prototype.logicalAnd=function(e){return this.throwIfDisposed(),fa(this,e)};z.prototype.logicalNot=function(){return this.throwIfDisposed(),Xc(this)};z.prototype.logicalOr=function(e){return this.throwIfDisposed(),Oh(this,e)};z.prototype.logicalXor=function(e){return this.throwIfDisposed(),F1(this,e)};z.prototype.matMul=function(e,t,n){return this.throwIfDisposed(),ze(this,e,t,n)};z.prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),$t(this,e,t,n,a)};z.prototype.max=function(e,t){return this.throwIfDisposed(),ea(this,e,t)};z.prototype.maximumStrict=function(e){return this.throwIfDisposed(),q1(this,e)};z.prototype.maximum=function(e){return this.throwIfDisposed(),Ca(this,e)};z.prototype.mean=function(e,t){return this.throwIfDisposed(),Ct(this,e,t)};z.prototype.min=function(e,t){return this.throwIfDisposed(),Jl(this,e,t)};z.prototype.minimumStrict=function(e){return this.throwIfDisposed(),K1(this,e)};z.prototype.minimum=function(e){return this.throwIfDisposed(),Ri(this,e)};z.prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),lb(this,e,t)};z.prototype.modStrict=function(e){return this.throwIfDisposed(),X1(this,e)};z.prototype.mod=function(e){return this.throwIfDisposed(),Lh(this,e)};z.prototype.mulStrict=function(e){return this.throwIfDisposed(),Y1(this,e)};z.prototype.mul=function(e){return this.throwIfDisposed(),L(this,e)};z.prototype.neg=function(){return this.throwIfDisposed(),St(this)};z.prototype.norm=function(e,t,n){return this.throwIfDisposed(),Jh(this,e,t,n)};z.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),G1(this,e)};z.prototype.notEqual=function(e){return this.throwIfDisposed(),rs(this,e)};z.prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Gl(this,e,t,n)};z.prototype.onesLike=function(){return this.throwIfDisposed(),Mn(this)};z.prototype.pad=function(e,t){return this.throwIfDisposed(),ta(this,e,t)};z.prototype.pool=function(e,t,n,a,r){return this.throwIfDisposed(),M1(this,e,t,n,a,r)};z.prototype.powStrict=function(e){return this.throwIfDisposed(),J1(this,e)};z.prototype.pow=function(e){return this.throwIfDisposed(),Za(this,e)};z.prototype.prelu=function(e){return this.throwIfDisposed(),Jc(this,e)};z.prototype.prod=function(e,t){return this.throwIfDisposed(),Bh(this,e,t)};z.prototype.reciprocal=function(){return this.throwIfDisposed(),pb(this)};z.prototype.relu=function(){return this.throwIfDisposed(),Ye(this)};z.prototype.relu6=function(){return this.throwIfDisposed(),Vh(this)};z.prototype.reshapeAs=function(e){return this.throwIfDisposed(),q(this,e.shape)};z.prototype.reshape=function(e){return this.throwIfDisposed(),q(this,e)};z.prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),hk(this,e,t,n)};z.prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),mk(this,e,t,n)};z.prototype.reverse=function(e){return this.throwIfDisposed(),Rn(this,e)};z.prototype.rfft=function(){return this.throwIfDisposed(),tp(this)};z.prototype.round=function(){return this.throwIfDisposed(),db(this)};z.prototype.rsqrt=function(){return this.throwIfDisposed(),Uh(this)};z.prototype.selu=function(){return this.throwIfDisposed(),Gh(this)};z.prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Pi(this,e,t,n,a,r,s)};z.prototype.sigmoid=function(){return this.throwIfDisposed(),ma(this)};z.prototype.sign=function(){return this.throwIfDisposed(),hb(this)};z.prototype.sin=function(){return this.throwIfDisposed(),Hh(this)};z.prototype.sinh=function(){return this.throwIfDisposed(),jh(this)};z.prototype.slice=function(e,t){return this.throwIfDisposed(),We(this,e,t)};z.prototype.softmax=function(e){return this.throwIfDisposed(),_a(this,e)};z.prototype.softplus=function(){return this.throwIfDisposed(),Yl(this)};z.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Yc(this,e,t)};z.prototype.split=function(e,t){return this.throwIfDisposed(),Pn(this,e,t)};z.prototype.sqrt=function(){return this.throwIfDisposed(),an(this)};z.prototype.square=function(){return this.throwIfDisposed(),ct(this)};z.prototype.squaredDifference=function(e){return this.throwIfDisposed(),np(this,e)};z.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),Z1(this,e)};z.prototype.squeeze=function(e){return this.throwIfDisposed(),ss(this,e)};z.prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof z?[this,e]:[this,...e];return Dt(n,t)};z.prototype.step=function(e){return this.throwIfDisposed(),tu(this,e)};z.prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),fb(this,e,t,n,a,r,s,i,o)};z.prototype.subStrict=function(e){return this.throwIfDisposed(),Q1(this,e)};z.prototype.sub=function(e){return this.throwIfDisposed(),ge(this,e)};z.prototype.sum=function(e,t){return this.throwIfDisposed(),Ce(this,e,t)};z.prototype.tan=function(){return this.throwIfDisposed(),gb(this)};z.prototype.tanh=function(){return this.throwIfDisposed(),ql(this)};z.prototype.tile=function(e){return this.throwIfDisposed(),Xa(this,e)};z.prototype.toBool=function(){return this.throwIfDisposed(),pe(this,"bool")};z.prototype.toFloat=function(){return this.throwIfDisposed(),pe(this,"float32")};z.prototype.toInt=function(){return this.throwIfDisposed(),pe(this,"int32")};z.prototype.topk=function(e,t){return this.throwIfDisposed(),yb(this,e,t)};z.prototype.transpose=function(e){return this.throwIfDisposed(),Ue(this,e)};z.prototype.unique=function(e){return this.throwIfDisposed(),Yh(this,e)};z.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),bb(this,e,t)};z.prototype.unstack=function(e){return this.throwIfDisposed(),ht(this,e)};z.prototype.where=function(e,t){return this.throwIfDisposed(),kn(e,this,t)};z.prototype.zerosLike=function(){return this.throwIfDisposed(),Ge(this)};var _k={};Oe(_k,{maxNorm:()=>$z,minMaxNorm:()=>Rz,nonNeg:()=>Mz,unitNorm:()=>Dz});var Tb;function Vt(){return Tb==null&&(Tb=i1().epsilon()),Tb}function Fa(){return"channelsLast"}var Tr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Tr.prototype)}},$a=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,$a.prototype)}},B=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,B.prototype)}},$e=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,$e.prototype)}},Ek=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ek.prototype)}},Pz=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Pz.prototype)}};function zi(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 tr(e,t){if(!e)throw new Ek(t)}function Ak(e,t){let n=0;for(let a of e)a===t&&n++;return n}function Nn(e){return e.length===1?e[0]:e}function vt(e){return Array.isArray(e)?e:[e]}function Sr(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 Bi(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var ga={};function Sb(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Cb(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Cb(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:Cb(a))}}}function rp(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 ga)i=ga[s];else if(i=t[s],i==null)throw new B(`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 B(`${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 ga?[o,l]=ga.className:i in t&&([o,l]=t[i]),o==null)throw new B(`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(ga))c[h]=ga[h];for(let h of Object.keys(n))c[h]=n[h];let u=s.config;u.customObjects=c;let p=Object.assign({},ga);for(let h of Object.keys(n))ga[h]=n[h];Cb(s.config);let d=l(o,s.config,n,r);return ga=Object.assign({},p),d}else{let c=Object.assign({},ga);for(let p of Object.keys(n))ga[p]=n[p];let u=new o(s.config);return ga=Object.assign({},c),u}}}function Oz(e,t){return e<t?-1:e>t?1:0}function um(e,t){return-1*Oz(e,t)}function os(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Lz(e){if(e==null)throw new B(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Wi(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new B(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function _b(e,t,n=0,a=Infinity){return tr(n>=0),tr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function Yt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>Yt(n,`element ${a+1} of ${t}`))):k.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${Fk(e)}.`)}function Fk(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>Fk(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function zz(e,t){let n=k.now(),a;return(...r)=>{let s=k.now();return s-n<t||(n=s,a=e(...r)),a}}function $k(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Eb(e,t){return D(()=>an(Ce(L(e,e),t,!0)))}var sp=class extends re.Serializable{getConfig(){return{}}},Ab=class extends sp{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=Eb(e,this.axis),n=Xt(t,0,this.maxValue);return L(e,we(n,Z(Vt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Ab.className="MaxNorm";re.registerClass(Ab);var Fb=class extends sp{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>we(e,Z(Vt(),Eb(e,this.axis))))}getConfig(){return{axis:this.axis}}};Fb.className="UnitNorm";re.registerClass(Fb);var $b=class extends sp{apply(e){return Ye(e)}};$b.className="NonNeg";re.registerClass($b);var Db=class extends sp{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=Eb(e,this.axis),n=Z(L(this.rate,Xt(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,we(n,Z(Vt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Db.className="MinMaxNorm";re.registerClass(Db);var Dk={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ut(e){return Sb(e)}function Mk(e,t={}){return rp(e,re.SerializationMap.getMap().classNameMap,t,"constraint")}function Gt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in Dk?Dk[e]:e,config:{}};return Mk(t)}else return e instanceof sp?e:Mk(e)}function $z(e){return new Ab(e)}function Dz(e){return new Fb(e)}function Mz(){return new $b}function Rz(e){return new Db(e)}var Rk={};Oe(Rk,{constant:()=>Vz,glorotNormal:()=>Xz,glorotUniform:()=>Kz,heNormal:()=>Yz,heUniform:()=>Jz,identity:()=>jz,leCunNormal:()=>Zz,leCunUniform:()=>Qz,ones:()=>Wz,orthogonal:()=>eB,randomNormal:()=>Gz,randomUniform:()=>Uz,truncatedNormal:()=>Hz,varianceScaling:()=>qz,zeros:()=>Bz});var tB=["channelsFirst","channelsLast"],nB=["nearest","bilinear"],aB=["valid","same","causal"],rB=["max","avg"],sB=["sum","mul","concat","ave"],au=new Map;function Mt(e){Wi(tB,"DataFormat",e)}function iB(e){Wi(nB,"InterpolationFormat",e)}function na(e){Wi(aB,"PaddingMode",e)}function Pk(e){Wi(rB,"PoolMode",e)}var ip=[],Ok="/";function Vi(e,t){ip.push(e);try{let n=t();return ip.pop(),n}catch(n){throw ip.pop(),n}}function oB(){return ip.length===0?"":ip.join(Ok)+Ok}function zk(e){if(!Lk(e))throw new Error("Not a valid tensor name: '"+e+"'");return oB()+e}function Bk(e){if(!Lk(e))throw new Error("Not a valid tensor name: '"+e+"'");au.has(e)||au.set(e,0);let t=au.get(e);if(au.set(e,au.get(e)+1),t>0){let n=`${e}_${t}`;return au.set(n,1),n}else return e}var lB=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Lk(e){return!!e.match(lB)}function uB(e){return e===parseInt(e.toString(),10)}function ls(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,nt(e)}function ru(e){return Jl(Wk(e)).dataSync()[0]}function us(e){return ea(Wk(e)).dataSync()[0]}function Da(e,t){if(t<e)throw new B(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let a=e;a<t;++a)n.push(a);return n}function op(e,t){return e.asType(t)}function lp(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 cB(e,t){return D(()=>{if(e.shape.length!==2)throw new B(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=lp(e,1);return Mb(n,[1,t,1])})}function pB(e){let t=[ls(e.shape)];return e.reshape(t)}function dB(e){if(e.rank<=1)throw new B(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],ls(e.shape,1)];return e.reshape(t)}function Ui(e,t,n){return D(()=>{switch(e.rank){case 1:return qh(e,t,n);case 2:return mb(e,[t,0],[n,e.shape[1]]);case 3:return Ql(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Qc(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 B(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Rb(e,t,n){return D(()=>{switch(e.rank){case 1:return qh(e,t,n);case 2:return mb(e,[0,t],[e.shape[0],n]);case 3:return Ql(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Qc(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new B(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function cm(e,t,n,a){return D(()=>{switch(e.rank){case 1:return qh(e,t,n);case 2:switch(a){case 1:return Ui(e,t,n);case 2:return Rb(e,t,n);default:throw new B(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return Ui(e,t,n);case 2:return Ql(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Rb(e,t,n);default:throw new B(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return Ui(e,t,n);case 2:return Qc(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Qc(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Rb(e,t,n);default:throw new B(`The axis is not within the rank of the tensor ${a}`)}default:throw new B(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Pb(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 Vk(e,t){switch(e.rank){case 1:return f1([e,t]);case 2:return g1([e,t],0);case 3:return y1([e,t],0);case 4:return b1([e,t],0);default:throw new B(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Mb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new B(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Xa(e,t)}function pm(e,t=0,n=1,a,r){return R1(e,t,n,a,r)}function nr(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 is.matMul({a:e,b:t,transposeA:r,transposeB:s,bias:a?Ob(e.rank,a,Fa()):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 is.matMul({a:e,b:t,transposeA:d,transposeB:h,bias:a?Ob(e.rank,a,Fa()):null,activation:n}).reshape(p)}}function Uk(e,t,n){return D(()=>(Array.isArray(t)?t=nt(t,"int32"):t=t.toInt(),Di(e,t,n)))}function up(e){return L(e,e)}function Ob(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new B(`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 B(`Unsupported input rank by biasAdd: ${t.rank}`)}function ar(e,t,n){return D(()=>(n==null&&(n=Fa()),Mt(n),e.add(Ob(e.rank,t,n))))}function hB(e,t=1){if(t!==1)throw new $e(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Kl(e)}function mB(e){return D(()=>we(e,Bt(e).add(1)))}function Gk(e,t,n,a){return D(()=>ak(e,t,n,a))}function fB(e){return D(()=>{let t=Z(.5,L(.2,e));return Xt(t,0,1)})}function cp(e,t,n=!1){return n?e():t()}var gB=["fanIn","fanOut","fanAvg"],yB=["normal","uniform","truncatedNormal"];function bB(e){Wi(gB,"FanMode",e)}function xB(e){Wi(yB,"Distribution",e)}var ya=class extends re.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Lb=class extends ya{apply(e,t){return xt(e,t)}};Lb.className="Zeros";re.registerClass(Lb);var dm=class extends ya{apply(e,t){return Ja(e,t)}};dm.className="Ones";re.registerClass(dm);var zb=class extends ya{constructor(e){super();if(typeof e!="object")throw new B(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new B(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return D(()=>L(he(this.value),Ja(e,t)))}getConfig(){return{value:this.value}}};zb.className="Constant";re.registerClass(zb);var Bb=class extends ya{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 Zl(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Bb.className="RandomUniform";re.registerClass(Bb);var Wb=class extends ya{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 pm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Wb.className="RandomNormal";re.registerClass(Wb);var Vb=class extends ya{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 Xh(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Vb.className="TruncatedNormal";re.registerClass(Vb);var Ub=class extends ya{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 B("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,nb(e[0]))})}getConfig(){return{gain:this.gain}}};Ub.className="Identity";re.registerClass(Ub);function vB(e,t="channelsLast"){let n,a;if(Mt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=ls(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=ls(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=ls(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var Tn=class extends ya{constructor(e){super();if(e.scale<0)throw new B(`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,bB(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,xB(this.distribution),this.seed=e.seed}apply(e,t){let n=vB(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 Xh(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Zl(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Tn.className="VarianceScaling";re.registerClass(Tn);var hm=class extends Tn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};hm.className="GlorotUniform";re.registerClass(hm);var mm=class extends Tn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};mm.className="GlorotNormal";re.registerClass(mm);var fm=class extends Tn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};fm.className="HeNormal";re.registerClass(fm);var gm=class extends Tn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};gm.className="HeUniform";re.registerClass(gm);var ym=class extends Tn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};ym.className="LeCunNormal";re.registerClass(ym);var bm=class extends Tn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Tn.className}};bm.className="LeCunNormal";re.registerClass(bm);var Gb=class extends ya{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=pm(n,0,1,"float32"),r=gk.gramSchmidt(a);return e[0]>e[1]&&(r=r.transpose()),L(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Gb.className="Orthogonal";re.registerClass(Gb);var Hk={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 jk(e,t={}){return rp(e,re.SerializationMap.getMap().classNameMap,t,"initializer")}function _t(e){return Sb(e)}function kt(e){if(typeof e=="string"){let t=e in Hk?Hk[e]:e;if(t==="GlorotNormal")return new mm;if(t==="GlorotUniform")return new hm;if(t==="HeNormal")return new fm;if(t==="HeUniform")return new gm;if(t==="LeCunNormal")return new ym;if(t==="LeCunUniform")return new bm;{let n={};return n.className=t,n.config={},jk(n)}}else return e instanceof ya?e:jk(e)}function Bz(){return new Lb}function Wz(){return new dm}function Vz(e){return new zb(e)}function Uz(e){return new Bb(e)}function Gz(e){return new Wb(e)}function Hz(e){return new Vb(e)}function jz(e){return new Ub(e)}function qz(e){return new Tn(e)}function Kz(e){return new hm(e)}function Xz(e){return new mm(e)}function Yz(e){return new fm(e)}function Jz(e){return new gm(e)}function Zz(e){return new ym(e)}function Qz(e){return new bm(e)}function eB(e){return new Gb(e)}var qk={};Oe(qk,{Layer:()=>qe,RNN:()=>rr,RNNCell:()=>pp,activation:()=>PB,add:()=>HB,alphaDropout:()=>_W,average:()=>jB,averagePooling1d:()=>Hb,averagePooling2d:()=>jb,averagePooling3d:()=>qb,avgPool1d:()=>tW,avgPool2d:()=>aW,avgPool3d:()=>sW,avgPooling1d:()=>nW,avgPooling2d:()=>rW,avgPooling3d:()=>iW,batchNormalization:()=>ZB,bidirectional:()=>vW,concatenate:()=>qB,conv1d:()=>_B,conv2d:()=>EB,conv2dTranspose:()=>AB,conv3d:()=>FB,convLstm2d:()=>gW,convLstm2dCell:()=>yW,cropping2D:()=>DB,dense:()=>OB,depthwiseConv2d:()=>RB,dot:()=>JB,dropout:()=>LB,elu:()=>kB,embedding:()=>GB,flatten:()=>BB,gaussianDropout:()=>CW,gaussianNoise:()=>SW,globalAveragePooling1d:()=>oW,globalAveragePooling2d:()=>lW,globalMaxPool1d:()=>kW,globalMaxPool2d:()=>IW,globalMaxPooling1d:()=>Xk,globalMaxPooling2d:()=>Yk,gru:()=>cW,gruCell:()=>pW,input:()=>Kk,inputLayer:()=>wB,layerNormalization:()=>QB,leakyReLU:()=>NB,lstm:()=>dW,lstmCell:()=>hW,masking:()=>EW,maxPool1d:()=>NW,maxPool2d:()=>TW,maxPooling1d:()=>Jk,maxPooling2d:()=>Zk,maxPooling3d:()=>uW,maximum:()=>KB,minimum:()=>XB,multiply:()=>YB,permute:()=>UB,prelu:()=>TB,reLU:()=>IB,repeatVector:()=>WB,reshape:()=>VB,rnn:()=>bW,separableConv2d:()=>$B,simpleRNN:()=>mW,simpleRNNCell:()=>fW,softmax:()=>SB,spatialDropout1d:()=>zB,stackedRNNCells:()=>xW,thresholdedReLU:()=>CB,timeDistributed:()=>wW,upSampling2d:()=>MB,zeroPadding2d:()=>eW});var AW=0;function Qk(){return AW++}var xm={};function vm(e=""){return e in xm||(xm[e]=0),xm[e]+=1,e+xm[e].toString()}function Kb(e){return Array.isArray(e)&&Array.isArray(e[0])}function wm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Re(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new B(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function mt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new B(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function km(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 eI="Variable",tI=class{constructor(e,t="float32",n=eI,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Qk(),n=n==null?eI:n,this.originalName=zk(n),this.name=Bk(this.originalName),this.trainable_=a,this.constraint=r,this.val=O1(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),FW(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 FW(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Xb(e){return e.map(t=>t.read())}function Yb(e){e.forEach(t=>{t[0].write(t[1])})}var Jt=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||{}}},Ma=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=Qk(),s!=null&&(this.originalName=zk(s),this.name=Bk(this.originalName)),this.rank=t.length}},$W=0,Im=class{constructor(e,t){this.callArgs=t,this.id=$W++,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}}},DW=0,qe=class extends re.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=DW++,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=Sr(n)+"_"+vm(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 $a(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new B(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Nn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Nn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Tr(`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 Tr(`Layer ${this.name} is not connected, no input to return.`);return Nn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Tr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Tr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Nn(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=vt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=vt(this.inputSpec);if(e.length!==t.length)throw new B(`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 B(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${s}`);if(r.maxNDim!=null&&s>r.maxNDim)throw new B(`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 B(`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 B(`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 B(`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 B(`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=vt(e),a=!0;for(let s of n)if(!(s instanceof Ma)){a=!1;break}let r=!0;for(let s of n)if(s instanceof Ma){r=!1;break}if(a===r)throw new B("Arguments to apply() must be all SymbolicTensors or all Tensors");return Vi(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of vt(e))s.push(i.shape);this.build(Nn(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=vt(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=Nn(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=MW(e),i=this.computeOutputShape(s),o,l=RW(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 Ma(l,c,this,vt(e),t,this.name,u)):o=new Ma(l,i,this,vt(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 Tr(`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 Tr(`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 $a(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return km(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Xb(e?this.trainableWeights:this.weights)}setWeights(e){D(()=>{let t=this.weights;if(t.length!==e.length)throw new B(`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=Xb(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 B(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}Yb(n)})}addWeight(e,t,n,a,r,s,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new B(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(a=kt("zeros"));let o=a.apply(t,n),l=new tI(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=vt(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=vt(e);t=vt(t),n=vt(n),a=vt(a),r=wm(r),s=wm(s);let l=[],c=[],u=[];for(let p of o)l.push(p.sourceLayer),c.push(p.nodeIndex),u.push(p.tensorIndex);new Im({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 MW(e){e=vt(e);let t=[];for(let n of e)t.push(n.shape);return Nn(t)}function RW(e){return"float32"}function nI(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=nI(i,o,l);for(let u of c)r.indexOf(u)===-1&&r.push(u)}return r}}}var su=class extends qe{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:vm("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 B("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 B("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new B("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 Ma(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new Im({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new B(`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}}};su.className="InputLayer";re.registerClass(su);function aI(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 B("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 su({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}async function cs(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 rI(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var sI;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(sI||(sI={}));var PW=125,iu=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){}},iI=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)}},OW=class extends iu{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(we(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),Kt(t[n])}))}},oI=class extends iu{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]}},lI=class extends iu{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=PW),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");k.isNumber(this.yieldEvery)&&(this.maybeWait=zz(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 cs(n),a.push(this.yield(e,t,n))),a.push(lm()),await Promise.all(a)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await cs(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await cs(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(lm()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await cs(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await cs(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(lm()):k.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await cs(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await cs(e),await this.trainEnd(e))}};function uI(e,t){return e==null&&(e={}),e instanceof iu?[e]:Array.isArray(e)&&e[0]instanceof iu?e:vt(e).map(n=>new lI(n,t))}var ba=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}`),ba.checkForDuplicate(t),ba.constructors[e]==null&&(ba.constructors[e]=[]),ba.constructors[e].push(t)}static checkForDuplicate(e){for(let t in ba.constructors)ba.constructors[+t].forEach(n=>{if(n===e)throw new B("Duplicate callback constructor.")})}static clear(){ba.constructors={}}static createCallbacks(e){let t=[];for(let n in ba.constructors){let a=+n;e>=a&&t.push(...ba.constructors[a])}return t.map(n=>new n)}};ba.constructors={};function cI(e,t,n,a,r,s,i,o,l){let c=new oI,u=[new OW,...ba.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let p=new iI(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 Ra(e,t={},n=!1){return rp(e,re.SerializationMap.getMap().classNameMap,t,"layer",n)}function Nm(e,t){return D(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));let n=Ce(up(e),t,!0),a=In(n.shape,Vt()),r=an(Ca(n,a));return we(e,r)})}function Gi(e,t){return D(()=>Ct(up(ge(t,e)),-1))}function Tm(e,t){return D(()=>Ct(Bt(ge(t,e)),-1))}function ou(e,t){return D(()=>{let n=ge(e,t),a=Xt(Bt(e),Vt(),Number.MAX_VALUE),r=Bt(we(n,a));return L(100,Ct(r,-1))})}function LW(e,t){return D(()=>{let n=Xt(t,Vt(),Number.MAX_VALUE),a=Dn(Z(1,n)),r=Xt(e,Vt(),Number.MAX_VALUE),s=Dn(Z(1,r));return Ct(up(ge(a,s)),-1)})}function zW(e,t){return D(()=>{let n=Ca(0,ge(1,L(e,t)));return Ct(up(n),-1)})}function BW(e,t){return D(()=>{let n=Ca(0,ge(1,L(e,t)));return Ct(n,-1)})}function WW(e,t){return D(()=>{let n=Ce(L(e,t),-1),a=ea(L(ge(1,e),t),-1);return Ca(0,Z(1,ge(a,n)))})}function VW(e,t){return D(()=>{let n=Math.log(2),a=ge(t,e),r=ge(Z(a,Yl(L(-2,a))),n);return Ct(r,-1)})}function dp(e,t,n=!1){return D(()=>{if(n)t=_a(t);else{let a=Ce(t,t.shape.length-1,!0);t=we(t,a)}return t=Xt(t,Vt(),1-Vt()),St(Ce(L(e.toFloat(),Dn(t)),t.shape.length-1))})}function Sm(e,t,n=!1){return D(()=>{let a=Xl(pB(e)).toInt();t=Xt(t,Vt(),1-Vt());let r=t.shape,s=Gl(a,r[r.length-1]).reshape(r);return dp(s,t,n)})}function UW(e,t){if(!k.arraysEqual(e.shape,t.shape))throw new B(`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 Cm(e,t){return D(()=>{let n;return n=Xt(t,Vt(),1-Vt()),n=Dn(we(n,ge(1,n))),Ct(UW(e,n),-1)})}function GW(e,t){return D(()=>{let n=Xt(e,Vt(),1),a=Xt(t,Vt(),1);return Ce(L(e,Dn(we(n,a))),-1)})}function HW(e,t){return D(()=>{let n=Dn(Z(Vt(),t));return Ct(ge(t,L(e,n)),-1)})}function Jb(e,t){return D(()=>{let n=Nm(e,-1),a=Nm(t,-1),r=L(n,a);return St(Ce(r,-1))})}var _m={meanSquaredError:Gi,meanAbsoluteError:Tm,meanAbsolutePercentageError:ou,meanSquaredLogarithmicError:LW,squaredHinge:zW,hinge:BW,categoricalHinge:WW,logcosh:VW,categoricalCrossentropy:dp,sparseCategoricalCrossentropy:Sm,binaryCrossentropy:Cm,kullbackLeiblerDivergence:GW,poisson:HW,cosineProximity:Jb};function Zb(e){if(typeof e=="string"){if(e in _m)return _m[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 B(t)}else return e}function Qb(e,t){return D(()=>{let n=L(.5,Mn(t)),a=op(Qn(t,n),e.dtype);return Ct(wr(e,a),-1)})}function ex(e,t){return D(()=>op(wr(Vc(e,-1),Vc(t,-1)),"float32"))}function pI(e,t){return D(()=>fa(e.equal(1),t.equal(1)).sum().cast("float32"))}function jW(e,t){return D(()=>fa(e.equal(1),t.equal(0)).sum().cast("float32"))}function qW(e,t){return D(()=>fa(e.equal(0),t.equal(1)).sum().cast("float32"))}function dI(e,t){return D(()=>{let n=pI(e,t),a=qW(e,t),r=n.add(a);return kn(Qn(r,0),n.div(r),0).cast("float32")})}function KW(e,t){return D(()=>{let n=pI(e,t),a=jW(e,t),r=n.add(a);return kn(Qn(r,0),n.div(r),0).cast("float32")})}function hI(e,t){return Cm(e,t)}function mI(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)),wr(e,t).asType("float32")}var XW=Gi,YW=Gi,JW=Tm,ZW=Tm,QW=ou,e4=ou,tx=dp,t4=Jb,fI=Sm,Em={binaryAccuracy:Qb,categoricalAccuracy:ex,precision:dI,categoricalCrossentropy:tx,sparseCategoricalCrossentropy:fI,mse:XW,MSE:YW,mae:JW,MAE:ZW,mape:QW,MAPE:e4,cosine:t4};function n4(e){if(typeof e=="string"&&e in Em)return Em[e];if(typeof e!="string"&&e!=null)return e;throw new B(`Unknown metric ${e}`)}function Am(e){if(tr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(_m))if(_m[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Em))if(Em[n]===e){t=n;break}return t!==void 0?t:e.name}}function a4(e){let t={Adagrad:()=>Li.adagrad(.01),Adadelta:()=>Li.adadelta(1,.95,Vt()),Adam:()=>Li.adam(.001,.9,.999,Vt()),Adamax:()=>Li.adamax(.002,.9,.999,Vt(),0),RMSProp:()=>Li.rmsprop(.001,.9,0,Vt()),SGD:()=>Li.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 B(`Unknown Optimizer ${e}`)}var gI=1*1024*1024;function yI(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!nx(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>gI&&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 <= ${gI}.`)}}function nx(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"||!nx(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!nx(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function l4(e,t,n,a=console.log){let r=s4(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)),Fm(s,n,a),a("=".repeat(t));let o=e.layers;for(let u=0;u<o.length;++u)r?i4(o[u],n,a):o4(o[u],n,i,a),a((u===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=r4(e),c=km(e.nonTrainableWeights);a(`Total params: ${l+c}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${c}`),a("_".repeat(t))}function r4(e){let t;return e.collectedTrainableWeights!=null?t=km(e.collectedTrainableWeights):t=km(e.trainableWeights),t}function s4(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 Fm(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 i4(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()];Fm(i,t,n)}function o4(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];Fm(c,t,a);for(let u=1;u<s.length;++u)Fm(["","","",s[u]],t,a)}function bI(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function hp(e,t){if(e===null)return null;if(typeof e=="string")return Bi(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];bI(t,r,s)?n.push(s):n.push(hp(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=Bi(a);n[s]=hp(r,s)}}return n}}function ax(e,t){if(e==null)return null;if(typeof e=="string")return Sr(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];bI(t,r,s)?n.push(s):n.push(ax(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a],s=Sr(a);(a==="name"||a==="className")&&typeof r=="string"?n[s]=r:n[s]=ax(r,a)}return n}}var $m="2.8.5";function u4(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return pe(t,e.dtype)}catch(n){throw new B(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var Hi=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Hi)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]=u4(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new B(`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 Ma){if(this.id2Value[e.id]==null)throw new B(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new B(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Ma){if(this.id2Value[e.id]==null)throw new B(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new B(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Fe(this.id2Mask)}},rx={},xI={};function mp(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(rx[u]==null){let m=c4(i,t);p=m.sorted,d=m.recipientCounts,rx[u]=p,xI[u]=d}p=rx[u],d={},r||Object.assign(d,xI[u]);let h=new Hi(t);for(let m=0;m<p.length;++m){if(a!=null){let F=Nh().numTensors;F>a.maxNumTensors&&(a.maxNumTensors=F),F<a.minNumTensors&&(a.minNumTensors=F)}let f=p[m],g=f.sourceLayer;if(g instanceof su)continue;let y=[],b=[],v=[],x=!1;for(let F of f.inputs){let O=h.getValue(F),W=h.getMask(F);y.push(O),b.push(W),W!=null&&(x=!0),r||(d[F.name]--,d[F.name]===0&&!t.hasKey(F)&&o.indexOf(F.name)===-1&&!O.isDisposed&&F.sourceLayer.stateful!==!0&&v.push(O))}x&&(n=n||{},n.mask=b[0]);let N=vt(g.apply(y,n)),T=null;g.supportsMasking&&(T=g.computeMask(y,b));let C=p4(f),$=Array.isArray(C)?C:[C];for(let F=0;F<$.length;++F){h.hasKey($[F])||h.add($[F],N[F],Array.isArray(T)?T[0]:T);let O=o.indexOf($[F].name);O!==-1&&(l[O]=N[F])}r||Fe(v)}return h.disposeMasks(),s?l:l[0]}function c4(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=vI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=vI(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:d4(a)}}function d4(e){let t={};for(let n in e)t[n]=e[n].size;return t}function vI(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 p4(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 sr=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=vm(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],os(this.inputs).length!==this.inputs.length)throw new B(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);os(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;tr(v===0,"input layer has >1 nodes"),tr(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 su))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 $a(`The tensor ${y.name} at layer "${x.name}" is part of a cycle.`);if(b.indexOf(C)!==-1)return;this.containerNodes.add(sr.nodeKey(x,N)),x.id in s||(s[x.id]=Object.keys(s).length),v.indexOf(C)===-1&&v.push(C);let $=C.inboundLayers.length;for(let F=0;F<$;F++){let O=C.inputTensors[F],W=C.inboundLayers[F],V=C.nodeIndices[F],H=C.tensorIndices[F];o(O,b,v,W,V,H)}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],$=t[C.id]==null?0:t[C.id];t[C.id]=Math.max(b+1,$),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(um);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 sr&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=d,h=Object.keys(p).map(y=>parseInt(y,10)).sort(um);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 $a(`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 $a(`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 Im({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 B("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 B(`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 B(`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 B(`${s.length} of ${a} weights are not set: ${s}`)}Yb(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${$m}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=ax(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return D(()=>{e=vt(e);let n=new Hi;for(let a=0;a<this.inputs.length;++a)n.add(this.inputs[a],e[a]);return mp(this.outputs,n,t)})}computeMask(e,t){return D(()=>{e=vt(e);let n;return t==null?n=zi(null,e.length):n=vt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=wm(e);if(t.length!==this.inputLayers.length)throw new B(`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(um);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(Nn(u)),d=wm(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];tr(o in n),r.push(n[o])}return Nn(r)}runInternalGraph(e,t){t==null&&(t=zi(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(um);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=vt(u.call(v,m)),b=vt(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=vt(u.call(f,m)),b=vt(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){tr(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 sr?1:0;for(let r=0;r<a.inboundNodes.length;r++){let s=sr.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 B(`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 B("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new B(`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=sr.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=sr.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=sr.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=sr.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=sr.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 $=C.inboundNodes[N];y.push($.outputTensors[T])}y.length>0&&f.apply(Nn(y),b)}function l(f){let g=f.name,y=Ra(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),r[g]=y,f.inboundNodes.forEach(b=>{if(!(b instanceof Array))throw new B(`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(;!Lz(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];tr(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];tr(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 B("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 h4(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 wI(e,t){return h4(e,t,"classWeight")}async function kI(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])}),nt(i,"float32")}else return null}function m4(e,t){return L(e,t)}var f4=32;function NI(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=II("input",e.inputNames,n),i=II("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 II(e,t,n){if(n instanceof z)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 B(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function g4(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 b4(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(TI(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=g4(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=uI(n.callbacks,n.yieldEvery),p=n.verbose==null?1:n.verbose,{callbackList:d,history:h}=cI(u,p,n.epochs,null,null,y4(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}=NI(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 O=wI(n.classWeight,e.outputNames);for(let W=0;W<O.length;++W)C.push(await kI(N[W],null,O[W]))}let $=x.concat(N).concat(C),F=o($);Fe($);for(let O=0;O<l.length;++O){let W=l[O],V=F[O];T[W]=V,Kt(V)}await d.onBatchEnd(b,T),rI(T),b++,y++}if(a?y>=n.batchesPerEpoch:v.done){if(r){let x;TI(n.validationData)?x=vt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):x=vt(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?f4: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 y4(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function TI(e){return typeof e.iterator=="function"}function x4(e){return typeof e.next=="function"}async function v4(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=x4(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}=NI(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(he(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]=we(s[c],o),Fe(u)}return Nn(s)}function sx(e){k.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function fp(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>Ui(a,t,n-t)):Ui(e,t,n-t)}function ix(e,t){return D(()=>e==null?null:Array.isArray(e)?e.map(n=>ix(n,t)):Uk(e,t.dtype==="int32"?t:t.toInt()))}function ox(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 w4(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 B("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=Da(0,g)),i==null&&(i=1);let{callbackList:b,history:v}=cI(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=nt(y),C=ox(g,r);for(let $=0;$<C.length;++$){let F={};if(await b.onBatchBegin($,F),D(()=>{let O=C[$][0],W=C[$][1],V=Ui(T,O,W-O);F.batch=$,F.size=W-O;let H=ix(n,V),K=t(H);for(let j=0;j<a.length;++j){let Y=a[j],J=K[j];F[Y]=J,Kt(J)}if($===C.length-1&&f){let j=e.testLoop(l,c,r);for(let Y=0;Y<a.length;++Y){let J=a[Y],ne=j[Y];Kt(ne),N["val_"+J]=ne}}}),await b.onBatchEnd($,F),rI(F),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 k4(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;sx(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 B(`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=fp(r,T,C),r=fp(r,0,T),c=fp(s,T,C),s=fp(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=uI(a.callbacks,a.yieldEvery);return await w4(e,y,g,b,p,a.epochs,a.verbose,N,v,f,a.shuffle,x,a.initialEpoch,null,null)}finally{e.isTraining=!1,ji(r,t),ji(s,n),ji(l,i),ji(c,o),u!=null&&Fe(u)}}function SI(e){let t=[];e instanceof z&&(e=[e]);for(let n=0;n<e.length;++n){let a=e[n];if(a.rank===1)t.push(lp(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 ji(e,t){if(e==null)return;let n=[];if(t instanceof z)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 z)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 I4(e){return e instanceof z}function lx(e){return Array.isArray(e)}function CI(e){return!I4(e)&&!lx(e)}function _I(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(lx(e)&&e.length>0)i=!0;else if(CI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new B(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(CI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new B(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(lx(e)){if(e=e,e.length!==t.length)throw new B(`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 B(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=SI(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 B(`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 B(`Error when checking ${r}: expected ${t[i]} to have shape [${n[i]}], but got array with shape [${o.shape}].`)}}return s}function N4(e,t,n){let a=os(e.map(s=>s.shape[0]));a.sort();let r=os(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new B(`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 B(`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 B(`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 T4(e,t,n){let a=[Gi,Cm,dp];for(let r=0;r<e.length;++r){let s=e[r],i=t[r],o=n[r];if(i!=null){if(i===dp&&s.shape[s.shape.length-1]===1)throw new B(`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 B(`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 EI(e,t,n,a=!0,r=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new B(`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 B(`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 B(`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 B(`Error when checking ${r}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function S4(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 C4="layers-model",Cr=class extends sr{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new B("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).");l4(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=a4(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Nr))throw new B("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 B(`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(Zb(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new B(`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=>Zb(s))}else{let s=Zb(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=[],Vi("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=S4(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])};Vi("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]===Cm?["accuracy","acc"].indexOf(d)!==-1?u=Qb:["crossentropy","ce"].indexOf(d)!==-1&&(u=hI):this.lossFunctions[s]===Sm?["accuracy","acc"].indexOf(d)!==-1?u=mI:["crossentropy","ce"].indexOf(d)!==-1&&(u=fI):["accuracy","acc"].indexOf(d)!==-1?u=ex:["crossentropy","ce"].indexOf(d)!==-1&&(u=tx);let f;["accuracy","acc"].indexOf(d)!==-1?f="acc":["crossentropy","ce"].indexOf(d)!==-1&&(f="ce"),p=u,c=l+f}else p=n4(d),c=l+Am(d);let h;Vi(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;sx(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 Nn(l)}finally{ji(s[0],e),ji(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),v4(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new B(`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 B(`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 B("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new Hi;if(e instanceof z&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new B(`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 B(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=mp(r,s);return n?i:i[0]}retrieveSymbolicTensors(e){let t=zi(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 B(`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=ox(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=fp(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 Hi(u);return mp(this.outputs,p)}).forEach((o,l)=>s[l].push(o));return Nn(s.map(i=>Qe(i,0)))})}predict(e,t={}){let n=SI(e);EI(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return sx(a),this.predictLoop(n,a)}finally{ji(n,e)}}predictOnBatch(e){EI(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 $a("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]===Sm?r.push(i.slice(0,i.length-1).concat([1])):r.push(i)}if(e=_I(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=_I(t,this.feedOutputNames,r,!1,"target"),N4(e,t,null),T4(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!=0)throw new B(`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=wI(a,this.outputNames);l=[];for(let u=0;u<c.length;++u)l.push(await kI(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=ox(s,n),l=nt(Da(0,s));for(let c=0;c<o.length;++c){let u=o[c][0],p=o[c][1],d=Ui(l,u,p-u),h=ix(t,d),m=e(h);if(c===0)for(let f=0;f<m.length;++f)i.push(he(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]=we(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;Ak(e,a)>1&&(r+=`_${Ak(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 Hi(c),p=mp(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=m4(m,r[h]));let f=Ct(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=Ct(f(a[g],p[g]))}Kt(m),s.push(m)}return d=Ct(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 Hi(s),o=mp(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let c=this.lossFunctions[l],u=Ct(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=Ct(c(r[u],o[u]));t.push(p)}return t})}async fit(e,t,n={}){return k4(this,e,t,n)}async fitDataset(e,t){return b4(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),Nn(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=Nh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Nh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Sr(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=>Sr(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]=Sr(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[Sr(Am(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Sr(Am(e)));{let e={};for(let t in this.metrics)e[t]=Sr(Am(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=hp(e.optimizer_config),n=Ra(t),a;if(typeof e.loss=="string")a=Bi(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>Bi(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=Bi(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>Bi(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=Bi(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let i=qt.getSaveHandlers(e);if(i.length===0)throw new B(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new B(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new B("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await qt.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:C4,generatedBy:`TensorFlow.js tfjs-layers v${$m}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await qt.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=qt.concatenateArrayBuffers([n.data,o])}if(this.userDefinedMetadata!=null){let i=!0;yI(this.userDefinedMetadata,this.name,i),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){yI(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Cr.className="Model";re.registerClass(Cr);var AI=class extends Cr{};AI.className="Functional";re.registerClass(AI);async function _4(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=hp(n),r=Ra(a,t);if(e.weightsManifest!=null){let s=await qt.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 A4(e,t){if(t==null&&(t={}),typeof e=="string"){let n=qt.getLoadHandlers(e,t);if(n.length===0)n.push(qt.browserHTTPRequest(e,t));else if(n.length>1)throw new B(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return E4(e,void 0,t)}async function E4(e,t,n){if(n==null&&(n={}),e.load==null)throw new B("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=Ra(hp(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 B("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=F4(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 F4(e,t){let n=qt.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 lu=class extends Cr{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:vm("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 B(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof lu||e instanceof Cr,n;if(t){if(n=e,n.outputs.length!==1)throw new B("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 B("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 B("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=aI({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 B(`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 B("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=nI(this.outputs[0])}this.inboundNodes=[],new Im({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:zi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=e.apply(this.outputs[0]);if(Array.isArray(a))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(mt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Cr({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 $a("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 $a("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 $a("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 $a("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 B("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 lu))throw new $e(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=Ra(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new B("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 B("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}}};lu.className="Sequential";re.registerClass(lu);function $4(e){return new Cr(e)}function D4(e){return new lu(e)}function M4(e,t){return t==null&&(t={}),A4(e,t)}function Kk(e){return aI(e)}function R4(e,t){ba.registerCallbackConstructor(e,t)}var On=class extends re.Serializable{getConfig(){return{}}},FI=class extends On{apply(e,t=1){return hB(e,t)}};FI.className="elu";re.registerClass(FI);var $I=class extends On{apply(e){return Gh(e)}};$I.className="selu";re.registerClass($I);var DI=class extends On{apply(e){return Ye(e)}};DI.className="relu";re.registerClass(DI);var MI=class extends On{apply(e){return D(()=>Ri(6,Ye(e)))}};MI.className="relu6";re.registerClass(MI);var RI=class extends On{apply(e){return e}};RI.className="linear";re.registerClass(RI);var PI=class extends On{apply(e){return ma(e)}};PI.className="sigmoid";re.registerClass(PI);var OI=class extends On{apply(e){return fB(e)}};OI.className="hardSigmoid";re.registerClass(OI);var LI=class extends On{apply(e){return Yl(e)}};LI.className="softplus";re.registerClass(LI);var zI=class extends On{apply(e){return mB(e)}};zI.className="softsign";re.registerClass(zI);var BI=class extends On{apply(e){return ql(e)}};BI.className="tanh";re.registerClass(BI);var ux=class extends On{apply(e,t=-1){return _a(e,t)}};ux.className="softmax";re.registerClass(ux);var WI=class extends On{apply(e,t=-1){return Ph(e,t)}};WI.className="logSoftmax";re.registerClass(WI);var VI=class extends On{apply(e,t=1){return D(()=>ma(e.mul(t)).mul(e))}};VI.className="swish";re.registerClass(VI);function ps(e){return e.getClassName()}function cx(e,t={}){return rp(e,re.SerializationMap.getMap().classNameMap,t,"activation")}function ds(e){if(e==null){let t={};return t.className="linear",t.config={},cx(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},cx(t)}else return e instanceof On?e:cx(e)}function px(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 UI=class extends re.Serializable{},gp=class extends UI{constructor(e){super();px(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=xt([1]);return this.hasL1&&(t=Z(t,Ce(L(this.l1,Bt(e))))),this.hasL2&&(t=Z(t,Ce(L(this.l2,up(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};gp.className="L1L2";re.registerClass(gp);function P4(e){return px(e),new gp({l1:e!=null?e.l1:null,l2:0})}function O4(e){return px(e),new gp({l2:e!=null?e.l2:null,l1:0})}var GI={l1l2:"L1L2"};function ft(e){return Sb(e)}function HI(e,t={}){return rp(e,re.SerializationMap.getMap().classNameMap,t,"regularizer")}function It(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in GI?GI[e]:e,config:{}};return HI(t)}else return e instanceof UI?e:HI(e)}var dx=class extends qe{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Re(e);let n=Ye(e);return this.maxValue!=null&&(n=Xt(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};dx.className="ReLU";re.registerClass(dx);var hx=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=Re(e);return qc(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};hx.className="LeakyReLU";re.registerClass(hx);var mx=class extends qe{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=kt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=It(e.alphaRegularizer),this.alphaConstraint=Gt(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 B(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a<e.length;++a)n[a]=e[a];this.inputSpec=[new Jt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Re(e),Jc(e,this.alpha.read())}getConfig(){let e={alphaInitializer:_t(this.alphaInitializer),alphaRegularizer:ft(this.alphaRegularizer),alphaConstraint:Ut(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};mx.className="PReLU";re.registerClass(mx);var fx=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=Re(e);return Kl(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};fx.className="ELU";re.registerClass(fx);var gx=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=Re(e);return n.mul(op(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};gx.className="ThresholdedReLU";re.registerClass(gx);var yx=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new ux().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Re(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}};yx.className="Softmax";re.registerClass(yx);function uu(e,t,n){if(typeof e=="number")return zi(e,t);if(e.length!==t)throw new B(`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(!uB(r))throw new B(`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 Pa(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 Dm(e,t,n,a){if(e==null)return null;if(a==="valid")e=e*t+us([n-t,0]);else if(a==="same")e=e*t;else throw new B(`Unsupport padding mode: ${a}.`);return e}function bx(e,t){return D(()=>(Mt(t),t==="channelsFirst"?Ue(e,[0,2,3,1]):e))}function jI(e,t){return D(()=>(Mt(t),t==="channelsFirst"?Ue(e,[0,2,3,4,1]):e))}function L4(e,t,n,a=1,r="valid",s,i=1){return D(()=>{if(s==null&&(s=Fa()),Mt(s),e.shape.length!==3)throw new B(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new B(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new B(`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=Eh(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=ar(o,n)),o})}function qI(e,t,n,a=[1,1],r="valid",s,i,o=null){return D(()=>{if(s==null&&(s=Fa()),Mt(s),e.rank!==3&&e.rank!==4)throw new B(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new B(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=bx(e,s);if(r==="causal")throw new $e("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=is.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 z4(e,t,n,a=[1,1,1],r="valid",s,i){return D(()=>{if(s==null&&(s=Fa()),Mt(s),e.rank!==4&&e.rank!==5)throw new B(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new B(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=jI(e,s);if(r==="causal")throw new $e("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Yy(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=ar(o,n)),s==="channelsFirst"&&(o=Ue(o,[0,4,1,2,3])),o})}var xx=class extends qe{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",xx.verifyArgs(t),this.rank=e,Yt(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=uu(t.kernelSize,e,"kernelSize"),this.strides=uu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,na(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Mt(this.dataFormat),this.activation=ds(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=kt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Gt(t.biasConstraint),this.biasRegularizer=It(t.biasRegularizer),this.activityRegularizer=It(t.activityRegularizer),this.dilationRate=uu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new B(`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 B(`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 B(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(tr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!_b(e.kernelSize,"number",1,3))throw new B(`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:ps(this.activation),useBias:this.useBias,biasInitializer:_t(this.biasInitializer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),biasConstraint:Ut(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},yp=class extends xx{constructor(e,t){super(e,t);this.kernel=null,yp.verifyArgs(t),this.filters=t.filters,Yt(this.filters,"filters"),this.kernelInitializer=kt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Gt(t.kernelConstraint),this.kernelRegularizer=It(t.kernelRegularizer)}build(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new B(`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=Re(e);let n,a=this.bias==null?null:this.bias.read(),r=$k(this.activation.getClassName());if(r!=null&&this.rank===2)n=qI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=L4(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=qI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=z4(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=mt(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=Pa(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:_t(this.kernelInitializer),kernelRegularizer:ft(this.kernelRegularizer),kernelConstraint:Ut(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 B(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},bp=class extends yp{constructor(e){super(2,e);bp.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!_b(e.kernelSize,"number",1,2))throw new B(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};bp.className="Conv2D";re.registerClass(bp);var Mm=class extends yp{constructor(e){super(3,e);Mm.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 B(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Mm.className="Conv3D";re.registerClass(Mm);var vx=class extends bp{constructor(e){super(e);if(this.inputSpec=[new Jt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new B(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==4)throw new B("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 B("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 Jt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{let n=Re(e);if(n.shape.length!==4)throw new B(`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=Dm(o,p,c,this.padding),m=Dm(l,d,u,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=Ue(n,[0,2,3,1]));let g=Ah(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Ue(g,[0,3,1,2])),this.bias!=null&&(g=ar(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,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]=Dm(t[a],o,s,this.padding),t[r]=Dm(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};vx.className="Conv2DTranspose";re.registerClass(vx);var KI=class extends yp{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 B("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new B("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 B(`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=kt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=It(t.depthwiseRegularizer),this.depthwiseConstraint=Gt(t.depthwiseConstraint),this.pointwiseInitializer=kt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=It(t.pointwiseRegularizer),this.pointwiseConstraint=Gt(t.pointwiseConstraint)}build(e){if(e=mt(e),e.length<this.rank+2)throw new B(`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 B(`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 Jt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{e=Re(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=Pi(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=ar(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=_t(this.depthwiseInitializer),e.pointwiseInitializer=_t(this.pointwiseInitializer),e.depthwiseRegularizer=ft(this.depthwiseRegularizer),e.pointwiseRegularizer=ft(this.pointwiseRegularizer),e.depthwiseConstraint=Ut(this.depthwiseConstraint),e.pointwiseConstraint=Ut(this.pointwiseConstraint),e}};KI.className="SeparableConv";var wx=class extends KI{constructor(e){super(2,e)}};wx.className="SeparableConv2D";re.registerClass(wx);var Rm=class extends yp{constructor(e){super(1,e);Rm.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"&&!_b(e.kernelSize,"number",1,1))throw new B(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};Rm.className="Conv1D";re.registerClass(Rm);var kx=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=Re(e),this.dataFormat==="channelsLast"){let n=cm(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return cm(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=cm(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return cm(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}};kx.className="Cropping2D";re.registerClass(kx);var Ix=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,Mt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,iB(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=Re(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}};Ix.className="UpSampling2D";re.registerClass(Ix);function B4(e,t,n=[1,1],a="valid",r,s){return D(()=>{r==null&&(r=Fa()),Mt(r);let i=bx(e,r);if(e.rank!==4)throw new B(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new B(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=vr(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=Ue(i,[0,3,1,2])),i})}var Nx=class extends xx{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=kt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Gt(e.depthwiseConstraint),this.depthwiseRegularizer=It(e.depthwiseRegularizer)}build(e){if(e=mt(e),e.length<4)throw new B(`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 B(`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=Re(e);let n=B4(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=ar(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Pa(t,this.kernelSize[0],this.padding,this.strides[0]),s=Pa(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=_t(this.depthwiseInitializer),e.depthwiseRegularizer=ft(this.depthwiseRegularizer),e.depthwiseConstraint=Ut(this.depthwiseRegularizer),e}};Nx.className="DepthwiseConv2D";re.registerClass(Nx);function XI(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new B("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 YI(e,t,n,a=!1,r,s,i=!1,o=!1){return D(()=>{let l=t.shape.length;if(l<3)throw new B(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(Da(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=Zn(r,-1)),r=Ue(r,c)),a&&(t=Rn(t,0),r!=null&&(r=Rn(r,0)));let u=[],p,d=n,h=t.shape[0],m=ht(t),f;r!=null&&(f=ht(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=Mn(N).sub(N),C=v[0].mul(N).add(d[0].mul(T)),$=d.map((F,O)=>v[1][O].mul(N).add(F.mul(T)));return{output:C,newStates:$}});p=x.output,d=x.newStates}o&&u.push(p)}let g;return o&&(g=Dt(u,1)),[p,g,d]})}var rr=class extends qe{constructor(e){super(e);let t;if(e.cell==null)throw new B("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Pm({cells:e.cell}):t=e.cell,t.stateSize==null)throw new B("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 Jt({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 Da(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Kb(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.");Kb(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,a=e.slice(2);this.inputSpec[0]=new Jt({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 B(`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 Jt({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new Tr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new B("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=>xt([n,a])):this.states_=[xt([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=>xt([n,a])):this.states_[0]=xt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new B(`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 B(`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=>Kt(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=XI(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 Jt({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 Ma){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=Re(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 B(`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=YI((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=xt(e.shape);return t=Ce(t,[1,2]),t=lp(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Mb(t,[1,n]):t):this.cell.stateSize>1?[Mb(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()===rr.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let a=t.cell,r=Ra(a,n);return new e(Object.assign(t,{cell:r}))}};rr.className="RNN";re.registerClass(rr);var pp=class extends qe{},Om=class extends pp{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Yt(this.units,"units"),this.activation=ds(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=kt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=kt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=kt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=It(e.kernelRegularizer),this.recurrentRegularizer=It(e.recurrentRegularizer),this.biasRegularizer=It(e.biasRegularizer),this.kernelConstraint=Gt(e.kernelConstraint),this.recurrentConstraint=Gt(e.recurrentConstraint),this.biasConstraint=Gt(e.biasConstraint),this.dropout=ru([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ru([1,us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return D(()=>{if(e=e,e.length!==2)throw new B(`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=hs({ones:()=>Mn(e),rate:this.dropout,training:a})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>Mn(n),rate:this.recurrentDropout,training:a}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=nr(L(e,s),this.kernel.read()):r=nr(e,this.kernel.read()),this.bias!=null&&(r=ar(r,this.bias.read())),i!=null&&(n=L(n,i));let o=Z(r,nr(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:ps(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};Om.className="SimpleRNNCell";re.registerClass(Om);var Tx=class extends rr{constructor(e){e.cell=new Om(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)}};Tx.className="SimpleRNN";re.registerClass(Tx);var Lm=class extends pp{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 B("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Yt(this.units,"units"),this.activation=ds(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ds(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=kt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=kt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=kt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=It(e.kernelRegularizer),this.recurrentRegularizer=It(e.recurrentRegularizer),this.biasRegularizer=It(e.biasRegularizer),this.kernelConstraint=Gt(e.kernelConstraint),this.recurrentConstraint=Gt(e.recurrentConstraint),this.biasConstraint=Gt(e.biasConstraint),this.dropout=ru([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ru([1,us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return D(()=>{if(e=e,e.length!==2)throw new B(`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=hs({ones:()=>Mn(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>Mn(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=nr(e,this.kernel.read());this.useBias&&(c=ar(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=nr(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=nr(L(o,a),d);l=this.activation.apply(Z(g,v));let x=Z(L(i,a),L(Z(1,St(i)),l));return[x,x]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ps(this.activation),recurrentActivation:ps(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Lm.className="GRUCell";re.registerClass(Lm);var Sx=class extends rr{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 Lm(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)}};Sx.className="GRU";re.registerClass(Sx);var xp=class extends pp{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Yt(this.units,"units"),this.activation=ds(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ds(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=kt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=kt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=kt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=It(e.kernelRegularizer),this.recurrentRegularizer=It(e.recurrentRegularizer),this.biasRegularizer=It(e.biasRegularizer),this.kernelConstraint=Gt(e.kernelConstraint),this.recurrentConstraint=Gt(e.recurrentConstraint),this.biasConstraint=Gt(e.biasConstraint),this.dropout=ru([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ru([1,us([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=mt(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let a;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,s=this.units;a=new(t=class extends ya{apply(i,o){let l=r.apply([s]),c=new dm().apply([s]),u=r.apply([s*2]);return Vk(Vk(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 B(`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=hs({ones:()=>Mn(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>Mn(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=nr(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,i[0])),p=Z(p,nr(a,this.recurrentKernel.read())),this.useBias&&(p=ar(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:ps(this.activation),recurrentActivation:ps(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};xp.className="LSTMCell";re.registerClass(xp);var Cx=class extends rr{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 xp(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)}};Cx.className="LSTM";re.registerClass(Cx);var Pm=class extends pp{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return 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){Kb(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,a)=>{Vi(`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(Ra(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 Xb(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]])}Yb(t)}};Pm.className="StackedRNNCells";re.registerClass(Pm);function hs(e){let{ones:t,rate:n,training:a=!1,count:r=1}=e,s=()=>Gk(t(),n),i=()=>cp(s,t,a);return!r||r<=1?Kt(i().clone()):Array(r).fill(void 0).map(i).map(o=>Kt(o.clone()))}var W4=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},JI=class extends rr{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 Jt({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 B("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=xt(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new Tr("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 B("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(()=>xt(r)):this.states_=[xt(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(()=>xt(r)):this.states_[0]=xt(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new B(`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 B(`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=>Kt(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=Pa(l,a[0],r,s[0],i[0]),p=Pa(c,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,u,p]:[u,p,n]]}};JI.className="ConvRNN2D";var zm=class extends xp{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,Yt(this.filters,"filters"),this.kernelSize=uu(n,2,"kernelSize"),this.kernelSize.forEach(o=>Yt(o,"kernelSize")),this.strides=uu(a||1,2,"strides"),this.strides.forEach(o=>Yt(o,"strides")),this.padding=r||"valid",na(this.padding),this.dataFormat=s||"channelsLast",Mt(this.dataFormat),this.dilationRate=uu(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>Yt(o,"dilationRate"))}build(e){var t;e=mt(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new B(`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 ya{apply(u,p){let d=l.apply([c]),h=Ja([c]),m=l.apply([c*2]);return Pb([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 B(`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=hs({ones:()=>Mn(a),rate:this.dropout,training:n,count:i}));let o=this.dropoutMask,l=(Q,ie,ee)=>!ie||!ie[ee]?Q:L(ie[ee],Q),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=hs({ones:()=>Mn(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,O]=this.useBias?Pn(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,v,C,this.padding),u=this.inputConv(u,x,$,this.padding),p=this.inputConv(p,N,F,this.padding),d=this.inputConv(d,T,O,this.padding);let[W,V,H,K]=Pn(this.recurrentKernel.read(),i,b);m=this.recurrentConv(m,W),f=this.recurrentConv(f,V),g=this.recurrentConv(g,H),y=this.recurrentConv(y,K);let j=this.recurrentActivation.apply(Z(c,m)),Y=this.recurrentActivation.apply(Z(u,f)),J=Z(L(Y,s),L(j,this.activation.apply(Z(p,g)))),ne=L(this.recurrentActivation.apply(Z(d,y)),this.activation.apply(J));return[ne,ne,J]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=W4(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=Ft(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?ar(r,n,this.dataFormat):r}recurrentConv(e,t){return Ft(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};zm.className="ConvLSTM2DCell";re.registerClass(zm);var _x=class extends JI{constructor(e){let t=new zm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};_x.className="ConvLSTM2D";re.registerClass(_x);var Bm=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=Re(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,r=this.getNoiseShape(n);return cp(()=>Gk(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()}};Bm.className="Dropout";re.registerClass(Bm);var Ex=class extends Bm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};Ex.className="SpatialDropout1D";re.registerClass(Ex);var Ax=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,Yt(this.units,"units"),this.activation=ds(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=kt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=kt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Gt(e.kernelConstraint),this.biasConstraint=Gt(e.biasConstraint),this.kernelRegularizer=It(e.kernelRegularizer),this.biasRegularizer=It(e.biasRegularizer),this.activityRegularizer=It(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=mt(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Re(e),a=$k(this.activation.getClassName()),r;return a!=null?r=nr(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=nr(n,this.kernel.read()),this.bias!=null&&(r=ar(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:ps(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),biasConstraint:Ut(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Ax.className="Dense";re.registerClass(Ax);var Fx=class extends qe{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(e);for(let t of e.slice(1))if(t==null)throw new B(`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],ls(e,1)]}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Re(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 dB(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Fx.className="Flatten";re.registerClass(Fx);var $x=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.activation=ds(e.activation)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Re(e);return this.activation.apply(n)})}getConfig(){let e={activation:ps(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};$x.className="Activation";re.registerClass($x);var Dx=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=Re(e),cB(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Dx.className="RepeatVector";re.registerClass(Dx);var Mx=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 B("Can only specifiy one unknown dimension.");else r*=l}let i=ls(e);if(s!==null){if(r===0||i%r!=0)throw new B(n);a[s]=i/r}else if(i!==r)throw new B(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=Re(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}};Mx.className="Reshape";re.registerClass(Mx);var Rx=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=Da(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 Jt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return Ue(Re(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Rx.className="Permute";re.registerClass(Rx);var Px=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=Re(e),a=-1;return Wc(rs(n,this.maskValue),a)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Re(e),a=-1,r=!0,s=Wc(rs(n,this.maskValue),a,r);return n.mul(s.asType(n.dtype))})}};Px.className="Masking";re.registerClass(Px);var Ox=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(vt(e.inputLength))}this.inputDim=e.inputDim,Yt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Yt(this.outputDim,"outputDim"),this.embeddingsInitializer=kt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=It(e.embeddingsRegularizer),this.activityRegularizer=It(e.activityRegularizer),this.embeddingsConstraint=Gt(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=Re(e),rs(e,Ge(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=vt(this.inputLength);if(t.length!==e.length-1)throw new B(`"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 B(`"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=Re(e);return n.dtype!=="int32"&&(n=op(n,"int32")),Uk(this.embeddings.read(),n.as1D()).reshape(mt(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:_t(this.embeddingsInitializer),embeddingsRegularizer:ft(this.embeddingsRegularizer),activityRegularizer:ft(this.activityRegularizer),embeddingsConstraint:Ut(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Ox.className="Embedding";re.registerClass(Ox);var qi=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 B("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=[mt(e)]),e=e,e.length<2)throw new B(`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=os(t),t.length>1)throw new B(`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&&os(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=us(a);for(let s of e){let i=s.rank;for(let o=0;o<r-i;++o)s=lp(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(ls(c.slice(1))));d=Ue(d,[1,0]),d=d.reshape(p),n.push(d),r=!0}else if(l>1){let c=Da(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(Da(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=os(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 B("`mask` should be an Array");if(!Array.isArray(e))throw new B("`inputs` should be an Array");if(t.length!==e.length)throw new B(`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:Zn(a,0));let n=t[0];for(let a=1;a<t.length-1;++a)n=fa(n,t[a]);return n})}},Lx=class extends qi{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})}};Lx.className="Add";re.registerClass(Lx);var zx=class extends qi{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})}};zx.className="Multiply";re.registerClass(zx);var Bx=class extends qi{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)})}};Bx.className="Average";re.registerClass(Bx);var Wx=class extends qi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Ca(t,e[n]);return t})}};Wx.className="Maximum";re.registerClass(Wx);var Vx=class extends qi{constructor(e){super(e)}mergeFunction(e){return D(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Ri(t,e[n]);return t})}};Vx.className="Minimum";re.registerClass(Vx);var Ux=class extends qi{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 B("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 B("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return D(()=>Pb(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new B("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 B("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new B("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new B(`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(Mn(e[s]).asType("bool")):t[s].rank<e[s].rank?a.push(Zn(t[s],-1)):a.push(t[s]);let r=Qe(a,this.axis);return Ch(r,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Ux.className="Concatenate";re.registerClass(Ux);function vp(e,t){for(;e<0;)e+=t;return e}function V4(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 Gx=class extends qi{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 B(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new B(`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)=>vp(r,e[s].shape.length)):a=[vp(this.axes,t.shape.length),vp(this.axes,n.shape.length)],this.normalize&&(t=Nm(t,a[0]),n=Nm(n,a[1])),V4(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[vp(this.axes,e.length),vp(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}};Gx.className="Dot";re.registerClass(Gx);var Hx=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=Re(e);return cp(()=>pm(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Hx.className="GaussianNoise";re.registerClass(Hx);var jx=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=Re(e);return this.rate>0&&this.rate<1?cp(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return n.mul(pm(n.shape,1,a))},()=>n,t.training||!1):n})}};jx.className="GaussianDropout";re.registerClass(jx);var qx=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Re(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 cp(()=>{let a=Re(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=kr(Zl(n),this.rate);o=op(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)},()=>Re(e),t.training||!1)}return e})}};qx.className="AlphaDropout";re.registerClass(qx);function wp(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=p1(e,t,n,a,r,s);else if(e.rank===3)i=d1(e,t,n,a,r,s);else if(e.rank===4)i=h1(e,t,n,a,r,s);else throw new $e(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function U4(e,t,n,a,r=.001){return D(()=>{let s=zh(e,a),i=s.mean,o=s.variance;return[wp(e,i,o,n,t,r),i,o]})}function G4(e,t,n,a,r=.001){return D(()=>{let s=zh(e,a),i=s.mean,o=s.variance,l=[];for(let h of Da(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[wp(e,c,u,d,p,r),i,o]})}function H4(e,t,n,a,r=.001){return k.arraysEqual(a.slice().sort(),Da(0,e.rank-1))?U4(e,t,n,a,r):G4(e,t,n,a,r)}var Kx=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=kt(e.betaInitializer||"zeros"),this.gammaInitializer=kt(e.gammaInitializer||"ones"),this.movingMeanInitializer=kt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=kt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Gt(e.betaConstraint),this.gammaConstraint=Gt(e.gammaConstraint),this.betaRegularizer=It(e.betaRegularizer),this.gammaRegularizer=It(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new B(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Jt({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=Re(e),r=a.shape,s=r.length,i=Da(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=zi(1,s);l[o]=r[o];let c=i.slice();c.sort();let u=!k.arraysEqual(c,Da(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 wp(a,g,y,b,v,this.epsilon)}else return wp(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]=H4(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:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),movingMeanInitializer:_t(this.movingMeanInitializer),movingVarianceInitializer:_t(this.movingVarianceInitializer),betaRegularizer:ft(this.betaRegularizer),gammaRegularizer:ft(this.gammaRegularizer),betaConstraint:Ut(this.betaConstraint),gammaConstraint:Ut(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Kx.className="BatchNormalization";re.registerClass(Kx);var Xx=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=kt(e.betaInitializer||"zeros"),this.gammaInitializer=kt(e.gammaInitializer||"ones"),this.betaRegularizer=It(e.betaRegularizer),this.gammaRegularizer=It(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(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!==os(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=Re(e),a=n.shape,r=a.length;return D(()=>{let s=!0,{mean:i,variance:o}=zh(n,this.axis,s),l=zi(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),wp(n,i,o,p,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),betaRegularizer:ft(this.betaRegularizer),gammaRegularizer:ft(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Xx.className="LayerNormalization";re.registerClass(Xx);function j4(e,t,n){return D(()=>{if(e.rank!==4)throw new B(`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 B("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=Fa()),n!=="channelsLast"&&n!=="channelsFirst")throw new B(`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]],ta(e,a)})}var Yx=class extends qe{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Fa():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 B(`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 B(`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 B(`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 Jt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return D(()=>j4(Re(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Yx.className="ZeroPadding2D";re.registerClass(Yx);function Wm(e,t,n,a,r,s){return D(()=>{Mt(r),Pk(s),na(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=Fa()),s==null&&(s="max"),e=bx(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=$t(e,t,n,o):i=Jn(e,t,n,o),r==="channelsFirst"&&(i=Ue(i,[0,3,1,2])),i})}function ZI(e,t,n,a,r,s){return D(()=>{Mt(r),Pk(s),na(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=Fa()),s==null&&(s="max"),e=jI(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=ob(e,t,n,o):i=qy(e,t,n,o),r==="channelsFirst"&&(i=Ue(i,[0,4,1,2,3])),i})}var QI=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 B(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Yt(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 B(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,na(this.padding),this.inputSpec=[new Jt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=Pa(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=lp(Re(e),2);let n=this.poolingFunction(Re(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return ss(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Jx=class extends QI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),Wm(e,t,n,a,r,"max")}};Jx.className="MaxPooling1D";re.registerClass(Jx);var Zx=class extends QI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),Wm(e,t,n,a,r,"avg")}};Zx.className="AveragePooling1D";re.registerClass(Zx);var eN=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 B(`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];Yt(this.poolSize,"poolSize"),Yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),na(this.padding),this.inputSpec=[new Jt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Pa(t,this.poolSize[0],this.padding,this.strides[0]),n=Pa(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(Re(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Qx=class extends eN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),Wm(e,t,n,a,r,"max")}};Qx.className="MaxPooling2D";re.registerClass(Qx);var ev=class extends eN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),Wm(e,t,n,a,r,"avg")}};ev.className="AveragePooling2D";re.registerClass(ev);var tN=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 B(`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];Yt(this.poolSize,"poolSize"),Yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),na(this.padding),this.inputSpec=[new Jt({ndim:5})]}computeOutputShape(e){e=mt(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=Pa(t,this.poolSize[0],this.padding,this.strides[0]),n=Pa(n,this.poolSize[1],this.padding,this.strides[1]),a=Pa(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(Re(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}},tv=class extends tN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),ZI(e,t,n,a,r,"max")}};tv.className="MaxPooling3D";re.registerClass(tv);var nv=class extends tN{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Mt(r),na(a),ZI(e,t,n,a,r,"avg")}};nv.className="AveragePooling3D";re.registerClass(nv);var nN=class extends qe{constructor(e){super(e);this.inputSpec=[new Jt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new $e}},av=class extends nN{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Re(e);return Ct(n,1)})}};av.className="GlobalAveragePooling1D";re.registerClass(av);var rv=class extends nN{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Re(e);return ea(n,1)})}};rv.className="GlobalMaxPooling1D";re.registerClass(rv);var aN=class extends qe{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),this.inputSpec=[new Jt({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}},sv=class extends aN{call(e,t){return D(()=>{let n=Re(e);return this.dataFormat==="channelsLast"?Ct(n,[1,2]):Ct(n,[2,3])})}};sv.className="GlobalAveragePooling2D";re.registerClass(sv);var iv=class extends aN{call(e,t){return D(()=>{let n=Re(e);return this.dataFormat==="channelsLast"?ea(n,[1,2]):ea(n,[2,3])})}};iv.className="GlobalMaxPooling2D";re.registerClass(iv);var rN=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=Ra(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},ov=class extends rN{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=mt(e),e.length<3)throw new B(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=mt(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return D(()=>(e=Re(e),YI((n,a)=>[Re(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ov.className="TimeDistributed";re.registerClass(ov);function q4(e){Wi(sB,"BidirectionalMergeMode",e)}var K4="concat",lv=class extends rN{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Ra(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=Ra(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?K4:e.mergeMode,q4(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()):Nn(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=XI(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 B("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 Jt({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 Ma;for(let l of s)if(l instanceof Ma!==o)throw new B("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=Rn(r,1));let i;return this.mergeMode==="concat"?i=Pb([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){Vi(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Vi(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=Ra(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)}};lv.className="Bidirectional";re.registerClass(lv);function wB(e){return new su(e)}function kB(e){return new fx(e)}function IB(e){return new dx(e)}function NB(e){return new hx(e)}function TB(e){return new mx(e)}function SB(e){return new yx(e)}function CB(e){return new gx(e)}function _B(e){return new Rm(e)}function EB(e){return new bp(e)}function AB(e){return new vx(e)}function FB(e){return new Mm(e)}function $B(e){return new wx(e)}function DB(e){return new kx(e)}function MB(e){return new Ix(e)}function RB(e){return new Nx(e)}function PB(e){return new $x(e)}function OB(e){return new Ax(e)}function LB(e){return new Bm(e)}function zB(e){return new Ex(e)}function BB(e){return new Fx(e)}function WB(e){return new Dx(e)}function VB(e){return new Mx(e)}function UB(e){return new Rx(e)}function GB(e){return new Ox(e)}function HB(e){return new Lx(e)}function jB(e){return new Bx(e)}function qB(e){return new Ux(e)}function KB(e){return new Wx(e)}function XB(e){return new Vx(e)}function YB(e){return new zx(e)}function JB(e){return new Gx(e)}function ZB(e){return new Kx(e)}function QB(e){return new Xx(e)}function eW(e){return new Yx(e)}function Hb(e){return new Zx(e)}function tW(e){return Hb(e)}function nW(e){return Hb(e)}function jb(e){return new ev(e)}function aW(e){return jb(e)}function rW(e){return jb(e)}function qb(e){return new nv(e)}function sW(e){return qb(e)}function iW(e){return qb(e)}function oW(e){return new av(e)}function lW(e){return new sv(e)}function Xk(e){return new rv(e)}function Yk(e){return new iv(e)}function Jk(e){return new Jx(e)}function Zk(e){return new Qx(e)}function uW(e){return new tv(e)}function cW(e){return new Sx(e)}function pW(e){return new Lm(e)}function dW(e){return new Cx(e)}function hW(e){return new xp(e)}function mW(e){return new Tx(e)}function fW(e){return new Om(e)}function gW(e){return new _x(e)}function yW(e){return new zm(e)}function bW(e){return new rr(e)}function xW(e){return new Pm(e)}function vW(e){return new lv(e)}function wW(e){return new ov(e)}var kW=Xk,IW=Yk,NW=Jk,TW=Zk;function SW(e){return new Hx(e)}function CW(e){return new jx(e)}function _W(e){return new qx(e)}function EW(e){return new Px(e)}var sN={};Oe(sN,{MAPE:()=>sV,MSE:()=>lV,binaryAccuracy:()=>X4,binaryCrossentropy:()=>Y4,categoricalAccuracy:()=>Z4,categoricalCrossentropy:()=>Q4,cosineProximity:()=>nV,mape:()=>iV,meanAbsoluteError:()=>aV,meanAbsolutePercentageError:()=>rV,meanSquaredError:()=>oV,mse:()=>uV,precision:()=>eV,recall:()=>tV,sparseCategoricalAccuracy:()=>J4});function X4(e,t){return Qb(e,t)}function Y4(e,t){return hI(e,t)}function J4(e,t){return mI(e,t)}function Z4(e,t){return ex(e,t)}function Q4(e,t){return tx(e,t)}function eV(e,t){return dI(e,t)}function tV(e,t){return KW(e,t)}function nV(e,t){return Jb(e,t)}function aV(e,t){return Tm(e,t)}function rV(e,t){return ou(e,t)}function sV(e,t){return ou(e,t)}function iV(e,t){return ou(e,t)}function oV(e,t){return Gi(e,t)}function lV(e,t){return Gi(e,t)}function uV(e,t){return Gi(e,t)}var iN={};Oe(iN,{modelFromJSON:()=>_4});var oN={};Oe(oN,{l1:()=>pV,l1l2:()=>cV,l2:()=>dV});function cV(e){return new gp(e)}function pV(e){return P4(e)}function dV(e){return O4(e)}var lN=class extends iu{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Cr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Vm(e,t){return e<t}function uN(e,t){return e>t}var cN=class extends lN{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=Vm:this.mode==="max"?this.monitorFunc=uN:this.monitor.indexOf("acc")!==-1?this.monitorFunc=uN:this.monitorFunc=Vm,this.monitorFunc===Vm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Vm?Infinity:-Infinity}async onEpochEnd(e,t){await cs(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 hV(e){return new cN(e)}var mV={earlyStopping:hV},Oa;(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"})(Oa||(Oa={}));var pN;(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={}))})(pN||(pN={}));var uv={};function fV(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};uv[e]=n}function dN(e){return uv[e]}function gV(e){delete uv[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 Sn(t.inputNames[s.inputIndexStart],n,a,r);if(s.type==="tensors")return t.inputNames.slice(o,l).map(p=>Sn(p,n,a,r));let c=Sn(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 Sn(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[Um(r,o)]);return i!==void 0?t[Um(r,i)][s]:void 0}function yV(e,t,n){return t[Um(e,n.currentContextId)]}function _r(e,t){let[n,a]=Ln(e);return[Um(n,t&&t.currentContextId),a]}function Um(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 Gm(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 Er(e){return e.kept?e:Qr(e)}var hN={};Oe(hN,{json:()=>bV});var bV=[{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}]}],mN={};Oe(mN,{json:()=>xV});var xV=[{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}]}],fN={};Oe(fN,{json:()=>vV});var vV=[{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"}]}],gN={};Oe(gN,{json:()=>wV});var wV=[{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"}]}],yN={};Oe(yN,{json:()=>kV});var kV=[{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"}]}],bN={};Oe(bN,{json:()=>IV});var IV=[{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}]}],xN={};Oe(xN,{json:()=>NV});var NV=[{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"}]}],vN={};Oe(vN,{json:()=>TV});var TV=[{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"}]}],wN={};Oe(wN,{json:()=>SV});var SV=[{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}]}],kN={};Oe(kN,{json:()=>CV});var CV=[{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"}]}],IN={};Oe(IN,{json:()=>_V});var _V=[{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}]}],NN={};Oe(NN,{json:()=>EV});var EV=[{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}]}],TN={};Oe(TN,{json:()=>AV});var AV=[{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}]}],SN={};Oe(SN,{json:()=>FV});var FV=[{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"}]}],CN={};Oe(CN,{json:()=>$V});var $V=[{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}]}],_N={};Oe(_N,{json:()=>DV});var DV=[{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}]}],EN={};Oe(EN,{json:()=>MV});var MV=[{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:[]}],FN=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[hN,mN,fN,gN,yN,bN,xN,IN,kN,vN,NN,TN,SN,CN,_N,EN,wN],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]=_r(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]=_r(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]=_r(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=dN(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=cv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=cv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=bv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=bv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=dv(e.attr,r.tfName,r.defaultValue||0),i===void 0&&!!r.tfDeprecatedName&&(i=dv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=yv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=yv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=pv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=pv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=vv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=vv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=gv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=gv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=xv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=xv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=mv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=mv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=fv(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=fv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=AN(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=AN(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]=_r(c.name),p={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:hv(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]=_r(p);u.inputs.push(r[d]),r[d].children.push(u)})});let o=e.ret;e.signature.outputArg.forEach(c=>{let[u,p]=_r(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 RV(e){let t=te().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 $N(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):RV(e);return t?n:n.toLowerCase()}function cv(e,t,n,a=!1){let r=e[t];return r!=null?$N(r.s,a):n}function pv(e,t,n){let a=e[t];return a?a.b:n}function dv(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 hv(e){switch(typeof e=="string"&&(e=Oa[e]),e){case Oa.DT_FLOAT:return"float32";case Oa.DT_INT32:case Oa.DT_INT64:case Oa.DT_INT8:case Oa.DT_UINT8:return"int32";case Oa.DT_BOOL:return"bool";case Oa.DT_DOUBLE:return"float32";case Oa.DT_STRING:return"string";default:return null}}function AN(e,t,n){let a=e[t];return a&&a.func?a.func.name:n}function mv(e,t,n){let a=e[t];return a&&a.type?hv(a.type):n}function fv(e,t,n){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(r=>hv(r)):n}function DN(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function gv(e,t,n){let a=e[t];return a&&a.shape?DN(a.shape):n}function yv(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 bv(e,t,n,a=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>$N(s,a)):n}function xv(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>DN(r)):n}function vv(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var PV=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 Sn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Sn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return dv(this.node.rawAttrs,e,t);if(n.s!=null)return cv(this.node.rawAttrs,e,t);if(n.b!=null)return pv(this.node.rawAttrs,e,t);if(n.shape!=null)return gv(this.node.rawAttrs,e,t);if(n.type!=null)return mv(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return yv(this.node.rawAttrs,e,t);if(n.list.s!=null)return bv(this.node.rawAttrs,e,t);if(n.list.shape!=null)return xv(this.node.rawAttrs,e,t);if(n.list.b!=null)return vv(this.node.rawAttrs,e,t);if(n.list.type!=null)return fv(this.node.rawAttrs,e,t)}return t}},OV=(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[o1(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[Lh(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[we(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[Qy(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[Sh(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[ge(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[Ri(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[Ca(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[Za(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[np(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},LV=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Bt(I("x",e,t,n))];case"Acos":return[Oy(I("x",e,t,n))];case"Acosh":return[Ly(I("x",e,t,n))];case"Asin":return[By(I("x",e,t,n))];case"Asinh":return[Wy(I("x",e,t,n))];case"Atan":return[Vy(I("x",e,t,n))];case"Atan2":return[Uy(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[Gy(I("x",e,t,n))];case"Ceil":return[Ky(I("x",e,t,n))];case"Complex":return[Yr(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[jc(I("x",e,t,n))];case"Cosh":return[Fh(I("x",e,t,n))];case"Elu":return[Kl(I("x",e,t,n))];case"Erf":return[eb(I("x",e,t,n))];case"Exp":return[hn(I("x",e,t,n))];case"Expm1":return[tb(I("x",e,t,n))];case"Floor":return[Xl(I("x",e,t,n))];case"Log":return[Dn(I("x",e,t,n))];case"Log1p":return[Mh(I("x",e,t,n))];case"Imag":return[Dh(I("x",e,t,n))];case"Neg":return[St(I("x",e,t,n))];case"Reciprocal":return[pb(I("x",e,t,n))];case"Real":return[Zc(I("x",e,t,n))];case"Relu":return[Ye(I("x",e,t,n))];case"Round":return[db(I("x",e,t,n))];case"Selu":return[Gh(I("x",e,t,n))];case"Sigmoid":return[ma(I("x",e,t,n))];case"Sin":return[Hh(I("x",e,t,n))];case"Sign":return[hb(I("x",e,t,n))];case"Sinh":return[jh(I("x",e,t,n))];case"Softplus":return[Yl(I("x",e,t,n))];case"Sqrt":return[an(I("x",e,t,n))];case"Square":return[ct(I("x",e,t,n))];case"Tanh":return[ql(I("x",e,t,n))];case"Tan":return[gb(I("x",e,t,n))];case"ClipByValue":return[Xt(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[Vh(I("x",e,t,n))];case"Rsqrt":return[Uh(Sn(e.inputNames[0],t,n))];case"Prod":return[Bh(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[qc(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[Jc(I("x",e,t,n),I("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function xa(e,t,n=""){k.assert(zV(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function zV(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==-1&&t[n]!==-1&&e[n]!==t[n])return!1;return!0}var BV=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=he(0),Kt(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),xa(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,Kt(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 Xn([],[0].concat(this.elementShape));let n=this.readMany(e);return xa(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Dt(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 Xn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return xa(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,ht(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=q(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]=q(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)}},kp=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}`);xa(t,r.shape,"TensorList shape mismatch: "),Kt(r)}),this.idTensor=he(0),this.maxNumElements=a,Kt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new kp([...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.`);return xa(e,this.elementShape,"TensorList shape mismatch: "),D(()=>{let a=this.tensors.map(r=>q(r,e));return Dt(a,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=this.tensors.pop();return xa(n.shape,e,"TensorList shape mismatch: "),q(n,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(xa(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Kt(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.`);return xa(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}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.`);xa(this.elementShape,t.shape,"TensorList shape mismatch: "),Kt(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}`);return xa(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?Xn([],[0].concat(this.elementShape)):D(()=>{let a=e.map(r=>q(this.tensors[r],n));return Dt(a,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return xa(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?Xn([],[0].concat(this.elementShape)):D(()=>{let n=this.tensors.map(a=>q(a,t));return Qe(n,0)})}};function WV(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);xa(r,t,"TensorList shape mismatch: ");let s=ht(e);return new kp(s,t,a)}function VV(e,t,n){return new kp([],e,t,n)}function UV(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 kp([],n,e.dtype,a),i=ht(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function GV(e,t,n){let a=0,r=t.map(l=>(a+=l,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=a===0?0:e.size/a,i=D(()=>{let l=[];e=q(e,[1,a,s]);for(let c=0;c<t.length;++c){let u=c===0?0:r[c-1],p=[0,u,0],d=[1,t[c],s];l[c]=q(We(e,p,d),n)}return e.dispose(),l}),o=new kp([],n,e.dtype,t.length);for(let l=0;l<i.length;l++)o.setItem(l,i[l]);return o}var HV=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[Er(a)]}case"Switch":{let a=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=Er(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>Sn(r,t,n)!==void 0);if(a){let r=Sn(a,t,n);return[Er(r)]}return}case"Enter":{let a=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(a),[Er(r)]}case"Exit":{let a=I("tensor",e,t,n);return n.exitFrame(),[Er(a)]}case"NextIteration":{let a=I("tensor",e,t,n);return n.nextIteration(),[Er(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 BV(c,r,a,s,l,i,o);return n.addTensorArray(u),[u.idTensor,he(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[he(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=UV(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=VV(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=WV(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=GV(a,s,r);return n.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function MN(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=Gm(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 jV=(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[Eh(I("x",e,t,n),I("filter",e,t,n),a,r,s,i)]}case"Conv2D":{let a=I("strides",e,t,n),r=Gm(e,t,n),s=I("dataFormat",e,t,n).toUpperCase(),i=I("dilations",e,t,n);return[Ft(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}=MN(e,t,n);return[is.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}=MN(e,t,n);return[is.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=Gm(e,t,n);return[Ah(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=Gm(e,t,n),s=I("dilations",e,t,n),i=I("dataFormat",e,t,n).toUpperCase();return[vr(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[Yy(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[Jn(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[$t(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}=$1(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[qy(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[ob(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[Zy(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`)}},qV=(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[In(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[T1(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[D1(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[Gl(a,r,s,i)]}case"Ones":return[Ja(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[Mn(I("x",e,t,n))];case"RandomUniform":return[Zl(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[Wh(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[Xh(a,r,s,I("dtype",e,t,n),i)]}case"Zeros":return[xt(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 wv(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 KV=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=wv(e,t,n),c=await Qa.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}=wv(e,t,n),l=I("padToMaxOutputSize",e,t,n),c=await Qa.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}=wv(e,t,n);return[await Qa.nonMaxSuppressionAsync(a,r,s,i,o)]}case"Where":{let a=pe(I("condition",e,t,n),"bool"),r=[await xb(a)];return a.dispose(),r}case"ListDiff":return P1(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},XV=(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=yb(a,r,s);return[i.values,i.indices]}case"Unique":{let a=I("x",e,t,n),r=Yh(a);return[r.values,r.indices]}case"UniqueV2":{let a=I("x",e,t,n),r=I("axis",e,t,n),s=Yh(a,r);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},YV=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=I("default",e,t,n);return[Sn(e.name,t,n)||a];case"Placeholder":return[Sn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[Er(c)]}case"IdentityN":return I("x",e,t,n).map(c=>Er(c));case"Snapshot":let r=I("x",e,t,n);return[Er(r)];case"Shape":return[nt(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>nt(c.shape));case"Size":return[he(I("x",e,t,n).size,"int32")];case"Rank":return[he(I("x",e,t,n).rank,"int32")];case"NoOp":return[he(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`)}},JV=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=he(0),this.tensorMap=new Map,Kt(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=ht(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];Kt(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 Dt(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}`)}},ZV=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 JV(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`)}},QV=(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[Qa.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[Qa.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[Qa.cropAndResize(a,r,s,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eU=(e,t,n)=>{switch(e.op){case"Equal":return[wr(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[rs(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[Qn(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[kr(I("a",e,t,n),I("b",e,t,n))];case"Less":return[Kc(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[as(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[fa(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Xc(I("a",e,t,n))];case"LogicalOr":return[Oh(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[kn(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`)}},tU=(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[is.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`)}},nU=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[xr(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[xr(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[ab(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[_a(I("x",e,t,n))];case"LogSoftmax":return[Ph(I("x",e,t,n))];case"SparseToDense":return[vb(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`)}},aU=(e,t,n)=>{switch(e.op){case"Max":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[ea(I("x",e,t,n),i,o)]}case"Mean":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Ct(I("x",e,t,n),i,o)]}case"Min":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Jl(I("x",e,t,n),i,o)]}case"Sum":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Ce(I("x",e,t,n),i,o)]}case"All":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Ch(I("x",e,t,n),i,o)]}case"Any":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Wc(I("x",e,t,n),i,o)]}case"ArgMax":{let i=I("axis",e,t,n);return[Vc(I("x",e,t,n),i)]}case"ArgMin":{let i=I("axis",e,t,n);return[zy(I("x",e,t,n),i)]}case"Prod":{let i=I("axis",e,t,n),o=I("keepDims",e,t,n);return[Bh(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[$h(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[m1(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[v1(i,o,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},rU=(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[Di(a,pe(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[Di(s,pe(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[Rn(s,r)]}case"ReverseV2":{let a=I("axis",e,t,n),r=I("x",e,t,n);return[Rn(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[fb(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=ss(r[0]).shape,o=r.map(l=>{let c=k.arraysEqual(l.shape,s);if(!c&&!k.arraysEqual(ss(l).shape,i))throw new Error("the input tensors shape does not match");return c?l:q(l,s)});return[Dt(o,a)]});case"Unpack":{let a=I("axis",e,t,n),r=I("tensor",e,t,n);return ht(r,a)}case"Tile":{let a=I("reps",e,t,n);return[Xa(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[tk(a,r,s)]}case"GatherNd":{let a=I("x",e,t,n),r=I("indices",e,t,n);return[nk(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[vb(a,s,r,s.dtype===i.dtype?i:pe(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sU=(e,t,n)=>{switch(e.op){case"FFT":return[ep(I("x",e,t,n))];case"IFFT":return[eu(I("x",e,t,n))];case"RFFT":return[tp(I("x",e,t,n))];case"IRFFT":return[Kh(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},iU=(e,t,n)=>{switch(e.op){case"Cast":return[pe(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let a=I("axis",e,t,n);return[Zn(I("x",e,t,n),a)]}case"Squeeze":{let a=I("axis",e,t,n);return[ss(I("x",e,t,n),a)]}case"Reshape":return[q(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[lb(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[ta(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[Yc(I("x",e,t,n),a,r)]}case"BatchToSpaceND":{let a=I("blockShape",e,t,n),r=I("crops",e,t,n);return[Gc(I("x",e,t,n),a,r)]}case"DepthToSpace":{let a=I("blockSize",e,t,n),r=I("dataFormat",e,t,n).toUpperCase();return[Jy(I("x",e,t,n),a,r)]}case"BroadcastTo":return[Hc(I("x",e,t,n),I("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function RN(e,t,n,a){let r=((s,i,o)=>{switch(s.category){case"arithmetic":return D(()=>OV(s,i,o));case"basic_math":return D(()=>LV(s,i,o));case"control":return HV(s,i,o);case"convolution":return D(()=>jV(s,i,o));case"creation":return D(()=>qV(s,i,o));case"dynamic":return KV(s,i,o);case"evaluation":return D(()=>XV(s,i,o));case"image":return D(()=>QV(s,i,o));case"graph":return D(()=>YV(s,i,o));case"logical":return D(()=>eU(s,i,o));case"matrices":return D(()=>tU(s,i,o));case"normalization":return D(()=>nU(s,i,o));case"reduction":return D(()=>aU(s,i,o));case"slice_join":return D(()=>rU(s,i,o));case"spectral":return D(()=>sU(s,i,o));case"transformation":return D(()=>iU(s,i,o));case"hash_table":return ZV(s,i,o,a);case"custom":let l=dN(s.op);if(l&&l.customExecutor)return l.customExecutor(new PV(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 PN=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 LN(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((ON(d)||oU(d)||lU(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 uU(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 cU=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],pU=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],dU=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function ON(e){return cU.indexOf(e.op)>=0}function oU(e){return pU.indexOf(e.op)>=0}function lU(e){return dU.indexOf(e.op)>=0}var kv=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 kv(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=LN(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 uU(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 PN(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=RN(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=>Sn(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=yV(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 PN(this.weightMap,a,r,this.functionExecutorMap),i=await this.executeWithControlFlow(e,s,t,n),o=t.map(p=>Sn(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}=LN(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=>!ON(b)&&!Sn(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]=_r(u.node.name,n)),a[u.node.name]==null){let d=RN(u.node,a,n,this._resourceManager);p||([p]=_r(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]=_r(i.name,n);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Sn(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(l=>!!Sn(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`)})}},hU=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]}},mU="?tfjs-format=file",fU="model.json",zN=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new hU}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=qt.browserHTTPRequest(e,this.loadOptions);else{let t=qt.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(qt.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=qt.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new kv(FN.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=FN.Instance.transformGraph(e.modelInitializer);this.initializer=new kv(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=qt.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 z)&&!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 gU(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}${fU}${mU}`);let n=new zN(e,t);return await n.load(),n}var BN="2.8.5",WN={};Oe(WN,{CSVDataset:()=>UN,Dataset:()=>cu,FileDataSource:()=>GN,TextLineDataset:()=>VN,URLDataSource:()=>HN,array:()=>yU,csv:()=>xU,func:()=>vU,generator:()=>wU,microphone:()=>IU,version_data:()=>jN,webcam:()=>kU,zip:()=>bU});var NU=Ro($d()),TU=Ro($d());function SU(e,t){return Hm(e,t)}function Hm(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(pu(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=Hm(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 CU(e,t=KN){return qN(e,t)}function qN(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(pu(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(c=>c[i]),l=qN(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 KN(e){return e===null?null:pu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function XN(e,t){let n=new Map;Hm(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 Hm(e,t,n)}function pu(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof z))}function EU(e){return e==null||_U(e)||Array.isArray(e)||typeof e=="object"&&e instanceof z||k.isTypedArray(e)}function _U(e){return e===null||typeof e!="object"&&typeof e!="function"}function FU(e){return SU(e,AU)}function AU(e){return e instanceof z?{value:e.clone(),recurse:!1}:pu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var YN=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}},Iv=class extends YN{constructor(){super(Iv.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}};Iv.INITIAL_CAPACITY=32;function JN(e){return new $U(e)}function Nv(e){return new DU(e)}function MU(e,t){return new ZN(e,t)}function PU(e,t=ms.FAIL){return new RU(e,t)}var Zt=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 UU(this,e)}filter(e){return new WU(this,e)}map(e){return new VU(this,e)}mapAsync(e){return new QN(this,e)}serialMapAsync(e){return new QN(this,e).serial()}flatmap(e){return new GU(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 BU(this,e,t)}columnMajorBatch(e,t=!0,n=KN){return this.rowMajorBatch(e,t).map(a=>CU(a,n))}concatenate(e,t){return new ZN(JN([this,e]),t)}take(e){return e<0||e==null?this:new zU(this,e)}skip(e){return e<0||e==null?this:new LU(this,e)}prefetch(e){return new eT(this,e)}shuffle(e,t){return new HU(this,e,t)}serial(){return new OU(this)}},$U=class extends Zt{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:FU(e),done:!1}}},DU=class extends Zt{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}}},OU=class extends Zt{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()}},LU=class extends Zt{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()}},zU=class extends Zt{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()}},BU=class extends Zt{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}}},WU=class extends Zt{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)}}},VU=class extends Zt{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=Sa.getTensorsInContainer(e.value),n=this.transform(e.value),a=Sa.getTensorsInContainer(n);for(let r of t)Sa.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},UU=class extends Zt{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}}}},QN=class extends Zt{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=Sa.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Sa.getTensorsInContainer(n);for(let r of t)Sa.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},Tv=class extends Zt{constructor(){super();this.outputQueue=new Iv,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}}},GU=class extends Tv{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=Sa.getTensorsInContainer(e.value),n=this.transform(e.value),a=Sa.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Sa.isTensorInList(r,a)||r.dispose();return!0}},ZN=class extends Zt{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}},ms;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(ms||(ms={}));var RU=class extends Zt{constructor(e,t=ms.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 Zt?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await XN(this.iterators,a);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case ms.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case ms.SHORTEST:return{value:null,done:!0};case ms.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},eT=class extends Zt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new YN(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()}},HU=class extends eT{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=TU.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}}},cu=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,jU),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=Nv(async()=>({value:await t.iterator(),done:!1}));return MU(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=NU.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()}};cu.MAX_BUFFER_SIZE=1e4;function zn(e,t=null){return new class extends cu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function yU(e){return zn(async()=>JN(e),e.length)}function bU(e){if(!pu(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 XN(e,a=>{if(a instanceof cu)return{value:a.iterator(),recurse:!1};if(pu(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return PU(n,ms.SHORTEST)},t)}function jU(e){if(e===null)return null;let t=e[0];return EU(t)?{value:qU(e),recurse:!1}:{value:null,recurse:!0}}function qU(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof z?Dt(e):Xn(e)}var VN=class extends cu{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))}},jm='"',Ip=Symbol("out"),tT=Symbol("field"),qm=Symbol("quote"),Sv=Symbol("quoteafterquote"),nT=Symbol("quoteinquote"),UN=class extends cu{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 VN(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=Ip;for(let i=0;i<r;i++)switch(s){case Ip:switch(e.charAt(i)){case jm:a=i+1,s=qm;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=Ip;break;default:s=tT,a=i;break}break;case tT:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=Ip,a=i+1;break;default:}break;case qm:switch(e.charAt(i)){case jm:s=Sv;break;default:}break;case Sv:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=Ip,a=i+1;break;case jm:s=qm;break;default:s=nT;break}break;case nT:switch(e.charAt(i)){case jm:s=qm;break;default:}break;default:}if(s===Sv?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}},aT=class extends Zt{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(te().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new aT(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),Xn(n,t)}},rT=class extends Zt{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=nt([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=Ea([s,r,o,i],[1,4])}else this.cropBox=Ea([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(te().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 rT(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=Ai.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=e.toFloat().expandDims(0),n;n=Qa.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return n.reshape(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.")}},sT=class{},iT=class extends Zt{split(e){return new KU(this,e)}},KU=class extends iT{constructor(e,t){super();this.upstream=e,this.impl=new XU(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},XU=class extends Tv{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}},JU=class extends Zt{decodeUTF8(){return new YU(this)}},YU=class extends iT{constructor(e){super();this.upstream=e,this.impl=new ZU(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},ZU=class extends Tv{constructor(e){super();if(this.upstream=e,te().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=sA();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 te().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},oT=class extends JU{constructor(e,t={}){super();this.file=e,this.options=t,k.assert(e instanceof Uint8Array||(te().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 eG(e,t={}){let n,a;typeof e=="string"?n=e:(n=e.url,a=QU(e));let r=await k.fetch(n,a);if(r.ok){let s=new Uint8Array(await r.arrayBuffer());return new oT(s,t)}else throw new Error(r.statusText)}var QU=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 lT(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var GN=class extends sT{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(lT(this.input)&&te().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new oT(this.input,this.options)}},HN=class extends sT{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return lT(this.url)?new GN(this.url,this.fileOptions).iterator():eG(this.url,this.fileOptions)}};function xU(e,t={}){return new UN(new HN(e),t)}function vU(e){let t=Nv(e);return zn(async()=>t)}function wU(e){return zn(async()=>{let t=await e();return Nv(()=>t.next())})}async function kU(e,t){return rT.create(e,t)}async function IU(e){return aT.create(e)}var jN="2.8.5";function Ie(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 tG=er.whereImpl,nG=class extends dc{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Dd(this,ts())}write(e,t,n){this.firstUse&&(this.firstUse=!1,te().get("IS_NODE")&&E.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={};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}}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){this.data.set(e,{values:t,dtype:a,refCount:1})}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 E.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 ts().makeTensorFromDataId(a,t,n,this)}disposeData(e){if(this.data.has(e)){let{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.data.has(t)){let n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}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){Ie([e],"where");let t=this.readSync(e.dataId);return tG(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},uT={};Oe(uT,{addImpl:()=>pT,bincountImpl:()=>Cv,bincountReduceImpl:()=>dT,ceilImpl:()=>hT,concatImpl:()=>_v,expImpl:()=>mT,expm1Impl:()=>fT,floorImpl:()=>gT,gatherV2Impl:()=>yT,greaterImpl:()=>bT,lessImpl:()=>xT,linSpaceImpl:()=>vT,logImpl:()=>wT,maxImpl:()=>kT,maximumImpl:()=>IT,minimumImpl:()=>NT,multiplyImpl:()=>Ev,negImpl:()=>TT,notEqualImpl:()=>ST,prodImpl:()=>CT,rangeImpl:()=>Fv,rsqrtImpl:()=>_T,simpleAbsImpl:()=>cT,sliceImpl:()=>Km,squaredDifferenceImpl:()=>ET,stridedSliceImpl:()=>AT,subImpl:()=>FT,tileImpl:()=>$T,topKImpl:()=>DT,transposeImpl:()=>Av,uniqueImpl:()=>MT});function cT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var aG=e=>{let{x:t}=e.inputs,n=e.backend;Ie(t,"abs");let a=new Float32Array(k.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=cT(r),n.makeOutput(a,t.shape,"float32")},rG={kernelName:Lo,backendName:"cpu",kernelFunc:aG};function Pt(e){return(t,n,a,r,s)=>{let i=E.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=E.getBroadcastDims(t,i),g=E.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 sG={kernelName:Vd,backendName:"cpu",kernelFunc:Bn};function Xm(e,t,n="float32"){if(n==="complex64"){let r=Xm(e,t,"float32"),s=Xm(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 ir(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 iG={kernelName:il,backendName:"cpu",kernelFunc:ir};function Ki(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 oG={kernelName:lh,backendName:"cpu",kernelFunc:Ki};function fs(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return ir({inputs:{x:r},backend:n});let i=Xm(n,r.shape,r.dtype),o=fs({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=Ki({inputs:{input:r},backend:n}),o=fs({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=ir({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]=Pt((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 lG={kernelName:Ls,backendName:"cpu",kernelFunc:fs};function Qt(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;Ie([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=fs({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=fs({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),$=l.makeTensorInfo(C,"float32",N),F=l.makeTensorInfo(C,"float32",T),O=Bn({inputs:{real:$,imag:F},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo($),l.disposeIntermediateTensorInfo(F),O}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 $v(e){return(t,n,a,r,s,i)=>{let o=E.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=E.getBroadcastDims(t,o),m=E.getBroadcastDims(n,o),f=E.mergeRealAndImagArrays(a,r),g=E.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,$=e(f[T*2],f[T*2+1],g[C*2],g[C*2+1]);p[N]=$.real,d[N]=$.imag}else for(let N=0;N<p.length;N++){let T=k.indexToLoc(N,c,u),C=T.slice(-y);h.forEach(V=>C[V]=0);let $=k.locToIndex(C,y,b),F=T.slice(-v);m.forEach(V=>F[V]=0);let O=k.locToIndex(F,v,x),W=e(f[$*2],f[$*2+1],g[O*2],g[O*2+1]);p[N]=W.real,d[N]=W.imag}return[p,d,o]}}var pT=Pt((e,t)=>e+t),uG=$v((e,t,n,a)=>({real:e+n,imag:t+a})),Np=Qt(Hr,pT,uG),cG={kernelName:Hr,backendName:"cpu",kernelFunc:Np};function Cv(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 dT(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 du(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 ot(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(Ie(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 hu(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(Ie(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 hT=du(e=>Math.ceil(e)),pG=hu(jo,hT),dG={kernelName:jo,backendName:"cpu",kernelFunc:pG};function _v(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"?E.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 mT=du(e=>Math.exp(e)),RT=hu(Hs,mT),hG={kernelName:Hs,backendName:"cpu",kernelFunc:RT},fT=du(e=>Math.expm1(e)),mG=hu(tl,fT),fG={kernelName:tl,backendName:"cpu",kernelFunc:mG},gT=du(e=>Math.floor(e)),gG=hu(js,gT),yG={kernelName:js,backendName:"cpu",kernelFunc:gG};function yT(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 bT=Pt((e,t)=>e>t?1:0),bG=Qt(sl,bT,null,"bool"),xG={kernelName:sl,backendName:"cpu",kernelFunc:bG},xT=Pt((e,t)=>e<t?1:0),vG=Qt(cl,xT,null,"bool"),wG={kernelName:cl,backendName:"cpu",kernelFunc:vG};function vT(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 wT=du(e=>Math.log(e)),kG=hu(Js,wT),IG={kernelName:Js,backendName:"cpu",kernelFunc:kG};function kT(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 IT=Pt((e,t)=>Math.max(e,t)),NG=Qt(Qs,IT),TG={kernelName:Qs,backendName:"cpu",kernelFunc:NG},NT=Pt((e,t)=>Math.min(e,t)),SG=Qt(ai,NT),CG={kernelName:ai,backendName:"cpu",kernelFunc:SG},Ev=Pt((e,t)=>e*t),_G=$v((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),Dv=Qt(ri,Ev,_G),EG={kernelName:ri,backendName:"cpu",kernelFunc:Dv};function TT(e,t,n){let a=k.createScalarValue(-1,n);return Ev([],t,a,e,n)}function AG(e){let{inputs:t,backend:n}=e,{x:a}=t;Ie(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=TT(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var FG={kernelName:fl,backendName:"cpu",kernelFunc:AG},ST=Pt((e,t)=>e!==t?1:0),$G=Qt(gl,ST,null,"bool"),DG={kernelName:gl,backendName:"cpu",kernelFunc:$G};function Av(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 va(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{perm:s}=n;Ie(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=Av(l,r.shape,r.dtype,s,o);return{dataId:a.write(c,o,r.dtype),shape:o,dtype:r.dtype}}var MG={kernelName:Ii,backendName:"cpu",kernelFunc:va};function CT(e,t,n,a){let[r,s]=E.computeOutAndReduceShapes(e,a),i=ha(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 RG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Ie(r,"prod");let o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=E.getAxesPermutation(l,o),u=l,p=r,d=[];c!=null&&(p=va({inputs:{x:r},backend:n,attrs:{perm:c}}),d.push(p),u=E.getInnerMostAxes(u.length,o));let h=n.data.get(p.dataId).values,{outVals:m,outShape:f,outDtype:g}=CT(p.shape,p.dtype,h,u),y=f;return i&&(y=E.expandShapeToKeepDim(f,l)),d.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.makeTensorInfo(y,g,m)}var PG={kernelName:kl,backendName:"cpu",kernelFunc:RG};function Fv(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 _T=du(e=>1/Math.sqrt(e)),OG=hu(mi,_T),LG={kernelName:mi,backendName:"cpu",kernelFunc:OG};function Km(e,t,n,a,r){let s=dn.isSliceContinous(a,t,n),i=k.sizeFromShape(n),o=k.computeStrides(a);if(s){let p=dn.computeFlatOffset(t,o);return r==="string"?e.slice(p,p+i):e.subarray(p,p+i)}let l=r==="string"?E.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"?E.fromStringArrayToUint8(u.values):u.values}function Xi(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;Ie(r,"slice");let[o,l]=dn.parseSliceParams(r,s,i);dn.assertParamsValid(r,o,l);let c=n.data.get(r.dataId).values,u=Km(c,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var zG={kernelName:_l,backendName:"cpu",kernelFunc:Xi},ET=Pt((e,t)=>{let n=e-t;return n*n}),BG=Qt(vi,ET),WG={kernelName:vi,backendName:"cpu",kernelFunc:BG};function AT(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 FT=Pt((e,t)=>e-t),VG=$v((e,t,n,a)=>({real:e-n,imag:t-a})),Mv=Qt(wi,FT,VG),UG={kernelName:wi,backendName:"cpu",kernelFunc:Mv};function $T(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 DT(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 MT(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 zt(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 zt(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 GG="2.8.5";Th("cpu",()=>new nG,1);var PT=ot(Jo,e=>e>=0?e:Math.exp(e)-1),HG={kernelName:Jo,backendName:"cpu",kernelFunc:PT};function OT(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;Ie([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 jG={kernelName:Ys,backendName:"cpu",kernelFunc:OT},qG=Pt((e,t)=>e<0?t*e:e);function LT(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;Ie([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=qG(a.shape,r.shape,s,i,a.dtype);return n.makeTensorInfo(l,a.dtype,o)}var KG={kernelName:li,backendName:"cpu",kernelFunc:LT},zT=ot(ui,e=>Math.max(0,e)),XG={kernelName:ui,backendName:"cpu",kernelFunc:zT},BT=ot(pi,e=>Math.min(Math.max(0,e),6)),YG={kernelName:pi,backendName:"cpu",kernelFunc:BT};function Rv(e,t,n,a,r){if(n==="linear")return ir({inputs:{x:t},backend:e});if(n==="relu")return zT({inputs:{x:t},backend:e});if(n==="elu")return PT({inputs:{x:t},backend:e});if(n==="relu6")return BT({inputs:{x:t},backend:e});if(n==="prelu")return LT({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return OT({inputs:{x:t},backend:e,attrs:{alpha:r}});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Nt(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 JG={kernelName:Nl,backendName:"cpu",kernelFunc:Nt};function WT(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;Ie([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=Nt({inputs:{x:r},backend:n,attrs:{shape:x}}),C=Nt({inputs:{x:s},backend:n,attrs:{shape:N}}),$=i?T.shape[1]:T.shape[2],F=i?T.shape[2]:T.shape[1],O=o?C.shape[1]:C.shape[2],W=Math.max(g,y),V=n.data.get(T.dataId).values,H=n.data.get(C.dataId).values,K=k.computeStrides(T.shape),j=k.computeStrides(C.shape),[Y,J,ne]=i?[K[0],1,K[1]]:[K[0],K[1],1],[Q,ie,ee]=o?[1,j[1],j[0]]:[j[1],1,j[0]],le=F*O,se=Le([W,F,O],T.dtype),ce=se.values,de=n.blockSize;for(let fe=0;fe<W;fe++)for(let xe=0;xe<F;xe+=de)for(let be=0;be<O;be+=de)for(let Se=0;Se<$;Se+=de){let _e=Math.min(xe+de,F),Me=Math.min(be+de,O),Ke=Math.min(Se+de,$);for(let Ve=xe;Ve<_e;Ve++)for(let it=be;it<Me;it++){let ut=0;for(let He=Se;He<Ke;He++){let pt=Math.min(fe,g-1)*Y,dt=Math.min(fe,y-1)*ee,jn=V[pt+Ve*J+He*ne],Ze=H[He*Q+it*ie+dt];ut+=jn*Ze}ce[fe*le+(Ve*O+it)]+=ut}}return n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(C),n.makeTensorInfo(v,se.dtype,se.values)}var ZG={kernelName:Os,backendName:"cpu",kernelFunc:WT};function QG(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=WT({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:c},backend:n}),i&&(h=Np({inputs:{a:d,b:i},backend:n}),f.push(d),d=h),u&&(m=Rv(n,d,u,o,p),f.push(d),d=m);for(let g of f)n.disposeIntermediateTensorInfo(g);return d}var eH={kernelName:Ni,backendName:"cpu",kernelFunc:QG},tH=ot(zo,e=>Math.acos(e)),nH={kernelName:zo,backendName:"cpu",kernelFunc:tH},aH=ot(Bo,e=>Math.acosh(e)),rH={kernelName:Bo,backendName:"cpu",kernelFunc:aH};function sH(e){let{inputs:t,backend:n}=e,a=t;Ie(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 iH={kernelName:Ms,backendName:"cpu",kernelFunc:sH};function oH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Ie(r,"all");let o=k.parseAxisParam(s,r.shape),l=o,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=va({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("all",l,u.shape.length);let[p,d]=E.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=E.expandShapeToKeepDim(p,o),b=Nt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var lH={kernelName:Od,backendName:"cpu",kernelFunc:oH};function uH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Ie(r,"any");let o=k.parseAxisParam(s,r.shape),l=o,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=va({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("any",l,u.shape.length);let[p,d]=E.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=E.expandShapeToKeepDim(p,o),b=Nt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var cH={kernelName:Ld,backendName:"cpu",kernelFunc:uH};function pH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;Ie(r,"argMax");let i=k.parseAxisParam(s,r.shape),o=E.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=va({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=E.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],E.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[u,p]=E.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 dH={kernelName:Rs,backendName:"cpu",kernelFunc:pH};function hH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;Ie(r,"argMin");let i=k.parseAxisParam(s,r.shape),o=E.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=va({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=E.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],E.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[u,p]=E.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 mH={kernelName:fc,backendName:"cpu",kernelFunc:hH},fH=ot(Wo,e=>Math.asin(e)),gH={kernelName:Wo,backendName:"cpu",kernelFunc:fH},yH=ot(Vo,e=>Math.asinh(e)),bH={kernelName:Vo,backendName:"cpu",kernelFunc:yH},xH=ot(Uo,e=>Math.atan(e)),vH={kernelName:Uo,backendName:"cpu",kernelFunc:xH},wH=Pt((e,t)=>Math.atan2(e,t)),kH=Qt(Ho,wH),IH={kernelName:Ho,backendName:"cpu",kernelFunc:kH},NH=ot(Go,e=>Math.atanh(e)),TH={kernelName:Go,backendName:"cpu",kernelFunc:NH};function Pv(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 $=0;$<r.outHeight;++$){let F=$*i-d,O=Math.max(0,F),W=Math.min(r.inHeight,u+F),V=N+$*b;for(let H=0;H<r.outWidth;++H){let K=H*o-h,j=Math.max(0,K),Y=Math.min(r.inWidth,p+K),J=m,ne=0,Q=0;for(let ee=O;ee<W;ee+=l){let le=T+ee*a[1];for(let se=j;se<Y;se+=c){let ce=le+se*a[2],de=e[ce+C];s==="max"&&de>J?J=de:s==="avg"&&(ne+=de,Q++)}if(isNaN(J))break}let ie=V+H*v+C;g[ie]=s==="avg"?ne/Q:J}}}return f}function VT(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,$=C;for(;$<0;)$+=u;let F=Math.min(a.inWidth,d+C),O=Number.NEGATIVE_INFINITY,W=-1;for(let V=x;V<N;V+=c){let H=V-v;for(let K=$;K<F;K+=u){let j=K-C,Y=f.get(g,V,K,y);Y>O&&(O=Y,r?W=s?((g*a.inHeight+V)*a.inWidth+K)*a.inChannels+y:(V*a.inWidth+K)*a.inChannels+y:W=H*d+j)}}i.set(W,g,b,T,y)}}return i}function UT(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],$=r.outShape[4];for(let F=0;F<r.batchSize;++F){let O=F*N,W=F*a[0];for(let V=0;V<r.inChannels;++V)for(let H=0;H<r.outDepth;++H){let K=H*i-f,j=K;for(;j<0;)j+=c;let Y=Math.min(r.inDepth,d+K),J=O+H*T;for(let ne=0;ne<r.outHeight;++ne){let Q=ne*o-g,ie=Q;for(;ie<0;)ie+=u;let ee=Math.min(r.inHeight,h+Q),le=J+ne*C;for(let se=0;se<r.outWidth;++se){let ce=se*l-y,de=ce;for(;de<0;)de+=p;let fe=Math.min(r.inWidth,m+ce),xe=le+se*$,be=b,Se=0,_e=0;for(let Ke=j;Ke<Y;Ke+=c){let Ve=W+Ke*a[1];for(let it=ie;it<ee;it+=u){let ut=Ve+it*a[2];for(let He=de;He<fe;He+=p){let pt=ut+He*a[3],dt=e[pt+V];if(s==="max"&&dt>be?be=dt:s==="avg"&&(Se+=dt,_e++),isNaN(be))break}if(isNaN(be))break}if(isNaN(be))break}let Me=xe+V;x[Me]=s==="avg"?Se/_e:be}}}}return v}function SH(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 $=Math.min(t.inHeight,u+T);for(let F=0;F<t.outWidth;++F){let O=F*s-m,W=O;for(;W<0;)W+=l;let V=Math.min(t.inWidth,p+O),H=Number.NEGATIVE_INFINITY,K=-1;for(let j=v;j<x;j+=i){let Y=j-b;for(let J=C;J<$;J+=o){let ne=J-T;for(let Q=W;Q<V;Q+=l){let ie=Q-O,ee=e.get(f,j,J,Q,g);ee>=H&&(H=ee,K=Y*u*p+ne*u+ie)}}}n.set(K,f,y,N,F,g)}}}return n}function CH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Ie(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(E.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))p=ir({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=k.computeStrides(r.shape),m=Pv(d,r.shape,r.dtype,h,u,"avg");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var _H={kernelName:Ps,backendName:"cpu",kernelFunc:CH};function EH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c,dilations:u}=a;Ie(r,"avgPool3d");let p=u;p==null&&(p=[1,1,1]);let d=E.computePool3DInfo(r.shape,s,i,p,o,l,c),h=n.data.get(r.dataId).values,m=UT(h,r.shape,r.dtype,k.computeStrides(r.shape),d,"avg");return n.makeTensorInfo(m.shape,"float32",m.values)}var AH={kernelName:gc,backendName:"cpu",kernelFunc:EH};function FH(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dilations:c,dimRoundingMode:u}=a;Ie([r,s],"avgPool3DGrad");let p=E.computePool3DInfo(s.shape,i,o,c,l,u),d=p.strideDepth,h=p.strideHeight,m=p.strideWidth,f=p.filterDepth,g=p.filterHeight,y=p.filterWidth,b=p.dilationDepth,v=p.dilationHeight,x=p.dilationWidth,N=p.effectiveFilterDepth,T=p.effectiveFilterHeight,C=p.effectiveFilterWidth,$=N-1-p.padInfo.front,F=C-1-p.padInfo.left,O=T-1-p.padInfo.top,W=Le(s.shape,"float32"),V=1/(f*g*y),H=n.bufferSync(r);for(let K=0;K<p.batchSize;++K)for(let j=0;j<p.inChannels;++j)for(let Y=0;Y<p.inDepth;++Y)for(let J=0;J<p.inHeight;++J)for(let ne=0;ne<p.inWidth;++ne){let Q=Y-$,ie=J-O,ee=ne-F,le=0;for(let se=0;se<N;se+=b){let ce=(Q+se)/d;if(!(ce<0||ce>=p.outDepth||Math.floor(ce)!==ce))for(let de=0;de<T;de+=v){let fe=(ie+de)/h;if(!(fe<0||fe>=p.outHeight||Math.floor(fe)!==fe))for(let xe=0;xe<C;xe+=x){let be=(ee+xe)/m;be<0||be>=p.outWidth||Math.floor(be)!==be||(le+=H.get(K,ce,fe,be,j))}}}W.set(le*V,K,Y,J,ne,j)}return n.makeTensorInfo(W.shape,W.dtype,W.values)}var $H={kernelName:Bd,backendName:"cpu",kernelFunc:FH};function DH(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;Ie([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=E.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,$=Le(r.shape,"float32",C);for(let F=0;F<u.batchSize;++F)for(let O=0;O<u.inChannels;++O)for(let W=0;W<u.inHeight;++W)for(let V=0;V<u.inWidth;++V){let H=W-x,K=V-v,j=0;for(let Y=0;Y<y;Y+=f){let J=(H+Y)/p;if(!(J<0||J>=u.outHeight||Math.floor(J)!==J))for(let ne=0;ne<b;ne+=g){let Q=(K+ne)/d;Q<0||Q>=u.outWidth||Math.floor(Q)!==Q||(j+=$.get(F,J,Q,O))}}N.set(j*T,F,W,V,O)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}var MH={kernelName:zd,backendName:"cpu",kernelFunc:DH};function RH(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."),Ie([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 $=0;$<u.length;++$)f[$]=m[x++]+(u[$]-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 PH={kernelName:Ks,backendName:"cpu",kernelFunc:RH};function OH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;Ie([r],"batchToSpaceND");let o=s.reduce((y,b)=>y*b),l=E.getReshaped(r.shape,s,o),c=E.getPermuted(l.length,s.length),u=E.getReshapedPermuted(r.shape,s,o),p=E.getSliceBeginCoords(i,s.length),d=E.getSliceSize(u,i,s.length),h=Nt({inputs:{x:r},backend:n,attrs:{shape:l}}),m=va({inputs:{x:h},backend:n,attrs:{perm:c}}),f=Nt({inputs:{x:m},backend:n,attrs:{shape:u}}),g=Xi({inputs:{x:f},backend:n,attrs:{begin:p,size:d}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var LH={kernelName:yc,backendName:"cpu",kernelFunc:OH};function zH(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=Cv(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var BH={kernelName:Wd,backendName:"cpu",kernelFunc:zH},WH=ot(jr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),VH={kernelName:jr,backendName:"cpu",kernelFunc:WH},UH=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")},GH={kernelName:bc,backendName:"cpu",kernelFunc:UH};function mu(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 HH={kernelName:th,backendName:"cpu",kernelFunc:mu};function fu(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=E.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 ir({inputs:{x:o[0]},backend:n});let l=o.map(f=>f.shape);if(E.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let f=o.map(x=>Ki({inputs:{input:x},backend:n})),g=o.map(x=>mu({inputs:{input:x},backend:n})),y=fu({inputs:f,backend:n,attrs:{axis:s}}),b=fu({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 Nt({inputs:{x:f},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));i=E.computeOutShape(c.map(f=>f.shape),1);let p=c[0].shape[0]===1,d=_v(u,i,t[0].dtype,p),h=E.computeOutShape(o.map(f=>f.shape),s),m=n.makeTensorInfo(h,t[0].dtype,d);return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var jH={kernelName:qo,backendName:"cpu",kernelFunc:fu};function GT(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;Ie([r,s],"conv2d");let p=E.convertConv2DDataFormat(l),d=E.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 zt(d.outShape,r.dtype),N=k.computeStrides(r.shape),T=k.computeStrides(s.shape),C=N[0],$=v?N[1]:N[2],F=v?N[2]:1,O=v?1:N[1],W=x.strides[0],V=v?x.strides[1]:x.strides[2],H=v?x.strides[2]:1,K=v?1:x.strides[1],j=n.data.get(r.dataId).values,Y=n.data.get(s.dataId).values,J=x.values;for(let ne=0;ne<d.batchSize;++ne){let Q=ne*C,ie=ne*W;for(let ee=0;ee<d.outHeight;++ee){let le=ie+ee*V,se=ee*d.strideHeight-b;for(let ce=0;ce<h;++ce){let de=se+ce*f;if(de<0||de>=d.inHeight)continue;let fe=ce*T[0],xe=Q+de*$;for(let be=0;be<d.outWidth;++be){let Se=le+be*H,_e=be*d.strideWidth-y;for(let Me=0;Me<m;++Me){let Ke=_e+Me*g;if(Ke<0||Ke>=d.inWidth)continue;let Ve=fe+Me*T[1],it=xe+Ke*F,ut=Ve;for(let He=0;He<d.inChannels;++He){let pt=j[it+He*O];for(let dt=0;dt<d.outChannels;++dt)J[Se+dt*K]+=pt*Y[ut+dt];ut+=d.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,J)}var qH={kernelName:zs,backendName:"cpu",kernelFunc:GT};function KH(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;Ie([r,s],"conv2dBackpropFilter");let p=E.convertConv2DDataFormat(l),d=E.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 zt(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 zt(r.shape,r.dtype,N),$=new zt(s.shape,s.dtype,T);for(let F=0;F<f;++F){let O=Math.max(0,Math.ceil((x-F)/h)),W=Math.min(d.outHeight,(d.inHeight+x-F)/h);for(let V=0;V<g;++V){let H=Math.max(0,Math.ceil((v-V)/m)),K=Math.min(d.outWidth,(d.inWidth+v-V)/m);for(let j=0;j<d.inChannels;++j)for(let Y=0;Y<d.outChannels;++Y){let J=0;for(let ne=0;ne<d.batchSize;++ne)for(let Q=O;Q<W;++Q){let ie=F+Q*h-x;for(let ee=H;ee<K;++ee){let le=V+ee*m-v;y?J+=C.get(ne,ie,le,j)*$.get(ne,Q,ee,Y):J+=C.get(ne,j,ie,le)*$.get(ne,Y,Q,ee)}}b.set(J,F,V,j,Y)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var XH={kernelName:Ud,backendName:"cpu",kernelFunc:KH};function YH(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;Ie([r,s],"conv2dBackpropInput");let p=k.computeStrides(s.shape),d=k.computeStrides(r.shape),h=E.convertConv2DDataFormat(c),m=E.computeConv2DInfo(i,s.shape,o,1,l,u,!1,h),f=new zt(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:$,inChannels:F,inHeight:O,inWidth:W,outChannels:V,outHeight:H,outWidth:K,strideHeight:j,strideWidth:Y}=m;h=m.dataFormat;let J=C-1-m.padInfo.top,ne=$-1-m.padInfo.left,Q=h==="channelsLast",ie=f.strides[0],ee=Q?f.strides[1]:f.strides[2],le=Q?f.strides[2]:1,se=Q?1:f.strides[1],ce=d[0],de=Q?d[1]:d[2],fe=Q?d[2]:1,xe=Q?1:d[1];for(let be=0;be<T;++be)for(let Se=0;Se<F;++Se)for(let _e=0;_e<O;++_e){let Me=_e-J,Ke=Math.max(0,Math.ceil(Me/j)),Ve=Math.min(H,(C+Me)/j);for(let it=0;it<W;++it){let ut=it-ne,He=Math.max(0,Math.ceil(ut/Y)),pt=Math.min(K,($+ut)/Y),dt=0;for(let Ze=Ke;Ze<Ve;++Ze){let En=Ze*j-Me;for(let nn=He;nn<pt;++nn){let An=nn*Y-ut,oa=ce*be+de*Ze+fe*nn,wn=v*(C-1-En)+x*($-1-An)+N*Se;for(let cn=0;cn<V;++cn){let la=y[oa+xe*cn],Ga=b[wn+cn];dt+=la*Ga}}}let jn=ie*be+ee*_e+le*it+se*Se;g[jn]=dt}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var JH={kernelName:Bs,backendName:"cpu",kernelFunc:YH};function ZH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;Ie([r,s],"conv3d");let c=E.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 zt(c.outShape,r.dtype),N=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=x.values,$=k.computeStrides(r.shape),F=k.computeStrides(s.shape);for(let O=0;O<c.batchSize;++O){let W=O*$[0],V=O*x.strides[0];for(let H=0;H<c.outDepth;++H){let K=V+H*x.strides[1],j=H*c.strideDepth-y;for(let Y=0;Y<u;++Y){let J=j+Y*h;if(J<0||J>=c.inDepth)continue;let ne=Y*F[0],Q=W+J*$[1];for(let ie=0;ie<c.outHeight;++ie){let ee=K+ie*x.strides[2],le=ie*c.strideHeight-v;for(let se=0;se<p;++se){let ce=le+se*m;if(ce<0||ce>=c.inHeight)continue;let de=ne+se*F[1],fe=Q+ce*$[2];for(let xe=0;xe<c.outWidth;++xe){let be=ee+xe*c.outChannels,Se=xe*c.strideWidth-b;for(let _e=0;_e<d;++_e){let Me=Se+_e*f;if(Me<0||Me>=c.inWidth)continue;let Ke=de+_e*F[2],Ve=fe+Me*c.inChannels,it=Ke;for(let ut=0;ut<c.inChannels;++ut){let He=N[Ve+ut];for(let pt=0;pt<c.outChannels;++pt)C[be+pt]+=He*T[it+pt];it+=c.outChannels}}}}}}}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}var QH={kernelName:xc,backendName:"cpu",kernelFunc:ZH};function e6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;Ie([r,s],"conv3dBackpropFilterV2");let c=k.computeStrides(r.shape),u=k.computeStrides(s.shape),p=E.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 zt(p.filterShape,"float32"),v=b.values,[x,N,T,C]=b.strides,$=n.data.get(s.dataId).values,[F,O,W,V]=u,H=n.data.get(r.dataId).values,[K,j,Y,J]=c,ne=p.padInfo.front,Q=p.padInfo.left,ie=p.padInfo.top;for(let ee=0;ee<f;++ee){let le=Math.max(0,Math.ceil((ne-ee)/d)),se=Math.min(p.outDepth,(p.inDepth+ne-ee)/d),ce=ee*x;for(let de=0;de<g;++de){let fe=Math.max(0,Math.ceil((ie-de)/h)),xe=Math.min(p.outHeight,(p.inHeight+ie-de)/h),be=de*N+ce;for(let Se=0;Se<y;++Se){let _e=Math.max(0,Math.ceil((Q-Se)/m)),Me=Math.min(p.outWidth,(p.inWidth+Q-Se)/m),Ke=Se*T+be;for(let Ve=0;Ve<p.inChannels;++Ve){let it=Ve*C+Ke;for(let ut=0;ut<p.outChannels;++ut){let He=0;for(let pt=0;pt<p.batchSize;++pt){let dt=pt*K,jn=pt*F;for(let Ze=le;Ze<se;++Ze){let En=(ee+Ze*d-ne)*j+dt,nn=Ze*O+jn;for(let An=fe;An<xe;++An){let oa=(de+An*h-ie)*Y+En,wn=An*W+nn;for(let cn=_e;cn<Me;++cn){let la=(Se+cn*m-Q)*J+oa,Ga=cn*V+wn;He+=H[la+Ve]*$[Ga+ut]}}}}v[it+ut]=He}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var t6={kernelName:Gd,backendName:"cpu",kernelFunc:e6};function n6(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;Ie([r],"conv3dBackpropInputV2");let c=k.computeStrides(r.shape),u=k.computeStrides(s.shape),p=E.computeConv3DInfo(l,s.shape,o,1,i),d=new zt(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,O,W]=u,{batchSize:V,filterDepth:H,filterHeight:K,filterWidth:j,inChannels:Y,inDepth:J,inHeight:ne,inWidth:Q,outChannels:ie,outDepth:ee,outHeight:le,outWidth:se,strideDepth:ce,strideHeight:de,strideWidth:fe}=p,xe=H-1-p.padInfo.front,be=K-1-p.padInfo.top,Se=j-1-p.padInfo.left;for(let _e=0;_e<V;++_e)for(let Me=0;Me<Y;++Me)for(let Ke=0;Ke<J;++Ke){let Ve=Ke-xe,it=Math.max(0,Math.ceil(Ve/ce)),ut=Math.min(ee,(H+Ve)/ce);for(let He=0;He<ne;++He){let pt=He-be,dt=Math.max(0,Math.ceil(pt/de)),jn=Math.min(le,(K+pt)/de);for(let Ze=0;Ze<Q;++Ze){let En=Ze-Se,nn=Math.max(0,Math.ceil(En/fe)),An=Math.min(se,(j+En)/fe),oa=0;for(let wn=it;wn<ut;++wn){let cn=wn*ce-Ve;for(let la=dt;la<jn;++la){let Ga=la*de-pt;for(let Fn=nn;Fn<An;++Fn){let ko=Fn*fe-En,Hu=v*_e+x*wn+N*la+T*Fn,Na=$*(H-1-cn)+F*(K-1-Ga)+O*(j-1-ko)+W*Me;for(let ua=0;ua<ie;++ua){let Ta=b[Hu+ua],Io=C[Na+ua];oa+=Ta*Io}}}}h[m*_e+f*Ke+g*He+y*Ze+Me]=oa}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}var a6={kernelName:Hd,backendName:"cpu",kernelFunc:n6},r6=ot(Ws,e=>Math.cos(e)),s6={kernelName:Ws,backendName:"cpu",kernelFunc:r6},i6=ot(Ko,e=>Math.cosh(e)),o6={kernelName:Ko,backendName:"cpu",kernelFunc:i6};function l6(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 $=C*4,F=b[$],O=b[$+1],W=b[$+2],V=b[$+3],H=v[C];if(H>=u)continue;let K=f>1?(W-F)*(p-1)/(f-1):0,j=g>1?(V-O)*(d-1)/(g-1):0;for(let Y=0;Y<f;Y++){let J=f>1?F*(p-1)+Y*K:.5*(F+W)*(p-1);if(J<0||J>p-1){for(let ne=0;ne<g;ne++)for(let Q=0;Q<h;Q++){let ie=Q+ne*T[2]+Y*T[1]+C*T[0];y.values[ie]=c}continue}if(l==="bilinear"){let ne=Math.floor(J),Q=Math.ceil(J),ie=J-ne;for(let ee=0;ee<g;ee++){let le=g>1?O*(d-1)+ee*j:.5*(O+V)*(d-1);if(le<0||le>d-1){for(let fe=0;fe<h;fe++){let xe=fe+ee*T[2]+Y*T[1]+C*T[0];y.values[xe]=c}continue}let se=Math.floor(le),ce=Math.ceil(le),de=le-se;for(let fe=0;fe<h;fe++){let xe=fe+se*N[2]+ne*N[1]+H*N[0],be=x[xe];xe=fe+ce*N[2]+ne*N[1]+H*N[0];let Se=x[xe];xe=fe+se*N[2]+Q*N[1]+H*N[0];let _e=x[xe];xe=fe+ce*N[2]+Q*N[1]+H*N[0];let Me=x[xe],Ke=be+(Se-be)*de,Ve=_e+(Me-_e)*de;xe=fe+ee*T[2]+Y*T[1]+C*T[0],y.values[xe]=Ke+(Ve-Ke)*ie}}}else for(let ne=0;ne<g;++ne){let Q=g>1?O*(d-1)+ne*j:.5*(O+V)*(d-1);if(Q<0||Q>d-1){for(let le=0;le<h;le++){let se=le+ne*T[2]+Y*T[1]+C*T[0];y.values[se]=c}continue}let ie=Math.round(Q),ee=Math.round(J);for(let le=0;le<h;le++){let se=le+ie*N[2]+ee*N[1]+H*N[0],ce=le+ne*T[2]+Y*T[1]+C*T[0];y.values[ce]=x[se]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var u6={kernelName:Xo,backendName:"cpu",kernelFunc:l6};function c6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;Ie(r,"cumsum");let l=E.getAxesPermutation([s],r.shape.length),c=r;l!=null&&(c=va({inputs:{x:r},backend:n,attrs:{perm:l}}));let u=E.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=ha(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=E.getUndoAxesPermutation(l),b=va({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(c),b}return g}var p6={kernelName:Vs,backendName:"cpu",kernelFunc:c6};function d6(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=Cv(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=dT(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 h6={kernelName:jd,backendName:"cpu",kernelFunc:d6};function m6(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,$=(x*s+C)*h;for(let F=0;F<h;++F){let O=F+$+u*(T+c*(v+l*y));f[g++]=m[O]}}}return n.makeTensorInfo([o,p,d,h],r.dtype,f)}var f6={kernelName:Yo,backendName:"cpu",kernelFunc:m6};function HT(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=a;Ie([r,s],"depthwiseConv2DNative");let u=k.computeStrides(r.shape),p=k.computeStrides(s.shape),d=l;d==null&&(d=[1,1]),k.assert(E.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=E.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 zt(h.outShape,r.dtype),C=n.data.get(r.dataId).values,$=n.data.get(s.dataId).values,F=T.values;for(let O=0;O<h.batchSize;++O){let W=O*u[0],V=O*T.strides[0];for(let H=0;H<h.outHeight;++H){let K=V+H*T.strides[1],j=H*h.strideHeight-v;for(let Y=0;Y<m;++Y){let J=j+Y*g;if(J<0||J>=h.inHeight)continue;let ne=Y*p[0],Q=W+J*u[1];for(let ie=0;ie<h.outWidth;++ie){let ee=K+ie*T.strides[2],le=ie*h.strideWidth-x;for(let se=0;se<f;++se){let ce=le+se*y;if(ce<0||ce>=h.inWidth)continue;let de=ne+se*p[1],fe=Q+ce*h.inChannels,xe=ee,be=de;for(let Se=0;Se<h.inChannels;++Se){let _e=C[fe+Se];for(let Me=0;Me<N;++Me)F[xe+Me]+=_e*$[be+Me];xe+=N,be+=N}}}}}}return n.makeTensorInfo(T.shape,T.dtype,T.values)}var g6={kernelName:Us,backendName:"cpu",kernelFunc:HT};function y6(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;Ie([r,s],"depthwiseConv2dNativeBackpropFilter");let p=E.computeConv2DInfo(r.shape,u,i,o,l,c,!0),{strideHeight:d,strideWidth:h,filterHeight:m,filterWidth:f}=p,g=new zt(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 zt(r.shape,r.dtype,x),T=n.data.get(s.dataId).values,C=new zt(s.shape,s.dtype,T);for(let $=0;$<m;++$){let F=Math.max(0,Math.ceil((b-$)/d)),O=Math.min(p.outHeight,(p.inHeight+b-$)/d);for(let W=0;W<f;++W){let V=Math.max(0,Math.ceil((y-W)/h)),H=Math.min(p.outWidth,(p.inWidth+y-W)/h);for(let K=0;K<p.outChannels;++K){let j=Math.trunc(K/v),Y=K%v,J=0;for(let ne=0;ne<p.batchSize;++ne)for(let Q=F;Q<O;++Q){let ie=$+Q*d-b;for(let ee=V;ee<H;++ee){let le=W+ee*h-y;J+=N.get(ne,ie,le,j)*C.get(ne,Q,ee,K)}}g.set(J,$,W,j,Y)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var b6={kernelName:qd,backendName:"cpu",kernelFunc:y6};function x6(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;Ie([r,s],"depthwiseConv2DNativeBackpropInput");let p=k.computeStrides(r.shape),d=k.computeStrides(s.shape),h=E.computeConv2DInfo(u,s.shape,i,o,l,c,!0),m=new zt(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,O]=d,{batchSize:W,filterHeight:V,filterWidth:H,inChannels:K,inHeight:j,inWidth:Y,outChannels:J,outHeight:ne,outWidth:Q,strideHeight:ie,strideWidth:ee}=h,le=V-1-h.padInfo.top,se=H-1-h.padInfo.left,ce=J/K;for(let de=0;de<W;++de)for(let fe=0;fe<K;++fe)for(let xe=0;xe<j;++xe){let be=xe-le,Se=Math.max(0,Math.ceil(be/ie)),_e=Math.min(ne,(V+be)/ie);for(let Me=0;Me<Y;++Me){let Ke=Me-se,Ve=Math.max(0,Math.ceil(Ke/ee)),it=Math.min(Q,(H+Ke)/ee),ut=0;for(let He=Se;He<_e;++He){let pt=He*ie-be;for(let dt=Ve;dt<it;++dt){let jn=dt*ee-Ke,Ze=x*de+N*He+T*dt,En=$*(V-1-pt)+F*(H-1-jn)+O*fe;for(let nn=0;nn<ce;++nn){let An=fe*ce+nn,oa=v[Ze+An],wn=C[En+nn];ut+=oa*wn}}}f[g*de+y*xe+b*Me+fe]=ut}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var v6={kernelName:Kd,backendName:"cpu",kernelFunc:x6};function w6(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 k6={kernelName:Xd,backendName:"cpu",kernelFunc:w6},I6={kernelName:vc,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:$,dilationWidth:F,outShape:O}=E.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),W=k.sizeFromShape(O),V=O.length,H=k.getArrayFromDType(a.dtype,W);for(let K=0;K<h;++K)for(let j=0;j<y;++j){let Y=j*x-v.top;for(let J=0;J<b;++J){let ne=J*N-v.left;for(let Q=0;Q<g;++Q){let ie=Number.MIN_SAFE_INTEGER;for(let le=0;le<T;++le){let se=Y+le*$;if(se>=0&&se<m)for(let ce=0;ce<C;++ce){let de=ne+ce*F;if(de>=0&&de<f){let fe=k.locToIndex([K,se,de,Q],u,k.computeStrides(a.shape)),xe=k.locToIndex([le,ce,Q],d,k.computeStrides(r.shape)),be=c[fe]+p[xe];be>ie&&(ie=be)}}}let ee=k.locToIndex([K,j,J,Q],V,k.computeStrides(O));H[ee]=ie}}}return{dataId:l.write(k.toTypedArray(H,a.dtype),O,a.dtype),shape:O,dtype:a.dtype}}},N6={kernelName:Jd,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:$,outShape:F}=E.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===F.length,()=>`Error in ${Jd}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let O=k.toNestedArray(F,c.data.get(s.dataId).values),W=k.makeZerosNestedTypedArray(r.shape,r.dtype);for(let V=0;V<d;++V)for(let H=0;H<g;++H){let K=H*v-b.top;for(let j=0;j<y;++j){let Y=j*x-b.left;for(let J=0;J<f;++J){let ne=Number.MIN_SAFE_INTEGER,Q=0,ie=0;for(let ee=0;ee<N;++ee){let le=K+ee*C;if(le>=0&&le<h)for(let se=0;se<T;++se){let ce=Y+se*$;if(ce>=0&&ce<m){let de=u[V][le][ce][J]+p[ee][se][J];de>ne&&(ne=de,Q=ee,ie=se)}}}W[Q][ie][J]+=O[V][H][j][J]}}}return{dataId:c.write(k.toTypedArray(W,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},T6={kernelName:Yd,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:$,outShape:F}=E.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===F.length,()=>`Error in ${Yd}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let O=k.toNestedArray(F,c.data.get(s.dataId).values),W=k.makeZerosNestedTypedArray(a.shape,a.dtype);for(let V=0;V<d;++V)for(let H=0;H<g;++H){let K=H*v-b.top;for(let j=0;j<y;++j){let Y=j*x-b.left;for(let J=0;J<f;++J){let ne=Number.MIN_SAFE_INTEGER,Q=K<0?0:K,ie=Y<0?0:Y;for(let ee=0;ee<N;++ee){let le=K+ee*C;if(le>=0&&le<h)for(let se=0;se<T;++se){let ce=Y+se*$;if(ce>=0&&ce<m){let de=u[V][le][ce][J]+p[ee][se][J];de>ne&&(ne=de,Q=le,ie=ce)}}}W[V][Q][ie][J]+=O[V][H][j][J]}}}return{dataId:c.write(k.toTypedArray(W,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function S6(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;Ie([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 C6={kernelName:Zd,backendName:"cpu",kernelFunc:S6},_6=Pt((e,t)=>e===t?1:0),jT=Qt(Qo,_6,null,"bool"),E6={kernelName:Qo,backendName:"cpu",kernelFunc:jT},A6=E.ERF_P,F6=E.ERF_A1,$6=E.ERF_A2,D6=E.ERF_A3,M6=E.ERF_A4,R6=E.ERF_A5,P6=ot(Zo,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+A6*n);return t*(1-((((R6*a+M6)*a+D6)*a+$6)*a+F6)*a*Math.exp(-n*n))}),O6={kernelName:Zo,backendName:"cpu",kernelFunc:P6};function Ym(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),Nt({inputs:{x:r},backend:n,attrs:{shape:o}})}var L6={kernelName:el,backendName:"cpu",kernelFunc:Ym},z6=Pt((e,t)=>e/t),Ov=Qt(Gs,z6),Lv={kernelName:Gs,backendName:"cpu",kernelFunc:Ov};function qT(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=Xi({inputs:{x:o},backend:n,attrs:{begin:[g,0],size:[1,s]}}),b=Xi({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}=B6(v,t,n),T=E.mergeRealAndImagArrays(x,N);for(let C=0;C<s;C++){let $=E.getComplexWithIndex(T,C);p[g*s+C]=$.real,d[g*s+C]=$.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 B6(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(W6(a)){let o=zv(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=ir({inputs:{x:p},backend:n}),h=Lv.kernelFunc({inputs:{a:c,b:p},backend:n}),m=Lv.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=E.mergeRealAndImagArrays(s,i),l=V6(o,a,t);return E.splitRealAndImagArrays(l)}}function W6(e){return(e&e-1)==0}function zv(e,t,n,a,r){if(n===1)return{real:e,imag:t};let s=E.mergeRealAndImagArrays(e,t),i=n/2,o=E.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=E.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=zv(l,c,i,a,r),T=N.real,C=N.imag,$=[T.length],F=r.makeTensorInfo($,"float32",T),O=r.makeTensorInfo($,"float32",C),W=Bn({inputs:{real:F,imag:O},backend:r}),V=zv(f,g,i,a,r),H=V.real,K=V.imag,j=[H.length],Y=r.makeTensorInfo(j,"float32",H),J=r.makeTensorInfo(j,"float32",K),ne=Bn({inputs:{real:Y,imag:J},backend:r}),Q=E.exponents(n,a),ie=[Q.real.length],ee=r.makeTensorInfo(ie,"float32",Q.real),le=r.makeTensorInfo(ie,"float32",Q.imag),se=Bn({inputs:{real:ee,imag:le},backend:r}),ce=Dv({inputs:{a:se,b:ne},backend:r}),de=Np({inputs:{a:W,b:ce},backend:r}),fe=Mv({inputs:{a:W,b:ce},backend:r}),xe=Ki({inputs:{input:de},backend:r}),be=Ki({inputs:{input:fe},backend:r}),Se=mu({inputs:{input:de},backend:r}),_e=mu({inputs:{input:fe},backend:r}),Me=fu({inputs:[xe,be],backend:r,attrs:{axis:0}}),Ke=fu({inputs:[Se,_e],backend:r,attrs:{axis:0}}),Ve=r.data.get(Me.dataId).values,it=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(F),r.disposeIntermediateTensorInfo(O),r.disposeIntermediateTensorInfo(W),r.disposeIntermediateTensorInfo(Y),r.disposeIntermediateTensorInfo(J),r.disposeIntermediateTensorInfo(ne),r.disposeIntermediateTensorInfo(ee),r.disposeIntermediateTensorInfo(le),r.disposeIntermediateTensorInfo(se),r.disposeIntermediateTensorInfo(ce),r.disposeIntermediateTensorInfo(de),r.disposeIntermediateTensorInfo(fe),r.disposeIntermediateTensorInfo(xe),r.disposeIntermediateTensorInfo(Se),r.disposeIntermediateTensorInfo(be),r.disposeIntermediateTensorInfo(_e),r.disposeIntermediateTensorInfo(Me),r.disposeIntermediateTensorInfo(Ke),{real:Ve,imag:it}}function V6(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=E.exponent(r*o,t,n),c=E.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),E.assignToTypedArray(a,s,i,r)}return a}function U6(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=Nt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=qT(o,!1,n),c=Nt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var G6={kernelName:Qd,backendName:"cpu",kernelFunc:U6};function Bv(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 H6(o,r,i),t.makeTensorInfo(a,i,o)}var j6={kernelName:wc,backendName:"cpu",kernelFunc:Bv};function H6(e,t,n){e.fill(t)}var q6={kernelName:nl,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}}},K6=Pt((e,t)=>Math.floor(e/t)),X6=Qt(qs,K6,null,"int32"),Y6={kernelName:qs,backendName:"cpu",kernelFunc:X6};function J6(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=GT({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=Np({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Rv(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var Z6={kernelName:Ti,backendName:"cpu",kernelFunc:J6};function Q6(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=HT({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=Np({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Rv(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var ej={kernelName:Si,backendName:"cpu",kernelFunc:Q6};function tj(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]=E.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 nj={kernelName:rl,backendName:"cpu",kernelFunc:tj};function aj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;Ie([r,s],"gatherV2");let l=o;o==null&&(l=0);let c=k.sizeFromShape(s.shape),u=k.parseAxisParam(i,r.shape)[0],p=E.segment_util.collectGatherOpShapeInfo(r,s,u,l),d=Nt({inputs:{x:r},backend:n,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),h=Nt({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=yT(g,f,m);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.makeTensorInfo(p.outputShape,y.dtype,y.values)}var rj={kernelName:al,backendName:"cpu",kernelFunc:aj},sj=Pt((e,t)=>e>=t?1:0),ij=Qt(Xs,sj,null,"bool"),oj={kernelName:Xs,backendName:"cpu",kernelFunc:ij};function lj(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=Nt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=qT(o,!0,n),c=Nt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var uj={kernelName:eh,backendName:"cpu",kernelFunc:lj},cj=ot(ol,e=>Number.isFinite(e)?1:0,"bool"),pj={kernelName:ol,backendName:"cpu",kernelFunc:cj},dj=ot(ll,e=>Math.abs(e)===Infinity?1:0,"bool"),hj={kernelName:ll,backendName:"cpu",kernelFunc:dj},mj=ot(ul,e=>Number.isNaN(e)?1:0,"bool"),fj={kernelName:ul,backendName:"cpu",kernelFunc:mj},gj=Pt((e,t)=>e<=t?1:0),yj=Qt(pl,gj,null,"bool"),bj={kernelName:pl,backendName:"cpu",kernelFunc:yj};function xj(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=vT(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var vj={kernelName:nh,backendName:"cpu",kernelFunc:xj},wj=ot(dl,e=>Math.log1p(e)),kj={kernelName:dl,backendName:"cpu",kernelFunc:wj},Ij=Pt((e,t)=>e&&t),Nj=Qt(hl,Ij,null,"bool"),Tj={kernelName:hl,backendName:"cpu",kernelFunc:Nj},Sj=ot(kc,e=>e?0:1,"bool"),Cj={kernelName:kc,backendName:"cpu",kernelFunc:Sj},_j=Pt((e,t)=>e||t),Ej=Qt(Ic,_j,null,"bool"),Aj={kernelName:Ic,backendName:"cpu",kernelFunc:Ej};function Fj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;Ie(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 $j={kernelName:Nc,backendName:"cpu",kernelFunc:Fj};function Dj(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;Ie(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 $=-2*c*u*m[C]*f[b]/T;b===C&&($+=Math.pow(T,-u)),$*=h[b],g[C]+=$}}return n.makeTensorInfo(i.shape,r.dtype,g)}var Mj={kernelName:ah,backendName:"cpu",kernelFunc:Dj};function KT(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=E.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=Av(h,l,r.dtype,d,x),p=E.getInnerMostAxes(p.length,c),l=x}Ie(r,"max"),E.assertAxesAreInnerMostDims("max",p,c);let[m,f]=E.computeOutAndReduceShapes(l,p),g=k.sizeFromShape(f),y=kT(h,g,m,r.dtype),b=o.write(y,m,r.dtype),v=m;return i&&(v=E.expandShapeToKeepDim(m,u)),{dataId:b,shape:v,dtype:r.dtype}}var Rj={kernelName:Zs,backendName:"cpu",kernelFunc:KT};function Pj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Ie(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(E.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))p=ir({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=k.computeStrides(r.shape),m=Pv(d,r.shape,r.dtype,h,u,"max");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var Oj={kernelName:ei,backendName:"cpu",kernelFunc:Pj};function Lj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c,dilations:u}=a;Ie(r,"maxPool3d");let p=u;p==null&&(p=[1,1,1]);let d=E.computePool3DInfo(r.shape,s,i,p,o,l,c),h=n.data.get(r.dataId).values,m=UT(h,r.shape,r.dtype,k.computeStrides(r.shape),d,"max");return n.makeTensorInfo(m.shape,"float32",m.values)}var zj={kernelName:Tc,backendName:"cpu",kernelFunc:Lj};function Bj(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dilations:c,dimRoundingMode:u}=a;Ie([r,s],"maxPool3DGrad");let p=E.computePool3DInfo(s.shape,i,o,c,l,u),d=n.bufferSync(s),h=SH(d,p),m=p.strideDepth,f=p.strideHeight,g=p.strideWidth,y=p.dilationDepth,b=p.dilationHeight,v=p.dilationWidth,x=p.effectiveFilterDepth,N=p.effectiveFilterHeight,T=p.effectiveFilterWidth,C=x-1-p.padInfo.front,$=T-1-p.padInfo.left,F=N-1-p.padInfo.top,O=Le(s.shape,"float32"),W=n.bufferSync(r);for(let V=0;V<p.batchSize;++V)for(let H=0;H<p.inChannels;++H)for(let K=0;K<p.inDepth;++K)for(let j=0;j<p.inHeight;++j)for(let Y=0;Y<p.inWidth;++Y){let J=K-C,ne=j-F,Q=Y-$,ie=0;for(let ee=0;ee<x;ee+=y){let le=(J+ee)/m;if(!(le<0||le>=p.outDepth||Math.floor(le)!==le))for(let se=0;se<N;se+=b){let ce=(ne+se)/f;if(!(ce<0||ce>=p.outHeight||Math.floor(ce)!==ce))for(let de=0;de<T;de+=v){let fe=(Q+de)/g;if(fe<0||fe>=p.outWidth||Math.floor(fe)!==fe)continue;let xe=x*N*T-1-h.get(V,le,ce,fe,H),be=ee*N*T+se*T+de,Se=xe===be?1:0;Se!==0&&(ie+=W.get(V,le,ce,fe,H)*Se)}}}O.set(ie,V,K,j,Y,H)}return n.makeTensorInfo(O.shape,O.dtype,O.values)}var Wj={kernelName:sh,backendName:"cpu",kernelFunc:Bj};function Vj(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;Ie([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=E.computePool2DInfo(o.shape,l,c,1,u,p),h=n.data.get(o.dataId).values,m=Le(d.outShape,o.dtype,VT(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"),$=n.data.get(r.dataId).values,F=Le(r.shape,"float32",$);for(let O=0;O<d.batchSize;++O)for(let W=0;W<d.inChannels;++W)for(let V=0;V<d.inHeight;++V)for(let H=0;H<d.inWidth;++H){let K=V-T,j=H-N,Y=0;for(let J=0;J<v;J+=y){let ne=(K+J)/f;if(!(ne<0||ne>=d.outHeight||Math.floor(ne)!==ne))for(let Q=0;Q<x;Q+=b){let ie=(j+Q)/g;if(ie<0||ie>=d.outWidth||Math.floor(ie)!==ie)continue;let ee=v*x-1-m.get(O,ne,ie,W),le=J*x+Q,se=ee===le?1:0;se!==0&&(Y+=F.get(O,ne,ie,W)*se)}}C.set(Y,O,V,H,W)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var Uj={kernelName:rh,backendName:"cpu",kernelFunc:Vj};function Gj(e,t,n,a,r){let s=k.computeStrides(t),i=Pv(e,t,n,s,r,"max"),o=VT(e,t,n,r,!0,a);return[i.values,o.values]}var Hj={kernelName:ih,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;Ie(a,"MaxPoolWithArgmax");let c=l.data.get(a.dataId).values,u=E.computePool2DInfo(a.shape,r,s,[1,1],i),[p,d]=Gj(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 Jm(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Ie(r,"sum");let o;r.dtype==="bool"?o=fs({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=ir({inputs:{x:r},backend:n});let l=o.shape.length,c=k.parseAxisParam(s,o.shape),u=E.getAxesPermutation(c,l),p=c,d=o;u!=null&&(d=va({inputs:{x:o},backend:n,attrs:{perm:u}}),p=E.getInnerMostAxes(p.length,l)),E.assertAxesAreInnerMostDims("sum",p,d.shape.length);let[h,m]=E.computeOutAndReduceShapes(d.shape,p),f=E.upcastType(d.dtype,"int32"),g=Xm(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=E.expandShapeToKeepDim(g.shape,c),N=g;g=Nt({inputs:{x:g},backend:n,attrs:{shape:x}}),n.disposeIntermediateTensorInfo(N)}return n.disposeIntermediateTensorInfo(o),u!=null&&n.disposeIntermediateTensorInfo(d),g}var jj={kernelName:bi,backendName:"cpu",kernelFunc:Jm};function qj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=k.parseAxisParam(s,r.shape),l=E.computeOutAndReduceShapes(r.shape,o)[1],c=k.sizeFromShape(l),u=[],p=n.makeTensorInfo([],"float32",new Float32Array([c]));u.push(p);let d=fs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(d);let h=Ov({inputs:{a:d,b:p},backend:n});u.push(h);let m=Jm({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var Kj={kernelName:ti,backendName:"cpu",kernelFunc:qj};function Xj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Ie(r,"min");let o=k.parseAxisParam(s,r.shape),l=o,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=va({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("min",l,u.shape.length);let[p,d]=E.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=E.expandShapeToKeepDim(p,o),b=Nt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var Yj={kernelName:ni,backendName:"cpu",kernelFunc:Xj};function Jj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,mode:i}=a;Ie(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 Zj={kernelName:Sc,backendName:"cpu",kernelFunc:Jj},Qj=Pt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),e5=Qt(ml,Qj),t5={kernelName:ml,backendName:"cpu",kernelFunc:e5},n5=Ro($d());function XT(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=KT({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=E.expandShapeToKeepDim(c.shape,l),p=Nt({inputs:{x:c},backend:n,attrs:{shape:u}}),d=Mv({inputs:{a:r,b:p},backend:n}),h=RT({inputs:{x:d},backend:n}),m=Jm({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),f=Nt({inputs:{x:m},backend:n,attrs:{shape:u}}),g=Ov({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 a5={kernelName:xi,backendName:"cpu",kernelFunc:XT};function r5(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;Ie(r,"multinomial");let l=o?r:XT({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=n5.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 s5={kernelName:oh,backendName:"cpu",kernelFunc:r5},i5=er.nonMaxSuppressionV3Impl;function o5(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;Ie(r,"NonMaxSuppression");let c=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,{selectedIndices:p}=i5(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var l5={kernelName:yl,backendName:"cpu",kernelFunc:o5},u5=er.nonMaxSuppressionV4Impl;function c5(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:c}=a;Ie(r,"NonMaxSuppressionPadded");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,{selectedIndices:d,validOutputs:h}=u5(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var p5={kernelName:bl,backendName:"cpu",kernelFunc:c5},d5=er.nonMaxSuppressionV5Impl;function h5(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:c}=a;Ie(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}=d5(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var m5={kernelName:xl,backendName:"cpu",kernelFunc:h5};function f5(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a;Ie(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 g5={kernelName:si,backendName:"cpu",kernelFunc:f5};function Zm(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=Ki({inputs:{input:a},backend:n}),s=Zm({inputs:{x:r},backend:n}),i=mu({inputs:{input:a},backend:n}),o=Zm({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 Bv({backend:n,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var y5={kernelName:Ol,backendName:"cpu",kernelFunc:Zm};function YT(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=Ki({inputs:{input:a},backend:n}),s=YT({inputs:{x:r},backend:n}),i=mu({inputs:{input:a},backend:n}),o=Zm({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 Bv({backend:n,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var b5={kernelName:vl,backendName:"cpu",kernelFunc:YT};function JT(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Ym({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=Ym({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=fu({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var x5={kernelName:wl,backendName:"cpu",kernelFunc:JT};function v5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;Ie(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 ZT={kernelName:ii,backendName:"cpu",kernelFunc:v5},w5=Pt((e,t)=>Math.pow(e,t)),k5=Qt(oi,w5),I5={kernelName:oi,backendName:"cpu",kernelFunc:k5};function N5(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=Fv(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var T5={kernelName:Cc,backendName:"cpu",kernelFunc:N5},S5=ot(Il,e=>1/e),C5={kernelName:Il,backendName:"cpu",kernelFunc:S5};function _5(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;Ie(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 $;i?$=x*(C+.5)-.5:$=x*C;let F=Math.max(0,Math.floor($)),O=$-F,W=Math.min(d-1,Math.ceil($)),V=T*l[0]+F*l[1],H=T*l[0]+W*l[1];for(let K=0;K<u;K++){let j;i?j=N*(K+.5)-.5:j=N*K;let Y=Math.max(0,Math.floor(j)),J=j-Y,ne=Math.min(h-1,Math.ceil(j)),Q=V+Y*l[2],ie=H+Y*l[2],ee=V+ne*l[2],le=H+ne*l[2];for(let se=0;se<m;se++){let ce=f[Q+se],de=f[ie+se],fe=f[ee+se],xe=f[le+se],be=ce+(fe-ce)*J,Se=de+(xe-de)*J,_e=be+(Se-be)*O;g[v++]=_e}}}return n.makeTensorInfo([p,c,u,m],"float32",g)}var E5={kernelName:ci,backendName:"cpu",kernelFunc:_5};function A5(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;Ie([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 $=C*y,F=Math.floor($),O=Math.min(Math.ceil($),c-1),W=T+F*o[1],V=T+O*o[1],H=$-F,K=1-H;for(let j=0;j<h;j++){let Y=j*b,J=Math.floor(Y),ne=Math.min(Math.ceil(Y),u-1),Q=Y-J,ie=1-Q,ee=W+J*o[2],le=W+ne*o[2],se=V+J*o[2],ce=V+ne*o[2],de=K*ie,fe=K*Q,xe=H*ie,be=H*Q;for(let Se=0;Se<p;Se++){let _e=v[x++];m[ee+Se]+=_e*de,m[le+Se]+=_e*fe,m[se+Se]+=_e*xe,m[ce+Se]+=_e*be}}}}return n.makeTensorInfo([l,u,c,p],"float32",m)}var F5={kernelName:ch,backendName:"cpu",kernelFunc:A5};function $5(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;Ie(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 $=0;$<c;$++){let F=i?v*($+.5):v*$,O=Math.min(d-1,s?Math.round(F):Math.floor(F));i&&(O=Math.max(0,O));let W=C+O*l[1];for(let V=0;V<u;V++){let H=i?x*(V+.5):x*V,K=Math.min(h-1,s?Math.round(H):Math.floor(H));i&&(K=Math.max(0,K));let j=W+K*l[2];for(let Y=0;Y<m;Y++){let J=f[j+Y];g[N++]=J}}}}return n.makeTensorInfo([p,c,u,m],r.dtype,g)}var D5={kernelName:_c,backendName:"cpu",kernelFunc:$5};function M5(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;Ie([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,$=Math.ceil(T)*2+2;for(let F=0;F<c;F++){let O=F*o[0];for(let W=0;W<u;W++){let V=O+W*o[1],H=Math.floor(W*N),K=Math.floor(H-C/2);for(let j=0;j<p;j++){let Y=V+j*o[2],J=Math.floor(j*T),ne=Math.floor(J-$/2);for(let Q=0;Q<d;Q++){let ie=0;for(let ee=0;ee<C;ee++){let le=ee+K;if(le<0||le>=h)continue;let se=O+le*l[1],ce=le*v,de=Math.min(u-1,i?Math.round(ce):Math.floor(ce));if(W===de)for(let fe=0;fe<$;fe++){let xe=fe+ne;if(xe<0||xe>=m)continue;let be=se+xe*l[2],Se=xe*x,_e=Math.min(p-1,i?Math.round(Se):Math.floor(Se));j===_e&&(ie+=g[be+Q])}}f[Y+Q]=ie}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var R5={kernelName:uh,backendName:"cpu",kernelFunc:M5};function P5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;Ie(r,"reverse");let i=r.shape.length,o=k.parseAxisParam(s,r.shape);if(i===0)return ir({inputs:{x:r},backend:n});let l=new zt(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 O5={kernelName:di,backendName:"cpu",kernelFunc:P5},L5={kernelName:Ll,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]=E.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 $=C*d;for(let F=0;F<d;F++){let O=[c,N,C,F],W=O[2],V=O[1],H=(W-h)*y-(V-m)*g,K=(W-h)*g+(V-m)*y;H=Math.round(H+h),K=Math.round(K+m);let j=s;if(typeof s!="number"&&(F===3?j=f:j=s[F]),H>=0&&H<p&&K>=0&&K<u){let J=K*(p*d),ne=H*d,Q=x+J+ne+F;j=b[Q]}let Y=x+T+$+F;l[Y]=j}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},z5=ot(hi,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}),B5={kernelName:hi,backendName:"cpu",kernelFunc:z5};function QT(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 W5(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}=E.calculateShapes(s,r,i),d=!0,h=n.bufferSync(r),m=n.bufferSync(s),f=QT(h,m,i,p,c,l,o,u,0,d);return n.makeTensorInfo(i,f.dtype,f.values)}var V5={kernelName:Tl,backendName:"cpu",kernelFunc:W5};function U5(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t;Ie([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=ha(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 G5={kernelName:Sl,backendName:"cpu",kernelFunc:U5},H5=E.SELU_SCALEALPHA,j5=E.SELU_SCALE,q5=ot(Cl,e=>e>=0?j5*e:H5*(Math.exp(e)-1)),K5={kernelName:Cl,backendName:"cpu",kernelFunc:q5},X5=ot(gi,e=>1/(1+Math.exp(-e))),Y5={kernelName:gi,backendName:"cpu",kernelFunc:X5},J5=ot(Al,e=>e<0?-1:e>0?1:0),Z5={kernelName:Al,backendName:"cpu",kernelFunc:J5},Q5=ot(fi,e=>Math.sin(e)),eq={kernelName:fi,backendName:"cpu",kernelFunc:Q5},tq=ot(El,e=>Math.sinh(e)),nq={kernelName:El,backendName:"cpu",kernelFunc:tq},aq=11920928955078125e-23,eS=Math.log(aq)+2,rq=ot(Fl,e=>{let t=e>-eS,n=e<eS,a=Math.exp(e),r;return n?r=a:t?r=e:r=Math.log(1+a),r}),sq={kernelName:Fl,backendName:"cpu",kernelFunc:rq};function iq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;Ie([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=ZT.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),u=E.getReshaped(c.shape,s,o,!1),p=E.getPermuted(u.length,s.length,!1),d=E.getReshapedPermuted(c.shape,s,o,!1),h=Nt({inputs:{x:c},backend:n,attrs:{shape:u}}),m=va({inputs:{x:h},backend:n,attrs:{perm:p}}),f=Nt({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}var oq={kernelName:Ec,backendName:"cpu",kernelFunc:iq};function lq(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}=E.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f=n.bufferSync(s),g=n.data.get(i.dataId).values[0],y=QT(m,f,o,d,u,c,l,p,g,h);return n.makeTensorInfo(o,y.dtype,y.values)}var uq={kernelName:ph,backendName:"cpu",kernelFunc:lq};function cq(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=E.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=Xi({inputs:{x:r},backend:n,attrs:{begin:c,size:d}});return c[o]+=p,h})}var pq={kernelName:$l,backendName:"cpu",kernelFunc:cq},dq=ot(yi,e=>Math.sqrt(e)),hq={kernelName:yi,backendName:"cpu",kernelFunc:dq},mq={kernelName:Ac,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;Ie(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}}},fq=ot(Kr,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),gq={kernelName:Kr,backendName:"cpu",kernelFunc:fq};function yq(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;Ie(r,"stridedSlice");let{nonStrided:h,$begin:m,$strides:f,size:g,newShape:y,outShape:b}=dn.sliceInfo(r.shape,s,i,o,l,c,u,p,d),v=Nt({inputs:{x:r},backend:n,attrs:{shape:y}}),x;if(h){let T=Xi({inputs:{x:v},backend:n,attrs:{begin:m,size:g}});x=Nt({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=AT(b,T,f,m);x=n.makeTensorInfo(C.shape,C.dtype,C.values)}let N=Nt({inputs:{x},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),N}var bq={kernelName:Dl,backendName:"cpu",kernelFunc:yq},xq=ot(Ml,e=>Math.tan(e)),vq={kernelName:Ml,backendName:"cpu",kernelFunc:xq},wq=ot(ki,e=>Math.tanh(e)),kq={kernelName:ki,backendName:"cpu",kernelFunc:wq};function Iq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;Ie(r,"tile");let i=$T(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var Nq={kernelName:qr,backendName:"cpu",kernelFunc:Iq};function Tq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;Ie(r,"topk");let o=n.data.get(r.dataId).values,[l,c]=DT(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 Sq={kernelName:Rl,backendName:"cpu",kernelFunc:Tq};function Cq(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;Ie(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:c}=MT(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var _q={kernelName:dh,backendName:"cpu",kernelFunc:Cq};function Eq(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=Xi({inputs:{x:r},backend:n,attrs:{begin:u,size:p}});d[h]=Nt({inputs:{x:m},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(m)}return d}var Aq={kernelName:Pl,backendName:"cpu",kernelFunc:Eq};function Fq(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a;Ie(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=Ym({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=jT({inputs:{a:g,b:d},backend:n}),b=fs({inputs:{x:y},backend:n,attrs:{dtype:"float32"}}),v=Dv({inputs:{a:b,b:r},backend:n}),x=Jm({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=JT({inputs:c,backend:n,attrs:{axis:0}});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var $q={kernelName:Fc,backendName:"cpu",kernelFunc:Fq},Dq=[eH,rG,nH,rH,cG,iH,lH,cH,dH,mH,gH,bH,vH,IH,TH,_H,AH,$H,MH,ZG,PH,LH,BH,lG,dG,VH,sG,GH,jH,XH,JH,qH,t6,a6,QH,s6,o6,u6,p6,h6,f6,g6,b6,v6,k6,I6,T6,N6,Lv,HG,C6,E6,O6,hG,L6,fG,G6,j6,q6,yG,Y6,Z6,ej,nj,rj,xG,oj,iG,uj,HH,pj,hj,fj,jG,wG,bj,vj,IG,kj,Tj,Cj,Aj,$j,Mj,TG,Oj,zj,Wj,Uj,Hj,Rj,Kj,Yj,CG,Zj,t5,s5,EG,FG,l5,p5,m5,DG,g5,b5,x5,ZT,I5,KG,PG,T5,oG,C5,XG,YG,JG,E5,F5,D5,R5,O5,L5,B5,LG,V5,G5,K5,Y5,Z5,eq,nq,zG,a5,sq,oq,uq,pq,hq,mq,WG,gq,bq,UG,jj,vq,kq,Nq,Sq,MG,_q,Aq,$q,y5];for(let e of Dq)Dc(e);var Yi={},Wv={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Mq(e,t){Yi[e]=t}function or(e){if(!(e in Yi)){let n=Rq(e);if(n!==null)Yi[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=Yi[e];return t.isContextLost()?(delete Yi[e],or(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),Yi[e])}function Pq(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function Rq(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=Pq(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Yi[e]},!1),e===1?t.getContext("webgl",Wv)||t.getContext("experimental-webgl",Wv):t.getContext("webgl2",Wv)}var Tp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(Tp||(Tp={}));var aa;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(aa||(aa={}));var rn;(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"})(rn||(rn={}));function Sp(e,t){return[t,e]}function Oq(e,t){return e*t}function Cp(e){let t=k.sizeFromShape(e),n=Math.ceil(t/4);return k.sizeToSquarishShape(n)}function gu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Lq(e,t){let[n,a]=gu(e,t);return n*a*4}function Vv(e,t){let n=e,a,r,s,i,o,l,c,u,p,d;return te().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 Te(e,t){let n=t();return te().getBool("DEBUG")&&zq(e),n}function zq(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+Bq(e,t))}var Wq=596e-10,Vq=65504;function Uq(e){return!!(te().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Wq<Math.abs(e)&&Math.abs(e)<Vq)}function Bq(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 Qm(e,t){return Ar(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function Gq(e,t){let n=Ar(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Te(e,()=>e.shaderSource(n,t)),Te(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 jq(e,t){let n=Ar(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Te(e,()=>e.shaderSource(n,t)),Te(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Hq(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var qq=/ERROR: [0-9]+:([0-9]+):/g;function Hq(e,t){let n=qq.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 Kq(e){return Ar(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function Xq(e,t){if(Te(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 Uv(e,t){if(Te(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Yq(e,t){let n=Ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Te(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Jq(e,t){let n=Ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Te(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Te(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Zq(e){return Ar(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Qq(e,t){let n=te().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 e8(e){return Ar(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function tS(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),Te(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),Te(e,()=>e.enableVertexAttribArray(o)),!0)}function n8(e,t,n){t8(e,n),Te(e,()=>e.activeTexture(e.TEXTURE0+n)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function a8(e,t,n){return Ar(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function r8(e,t,n){return e.getUniformLocation(t,n)}function s8(e,t,n,a){Te(e,()=>n8(e,t,a)),Te(e,()=>e.uniform1i(n,a))}function Gv(e,t,n){Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Te(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function nS(e,t){Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Te(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function ef(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+i8(e,t))}function i8(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 Ar(e,t,n){let a=Te(e,()=>t());if(a==null)throw new Error(n);return a}function t8(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 yu(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function bu(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 Hv(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[yu(e),...bu(e)]),t}function o8(e,t=!1){let n=te().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=yu(e),s=2,i=2;return e.length&&([s,i]=bu(e)),a=r*(s/2)*(i/2),k.sizeToSquarishShape(a).map(o=>o*2)}return k.sizeToSquarishShape(a)}function tf(e){return e%2==0}function nf(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||tf(n)&&tf(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&tf(e[0])&&tf(t[0])}var jv,qv;function l8(e){if(jv==null){let t=or(e);jv=t.getParameter(t.MAX_TEXTURE_SIZE)}return jv}function u8(e){if(qv==null){let t=or(e);qv=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,qv)}function c8(e){if(e===0)return 0;let t,n=or(e);return wa(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:wa(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function wa(e,t){return e.getExtension(t)!=null}function aS(e){try{if(or(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function p8(e){if(e===0)return!1;let t=or(e);if(e===1){if(!wa(t,"OES_texture_float"))return!1}else if(!wa(t,"EXT_color_buffer_float"))return!1;return Kv(t)}function h8(e){if(e===0)return!1;let t=or(e);if(e===1){if(!wa(t,"OES_texture_float")||!wa(t,"WEBGL_color_buffer_float"))return!1}else{if(wa(t,"EXT_color_buffer_float"))return Kv(t);let n="EXT_color_buffer_half_float";if(wa(t,n)){let a=t.getExtension(n);return d8(t,a)}return!1}return Kv(t)}function Kv(e){let t=Vv(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 d8(e,t){let n=Vv(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 m8(e){return e!==2?!1:or(e).fenceSync!=null}function _p(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 Ae=te();Ae.registerFlag("HAS_WEBGL",()=>Ae.getNumber("WEBGL_VERSION")>0);Ae.registerFlag("WEBGL_VERSION",()=>aS(2)?2:aS(1)?1:0);Ae.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ae.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ae.get("WEBGL_VERSION")===2);Ae.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ae.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ae.registerFlag("WEBGL_PACK",()=>Ae.getBool("HAS_WEBGL"));Ae.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_CLIP",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);Ae.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_PACK_REDUCE",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_CONV_IM2COL",()=>Ae.getBool("WEBGL_PACK"));Ae.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>l8(Ae.getNumber("WEBGL_VERSION")));Ae.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>u8(Ae.getNumber("WEBGL_VERSION")));Ae.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Ae.getNumber("WEBGL_VERSION");return e===0?0:c8(e)});Ae.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ae.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!xh.isMobile());Ae.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>p8(Ae.getNumber("WEBGL_VERSION")));Ae.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ae.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ae.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ae.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>h8(Ae.getNumber("WEBGL_VERSION")));Ae.registerFlag("WEBGL_FENCE_API_ENABLED",()=>m8(Ae.getNumber("WEBGL_VERSION")));Ae.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ae.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ae.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 fn(){let e,t,n,a,r,s,i,o,l,c;return te().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 Xv(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 rS=`
|
|
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;
|
|
}
|
|
`,f8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Tp.DENSE;let t=Cp(e),n=fn();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;
|
|
}
|
|
`}},g8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Tp.DENSE;let t=Cp(e),n=fn();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;
|
|
}
|
|
`}},y8=class{constructor(e){this.variableNames=["A"],this.outTexUsage=aa.DOWNLOAD;let t=fn();this.outputShape=e,this.userCode=`
|
|
${rS}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},b8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=aa.DOWNLOAD;let t=fn();this.outputShape=e,this.userCode=`
|
|
${rS}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},x8=class{constructor(e,t,n=!1){this.variableNames=["A"];let a=fn(),[r,s]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${Xv(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.);
|
|
}
|
|
`}},v8=class{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let a=fn(),[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=`
|
|
${Xv(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 w8(e){let t=fn(),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 Gq(e,n)}function k8(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 Yq(e,t)}function I8(e){let t=new Uint16Array([0,1,2,2,1,3]);return Jq(e,t)}function Ep(e,t,n,a,r,s){Qq(t,n);let i=Zq(e),o=e.TEXTURE_2D;return Te(e,()=>e.bindTexture(o,i)),Te(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Te(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Te(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),Te(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Te(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null)),i}function sS(e){return e.internalFormatFloat}function N8(e,t,n,a){let[r,s]=Sp(t,n);return Ep(e,r,s,sS(a),a.textureFormatFloat,e.FLOAT)}function iS(e){return e.internalFormatHalfFloat}function T8(e,t,n,a){let[r,s]=Sp(t,n);return Ep(e,r,s,iS(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function oS(e){return e.downloadTextureFormat}function S8(e,t,n,a){let[r,s]=Sp(t,n);return Ep(e,r,s,oS(a),e.RGBA,e.UNSIGNED_BYTE)}function lS(e){return e.internalFormatPackedFloat}function C8(e,t,n,a){let[r,s]=gu(t,n);return Ep(e,r,s,lS(a),e.RGBA,e.FLOAT)}function uS(e){return e.internalFormatPackedHalfFloat}function _8(e,t,n,a){let[r,s]=gu(t,n);return Ep(e,r,s,uS(a),e.RGBA,a.textureTypeHalfFloat)}function E8(e,t,n){let a=0,r=3*4,s=3*4+2*4;return Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),tS(e,t,"clipSpacePos",n,3,s,a)&&tS(e,t,"uv",n,2,s,r)}function A8(e,t,n,a,r,s){Te(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),Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function F8(e,t,n){Te(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function $8(e,t,n,a){let r=e.createBuffer();Te(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return Te(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),Te(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Te(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function D8(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 M8(e,t,n,a){let[r,s]=Sp(t,n),i=4,o=new Uint8Array(Oq(t*n,i));return Te(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function R8(e,t,n,a,r,s,i,o){let l=e,c=new Float32Array(Lq(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 P8(e,t,n){let a=new Float32Array(t*n*4);return Te(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var L8=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=te().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Mq(t,e)):this.gl=or(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(te().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Qm(this.gl,r),wa(this.gl,s))this.textureHalfFloatExtension=Qm(this.gl,s);else if(te().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),wa(this.gl,a))this.colorBufferHalfFloatExtension=Qm(this.gl,a);else if(te().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",wa(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(wa(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=k8(this.gl),this.indexBuffer=I8(this.gl),this.framebuffer=e8(this.gl),this.textureConfig=Vv(this.gl,this.textureHalfFloatExtension)}get debug(){return te().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;Te(e,()=>e.finish()),Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Te(e,()=>e.deleteFramebuffer(this.framebuffer)),Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Te(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Te(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),N8(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),T8(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),S8(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),F8(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),A8(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),_8(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),C8(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(nS(this.gl,this.framebuffer),this.outputTexture=null),Te(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>M8(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return R8(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return D8(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=$8(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(te().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 te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>P8(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=jq(t,e),a=w8(t),r=Kq(t);return Te(t,()=>t.attachShader(r,a)),Te(t,()=>t.attachShader(r,n)),Xq(t,r),this.debug&&Uv(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=E8(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Te(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Uv(this.gl,this.program),Te(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?a8(this.gl,e,t):r8(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Te(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(),s8(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=gu(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&&Uv(this.gl,this.program),ef(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Te(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Te(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Qm(this.gl,te().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(te().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(te().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,te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,te().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=O8(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(),Gv(this.gl,e,this.framebuffer),this.debug&&ef(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Gv(this.gl,this.outputTexture,this.framebuffer),this.debug&&ef(this.gl)):nS(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;Gv(a,e,this.framebuffer),this.debug&&ef(a),this.outputTexture=e,Te(a,()=>a.viewport(0,0,t,n)),Te(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),Te(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 O8(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{getBroadcastDims:cS}=E;function q8(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=>z8(h,t,a)).join(`
|
|
`),o=t.texShape,l=fn(),c=V8(l),u,p,d=H8(l);return t.isPacked?(u=B8(t.logicalShape,o),p=G8(l)):(u=W8(t.logicalShape,o),p=U8(l)),a&&(d+=j8),[d,c,p,s,u,i,n].join(`
|
|
`)}function xu(e){let t=e.shapeInfo.logicalShape;switch(t.length){case 0:return K8(e);case 1:return X8(e);case 2:return Y8(e);case 3:return J8(e);case 4:return Z8(e);case 5:return Q8(e);case 6:return eK(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function pS(e){switch(e.shapeInfo.logicalShape.length){case 0:return tK(e);case 1:return nK(e);case 2:return aK(e);case 3:return rK(e);default:return sK(e)}}function z8(e,t,n=!1){let a="";n?a+=pS(e):a+=xu(e);let r=e.shapeInfo.logicalShape,s=t.logicalShape;return r.length<=s.length&&(n?a+=iK(e,t):a+=oK(e,t)),a}function B8(e,t){switch(e.length){case 0:return dS();case 1:return lK(e,t);case 2:return pK(e,t);case 3:return uK(e,t);default:return cK(e,t)}}function W8(e,t){switch(e.length){case 0:return dS();case 1:return dK(e,t);case 2:return yK(e,t);case 3:return hK(e,t);case 4:return mK(e,t);case 5:return fK(e,t);case 6:return gK(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function V8(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function U8(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function G8(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function H8(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);
|
|
}
|
|
|
|
${bK}
|
|
${xK}
|
|
${vK}
|
|
`}var bK=`
|
|
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);
|
|
}
|
|
`,xK=`
|
|
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);
|
|
}
|
|
`,vK=`
|
|
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);
|
|
}
|
|
`,j8=`
|
|
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 dS(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function lK(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 dK(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 uK(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 hK(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 cK(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 mK(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 fK(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 gK(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 pK(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 yK(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 Zi(e){return`offset${e}`}function tK(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=fn();return`
|
|
vec4 ${n}() {
|
|
return ${a.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function K8(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=Zi(t);return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, ${o});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function nK(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=fn();return`
|
|
vec4 ${n}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${r[0]}, ${r[1]}, index);
|
|
return ${s.texture2D}(${t}, uv);
|
|
}
|
|
`}function X8(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${vu(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=Zi(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 aK(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=fn();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 Y8(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=wu(e,o),d=["row","col"];return`
|
|
${xu(p)}
|
|
float ${a}(int row, int col) {
|
|
return ${a}(${ku(d,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
|
|
${vu(e)}
|
|
}
|
|
`;let l=r[0],c=r[1],u=Zi(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 rK(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=wu(e,p),m=["b","row","col"];return`
|
|
${pS(h)}
|
|
vec4 ${a}(int b, int row, int col) {
|
|
return ${a}(${ku(m,d)});
|
|
}
|
|
`}let i=s[0],o=s[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),u=fn();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 J8(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=wu(e,l),f=["row","col","depth"];return`
|
|
${xu(m)}
|
|
float ${a}(int row, int col, int depth) {
|
|
return ${a}(${ku(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)));
|
|
${vu(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=Zi(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 sK(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=fn();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 Z8(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=wu(e,o),f=["row","col","depth","depth2"];return`
|
|
${xu(m)}
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
return ${a}(${ku(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)));
|
|
${vu(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=Zi(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 Q8(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=wu(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${xu(f)}
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${a}(${ku(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;
|
|
${vu(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=Zi(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 eK(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=wu(e,r),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${xu(g)}
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${a}(${ku(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)));
|
|
${vu(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=Zi(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 vu(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 iK(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=cS(e.shapeInfo.logicalShape,t.logicalShape),l=gt(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 oK(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=gt(l),u=cS(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 gt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function wu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function ku(e,t){return t.map(n=>e[n]).join(", ")}function wK(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=q8(s,o,r,t.packedInputs),c=e.createProgram(l),u=null,p=e.getUniformLocation(c,"NAN",!1);te().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 hS(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 kK(e,t,n,a,r){hS(t.inShapeInfos,n),hS([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),te().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 IK(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:NK,bincountImpl:mS,bincountReduceImpl:TK,ceilImpl:SK,concatImpl:CK,expImpl:_K,expm1Impl:EK,floorImpl:AK,gatherV2Impl:FK,greaterImpl:$K,lessImpl:DK,linSpaceImpl:MK,logImpl:RK,maxImpl:PK,maximumImpl:OK,minimumImpl:LK,multiplyImpl:zK,negImpl:BK,prodImpl:WK,rangeImpl:VK,rsqrtImpl:UK,simpleAbsImpl:fS,sliceImpl:GK,stridedSliceImpl:HK,subImpl:jK,tileImpl:qK,topKImpl:KK,transposeImpl:Yv,uniqueImpl:XK}=uT;function gS(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function gn(e,t){return t===1?[e]:gS(e,t)}function YK(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 eX=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=gn("rc",t),a=gt(t),r=JK(t,e,n),s=ZK(t,e[e.length-1],e[e.length-2],n),i=QK(e,n);this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
|
|
if(${r}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${s}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function tX(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 JK(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 ZK(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 QK(e,t){let n=e.length,a=tX(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 yS=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=`
|
|
${nX(t)}
|
|
${Xv(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function nX(e){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Ji(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var aX=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=xS(t,n),r=vS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=bS(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===rn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===rn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===rn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===rn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===rn.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=xS(n,a),s=vS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=bS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=te().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 rX(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 bS(e,t,n,a,r){let s=sX(t,a),i;if(r){let[l,c]=gu(e[0],e[1]);i=l*c}else{let[l,c]=Sp(e[0],e[1]);i=l*c}let o=rX(n,s);return i*o}function sX(e,t){switch(e){case rn.PACKED_2X2_FLOAT32:return lS(t);case rn.PACKED_2X2_FLOAT16:return uS(t);case rn.UNPACKED_FLOAT32:return sS(t);case rn.UNPACKED_FLOAT16:return iS(t);case rn.PACKED_4X1_UNSIGNED_BYTE:return oS(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function iX(e){return te().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?rn.PACKED_2X2_FLOAT32:rn.UNPACKED_FLOAT32:e?rn.PACKED_2X2_FLOAT16:rn.UNPACKED_FLOAT16}function xS(e,t){if(e===aa.UPLOAD)return rn.PACKED_2X2_FLOAT32;if(e===aa.RENDER||e==null)return iX(t);if(e===aa.DOWNLOAD||e===aa.PIXELS)return rn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function vS(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var gs=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);
|
|
}
|
|
`}},La="if (isnan(x)) return x;",oX="return x;",wS="return abs(x);",lX="return (x >= 0.0) ? x : (exp(x) - 1.0);",uX=La+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,cX=La+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,af="return x;",pX="return x;",dX=`
|
|
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;
|
|
`,hX=`
|
|
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;
|
|
`,mX=`
|
|
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;
|
|
`,Iu=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);
|
|
}
|
|
`}},fX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=gn("rc",t),a=gt(t),r=YK(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}));
|
|
}
|
|
`}},gX=er.whereImpl,yX=1e-7,bX=1e-4,Jv={};function xX(e){return e in Jv||(Jv[e]={}),Jv[e]}var vX=128,wX=600;function kX(){return te().global.screen==null?1024:te().global.screen.height*te().global.screen.width*window.devicePixelRatio*wX/1024/1024}var NX=class extends dc{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,!te().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=or(te().getNumber("WEBGL_VERSION"));this.binaryCache=xX(te().getNumber("WEBGL_VERSION")),this.gpgpu=new L8(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 aX(this.gpgpu),this.numMBBeforeWarning=kX(),this.texData=new Dd(this,ts())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((te().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||te().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={};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:aa.UPLOAD,refCount:1,complexParentRefCount:0}),a}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--}}decComplexRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.complexParentRefCount>0&&t.refCount--}}move(e,t,n,a){if(te().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:aa.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.texData.has(t)){let n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}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 Iu(i,af):p=new gs(i,af);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=E.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 Iu(a,af):h=new gs(a,af);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(!te().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&te().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"&&te().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...Cp(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=E.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),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(!Uq(n))throw te().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(te().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(e),d=this.texData.get(p.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(d.texture,...Cp(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(p),h}let s=te().getBool("WEBGL_PACK")&&a===!0,i=s?Hv(t):t,o=s?new b8(i):new y8(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}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(te().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 te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:k.now(),endMs:null}}endTimer(e){return te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=k.now(),e)}async getQueryTime(e){if(te().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;if(this.texData.get(e).complexParentRefCount>0){this.texData.get(e).refCount--;return}this.releaseGPUData(e);let{complexTensorInfos:t}=this.texData.get(e);t!=null&&(this.texData.get(t.real.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.real),this.texData.get(t.imag.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.imag)),this.texData.delete(e)}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 te().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=ts().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=vX){let n=this.getCPUBackend();return!te().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){E.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return gX(e.shape,t)}packedUnaryOp(e,t,n){let a=new Iu(e.shape,t);return this.compileAndRun(a,[e],n)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let n=fS(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(te().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,wS,e.dtype);let t=new gs(e.shape,wS);return this.compileAndRun(t,[e])}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 ts().makeTensorFromDataId(a,e,t,this)}unpackTensor(e){let t=new fX(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new eX(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[yu(e.shape),...bu(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},r=[yu(t),...bu(t)],s=new yS(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=Hv(a),i;n?i=new g8(s):i=new f8(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===Tp.DENSE){let m=Cp(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)<=te().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&&!nf(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=IK(e,l,c),p=this.getAndSaveBinary(u,()=>wK(this.gpgpu,e,l,c)),d=this.activeTimers!=null,h;if(d&&(h=this.startTimer()),kK(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)})),!te().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){n=n||t[0].dtype;let s=this.runWebGLProgram(e,t,n,a,r);return ts().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(te().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(!te().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=te().getBool("DEBUG");te().set("DEBUG",!1);let t=this.abs(he(1e-8)).dataSync()[0];if(te().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?yX:bX}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=o8(n,o),t.texShape=u),r!=null){let p=Hv(n),d,h=u[1],m=u[0],f=r instanceof Uint8Array;o?([h,m]=gu(u[0],u[1]),d=new v8(p,[m,h],f)):d=new x8(p,[m,h],f);let g=this.makeTensorInfo([m,h],a);f?this.texData.get(g.dataId).usage=aa.PIXELS:this.texData.get(g.dataId).usage=aa.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=IX(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)}};function IX(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 TX="2.8.5";xh.isBrowser()&&Th("webgl",()=>new NX,2);var kS=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Nu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},rf=`
|
|
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;
|
|
`,Ap=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=E.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=`
|
|
${gt(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=gn("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 SX={kernelName:il,backendName:"webgl",kernelFunc:Wn};function ys(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=n.texData.get(o.dataId);l.complexParentRefCount++;let c=Wn({inputs:{x:r},backend:n}),u=n.texData.get(c.dataId);return u.complexParentRefCount++,i.complexTensorInfos={real:o,imag:c},s}var CX={kernelName:Vd,backendName:"webgl",kernelFunc:ys},IS="return (a < 0.) ? b * a : a;",NS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function _X(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",k.createScalarValue(s,"float32")),o=te().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ap(NS,r.shape,i.shape):new Nu(IS,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],r.dtype);return n.disposeIntermediateTensorInfo(i),l}var EX={kernelName:Ys,backendName:"webgl",kernelFunc:_X},TS="return (a < 0.) ? b * a : a;",SS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function AX(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=te().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ap(SS,a.shape,r.shape):new Nu(TS,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)}var FX={kernelName:li,backendName:"webgl",kernelFunc:AX},CS="if (isnan(x)) return x;",$X=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,DX=`
|
|
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 Je({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=te().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new Iu(i.shape,t):u=new gs(i.shape,e),o.runWebGLProgram(u,[i],l)}}function sn({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},$=new Nu(e,l.shape,c.shape);return u.runWebGLProgram($,[T,C],ha(x.dtype,N.dtype))}),b=ys({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),b}let p=s||ha(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=te().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new Ap(t,l.shape,c.shape,n):h=new Nu(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],p)}}function sf(e,t=!1){if(e==="linear")return t?pX:oX;if(e==="relu")return t?hX:uX;if(e==="elu")return t?dX:lX;if(e==="relu6")return t?mX:cX;if(e==="prelu")return t?SS:TS;if(e==="leakyrelu")return t?NS:IS;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var _S=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);
|
|
}
|
|
`}},ES={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},AS=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=E.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));
|
|
}
|
|
`}},FS="return a * b;";function $S(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=E.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),c=new AS(ES.REAL,a.shape,r.shape),u=new AS(ES.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=ys({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]=zK(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 te().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Ap(FS,a.shape,r.shape):i=new Nu(FS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var MX={kernelName:ri,backendName:"webgl",kernelFunc:$S};function RX(e,t,n){let a=[yu(e.shape),...bu(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[yu(t),...bu(t)],i=new yS(s,a),o=!0,l=n.runWebGLProgram(i,[r],e.dtype,null,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function ve(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&&!nf(r.shape,l)&&!(u.texture!==null&&nf(u.shape,l))?RX(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var PX={kernelName:Nl,backendName:"webgl",kernelFunc:ve},DS=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);
|
|
}
|
|
`}},OX=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 LX(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=E.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function Qi(e,t,n,a){let r=LX(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 DS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},o):new DS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c}):u=new OX({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 BX=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=gt(this.rank),r=zX(t);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function zX(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 WX=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=gt(this.rank),r=gS("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 of(e,t,n){let a=te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WX(e.shape,t):new BX(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function VX(e,t,n,a){let r=t,s=e.shape.length,i=k.parseAxisParam(r,e.shape),o=i,l=E.getAxesPermutation(o,s),c=l!=null,u=e;c&&(u=of(e,l,a),o=E.getInnerMostAxes(o.length,s)),E.assertAxesAreInnerMostDims("sum",o,s);let[p,d]=E.computeOutAndReduceShapes(u.shape,o),h=p;n&&(h=E.expandShapeToKeepDim(p,i));let m=k.sizeFromShape(d),f=k.sizeFromShape(e.shape)/m,g=ve({inputs:{x:u},attrs:{shape:[f,m]},backend:a}),y=bh(e.dtype),b=Qi(g,y,"sum",a),v=ve({inputs:{x:b},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(b),c&&a.disposeIntermediateTensorInfo(u),v}function Zv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return VX(r,s,i,n)}var UX={kernelName:bi,backendName:"webgl",kernelFunc:Zv};function Cn(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=Yv(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=of(r,s,i);return c}var GX={kernelName:Ii,backendName:"webgl",kernelFunc:Cn},MS=1e3;function lf({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=ve({inputs:{x:e},backend:r,attrs:{shape:N}}),$=ve({inputs:{x:t},backend:r,attrs:{shape:T}}),F=[C,$],O=Math.max(y,b),W=n?C.shape[1]:C.shape[2],V=s!=null,H=i!=null,K=l==="leakyrelu",j=l!=null?sf(l,!0):null,Y=V||H||K||j!=null,J;if((h===1||m===1)&&W>MS&&Y===!1){let Q=C,ie=$;n&&(Q=Cn({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),F.push(Q)),a&&(ie=Cn({inputs:{x:$},backend:r,attrs:{perm:[0,2,1]}}),F.push(ie));let ee=m!==1,le=m===1,se=Q;ee&&(se=ve({inputs:{x:Q},backend:r,attrs:{shape:[O,W,1]}}),F.push(se));let ce=m===1?2:1,de=ie;le&&(de=ve({inputs:{x:ie},backend:r,attrs:{shape:[O,1,W]}}),F.push(de));let fe=$S({inputs:{a:se,b:de},backend:r});J=Zv({inputs:{x:fe},backend:r,attrs:{axis:ce,keepDims:!0}}),F.push(fe)}else{let Q=ha(e.dtype,t.dtype),ie=new _S(N,T,[O,h,m],n,a,V,j,H,K),ee=[C,$];if(s!=null&&ee.push(s),H&&ee.push(i),K){let le=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));ee.push(le),F.push(le)}J=r.runWebGLProgram(ie,ee,Q)}let ne=ve({inputs:{x:J},backend:r,attrs:{shape:x}});F.push(J);for(let Q of F)r.disposeIntermediateTensorInfo(Q);return ne}function HX(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 lf({a:r,b:s,transposeA:l,transposeB:c,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var jX={kernelName:Ni,backendName:"webgl",kernelFunc:HX},RS="return abs(x);";function qX(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=fS(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return te().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Iu(a.shape,RS):r=new gs(a.shape,RS),n.runWebGLProgram(r,[a],a.dtype)}var KX={kernelName:Lo,backendName:"webgl",kernelFunc:qX},XX=La+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,YX=Je({opSnippet:XX}),JX={kernelName:zo,backendName:"webgl",kernelFunc:YX},ZX=La+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,QX=Je({opSnippet:ZX}),eY={kernelName:Bo,backendName:"webgl",kernelFunc:QX},PS="return a + b;",tY=sn({opSnippet:PS,packedOpSnippet:PS,supportsComplex:!0,cpuKernelImpl:NK}),nY={kernelName:Hr,backendName:"webgl",kernelFunc:tY},aY=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);
|
|
}
|
|
`}},rY=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 uf(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return Wn({inputs:{x:a[0]},backend:n});if(a.length>te().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=uf({inputs:a.slice(0,o),backend:n}),c=uf({inputs:a.slice(o),backend:n});return uf({inputs:[l,c],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>ha(o,l)),s=a.map(o=>o.shape),i=te().getBool("WEBGL_PACK")?new rY(a[0].shape,s):new aY(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var sY={kernelName:Ms,backendName:"webgl",kernelFunc:uf};function iY(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=E.getAxesPermutation(c,o),p=r;u!=null&&(p=Cn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,o)),E.assertAxesAreInnerMostDims("all",c,o);let[d,h]=E.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Qi(f,f.dtype,"all",n),y;if(i){let b=E.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var oY={kernelName:Od,backendName:"webgl",kernelFunc:iY};function lY(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=E.getAxesPermutation(c,o),p=r;u!=null&&(p=Cn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,o)),E.assertAxesAreInnerMostDims("any",c,o);let[d,h]=E.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Qi(f,f.dtype,"any",n),y;if(i){let b=E.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var uY={kernelName:Ld,backendName:"webgl",kernelFunc:lY},cY=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));
|
|
}
|
|
`}},pY=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=gt(o),c=gn("coords",o),u,p;if(s===1){p=o+1;let C=gt(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=gn("sourceLocR",p-1).concat("inIdx.r"),g=gn("sourceLocG",p-1).concat("inIdx.g"),y=gn("sourceLocB",p-1).concat("inIdx.b"),b=gn("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 OS(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=E.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new cY(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=OS(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}function LS(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=E.computeOptimalWindowSize(s),o=new pY(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=LS(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function zS(e,t,n,a){let r=[n];if(E.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!te().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],[i,o]=E.computeOutAndReduceShapes(t.shape,r),l=k.sizeFromShape(o),c=ve({inputs:{x:t},backend:e,attrs:{shape:[-1,l]}});s.push(c);let u=OS(e,c,a);s.push(u);let p=ve({inputs:{x:u},backend:e,attrs:{shape:i}});return s.forEach(d=>e.disposeIntermediateTensorInfo(d)),p}return LS(e,t,a)}function dY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=E.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=Cn({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=E.getInnerMostAxes(i.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=zS(n,l,i[0],"max");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var hY={kernelName:Rs,backendName:"webgl",kernelFunc:dY};function mY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=E.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=Cn({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=E.getInnerMostAxes(i.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=zS(n,l,i[0],"min");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var fY={kernelName:fc,backendName:"webgl",kernelFunc:mY},gY=La+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,yY=Je({opSnippet:gY}),bY={kernelName:Wo,backendName:"webgl",kernelFunc:yY},xY=La+"return log(x + sqrt(x * x + 1.0));",vY=Je({opSnippet:xY}),wY={kernelName:Vo,backendName:"webgl",kernelFunc:vY},kY=La+`
|
|
return atan(x);
|
|
`,IY=Je({opSnippet:kY}),NY={kernelName:Uo,backendName:"webgl",kernelFunc:IY},TY=$X+`
|
|
return atan(a, b);
|
|
`,SY=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+DX+`
|
|
return result;
|
|
`,CY=sn({opSnippet:TY,packedOpSnippet:SY}),_Y={kernelName:Ho,backendName:"webgl",kernelFunc:CY},EY=La+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,AY=Je({opSnippet:EY}),FY={kernelName:Go,backendName:"webgl",kernelFunc:AY},Fp=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});
|
|
}
|
|
`}},Qv=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 F=">=";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 ${F} 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,$=`
|
|
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)
|
|
);
|
|
|
|
${$}
|
|
}
|
|
|
|
int xC = xCCorner + ${T};
|
|
if (${C===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${$}
|
|
} else if (${C===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${$}
|
|
} 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
|
|
);
|
|
|
|
${$}
|
|
}
|
|
}
|
|
setOutput(${N});
|
|
}
|
|
}
|
|
`}};function $Y(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;_p(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(E.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=E.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 Fp(u,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var DY={kernelName:Ps,backendName:"webgl",kernelFunc:$Y};function MY(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=E.computePool3DInfo(r.shape,s,i,u,o,l,c),d=new Qv(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var RY={kernelName:gc,backendName:"webgl",kernelFunc:MY},PY=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);
|
|
}
|
|
`}},OY=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 LY(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=E.computePool3DInfo(i.shape,o,l,p,c,u),h=new OY(d);return n.runWebGLProgram(h,[r],i.dtype)}var zY={kernelName:Bd,backendName:"webgl",kernelFunc:LY};function BY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;_p([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=E.computePool2DInfo(i.shape,o,l,1,c),p=new PY(u);return n.runWebGLProgram(p,[r],i.dtype)}var WY={kernelName:zd,backendName:"webgl",kernelFunc:BY};function VY(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return lf({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var UY={kernelName:Os,backendName:"webgl",kernelFunc:VY},GY=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(E.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(E.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)));
|
|
}
|
|
`}},HY=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(E.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(E.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);
|
|
}
|
|
`}},jY=({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=te().getBool("WEBGL_PACK_NORMALIZATION")?new HY(a.shape,r.shape,s.shape,u,p,l):new GY(a.shape,r.shape,s.shape,u,p,l);return t.runWebGLProgram(d,c,c[0].dtype)},qY={kernelName:Ks,backendName:"webgl",kernelFunc:jY},XY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=gt(this.rank),n=`uniform int start[${this.rank}];`,a=KY(this.rank),r,s=e.map((i,o)=>`sourceLoc.${ew[o]} = start[${o}] + coords.${ew[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)}}},ew=["x","y","z","w","u","v"];function KY(e){if(e===1)return"sourceLoc";if(e<=6)return ew.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var YY=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=gt(this.rank),n=gn("coords",this.rank),a=gn("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 JY(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.complexParentRefCount=0,i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=dn.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 $p(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=dn.parseSliceParams(r,s,i);if(dn.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=GK(p.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}let{isPacked:c}=n.texData.get(r.dataId),u=dn.isSliceContinous(r.shape,o,l);if(c||!u){let p=te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new YY(l):new XY(l),d=p.getCustomSetupFunc(o);return n.runWebGLProgram(p,[r],r.dtype,d)}return n.uploadToGPU(r.dataId),JY(r,o,l,n)}var ZY={kernelName:_l,backendName:"webgl",kernelFunc:$p},QY=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=E.getReshaped(r.shape,s,o),c=E.getPermuted(l.length,s.length),u=E.getReshapedPermuted(r.shape,s,o),p=E.getSliceBeginCoords(i,s.length),d=E.getSliceSize(u,i,s.length),h=[],m=ve({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Cn({inputs:{x:m},backend:n,attrs:{perm:c}}),g=ve({inputs:{x:f},backend:n,attrs:{shape:u}}),y=$p({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},e7={kernelName:yc,backendName:"webgl",kernelFunc:QY};function t7(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=mS(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var n7={kernelName:Wd,backendName:"webgl",kernelFunc:t7},a7="return float(a != b);",BS=sn({opSnippet:a7,dtype:"bool"}),r7={kernelName:gl,backendName:"webgl",kernelFunc:BS};function Dp(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 s7={kernelName:lh,backendName:"webgl",kernelFunc:Dp},i7="return float(int(x));";function o7(e,t){let n=new gs(e.shape,i7),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function tw(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=xt(r.shape),o=tw({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=ys({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Dp({inputs:{input:r},backend:n}),o=tw({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 o7(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),o=BS({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 l7={kernelName:Ls,backendName:"webgl",kernelFunc:tw},WS="return ceil(x);",u7=Je({opSnippet:WS,packedOpSnippet:WS,cpuKernelImpl:SK}),c7={kernelName:jo,backendName:"webgl",kernelFunc:u7},p7=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)}}},d7=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 h7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;te().getBool("WEBGL_PACK_CLIP")?o=new d7(r.shape):o=new p7(r.shape);let l=o.getCustomSetupFunc(s,i);return n.runWebGLProgram(o,[r],r.dtype,l)}var m7={kernelName:jr,backendName:"webgl",kernelFunc:h7},f7=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 VS(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function g7(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new f7(a.shape),i=[VS(a,r.complexTensorInfos.real),VS(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var y7={kernelName:bc,backendName:"webgl",kernelFunc:g7},b7=class{constructor(e){this.outputShape=[],this.outputShape=E.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(`
|
|
`)}
|
|
}
|
|
`}},x7=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=E.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=gt(a),s=gn("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}(${cf(i,l,f)}),
|
|
vec2(${cf(c,l,f)}));
|
|
}`}let d=o.length,h=o[o.length-1];p+=`
|
|
return getChannel(
|
|
getT${d}(${cf(i,l,h)}),
|
|
vec2(${cf(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 cf(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function pf(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 v7={kernelName:th,backendName:"webgl",kernelFunc:pf};function Tu(e,t,n){let a=e[0].dtype;if(a==="complex64"){let c=e.map(m=>Dp({inputs:{input:m},backend:n})),u=e.map(m=>pf({inputs:{input:m},backend:n})),p=Tu(c,t,n),d=Tu(u,t,n),h=ys({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}=US(e,t,n),p=c.map(g=>({vals:n.readSync(g.dataId),shape:g.shape})),d=c[0].shape[0]===1,h=CK(p,u,a,d),m=E.computeOutShape(e.map(g=>g.shape),t),f=n.makeTensorInfo(m,a,h);return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}if(e.length>te().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(e.length/2),u=Tu(e.slice(0,c),t,n),p=Tu(e.slice(c),t,n),d=Tu([u,p],t,n);return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),d}if(te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let c=new x7(e.map(u=>u.shape),t);return n.runWebGLProgram(c,e,a)}let{tensors2D:r,outShape:s}=US(e,t,n),i=new b7(r.map(c=>c.shape)),o=n.runWebGLProgram(i,r,a);r.forEach(c=>n.disposeIntermediateTensorInfo(c));let l=ve({inputs:{x:o},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(o),l}function US(e,t,n){let a=E.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ve({inputs:{x:r},attrs:{shape:[-1,k.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function GS(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=E.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 E.assertParamsConsistent(l,s),Tu(o,s,n)}var w7={kernelName:qo,backendName:"webgl",kernelFunc:GS},HS=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);
|
|
}
|
|
`}},k7=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);
|
|
}
|
|
`}},I7=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=fn(),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 jS({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>MS,v=l[2]%2!=0&&!!c.isPacked;if(b||!te().getBool("WEBGL_LAZILY_UNPACK")||!te().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){let x=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],N=ve({inputs:{x:e},backend:a,attrs:{shape:[1,x,n.inChannels]}}),T=ve({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),C=lf({a:N,b:T,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ve({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(nf(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);let C=ve({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(C);let $=lf({a:N,b:C,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),F=a.texData.get($.dataId);k.assert(F.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=T,F.shape=n.outShape,g=Wn({inputs:{x:$},backend:a}),g.shape=n.outShape,y.push($)}for(let x of y)a.disposeIntermediateTensorInfo(x);return g}function qS({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=ve({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),T=ve({inputs:{x:t},backend:a,attrs:{shape:[1,f,k.sizeFromShape(t.shape)/f]}});x.push(N),x.push(T);let C=new I7(y,N.shape,n),$=a.runWebGLProgram(C,[N],"float32"),F=ve({inputs:{x:$},backend:a,attrs:{shape:[1,y[0],y[1]]}});x.push($),x.push(F);let O=r!=null,W=s!=null,V=o==="leakyrelu",H=o?sf(o,!0):null,K=new _S(F.shape,T.shape,[1,g,n.outChannels],b,v,O,H,W,V),j=[F,T];if(r&&j.push(r),W&&j.push(s),V){let Q=a.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));j.push(Q),x.push(Q)}let Y=a.runWebGLProgram(K,j,"float32"),J=m?[1,d,p,n.outChannels]:[1,n.outChannels,d,p],ne=ve({inputs:{x:Y},backend:a,attrs:{shape:J}});x.push(Y);for(let Q of x)a.disposeIntermediateTensorInfo(Q);return ne}function N7(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=E.convertConv2DDataFormat(l),d=E.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=jS({x:r,filter:s,convInfo:d,backend:n});else if(te().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=qS({x:r,filter:s,convInfo:d,backend:n});else{let f=new HS(d);h=n.runWebGLProgram(f,[r,s],"float32")}let m=ve({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),m}var T7={kernelName:zs,backendName:"webgl",kernelFunc:N7},S7=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);
|
|
}
|
|
`}},C7=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);
|
|
}
|
|
`}},_7=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);
|
|
}
|
|
`}},E7=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 A7(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=E.convertConv2DDataFormat(l),d=E.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),h=new S7(d);return n.runWebGLProgram(h,[r,s],"float32")}var F7={kernelName:Ud,backendName:"webgl",kernelFunc:A7};function $7(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=E.convertConv2DDataFormat(c),d=E.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),h=new C7(d);return n.runWebGLProgram(h,[r,s],"float32")}var D7={kernelName:Bs,backendName:"webgl",kernelFunc:$7};function M7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=E.computeConv3DInfo(r.shape,s.shape,i,l,o),u=new k7(c);return n.runWebGLProgram(u,[r,s],"float32")}var R7={kernelName:xc,backendName:"webgl",kernelFunc:M7};function P7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,c=E.computeConv3DInfo(r.shape,l,i,1,o),u=new _7(c);return n.runWebGLProgram(u,[r,s],"float32")}var O7={kernelName:Gd,backendName:"webgl",kernelFunc:P7};function L7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,c=E.computeConv3DInfo(l,s.shape,o,1,i),u=new E7(c);return n.runWebGLProgram(u,[r,s],"float32")}var z7={kernelName:Hd,backendName:"webgl",kernelFunc:L7},B7=CS+`
|
|
return cos(x);
|
|
`,W7=Je({opSnippet:B7}),V7={kernelName:Ws,backendName:"webgl",kernelFunc:W7},U7=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,G7=Je({opSnippet:U7}),H7={kernelName:Ko,backendName:"webgl",kernelFunc:G7},j7=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);
|
|
}
|
|
}
|
|
`}},q7=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 j7(r.shape,s.shape,o,l,c);return n.runWebGLProgram(u,[r,s,i],"float32")},K7={kernelName:Xo,backendName:"webgl",kernelFunc:q7},YS=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let a=e.length,r=t?"0.0":`getX(${KS(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() {
|
|
${gt(a)} coords = getOutputCoords();
|
|
int end = ${XS(a,"coords")};
|
|
float val = ${r};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${XS(a,"coords")} = idx;
|
|
val += getX(${KS(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 KS(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 XS(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 X7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length,c=E.getAxesPermutation([s],l),u=r;c!=null&&(u=Cn({inputs:{x:r},backend:n,attrs:{perm:c}}));let p=E.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=r.shape[p],h=Wn({inputs:{x:u},backend:n});for(let m=0;m<=Math.ceil(Math.log2(d))-1;m++){let f=new YS(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 YS(u.shape,i,o),f=h;h=n.runWebGLProgram(m,[h],h.dtype),n.disposeIntermediateTensorInfo(f)}if(c!=null){let m=E.getUndoAxesPermutation(c),f=Cn({inputs:{x:h},backend:n,attrs:{perm:m}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),f}return h}var Y7={kernelName:Vs,backendName:"webgl",kernelFunc:X7};function J7(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=mS(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=TK(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 Z7={kernelName:jd,backendName:"webgl",kernelFunc:J7},Q7=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 eJ(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 Q7(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var tJ={kernelName:Yo,backendName:"webgl",kernelFunc:eJ},JS=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);
|
|
}
|
|
`}},ZS=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 nJ(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(E.eitherStridesOrDilationsAreOne(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=E.computeConv2DInfo(r.shape,s.shape,i,u,o,c,!0),d;return te().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?d=new ZS(p):d=new JS(p),n.runWebGLProgram(d,[r,s],"float32")}var aJ={kernelName:Us,backendName:"webgl",kernelFunc:nJ},rJ=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);
|
|
}
|
|
`}},sJ=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 iJ(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=E.computeConv2DInfo(r.shape,u,i,o,l,c,!0),d=new rJ(p);return n.runWebGLProgram(d,[r,s],"float32")}var oJ={kernelName:qd,backendName:"webgl",kernelFunc:iJ};function lJ(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=E.computeConv2DInfo(u,s.shape,i,o,l,c,!0),d=new sJ(p);return n.runWebGLProgram(d,[r,s],"float32")}var uJ={kernelName:Kd,backendName:"webgl",kernelFunc:lJ},cJ=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 pJ(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=k.sizeFromShape(a.shape),i=ve({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new cJ(s),l=n.runWebGLProgram(o,[i],i.dtype),c=ve({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var dJ={kernelName:Xd,backendName:"webgl",kernelFunc:pJ},hJ=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 mJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=E.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),u,p=new hJ(c);u=n.runWebGLProgram(p,[r,s],"float32");let d=ve({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),d}var fJ={kernelName:vc,backendName:"webgl",kernelFunc:mJ},gJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",yJ=`
|
|
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;
|
|
`,bJ=Je({opSnippet:gJ,packedOpSnippet:yJ}),xJ={kernelName:Jo,backendName:"webgl",kernelFunc:bJ},vJ="return (b >= 1.0) ? a : a * (b + 1.0);",wJ=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,kJ=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=te().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ap(wJ,a.shape,r.shape):new Nu(vJ,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},IJ={kernelName:Zd,backendName:"webgl",kernelFunc:kJ},NJ=`
|
|
return vec4(equal(a, b));
|
|
`,TJ="return float(a == b);",SJ=sn({opSnippet:TJ,packedOpSnippet:NJ,dtype:"bool"}),CJ={kernelName:Qo,backendName:"webgl",kernelFunc:SJ},_J=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${E.ERF_P};
|
|
float a1 = ${E.ERF_A1};
|
|
float a2 = ${E.ERF_A2};
|
|
float a3 = ${E.ERF_A3};
|
|
float a4 = ${E.ERF_A4};
|
|
float a5 = ${E.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));
|
|
`,EJ=Je({opSnippet:_J}),AJ={kernelName:Zo,backendName:"webgl",kernelFunc:EJ},QS="return exp(x);",e2=Je({opSnippet:QS,packedOpSnippet:QS,cpuKernelImpl:_K}),FJ={kernelName:Hs,backendName:"webgl",kernelFunc:e2};function nw(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),ve({inputs:{x:s},backend:a,attrs:{shape:o}})}var $J={kernelName:el,backendName:"webgl",kernelFunc:nw},t2="return exp(x) - 1.0;",DJ=Je({opSnippet:t2,packedOpSnippet:t2,cpuKernelImpl:EK}),MJ={kernelName:tl,backendName:"webgl",kernelFunc:DJ},n2=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 a2(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=ve({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,c=new n2("real",l,t),u=new n2("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=ys({inputs:{real:d,imag:h},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h);let f=ve({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function RJ(e){let{inputs:t,backend:n}=e,{input:a}=t;return a2(a,!1,n)}var PJ={kernelName:Qd,backendName:"webgl",kernelFunc:RJ},OJ=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 aw(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 OJ(a,r),o=i.getCustomSetupFunc(r);return t.runWebGLProgram(i,[],s,o)}}var LJ={kernelName:wc,backendName:"webgl",kernelFunc:aw},zJ=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);
|
|
}
|
|
`}},BJ={kernelName:nl,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new zJ(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},r2="return floor(x);",WJ=Je({opSnippet:r2,packedOpSnippet:r2,cpuKernelImpl:AK}),VJ={kernelName:js,backendName:"webgl",kernelFunc:WJ},UJ=`
|
|
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;
|
|
}
|
|
`,GJ=`
|
|
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);
|
|
`,HJ=sn({opSnippet:UJ,packedOpSnippet:GJ,dtype:"int32"}),jJ={kernelName:qs,backendName:"webgl",kernelFunc:HJ},qJ=class{constructor(e){this.variableNames=["A"];let t=fn(),[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));
|
|
}
|
|
`}},KJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=fn(),[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;
|
|
}
|
|
`}},YJ={kernelName:hh,backendName:"webgl",kernelFunc:XJ},Su;function XJ(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)&&(Su==null&&(Su=document.createElement("canvas").getContext("2d")),Su.canvas.width=c,Su.canvas.height=u,Su.drawImage(r,0,0,c,u),r=Su.canvas);let h=n.makeTensorInfo(p,"int32");n.texData.get(h.dataId).usage=aa.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),r);let m=te().getBool("WEBGL_PACK")?new KJ(d):new qJ(d),f=n.runWebGLProgram(m,[h],"int32");return n.disposeData(h.dataId),f}function JJ(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=E.convertConv2DDataFormat(u),g=E.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=jS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(te().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=qS({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?sf(h,!1):null,$=new HS(g,x,C,N,T),F=[r,s];if(i&&F.push(i),o&&F.push(o),T){let O=n.makeTensorInfo([],"float32",k.createScalarValue(m,"float32"));F.push(O),b.push(O)}y=n.runWebGLProgram($,F,"float32")}let v=ve({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var ZJ={kernelName:Ti,backendName:"webgl",kernelFunc:JJ};function QJ(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(E.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=E.computeConv2DInfo(r.shape,s.shape,l,f,c,p,!0),y=te().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=d?sf(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 F=n.makeTensorInfo([],"float32",k.createScalarValue(h,"float32"));v.push(F),m.push(F)}let C;y?C=new ZS(g,x,b,N,T):C=new JS(g,x,b,N,T);let $=n.runWebGLProgram(C,v,"float32");return m.forEach(F=>n.disposeIntermediateTensorInfo(F)),$}var e9={kernelName:Si,backendName:"webgl",kernelFunc:QJ},t9=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=gt(t.length),r=gt(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 n9(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],[o,l,c,u]=E.prepareAndValidate(a,r),p=ve({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),d=ve({inputs:{x:a},backend:n,attrs:{shape:[k.sizeFromShape(a.shape)/c,c]}}),h=new t9(i,u,[l,c]),m=n.runWebGLProgram(h,[d,p],d.dtype),f=ve({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),f}var a9={kernelName:rl,backendName:"webgl",kernelFunc:n9},s9=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=gt(this.rank),a=r9(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function r9(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 i9(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=E.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=k.sizeFromShape(s.shape),p=[],d=ve({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),h=ve({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=FK(v,b,m);return p.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(c.outputShape,x.dtype,x.values)}let f=new s9(d.shape,m),g=n.runWebGLProgram(f,[d,h],d.dtype);p.push(g);let y=ve({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return p.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var o9={kernelName:al,backendName:"webgl",kernelFunc:i9},l9="return float(a > b);",u9=`
|
|
return vec4(greaterThan(a, b));
|
|
`,c9=sn({opSnippet:l9,packedOpSnippet:u9,cpuKernelImpl:$K,dtype:"bool"}),p9={kernelName:sl,backendName:"webgl",kernelFunc:c9},d9="return float(a >= b);",h9=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,m9=sn({opSnippet:d9,packedOpSnippet:h9,dtype:"bool"}),f9={kernelName:Xs,backendName:"webgl",kernelFunc:m9};function g9(e){let{inputs:t,backend:n}=e,{input:a}=t;return a2(a,!0,n)}var y9={kernelName:eh,backendName:"webgl",kernelFunc:g9},b9="return float(!isnan(x) && !isinf(x));",x9=Je({opSnippet:b9,dtype:"bool"}),v9={kernelName:ol,backendName:"webgl",kernelFunc:x9},w9="return float(isinf(x));",k9=Je({opSnippet:w9,dtype:"bool"}),I9={kernelName:ll,backendName:"webgl",kernelFunc:k9},N9="return float(isnan(x));",T9=Je({opSnippet:N9,dtype:"bool"}),S9={kernelName:ul,backendName:"webgl",kernelFunc:T9},C9="return float(a < b);",_9=`
|
|
return vec4(lessThan(a, b));
|
|
`,E9=sn({opSnippet:C9,packedOpSnippet:_9,cpuKernelImpl:DK,dtype:"bool"}),A9={kernelName:cl,backendName:"webgl",kernelFunc:E9},F9="return float(a <= b);",$9=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,D9=sn({opSnippet:F9,packedOpSnippet:$9,dtype:"bool"}),M9={kernelName:pl,backendName:"webgl",kernelFunc:D9};function R9(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=MK(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var P9={kernelName:nh,backendName:"webgl",kernelFunc:R9},O9=`if (x < 0.0) return NAN;
|
|
return log(x);`,L9=`
|
|
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;
|
|
`,z9=Je({opSnippet:O9,packedOpSnippet:L9,cpuKernelImpl:RK}),B9={kernelName:Js,backendName:"webgl",kernelFunc:z9},W9="return log(1.0 + x);",V9=Je({opSnippet:W9}),U9={kernelName:dl,backendName:"webgl",kernelFunc:V9},G9="return float(a >= 1.0 && b >= 1.0);",H9=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,j9=sn({opSnippet:G9,packedOpSnippet:H9,dtype:"bool"}),q9={kernelName:hl,backendName:"webgl",kernelFunc:j9},K9="return float(!(x >= 1.0));",X9=Je({opSnippet:K9}),Y9={kernelName:kc,backendName:"webgl",kernelFunc:X9},J9="return float(a >= 1.0 || b >= 1.0);",Z9=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,Q9=sn({opSnippet:J9,packedOpSnippet:Z9,dtype:"bool"}),eZ={kernelName:Ic,backendName:"webgl",kernelFunc:Q9},tZ=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);
|
|
}
|
|
`}},nZ=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);
|
|
}
|
|
`}},aZ=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,c=te().getBool("WEBGL_PACK_NORMALIZATION")?new nZ(r.shape,s,i,o,l):new tZ(r.shape,s,i,o,l);return n.runWebGLProgram(c,[r],r.dtype)},rZ={kernelName:Nc,backendName:"webgl",kernelFunc:aZ},sZ=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);
|
|
}
|
|
`}},iZ=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 sZ(r.shape,o,l,c,u);return n.runWebGLProgram(p,[r,s,i],r.dtype)},oZ={kernelName:ah,backendName:"webgl",kernelFunc:iZ};function lZ(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=ve({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=Qi(i,e.dtype,"max",a),l=ve({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function s2(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=E.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=Yv(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=of(r,u,n);c=E.getInnerMostAxes(c.length,o)}E.assertAxesAreInnerMostDims("max",c,o);let[m,f]=E.computeOutAndReduceShapes(h.shape,c),g=m;i&&(g=E.expandShapeToKeepDim(m,l));let y;if(d){let b=n.texData.get(h.dataId).values,v=PK(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=lZ(h,f,g,n);return p&&n.disposeIntermediateTensorInfo(h),y}var uZ={kernelName:Zs,backendName:"webgl",kernelFunc:s2},cZ=kS+`
|
|
return max(a, b);
|
|
`,pZ=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+rf+`
|
|
return result;
|
|
`,dZ=sn({opSnippet:cZ,packedOpSnippet:pZ,cpuKernelImpl:OK}),hZ={kernelName:Qs,backendName:"webgl",kernelFunc:dZ};function mZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;_p(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(E.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=E.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 Fp(u,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var fZ={kernelName:ei,backendName:"webgl",kernelFunc:mZ};function gZ(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=E.computePool3DInfo(r.shape,s,i,u,o,c,l),d=new Qv(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var yZ={kernelName:Tc,backendName:"webgl",kernelFunc:gZ},bZ=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);
|
|
}
|
|
`}},xZ=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 vZ(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=E.computePool3DInfo(i.shape,o,l,p,c,u),h=new Qv(d,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new xZ(d),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var wZ={kernelName:sh,backendName:"webgl",kernelFunc:vZ};function kZ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;_p([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=E.computePool2DInfo(o.shape,l,c,1,u,p),h=!0,m=new Fp(d,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new bZ(d),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var IZ={kernelName:rh,backendName:"webgl",kernelFunc:kZ};function NZ(e,t,n,a){let r=new Fp(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new Fp(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var TZ={kernelName:ih,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(E.eitherStridesOrDilationsAreOne(s,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=E.computePool2DInfo(a.shape,r,s,c,i),[p,d]=NZ(a,o,u,l);return[p,d]}};function SZ(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=ve({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=Qi(i,"float32","mean",a),l=ve({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var CZ={kernelName:ti,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=E.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=Yv(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=of(a,u,i);h.push(m),c=E.getInnerMostAxes(c.length,o)}E.assertAxesAreInnerMostDims("sum",c,o);let[f,g]=E.computeOutAndReduceShapes(m.shape,c),y=f;r&&(y=E.expandShapeToKeepDim(f,l));let b=SZ(m,g,y,i);for(let v of h)i.disposeIntermediateTensorInfo(v);return b}};function _Z(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=E.getAxesPermutation(c,o),p=r;u!=null&&(p=Cn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,r.shape.length)),E.assertAxesAreInnerMostDims("min",c,o);let[d,h]=E.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Qi(f,f.dtype,"min",n),y;if(i){let b=E.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var EZ={kernelName:ni,backendName:"webgl",kernelFunc:_Z},AZ=kS+`
|
|
return min(a, b);
|
|
`,FZ=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+rf+`
|
|
return result;
|
|
`,$Z=sn({opSnippet:AZ,packedOpSnippet:FZ,cpuKernelImpl:LK}),DZ={kernelName:ai,backendName:"webgl",kernelFunc:$Z},MZ=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=gt(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}));
|
|
}
|
|
`}},RZ=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=gt(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=gn("rc",a),l=gn("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);
|
|
}
|
|
`}},PZ=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new RZ(a.shape,r,s):new MZ(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},OZ={kernelName:Sc,backendName:"webgl",kernelFunc:PZ},LZ=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,zZ=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+rf+`
|
|
return result;
|
|
`,BZ=sn({opSnippet:LZ,packedOpSnippet:zZ}),WZ={kernelName:ml,backendName:"webgl",kernelFunc:BZ},VZ=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)}}},UZ=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,GZ=`
|
|
// 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;
|
|
`,i2=sn({opSnippet:UZ,packedOpSnippet:GZ,checkOutOfBounds:!0}),HZ={kernelName:Gs,backendName:"webgl",kernelFunc:i2},o2="return a - b;",l2=sn({opSnippet:o2,packedOpSnippet:o2,supportsComplex:!0,cpuKernelImpl:jK}),jZ={kernelName:wi,backendName:"webgl",kernelFunc:l2};function u2(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=k.parseAxisParam([s],r.shape),o=s2({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=E.expandShapeToKeepDim(o.shape,i),c=ve({inputs:{x:o},backend:n,attrs:{shape:l}}),u=l2({inputs:{a:r,b:c},backend:n}),p=e2({inputs:{x:u},backend:n}),d=Zv({inputs:{x:p},backend:n,attrs:{axis:i,keepDims:!1}}),h=ve({inputs:{x:d},backend:n,attrs:{shape:l}}),m=i2({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 qZ={kernelName:xi,backendName:"webgl",kernelFunc:u2};function KZ(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:u2({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],p=new VZ(c,u,s),d=p.getCustomSetupFunc(i),h=n.runWebGLProgram(p,[l],"int32",d);return o||n.disposeIntermediateTensorInfo(l),h}var XZ={kernelName:oh,backendName:"webgl",kernelFunc:KZ},c2="return -x;";function YZ(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=BK(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return te().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Iu(a.shape,c2):r=new gs(a.shape,c2),n.runWebGLProgram(r,[a],a.dtype)}var JZ={kernelName:fl,backendName:"webgl",kernelFunc:YZ},ZZ=er.nonMaxSuppressionV3Impl;function QZ(e){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}=ZZ(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var eQ={kernelName:yl,backendName:"webgl",kernelFunc:QZ},tQ=er.nonMaxSuppressionV4Impl;function nQ(e){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}=tQ(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var aQ={kernelName:bl,backendName:"webgl",kernelFunc:nQ},rQ=er.nonMaxSuppressionV5Impl;function sQ(e){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}=rQ(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var iQ={kernelName:xl,backendName:"webgl",kernelFunc:sQ},oQ=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)));
|
|
}
|
|
`}},lQ=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 oQ(l,s,i,o),u=ve({inputs:{x:r},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let d=[...r.shape,s],h=ve({inputs:{x:p},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(p),h},uQ={kernelName:si,backendName:"webgl",kernelFunc:lQ};function df(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=Dp({inputs:{input:a},backend:n}),s=df({inputs:{x:r},backend:n}),i=pf({inputs:{input:a},backend:n}),o=df({inputs:{x:i},backend:n}),l=ys({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return aw({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var cQ={kernelName:Ol,backendName:"webgl",kernelFunc:df};function p2(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=Dp({inputs:{input:a},backend:n}),s=p2({inputs:{x:r},backend:n}),i=pf({inputs:{input:a},backend:n}),o=df({inputs:{x:i},backend:n}),l=ys({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return aw({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var pQ={kernelName:vl,backendName:"webgl",kernelFunc:p2};function dQ(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return nw({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=nw({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=GS({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var hQ={kernelName:wl,backendName:"webgl",kernelFunc:dQ},mQ=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=gt(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}));
|
|
}
|
|
}
|
|
`}},fQ=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=gt(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=gn("rc",a),l=gn("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);
|
|
}
|
|
`}},d2=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a,o=te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fQ(r.shape,s,i):new mQ(r.shape,s,i);return n.runWebGLProgram(o,[r],r.dtype)},gQ={kernelName:ii,backendName:"webgl",kernelFunc:d2},yQ=`
|
|
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);
|
|
`,bQ=`
|
|
// 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));
|
|
`+rf+`
|
|
return result;
|
|
`,xQ=sn({opSnippet:yQ,packedOpSnippet:bQ}),vQ={kernelName:oi,backendName:"webgl",kernelFunc:xQ};function wQ(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=E.getAxesPermutation(u,o),d=r;p!=null&&(d=Cn({inputs:{x:r},backend:n,attrs:{perm:p}}),u=E.getInnerMostAxes(u.length,o),l.push(d)),E.assertAxesAreInnerMostDims("prod",u,o);let h;if(n.shouldExecuteOnCPU([d])){let m=n.texData.get(d.dataId).values,{outVals:f,outShape:g,outDtype:y}=WK(d.shape,d.dtype,m,u);h=n.makeTensorInfo(g,y,f)}else{let[m,f]=E.computeOutAndReduceShapes(d.shape,u),g=k.sizeFromShape(f),y=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),b=bh(r.dtype),v=Qi(y,b,"prod",n);h=ve({inputs:{x:v},backend:n,attrs:{shape:m}}),l.push(y),l.push(v)}if(i){l.push(h);let m=E.expandShapeToKeepDim(h.shape,c);h=ve({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var kQ={kernelName:kl,backendName:"webgl",kernelFunc:wQ},h2=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=VK(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},IQ={kernelName:Cc,backendName:"webgl",kernelFunc:h2},NQ="return 1.0 / x;",TQ=Je({opSnippet:NQ}),SQ={kernelName:Il,backendName:"webgl",kernelFunc:TQ},CQ=La+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,_Q=`
|
|
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;
|
|
`,EQ=Je({opSnippet:CQ,packedOpSnippet:_Q}),AQ={kernelName:ui,backendName:"webgl",kernelFunc:EQ},FQ=La+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,$Q=`
|
|
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;
|
|
`,DQ=Je({opSnippet:FQ,packedOpSnippet:$Q}),MQ={kernelName:pi,backendName:"webgl",kernelFunc:DQ},RQ=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);
|
|
}
|
|
`}},PQ=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 OQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=te().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new PQ(r.shape,l,c,s,i):new RQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],"float32")}var LQ={kernelName:ci,backendName:"webgl",kernelFunc:OQ},zQ=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 BQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new zQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var WQ={kernelName:ch,backendName:"webgl",kernelFunc:BQ},VQ=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 UQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=new VQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],r.dtype)}var GQ={kernelName:_c,backendName:"webgl",kernelFunc:UQ},HQ=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 jQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new HQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var qQ={kernelName:uh,backendName:"webgl",kernelFunc:jQ},KQ=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=gt(n);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},XQ=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=gn("rc",n),r=`${a[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${a[n-2]} + 1 < ${this.outputShape[n-2]}`,i=gt(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 YQ(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=te().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XQ(r.shape,o):new KQ(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var JQ={kernelName:di,backendName:"webgl",kernelFunc:YQ},ZQ=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]=E.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);
|
|
}
|
|
`}},QQ={kernelName:Ll,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new ZQ(a.shape,r,s,i);return o.runWebGLProgram(l,[a],a.dtype)}},eee=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,tee=Je({opSnippet:eee}),nee={kernelName:hi,backendName:"webgl",kernelFunc:tee},aee="return inversesqrt(x);",ree=Je({opSnippet:aee,cpuKernelImpl:UK}),see={kernelName:mi,backendName:"webgl",kernelFunc:ree},m2=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=gt(r.length),l=gt(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 iee(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}=E.calculateShapes(s,r,i),d=[p/c,c];if(p===0)return n.makeTensorInfo(i,r.dtype);let h=ve({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=ve({inputs:{x:s},backend:n,attrs:{shape:[l,c]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new m2(l,o,h.shape.length,m.shape.length,u,d),y=n.runWebGLProgram(g,[m,h,f],m.dtype),b=ve({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),b}var oee={kernelName:Tl,backendName:"webgl",kernelFunc:iee},lee=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=gt(n);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${a});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function uee(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new lee(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],ha(r.dtype,s.dtype))}var cee={kernelName:Sl,backendName:"webgl",kernelFunc:uee},pee=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${E.SELU_SCALEALPHA};
|
|
float scale = ${E.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,dee=Je({opSnippet:pee}),hee={kernelName:Cl,backendName:"webgl",kernelFunc:dee},mee="return 1.0 / (1.0 + exp(-1.0 * x));",fee=Je({opSnippet:mee}),gee={kernelName:gi,backendName:"webgl",kernelFunc:fee},yee=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,bee=Je({opSnippet:yee}),xee={kernelName:Al,backendName:"webgl",kernelFunc:bee},vee=CS+`
|
|
return sin(x);
|
|
`,wee=Je({opSnippet:vee}),kee={kernelName:fi,backendName:"webgl",kernelFunc:wee},Iee=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Nee=Je({opSnippet:Iee}),Tee={kernelName:El,backendName:"webgl",kernelFunc:Nee},See=`
|
|
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;
|
|
`,Cee=Je({opSnippet:See}),_ee={kernelName:Fl,backendName:"webgl",kernelFunc:Cee},Eee=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=d2({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=E.getReshaped(u.shape,s,o,!1),d=E.getPermuted(p.length,s.length,!1),h=E.getReshapedPermuted(u.shape,s,o,!1),m=ve({inputs:{x:u},backend:n,attrs:{shape:p}}),f=Cn({inputs:{x:m},backend:n,attrs:{perm:d}}),g=ve({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},Aee={kernelName:Ec,backendName:"webgl",kernelFunc:Eee};function Fee(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}=E.calculateShapes(s,r,o),d=!1,h=new m2(c,l,r.shape.length,s.shape.length,u,[p,1],d),m=n.runWebGLProgram(h,[s,r,i],s.dtype),f=ve({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),f}var $ee={kernelName:ph,backendName:"webgl",kernelFunc:Fee};function Dee(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=E.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=$p({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[o]+=d,m})}var Mee={kernelName:$l,backendName:"webgl",kernelFunc:Dee},Ree="return sqrt(x);",Pee=Je({opSnippet:Ree}),Oee={kernelName:yi,backendName:"webgl",kernelFunc:Pee},Lee="return x * x;",zee=Je({opSnippet:Lee}),Bee={kernelName:Ac,backendName:"webgl",kernelFunc:zee},f2="return (a - b) * (a - b);",Wee=sn({opSnippet:f2,packedOpSnippet:f2}),Vee={kernelName:vi,backendName:"webgl",kernelFunc:Wee};function Uee({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=La+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new gs(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var Gee={kernelName:Kr,backendName:"webgl",kernelFunc:Uee},Hee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=gt(n.length),s=gt(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 jee(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}=dn.sliceInfo(r.shape,s,i,o,l,c,u,p,d),v=ve({inputs:{x:r},backend:n,attrs:{shape:y}}),x;if(h){let T=$p({inputs:{x:v},backend:n,attrs:{begin:m,size:g}});x=ve({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),$=HK(b,C,f,m);x=n.makeTensorInfo(b,v.dtype,$.values)}else{let T=new Hee(m,f,b);x=n.runWebGLProgram(T,[v],v.dtype)}let N=ve({inputs:{x},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),N}var qee={kernelName:Dl,backendName:"webgl",kernelFunc:jee},Kee="return tan(x);",Xee=Je({opSnippet:Kee}),Yee={kernelName:Ml,backendName:"webgl",kernelFunc:Xee},Jee=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Zee=Je({opSnippet:Jee}),Qee={kernelName:ki,backendName:"webgl",kernelFunc:Zee},tte=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=gt(this.rank),r=ete(e);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function ete(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 g2(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=qK(l,s);return n.makeTensorInfo(c.shape,c.dtype,c.values)}let i=new tte(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var nte={kernelName:qr,backendName:"webgl",kernelFunc:g2};function ate(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=n.readSync(r.dataId),[l,c]=KK(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 rte={kernelName:Rl,backendName:"webgl",kernelFunc:ate};function ste(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;_p(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}=XK(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var ite={kernelName:dh,backendName:"webgl",kernelFunc:ste};function ote(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=$p({inputs:{x:i},backend:n,attrs:{begin:d,size:h}}),y=ve({inputs:{x:g},backend:n,attrs:{shape:c}});m[f]=y,p.push(g)}return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var lte={kernelName:Pl,backendName:"webgl",kernelFunc:ote},ute=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 cte(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=E.getAxesPermutation([c],o),p=r;u!=null&&(p=Cn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(p),c=E.getInnerMostAxes(1,o)[0]);let d=E.segment_util.computeOutShape(p.shape,c,i),h=k.sizeFromShape([p.shape[c]]),m=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=bh(r.dtype),g=(x,N,T,C,$)=>{let F=x.shape[0],O=x.shape[1],W=E.segment_util.segOpComputeOptimalWindowSize(O,$),V={windowSize:W,inSize:O,batchSize:F,numSegments:$},H=new ute(V,N),K=n.compileAndRun(H,[x,T],C);if(l.push(K),K.shape[1]===$)return K;let j=h2({backend:n,attrs:{start:0,stop:$,step:1,dtype:"float32"}}),Y=g2({inputs:{x:j},backend:n,attrs:{reps:[O/W]}});return l.push(j),l.push(Y),g(K,N,Y,C,$)},y=g(m,"unsortedSegmentSum",s,f,i),b=ve({inputs:{x:y},backend:n,attrs:{shape:d}}),v=b;if(u!=null){l.push(b);let x=E.getUndoAxesPermutation(u);v=Cn({inputs:{x:v},backend:n,attrs:{perm:x}})}return l.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var pte={kernelName:Fc,backendName:"webgl",kernelFunc:cte},dte=[rZ,oZ,jX,KX,JX,eY,nY,sY,oY,uY,hY,fY,bY,wY,_Y,NY,FY,RY,DY,zY,WY,UY,qY,e7,n7,l7,c7,m7,y7,CX,w7,F7,D7,T7,O7,z7,R7,V7,H7,K7,Y7,Z7,tJ,oJ,uJ,aJ,dJ,fJ,xJ,IJ,CJ,AJ,FJ,$J,MJ,PJ,LJ,BJ,VJ,jJ,YJ,ZJ,e9,a9,o9,p9,f9,SX,y9,v7,v9,I9,S9,EX,A9,M9,P9,U9,B9,q9,Y9,eZ,uZ,yZ,fZ,wZ,IZ,TZ,hZ,CZ,EZ,DZ,OZ,WZ,XZ,MX,JZ,eQ,aQ,iQ,r7,uQ,pQ,hQ,gQ,vQ,FX,kQ,IQ,s7,HZ,SQ,MQ,AQ,PX,LQ,WQ,GQ,qQ,JQ,QQ,nee,see,oee,cee,hee,gee,xee,kee,Tee,ZY,qZ,_ee,Aee,$ee,Mee,Oee,Bee,Vee,Gee,qee,jZ,UX,Yee,Qee,nte,rte,GX,ite,lte,pte,cQ];for(let e of dte)Dc(e);var hte="2.8.5",mte={"tfjs-core":s1,"tfjs-backend-cpu":GG,"tfjs-backend-webgl":TX,"tfjs-data":jN,"tfjs-layers":$m,"tfjs-converter":BN,tfjs:hte},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 Mp;(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"})(Mp||(Mp={}));var y2;function fte(e){y2=e.wasm.cwrap(Ni,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function gte(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 $=n.dataIdMap.get(i.dataId);if($.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${$.shape.length}.`);m=$.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=Mp[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 y2(d,T,r.shape.length,h,C,s.shape.length,l,c,g,m,f,p||0,N),x}var yte={kernelName:Ni,backendName:"wasm",setupFunc:fte,kernelFunc:gte};function Un(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number"])}function a(r){let{backend:s,inputs:{x:i}}=r,o=s.dataIdMap.get(i.dataId).id,l=s.makeOutput(i.shape,i.dtype),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 bte=Un(Lo);function yn(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=E.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=E.getBroadcastDims(c.shape,m),N=E.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 xte=!0,vte=yn(Hr,xte),b2;function wte(e){b2=e.wasm.cwrap(Ms,null,["array","number","number","number"])}function kte(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 b2(s,r.length,Vn[a.dtype],i),a}var Ite={kernelName:Ms,backendName:"wasm",setupFunc:wte,kernelFunc:kte};function hf(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 Nte={kernelName:il,backendName:"wasm",kernelFunc:hf},x2;function Tte(e){x2=e.wasm.cwrap(Ii,null,["number","array","number","number","number","array","number"])}function mf(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=Cte(t.x.shape,a.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=Ste(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=hf({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 x2(u,h,l.shape.length,Vn[l.dtype],p,d,s.length),c}function Ste(e,t){let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];return n}function Cte(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 _te={kernelName:Ii,backendName:"wasm",kernelFunc:mf,setupFunc:Tte};function Cu(e,t,n){let a=e.shape,r=e.shape.length,s=k.parseAxisParam(t,a),i=s,o=E.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=E.getInnerMostAxes(i.length,r),l=mf({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 v2;function Ete(e){v2=e.wasm.cwrap(Rs,null,["number","number","number","number","number"])}function Ate(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}=Cu(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 v2(o,Vn[l.dtype],f,g,m),p&&t.disposeData(c.dataId),h}var Fte={kernelName:Rs,backendName:"wasm",kernelFunc:Ate,setupFunc:Ete},w2;function $te(e){w2=e.wasm.cwrap(Ps,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Dte(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=E.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 w2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,v,N),x}var Mte={kernelName:Ps,backendName:"wasm",setupFunc:$te,kernelFunc:Dte};function za(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.`),{dataId:a.dataId,shape:i,dtype:a.dtype}}var Rte={kernelName:Nl,backendName:"wasm",kernelFunc:za},k2;function Pte(e){k2=e.wasm.cwrap(Os,null,["number","array","number","number","array","number","number","number","number"])}function Ote(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=za({inputs:{x:r},backend:n,attrs:{shape:x}}),C=za({inputs:{x:s},backend:n,attrs:{shape:N}}),$=n.dataIdMap.get(T.dataId).id,F=n.dataIdMap.get(C.dataId).id,O=i?T.shape[2]:T.shape[1],W=o?C.shape[1]:C.shape[2],V=Math.max(g,y),H=n.makeOutput([V,O,W],T.dtype),K=n.dataIdMap.get(H.dataId).id,j=new Uint8Array(new Int32Array(T.shape).buffer),Y=new Uint8Array(new Int32Array(C.shape).buffer);return k2($,j,T.shape.length,F,Y,C.shape.length,i,o,K),H.shape=v,H}var Lte={kernelName:Os,backendName:"wasm",setupFunc:Pte,kernelFunc:Ote};function ff(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 zte={kernelName:Ls,backendName:"wasm",kernelFunc:ff},I2;function Bte(e){I2=e.wasm.cwrap(jr,null,["number","number","number","number"])}function Wte(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 I2(o,s,i,c),l}var Vte={kernelName:jr,backendName:"wasm",setupFunc:Bte,kernelFunc:Wte};function N2(e){let{inputs:t,backend:n}=e,a=k.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=E.computeOutShape(t.map(h=>h.shape),a),s=t.filter(h=>k.sizeFromShape(h.shape)>0);if(s.length===1)return hf({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(E.assertParamsConsistent(o,a),s[0].dtype==="string"){let h=s.map(v=>{let x=k.sizeFromShape(v.shape.slice(a));return za({inputs:{x:v},backend:n,attrs:{shape:[-1,x]}})}),m=h.map(v=>({vals:n.readSync(v.dataId),shape:v.shape}));r=E.computeOutShape(h.map(v=>v.shape),1);let f=h[0].shape[0]===1,g=_v(m,r,t[0].dtype,f),y=E.computeOutShape(s.map(v=>v.shape),a);i.shape=y;let b=n.dataIdMap.get(i.dataId);return b.stringBytes=E.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 Ute={kernelName:qo,backendName:"wasm",kernelFunc:N2},T2;function Gte(e){T2=e.wasm.cwrap(zs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Hte(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=E.convertConv2DDataFormat(d),m=E.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,$=m.strideWidth,F=m.inChannels,O=m.outChannels,W=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 V=a.makeOutput(m.outShape,"float32"),H=a.dataIdMap.get(V.dataId).id;return T2(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,y,b,v,x,W,N,T,C,$,F,O,H),V}var jte={kernelName:zs,backendName:"wasm",setupFunc:Gte,kernelFunc:Hte},S2;function qte(e){S2=e.wasm.cwrap(Bs,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 Kte(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=E.convertConv2DDataFormat(l),h=E.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:$}=h,F=f-1-h.padInfo.top,O=g-1-h.padInfo.left,W=h.dataFormat==="channelsLast",V=k.computeStrides(h.inShape),H=k.computeStrides(r.shape),[K,j,Y]=k.computeStrides(s.shape),J=V[0],ne=W?V[1]:V[2],Q=W?V[2]:1,ie=W?1:V[1],ee=H[0],le=W?H[1]:H[2],se=W?H[2]:1,ce=W?1:H[1],de=t.makeOutput(h.inShape,"float32"),fe=t.dataIdMap.get(de.dataId).id,xe=t.dataIdMap.get(r.dataId).id,be=t.dataIdMap.get(s.dataId).id;return S2(xe,be,m,f,g,b,v,y,N,T,x,C,$,F,O,K,j,Y,J,ne,Q,ie,ee,le,se,ce,fe),de}var Xte={kernelName:Bs,backendName:"wasm",setupFunc:qte,kernelFunc:Kte},Yte=Un(Ws),rw;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(rw||(rw={}));var C2;function Jte(e){C2=e.wasm.cwrap(Xo,null,["number","number","number","number","array","number","number","number","number","number"])}function Zte(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=ff({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 C2(g,y,b,u,N,p,d,rw[r],s,x),f!=null&&t.disposeData(f.dataId),v}var Qte={kernelName:Xo,backendName:"wasm",setupFunc:Jte,kernelFunc:Zte},_2;function ene(e){_2=e.wasm.cwrap(Vs,null,["number","number","number","number","number","number"])}function tne(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=E.getAxesPermutation([s],l),u=r;c!==null&&(u=mf({inputs:{x:r},attrs:{perm:c},backend:n}));let p=E.getInnerMostAxes(1,l)[0];E.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;_2(m,i?1:0,o?1:0,h,f,Vn[r.dtype]);let g=d;if(c!==null){let y=E.getUndoAxesPermutation(c);g=mf({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(u.dataId),n.disposeData(d.dataId)}return g}var nne={kernelName:Vs,backendName:"wasm",setupFunc:ene,kernelFunc:tne},E2;function ane(e){E2=e.wasm.cwrap(Yo,null,["number","number","number","array","number","array","array","number","number"])}function rne(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 E2(g,s,i==="NHWC"?1:0,y,r.shape.length-1,b,v,m.length,x),f}var sne={kernelName:Yo,backendName:"wasm",setupFunc:ane,kernelFunc:rne},A2;function ine(e){A2=e.wasm.cwrap(Us,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function one(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=E.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,$=h.inChannels,F=h.outChannels,O=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 W=a.makeOutput(h.outShape,"float32"),V=a.dataIdMap.get(W.dataId).id;return A2(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,y,b,v,O,x,N,T,C,$,F,V),W}var lne={kernelName:Us,backendName:"wasm",setupFunc:ine,kernelFunc:one},une=!1,cne=yn(Qo,une,"bool"),pne=Un(Hs);function sw(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),za({inputs:{x:r},backend:a,attrs:{shape:o}})}var dne={kernelName:el,backendName:"wasm",kernelFunc:sw};function hne(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 mne={kernelName:wc,backendName:"wasm",kernelFunc:hne},F2;function fne(e){F2=e.wasm.cwrap(nl,null,["number","number","number","number","number","number"])}function gne(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 F2(s,o,l,c,u,i),r}var yne={kernelName:nl,backendName:"wasm",kernelFunc:gne,setupFunc:fne},bne=Un(js),xne=!1,vne=yn(qs,xne),$2;function wne(e){$2=e.wasm.cwrap(Ks,null,["number","number","number","number","number","number","number"])}function kne(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 $2(u,p,d,h,m,r,g),f}var Ine={kernelName:Ks,backendName:"wasm",setupFunc:wne,kernelFunc:kne},D2;function Nne(e){D2=e.wasm.cwrap(Ti,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Tne(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=E.computeConv2DInfo(r.shape,s.shape,l,u,c,d),g=Mp[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 se=a.dataIdMap.get(i.dataId);if(se.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${se.shape.length}.`);if(se.shape[0]!==v)throw new Error(`FusedConv2D bias shape (${se.shape}) does not match the number of output channels (${v})`);x=se.id}let N=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,$=f.padInfo.right,F=f.padInfo.bottom,O=f.padInfo.left,W=f.dilationHeight,V=f.dilationWidth,H=f.strideHeight,K=f.strideWidth,j=f.inChannels,Y=f.padInfo.type==="SAME"?1:0,J=f.batchSize,ne=f.inHeight,Q=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ie=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(ie.dataId).id,le=o==null?0:a.dataIdMap.get(o.dataId).id;return D2(y,J,ne,Q,b,N,T,x,C,$,F,O,Y,W,V,H,K,j,v,g,le,m||0,ee),ie}var Sne={kernelName:Ti,backendName:"wasm",setupFunc:Nne,kernelFunc:Tne},M2;function Cne(e){M2=e.wasm.cwrap(Si,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 _ne(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=E.computeConv2DInfo(r.shape,s.shape,l,u,c,d,!0),g=Mp[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 se=a.dataIdMap.get(i.dataId);if(se.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${se.shape.length}.`);if(se.shape[0]!==v)throw new Error(`FusedDepthwiseConv2D bias shape (${se.shape}) does not match the number of output channels (${v})`);x=se.id}let N=f.filterHeight,T=f.filterWidth,C=f.padInfo.top,$=f.padInfo.right,F=f.padInfo.bottom,O=f.padInfo.left,W=f.dilationHeight,V=f.dilationWidth,H=f.strideHeight,K=f.strideWidth,j=f.inChannels,Y=f.padInfo.type==="SAME"?1:0,J=f.batchSize,ne=f.inHeight,Q=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ie=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(ie.dataId).id,le=o==null?0:a.dataIdMap.get(o.dataId).id;return M2(y,J,ne,Q,b,N,T,x,C,$,F,O,Y,W,V,H,K,j,v,g,le,m||0,ee),ie}var Ene={kernelName:Si,backendName:"wasm",setupFunc:Cne,kernelFunc:_ne},R2;function Ane(e){R2=e.wasm.cwrap(rl,null,["number","number","number","number","number","number","array","number"])}function Fne(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=Ay.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 R2(d,Vn[a.dtype],h,i,p,o,m,f),c}var $ne={kernelName:rl,backendName:"wasm",setupFunc:Ane,kernelFunc:Fne},P2;function Dne(e){P2=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Mne(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=E.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=za({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),p=k.sizeFromShape(s.shape),d=za({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 P2(g,Vn[r.dtype],v,f,y,c.batchSize,x,b),m.shape=c.outputShape,m}var Rne={kernelName:al,backendName:"wasm",setupFunc:Dne,kernelFunc:Mne},Pne=!1,One=yn(sl,Pne,"bool"),Lne=!1,zne=yn(Xs,Lne,"bool"),O2;function Bne(e){O2=e.wasm.cwrap(Ys,null,["number","number","number"])}function Wne(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;O2(r,n,i)}return s}var Vne={kernelName:Ys,backendName:"wasm",setupFunc:Bne,kernelFunc:Wne},Une=!1,Gne=yn(cl,Une,"bool"),Hne=!1,jne=yn(pl,Hne,"bool"),qne=Un(Js),Kne=!1,Xne=yn(hl,Kne,"bool"),L2;function Yne(e){L2=e.wasm.cwrap(Zs,null,["number, number, number"])}function Jne(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}=Cu(i,r,t);if(d){let b=t.dataIdMap.get(c.dataId).id;l=c,o=b}let h=l.shape.length;E.assertAxesAreInnerMostDims("max",u,h);let[m,f]=E.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;L2(o,g,b)}if(d&&t.disposeData(c.dataId),s){let b=E.expandShapeToKeepDim(y.shape,p);y.shape=b}return y}var Zne={kernelName:Zs,backendName:"wasm",setupFunc:Yne,kernelFunc:Jne},Qne=!1,eae=yn(Qs,Qne),z2;function tae(e){z2=e.wasm.cwrap(ei,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function nae(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=E.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"),$=a.dataIdMap.get(C.dataId).id;return z2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,v,x,N,T,$),C}var aae={kernelName:ei,backendName:"wasm",setupFunc:tae,kernelFunc:nae},B2;function rae(e){B2=e.wasm.cwrap(ti,null,["number, number, number"])}function sae(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}=Cu(i,r,t),m=p;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(c=u,l=x,m=E.getInnerMostAxes(m.length,c.shape.length))}E.assertAxesAreInnerMostDims("mean",m,c.shape.length);let[f,g]=E.computeOutAndReduceShapes(c.shape,m),y=k.sizeFromShape(g),b=c;c.dtype!=="float32"&&(b=ff({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;B2(l,y,x)}if(h&&t.disposeData(u.dataId),s){let x=E.expandShapeToKeepDim(v.shape,d);v.shape=x}return c.dtype!=="float32"&&t.disposeData(b.dataId),v}var iae={kernelName:ti,backendName:"wasm",setupFunc:rae,kernelFunc:sae},W2;function oae(e){W2=e.wasm.cwrap(ni,null,["number, number, number"])}function lae(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}=Cu(i,r,t);if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v)}let m=c.shape.length;E.assertAxesAreInnerMostDims("min",p,m);let[f,g]=E.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;W2(l,y,v)}if(h&&t.disposeData(u.dataId),s){let v=E.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var uae={kernelName:ni,backendName:"wasm",setupFunc:oae,kernelFunc:lae},cae=!1,pae=yn(ai,cae),dae=!0,hae=yn(ri,dae),mae=Un(fl);function iw(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 V2;function fae(e){V2=e.wasm.cwrap(yl,"number",["number","number","number","number","number"])}function gae(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=V2(c,u,s,r,i),{pSelectedIndices:d,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=iw(t,p);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",d)}var yae={kernelName:yl,backendName:"wasm",setupFunc:fae,kernelFunc:gae},U2;function bae(e){U2=e.wasm.cwrap(bl,"number",["number","number","number","number","number","bool"])}function xae(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=U2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=iw(t,d);t.wasm._free(f);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([],"int32",g);return[y,b]}var vae={kernelName:bl,backendName:"wasm",setupFunc:bae,kernelFunc:xae},G2;function wae(e){G2=e.wasm.cwrap(xl,"number",["number","number","number","number","number","number"])}function kae(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=G2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=iw(t,d);t.wasm._free(g);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([m],"float32",f);return[y,b]}var Iae={kernelName:xl,backendName:"wasm",setupFunc:wae,kernelFunc:kae},Nae=!1,Tae=yn(gl,Nae,"bool"),H2;function Sae(e){H2=e.wasm.cwrap(si,null,["number","number","number","number","number"])}function Cae(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 H2(u,s,i,o,c),l}var _ae={kernelName:si,backendName:"wasm",setupFunc:Sae,kernelFunc:Cae};function Eae(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var Aae={kernelName:vl,backendName:"wasm",kernelFunc:Eae};function Fae(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return sw({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=>sw({inputs:{input:l},backend:n,attrs:{dim:r}}));return N2({inputs:o,backend:n,attrs:{axis:r}})}var $ae={kernelName:wl,backendName:"wasm",kernelFunc:Fae},j2;function Dae(e){j2=e.wasm.cwrap(ii,null,["number","array","number","number","array","array","number","number"])}function Mae(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 j2(i,c,t.shape.length,Vn[t.dtype],d,h,r,l),o}var Rae={kernelName:ii,backendName:"wasm",kernelFunc:Mae,setupFunc:Dae},Pae=!1,Oae=yn(oi,Pae),q2;function Lae(e){q2=e.wasm.cwrap(li,null,["number","number","number"])}function zae(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 q2(s,i,l),o}var Bae={kernelName:li,backendName:"wasm",setupFunc:Lae,kernelFunc:zae},K2;function Wae(e){K2=e.wasm.cwrap(kl,null,["number","number","number","number"])}function Vae(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}=Cu(i,r,t),m=p;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v,m=E.getInnerMostAxes(m.length,c.shape.length))}E.assertAxesAreInnerMostDims("prod",m,c.shape.length);let[f,g]=E.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;K2(l,y,Vn[b.dtype],v)}if(h&&t.disposeData(u.dataId),s){let v=E.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var Uae={kernelName:kl,backendName:"wasm",setupFunc:Wae,kernelFunc:Vae},Gae=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=Fv(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Hae={kernelName:Cc,backendName:"wasm",kernelFunc:Gae},jae=!0,qae=yn(Gs,jae),Kae=Un(ui),Xae=Un(pi),X2;function Yae(e){X2=e.wasm.cwrap(ci,null,["number","number","number","number","number","number","number","number","number","number"])}function Jae(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=ff({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 X2(y,u,p,d,h,l,c,s?1:0,i?1:0,v),g!=null&&t.disposeData(g.dataId),b}var Zae={kernelName:ci,backendName:"wasm",setupFunc:Yae,kernelFunc:Jae},Y2;function Qae(e){Y2=e.wasm.cwrap(di,null,["number","array","number","array","number","number"])}function ere(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 hf({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);return Y2(l,u,i.length,p,r.shape.length,c),za({inputs:{x:o},attrs:{shape:r.shape},backend:n})}var tre={kernelName:di,backendName:"wasm",kernelFunc:ere,setupFunc:Qae},J2;function nre(e){J2=e.wasm.cwrap(Ll,null,["number","number","number","number","number","number","number","number","array","number","number"])}function are(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]=E.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 J2(c,p,d,h,m,s,f,g,x,v.length,u),l}var rre={kernelName:Ll,backendName:"wasm",kernelFunc:are,setupFunc:nre},sre=Un(hi),ire=Un(mi),Z2;function ore(e){Z2=e.wasm.cwrap(Tl,null,["number","number","number","number","number","number","array","number","number"])}function lre(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}=Fy.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 Z2(h,m,Vn[s.dtype],l,c,u,f,d,g),o}var ure={kernelName:Tl,backendName:"wasm",setupFunc:ore,kernelFunc:lre},Q2;function cre(e){Q2=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function pre(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 Q2(i,o,l,h,u),c}var dre={kernelName:Sl,backendName:"wasm",kernelFunc:pre,setupFunc:cre},eC;function hre(e){eC=e.wasm.cwrap(gi,null,["number","number"])}function mre(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||eC(a,s),r}var fre={kernelName:"Sigmoid",backendName:"wasm",setupFunc:hre,kernelFunc:mre},gre=Un(fi);function gf(e){let{inputs:{x:t},attrs:{begin:n,size:a},backend:r}=e,[s,i]=dn.parseSliceParams(t,n,a),o=dn.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=dn.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=Km(l,s,i,t.shape,t.dtype);return p.stringBytes=m,c}let d=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)yre(l,u[0],d,s,i);else if(h===3)bre(l,u[0],u[1],d,s,i);else if(h===4)xre(l,u[0],u[1],u[2],d,s,i);else{let m=Km(l,s,i,t.shape,t.dtype);d.set(m)}return c}function yre(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 bre(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 xre(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 vre={kernelName:_l,backendName:"wasm",kernelFunc:gf},tC;function wre(e){tC=e.wasm.cwrap(xi,null,["number","number","number","number"])}function kre(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||tC(r,i,o,l),s}var Ire={kernelName:xi,backendName:"wasm",setupFunc:wre,kernelFunc:kre};function Nre(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=E.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=gf({inputs:{x:r},attrs:{begin:c,size:d},backend:a});return c[o]+=p,h})}var Tre={kernelName:$l,backendName:"wasm",kernelFunc:Nre},Sre=Un(yi),Cre=Un(Ac),_re=!0,Ere=yn(vi,_re),nC;function Are(e){nC=e.wasm.cwrap(Kr,null,["number","number","number"])}function Fre(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 nC(i,r,l),o}var $re={kernelName:Kr,backendName:"wasm",setupFunc:Are,kernelFunc:Fre},aC;function Dre(e){aC=e.wasm.cwrap(Dl,null,["number","array","number","array","array","array","array","array","number","number"])}function Mre(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=E.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=E.slice_util.maskToAxes(p),g=r.shape.slice();f.forEach(F=>{s[F]=0,i[F]=1,g.splice(F,0,1)});let y=za({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:b,end:v,strides:x}=E.slice_util.getNormalizedAxes(y.shape,h,m,s,i,o,l,c,u);s=b,i=v,o=x;let N=E.slice_util.maskToAxes(d);N.forEach(F=>{i[F]=s[F]+1,o[F]=1});let T=E.slice_util.computeOutShape(s,i,o),C=T.filter((F,O)=>N.indexOf(O)===-1);if(o.every(F=>F===1)){let F=gf({inputs:{x:r},attrs:{begin:s,size:T},backend:t});return za({inputs:{x:F},attrs:{shape:C},backend:t})}let $=t.makeOutput(C,"float32");if(!C.some(F=>F===0)){let F=t.dataIdMap.get(y.dataId).id,O=new Uint8Array(new Int32Array(k.computeStrides(y.shape)).buffer),W=new Uint8Array(new Int32Array(s).buffer),V=new Uint8Array(new Int32Array(i).buffer),H=new Uint8Array(new Int32Array(o).buffer),K=new Uint8Array(new Int32Array(C).buffer),j=new Uint8Array(new Int32Array(k.computeStrides(C)).buffer),Y=t.dataIdMap.get($.dataId).id;aC(F,O,y.shape.length,W,V,H,K,j,C.length,Y)}return za({inputs:{x:$},attrs:{shape:C},backend:t})}var Rre={kernelName:Dl,backendName:"wasm",setupFunc:Dre,kernelFunc:Mre},Pre=!0,Ore=yn(wi,Pre),rC;function Lre(e){rC=e.wasm.cwrap(bi,null,["number, number, number"])}function zre(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}=Cu(i,r,t),m=p;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v,m=E.getInnerMostAxes(m.length,c.shape.length))}E.assertAxesAreInnerMostDims("sum",m,c.shape.length);let[f,g]=E.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;rC(l,y,v)}if(h&&t.disposeData(u.dataId),s){let v=E.expandShapeToKeepDim(b.shape,d);b.shape=v}return b}var Bre={kernelName:bi,backendName:"wasm",setupFunc:Lre,kernelFunc:zre},Wre=Un(ki),sC;function Vre(e){sC=e.wasm.cwrap(qr,null,["number","array","number","array","number","number"])}function Ure(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 sC(s,l,r.shape.length,c,o.length,Vn[u.dtype],p),u}var Gre={kernelName:qr,backendName:"wasm",setupFunc:Vre,kernelFunc:Ure},iC;function Hre(e){iC=e.wasm.cwrap(Rl,null,["number","array","number","number","number","bool","number","number"])}var jre=({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 iC(i,o,a.shape.length,Vn[a.dtype],r,s,u,d),[c,p]},qre={kernelName:Rl,backendName:"wasm",setupFunc:Hre,kernelFunc:jre};function Kre(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]=gf({inputs:{x:r},attrs:{begin:p,size:d},backend:n});return u.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var Xre={kernelName:Pl,backendName:"wasm",kernelFunc:Kre};function Yre(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var Jre={kernelName:Ol,backendName:"wasm",kernelFunc:Yre},Zre=[bte,vte,Ite,Fte,Mte,Lte,zte,Vte,Ute,jte,Xte,Yte,Qte,nne,sne,lne,cne,pne,dne,mne,yne,bne,vne,yte,Ine,Sne,Ene,$ne,Rne,One,zne,Nte,Vne,Gne,jne,qne,Xne,Zne,eae,aae,iae,uae,pae,hae,mae,yae,vae,Iae,Tae,_ae,Aae,$ae,Rae,Oae,Bae,Uae,Hae,qae,Kae,Xae,Rte,Zae,tre,rre,ire,sre,ure,dre,fre,gre,vre,Ire,Tre,Sre,Cre,Ere,$re,Rre,Ore,Bre,Wre,Gre,qre,_te,Xre,Jre];for(let e of Zre)Dc(e);var ow=te();ow.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])));ow.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(ow.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 oC=Ro(lA()),Qre='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()}}}}',ese=Ro(uA()),lC=class extends dc{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new Dd(this,ts())}write(e,t,n){let a={};return this.move(a,e,t,n),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=k.now();return e(),{kernelMs:k.now()-t}}move(e,t,n,a){let r=this.dataIdNextNumber++;if(a==="string"){let l=t;this.dataIdMap.set(e,{id:r,stringBytes:l,shape:n,dtype:a,memoryOffset:null});return}let s=k.sizeFromShape(n),i=s*k.bytesPerElement(a),o=this.wasm._malloc(i);this.dataIdMap.set(e,{id:r,memoryOffset:o,shape:n,dtype:a}),this.wasm.tfjs.registerTensor(r,s,o),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),o)}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 tse(s.buffer,n)}disposeData(e){let t=this.dataIdMap.get(e);this.wasm._free(t.memoryOffset),this.wasm.tfjs.disposeData(t.id),this.dataIdMap.delete(e)}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{a={};let r=this.dataIdNextNumber++;this.dataIdMap.set(a,{id:r,memoryOffset:n,shape:e,dtype:t});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 nse(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 uC(e,t,n){if(yf!=null)return yf;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),Rp!=null&&Rp[a]!=null?Rp[a]:n+a}async function ase(){let[e,t]=await Promise.all([te().getAsync("WASM_HAS_SIMD_SUPPORT"),te().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(l,c)=>{if(l.endsWith(".worker.js")){let u=Qre,p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return l.endsWith(".wasm")?uC(e,t,Pp!=null?Pp:c):c+l},lw&&(r.instantiateWasm=nse(uC(e,t,Pp!=null?Pp:"")));let s;t&&e&&yf==null?(s=oC.default(r),s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+oC.default.toString()],{type:"text/javascript"})):s=ese.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,Op=!1,n({wasm:s})},s.onAbort=()=>{o||Op||(Op=!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 tse(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 rse=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],yf=null,Pp=null,Rp={},Op=!1,lw=!1;function sse(e,t=!1){if(Rt("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Op)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");yf=e,lw=t}function ise(e,t=!1){if(Op)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")Pp=e;else{Rp=e;let n=rse.filter(a=>Rp[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.`)}lw=t}var ose="2.8.5",lse=2;Th("wasm",async()=>{let{wasm:e}=await ase();return new lC(e)},lse);var Uf={};cc(Uf,{AnchorPosition:()=>cr,DrawBox:()=>Sf,DrawBoxOptions:()=>vw,DrawFaceLandmarks:()=>kw,DrawFaceLandmarksOptions:()=>ww,DrawTextField:()=>vs,DrawTextFieldOptions:()=>Lp,drawContour:()=>Fr,drawDetections:()=>yse,drawFaceExpressions:()=>bse,drawFaceLandmarks:()=>xse});function Fr(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 bf={};cc(bf,{computeReshapedDimensions:()=>pw,getCenterPoint:()=>no,isDimensions:()=>vf,isEven:()=>xf,isFloat:()=>cw,isTensor:()=>eo,isTensor1D:()=>use,isTensor2D:()=>uw,isTensor3D:()=>$r,isTensor4D:()=>ra,isValidNumber:()=>Ba,isValidProbablitiy:()=>_u,range:()=>lr,round:()=>to});var un=class{constructor(t,n){if(!Ba(t)||!Ba(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 un(1/this.width,1/this.height)}};function eo(e,t){return e instanceof z&&e.shape.length===t}function use(e){return eo(e,1)}function uw(e){return eo(e,2)}function $r(e){return eo(e,3)}function ra(e){return eo(e,4)}function cw(e){return e%1!=0}function xf(e){return e%2==0}function to(e,t=2){let n=10**t;return Math.floor(e*n)/n}function vf(e){return e&&e.width&&e.height}function pw({width:e,height:t},n){let a=n/Math.max(t,e);return new un(Math.round(e*a),Math.round(t*a))}function no(e){return e.reduce((t,n)=>t.add(n),new De(0,0)).div(new De(e.length,e.length))}function lr(e,t,n){return Array(e).fill(0).map((a,r)=>t+r*n)}function Ba(e){return!!e&&e!==Infinity&&e!==-Infinity&&!Number.isNaN(e)||e===0}function _u(e){return Ba(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 lt=class{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(Ba)}static assertIsValidBox(t,n,a=!1){if(!lt.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(Ba),s=[a.x,a.y,a.width,a.height].every(Ba);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];lt.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 lt({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 lt({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 lt({x:t,y:n,width:a,height:r})}rescale(t){let n=vf(t)?t.width:t,a=vf(t)?t.height:t;return new lt({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 lt({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 lt({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 lt({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 lt({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 ao=class extends lt{constructor(t,n,a,r,s=!1){super({left:t,top:n,right:a,bottom:r},s)}};var Dr=class{constructor(t,n,a,r,s){this._imageDims=new un(s.width,s.height),this._score=t,this._classScore=n,this._className=a,this._box=new lt(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 lt(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new Dr(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var bt=class extends Dr{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 wf(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 kf(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 ao(a,r,s,i)}function If(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(wf(p,d,a))}r=r.filter((c,u)=>l[u]<=n)}return s}function ka(e,t){return D(()=>{let[n,a,r]=t,s=In([...e.shape.slice(0,3),1],n,"float32"),i=In([...e.shape.slice(0,3),1],a,"float32"),o=In([...e.shape.slice(0,3),1],r,"float32"),l=Qe([s,i,o],3);return ge(e,l)})}function Nf(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,In(h,0,"float32")},l=o(s),c=r-l.shape[i],p=[t&&c?o(c):null,e,l].filter(d=>!!d).map(d=>pe(d,"float32"));return Qe(p,i)})}function cC(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 Eu(e){return 1/(1+Math.exp(-e))}function pC(e){return Math.log(e/(1-e))}var ro=class extends lt{constructor(t,n,a,r,s=!1){super({x:t,y:n,width:a,height:r},s)}};var cse=.5,pse=.43,dse=.45,Gn=class{constructor(t,n,a=new De(0,0)){let{width:r,height:s}=n;this._imgDims=new un(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 lt(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/dse),l=no(t),c=Math.floor(Math.max(0,l.x-cse*o)),u=Math.floor(Math.max(0,l.y-pse*o));return new ro(c,u,Math.min(o,this.imageWidth+c),Math.min(o,this.imageHeight+u))}alignMinBbox(t){let n=kf(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var dw=class extends Gn{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],no([t[3],t[4]])]}};var so=class extends Gn{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(no)}};var Au=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?` (${to(this.distance)})`:""}`}};var Fu=class extends lt{static assertIsValidLabeledBox(t,n){if(lt.assertIsValidBox(t,n),!Ba(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 ur=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 ur(t.label,n)}};var hw=class extends Fu{static assertIsValidPredictedBox(t,n){if(Fu.assertIsValidLabeledBox(t,n),!_u(t.score)||!_u(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 Wa(e){return e.detection instanceof bt}function bs(e,t){return{...e,...{detection:t}}}function mw(){let e=window.fetch;if(!e)throw new Error("fetch - missing fetch implementation for browser environment");let t=()=>{throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:t}}function Tf(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 fw(){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=Tf();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 gw(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var yw=UE(hC()),en;function fse(){if(!en)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return en}function bw(e){en=e}function xw(){return gw()?bw(mw()):yw.isNodejs()?bw(fw()):null}function gse(e){if(en||xw(),!en)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=en.Canvas,Image:n=en.Image}=e;en.Canvas=t,en.Image=n,en.createCanvasElement=e.createCanvasElement||(()=>new t),en.createImageElement=e.createImageElement||(()=>new n),en.ImageData=e.ImageData||en.ImageData,en.Video=e.Video||en.Video,en.fetch=e.fetch||en.fetch,en.readFile=e.readFile||en.readFile}var st={getEnv:fse,setEnv:bw,initialize:xw,createBrowserEnv:mw,createFileSystem:Tf,createNodejsEnv:fw,monkeyPatch:gse,isBrowser:gw,isNodejs:yw.isNodejs};xw();function xs(e){return!st.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function bn(e){let{Canvas:t,CanvasRenderingContext2D:n}=st.getEnv();if(e instanceof n)return e;let a=xs(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 cr;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(cr||(cr={}));var Lp=class{constructor(t={}){let{anchorPosition:n,backgroundColor:a,fontColor:r,fontSize:s,fontStyle:i,padding:o}=t;this.anchorPosition=n||cr.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}},vs=class{constructor(t,n,a={}){this.text=typeof t=="string"?[t]:t instanceof vs?t.text:t,this.anchor=n,this.options=new Lp(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===cr.BOTTOM_RIGHT||a===cr.TOP_RIGHT,s=a===cr.BOTTOM_LEFT||a===cr.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=xs(t),a=bn(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 vw=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:cr.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Lp({...i,...s})}},Sf=class{constructor(t,n={}){this.box=new lt(t),this.options=new vw(n)}draw(t){let n=bn(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 vs([c],{x:s-r/2,y:i},this.options.drawLabelOptions).draw(t)}};function yse(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof bt?a.score:Wa(a)?a.detection.score:void 0,s=a instanceof bt?a.box:Wa(a)?a.detection.box:new lt(a),i=r?`${to(r)}`:void 0;new Sf(s,{label:i}).draw(e)})}function $u(e){let{Image:t,Video:n}=st.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function Cf(e){return new Promise((t,n)=>{if(e instanceof st.getEnv().Canvas||$u(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 _f(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 ws(e){let{Image:t,Video:n}=st.getEnv();return e instanceof t?new un(e.naturalWidth,e.naturalHeight):e instanceof n?new un(e.videoWidth,e.videoHeight):new un(e.width,e.height)}function io({width:e,height:t}){let{createCanvasElement:n}=st.getEnv(),a=n();return a.width=e,a.height=t,a}function Du(e,t){let{ImageData:n}=st.getEnv();if(!(e instanceof n)&&!$u(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:a,height:r}=t||ws(e),s=io({width:a,height:r});return e instanceof n?bn(s).putImageData(e,0,0):bn(s).drawImage(e,0,0,a,r),s}async function Ef(e,t){let n=t||st.getEnv().createCanvasElement(),[a,r,s]=e.shape.slice(ra(e)?1:0),i=D(()=>e.as3D(a,r,s).toInt());return await Ai.toPixels(i,n),i.dispose(),n}function zp(e){let{Image:t,Canvas:n,Video:a}=st.getEnv();return e instanceof t||e instanceof n||e instanceof a}function Af(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");let s=ws(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,c=io({width:t,height:t}),u=e instanceof r?e:Du(e),p=Math.abs(o-l)/2,d=n&&o<l?p:0,h=n&&l<o?p:0;return bn(c).drawImage(u,d,h,o,l),c}var pr=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($r(a)){this._imageTensors[r]=a,this._inputDimensions[r]=a.shape;return}if(ra(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:Du(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 lr(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 pw({width:n,height:a},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,D(()=>{let a=lr(this.batchSize,0,1).map(s=>{let i=this.getInput(s);if(i instanceof z){let o=ra(i)?i:i.expandDims();return o=Nf(o,n),(o.shape[1]!==t||o.shape[2]!==t)&&(o=Qa.resizeBilinear(o,[t,t])),o.as3D(t,t,3)}if(i instanceof st.getEnv().Canvas)return Ai.fromPixels(Af(i,t,n));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)});return Dt(a.map(s=>pe(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function yt(e){if(e instanceof pr)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(xs);return a.forEach((r,s)=>{if(!zp(r)&&!$r(r)&&!ra(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(ra(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=>zp(r)&&Cf(r))),new pr(a,Array.isArray(e))}async function oo(e,t){let{Canvas:n}=st.getEnv(),a=e;if(!(e instanceof n)){let i=await yt(e);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let o=i.getInput(0);a=o instanceof n?o:await Ef(o)}let r=bn(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=io({width:l,height:c});return bn(u).putImageData(r.getImageData(i,o,l,c),0,0),u})}async function lo(e,t){if(!$r(e)&&!ra(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(ra(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return D(()=>{let[n,a,r]=e.shape.slice(ra(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})=>Ql(e.as3D(n,a,r),[l,o,0],[u,c,r]))})}async function ks(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 mC(e){let t=await ks(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 _f(n)}async function Ff(e){return(await ks(e)).json()}async function fC(e){return new Float32Array(await(await ks(e)).arrayBuffer())}function $f(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 Df(e,t){let{manifestUri:n,modelBaseUri:a}=$f(e,t),r=await Ff(n);return qt.loadWeights(r,a)}function gC(e,t,n=!1){let{width:a,height:r}=n?ws(t):t;return e.width=a,e.height=r,{width:a,height:r}}var tn=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 Xr)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof Xr))}variable(){this.getFrozenParams().forEach(({path:t,tensor:n})=>{this.reassignParamFromPath(t,n.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:n})=>{let a=Xn(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 Df(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}=$f(t,this.getDefaultModelName()),s=c=>Promise.all(c.map(u=>n(u).then(p=>p.buffer))),i=qt.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 z))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=Pi(e,t.depthwise_filter,t.pointwise_filter,n,"same");return a=Z(a,t.bias),a})}function Mf(e,t,n=!1){return D(()=>{let a=Ye(n?Z(Ft(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 Bp(e,t,n=!1,a=!0){return D(()=>{let r=Ye(n?Z(Ft(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 uo(e,t,n="same",a=!1){return D(()=>{let r=Z(Ft(e,t.filters,[1,1],n),t.bias);return a?Ye(r):r})}function xn(e,t){Object.keys(e).forEach(n=>{t.some(a=>a.originalPath===n)||e[n].dispose()})}function Mu(e,t){return(n,a,r,s)=>{let i=Aa(e(n*a*r*r),[r,r,n,a]),o=nt(e(a));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function Rf(e,t){return(n,a,r)=>{let s=Ea(e(n*a),[n,a]),i=nt(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 Ru(e,t){return(n,a,r)=>{let s=Aa(e(3*3*n),[3,3,n,1]),i=Aa(e(n*a),[1,1,n,a]),o=nt(e(a));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new Pf(s,i,o)}}function Pu(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 Hn(e,t){return(n,a,r)=>{let s=e[n];if(!eo(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 vn(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 Of(e,t){let n=Mu(e,t),a=Ru(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 yC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractDenseBlock4Params:r}=Of(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 Lf(e){return t=>{let n=e(`${t}/filters`,4),a=e(`${t}/bias`,1);return{filters:n,bias:a}}}function zf(e,t){let n=Hn(e,t),a=Lf(n),r=Pu(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 bC(e){let t=[],{extractDenseBlock4Params:n}=zf(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return xn(e,t),{params:a,paramMappings:t}}var Wp=class extends tn{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return D(()=>{let a=pe(t.toBatchTensor(112,!0),"float32"),s=ka(a,[122.782,117.001,104.298]).div(he(255)),i=Bp(s,n.dense0,!0);return i=Bp(i,n.dense1),i=Bp(i,n.dense2),i=Bp(i,n.dense3),i=Jn(i,[7,7],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await yt(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return bC(t)}extractParams(t){return yC(t)}};function Vp(e,t){return D(()=>Z(ze(e,t.weights),t.bias))}function xC(e,t,n){let a=[],{extractWeights:r,getRemainingWeights:s}=vn(e),o=Rf(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 vC(e){let t=[],n=Hn(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 xn(e,t),{params:r,paramMappings:t}}function Bf(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 Up=class extends tn{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 pr?this.faceFeatureExtractor.forwardInput(t):t;return Vp(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 xC(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=Bf(t);return this.faceFeatureExtractor.loadFromWeightMap(n),vC(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 Wf=["neutral","happy","sad","angry","fearful","disgusted","surprised"],Mr=class{constructor(t){if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);Wf.forEach((n,a)=>{this[n]=t[a]})}asSortedArray(){return Wf.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var Gp=class extends Up{constructor(t=new Wp){super("FaceExpressionNet",t)}forwardInput(t){return D(()=>_a(this.runNet(t)))}async forward(t){return this.forwardInput(await yt(t))}async predictExpressions(t){let n=await yt(t),a=await this.forwardInput(n),r=await Promise.all(ht(a).map(async i=>{let o=await i.data();return i.dispose(),o}));a.dispose();let s=r.map(i=>new Mr(i));return n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function Vf(e){return e.expressions instanceof Mr}function Hp(e,t){return{...e,...{expressions:t}}}function bse(e,t,n=.1,a){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof Mr?s:Vf(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=Wa(s)?s.detection.box.bottomLeft:a||new De(0,0);new vs(l.map(p=>`${p.expression} (${to(p.probability)})`),c).draw(e)})}function Is(e){return Wa(e)&&e.landmarks instanceof Gn&&e.unshiftedLandmarks instanceof Gn&&e.alignedRect instanceof bt}function co(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 ww=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)"}},kw=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new ww(n)}draw(t){let n=bn(t),{drawLines:a,drawPoints:r,lineWidth:s,lineColor:i,pointSize:o,pointColor:l}=this.options;if(a&&this.faceLandmarks instanceof so&&(n.strokeStyle=i,n.lineWidth=s,Fr(n,this.faceLandmarks.getJawOutline()),Fr(n,this.faceLandmarks.getLeftEyeBrow()),Fr(n,this.faceLandmarks.getRightEyeBrow()),Fr(n,this.faceLandmarks.getNose()),Fr(n,this.faceLandmarks.getLeftEye(),!0),Fr(n,this.faceLandmarks.getRightEye(),!0),Fr(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 xse(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof Gn?a:Is(a)?a.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new kw(r).draw(e)})}var wC="0.11.5";function vse(e,t){let n=Mu(e,t),a=Ru(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 kC(e,t){let n=[],{extractWeights:a,getRemainingWeights:r}=vn(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=vse(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={};lr(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 wse(e,t){let n=Hn(e,t),a=Lf(n),r=Pu(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 IC(e,t){let n=[],{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}=wse(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={};lr(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 xn(e,n),{params:{entry_flow:u,middle_flow:p,exit_flow:m},paramMappings:n}}function NC(e,t,n){return Z(Ft(e,t.filters,n,"same"),t.bias)}function Iw(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=$t(a,[3,3],[2,2],"same"),a=Z(a,NC(e,t.expansion_conv,[2,2])),a}function kse(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 Nw=class extends tn{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=pe(t.toBatchTensor(112,!0),"float32"),s=ka(a,[122.782,117.001,104.298]).div(he(256)),i=Ye(NC(s,n.entry_flow.conv_in,[2,2]));return i=Iw(i,n.entry_flow.reduction_block_0,!1),i=Iw(i,n.entry_flow.reduction_block_1),lr(this._numMainBlocks,0,1).forEach(o=>{i=kse(i,n.middle_flow[`main_block_${o}`])}),i=Iw(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 yt(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return IC(t,this._numMainBlocks)}extractParams(t){return kC(t,this._numMainBlocks)}};function TC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),r=Rf(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 SC(e){let t=[],n=Hn(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 xn(e,t),{params:r,paramMappings:t}}var dr;(function(e){e.FEMALE="female",e.MALE="male"})(dr||(dr={}));var jp=class extends tn{constructor(t=new Nw(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 pr?this.faceFeatureExtractor.forwardInput(t):t,r=Jn(a,[7,7],[2,2],"valid").as2D(a.shape[0],-1),s=Vp(r,n.fc.age).as1D(),i=Vp(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:_a(a)}})}async forward(t){return this.forwardInput(await yt(t))}async predictAgeAndGender(t){let n=await yt(t),a=await this.forwardInput(n),r=ht(a.age),s=ht(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?dr.MALE:dr.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 TC(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=Bf(t);return this.faceFeatureExtractor.loadFromWeightMap(n),SC(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 qp=class extends Up{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)=>Dt([In([68],p,"float32"),In([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(In([s,136],n,"float32")).sub(Dt(Array.from(Array(s),(p,d)=>i(l(d),c(d))))).div(Dt(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 yt(t))}async detectLandmarks(t){let n=await yt(t),a=D(()=>ht(this.forwardInput(n))),r=await Promise.all(a.map(async(s,i)=>{let o=Array.from(await s.data()),l=o.filter((u,p)=>xf(p)),c=o.filter((u,p)=>!xf(p));return new so(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 po=class extends qp{constructor(t=new Wp){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function CC(e){let t=[],{extractDenseBlock3Params:n}=zf(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return xn(e,t),{params:a,paramMappings:t}}function _C(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractDenseBlock3Params:r}=Of(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 Tw=class extends tn{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return D(()=>{let a=pe(t.toBatchTensor(112,!0),"float32"),s=ka(a,[122.782,117.001,104.298]).div(he(255)),i=Mf(s,n.dense0,!0);return i=Mf(i,n.dense1),i=Mf(i,n.dense2),i=Jn(i,[14,14],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await yt(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return CC(t)}extractParams(t){return _C(t)}};var Kp=class extends qp{constructor(t=new Tw){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var Sw=class extends po{};function EC(e,t){return Z(L(e,t.weights),t.biases)}function Cw(e,t,n,a,r="same"){let{filters:s,bias:i}=t.conv,o=Ft(e,s,n,r);return o=Z(o,i),o=EC(o,t.scale),a?Ye(o):o}function AC(e,t){return Cw(e,t,[1,1],!0)}function _w(e,t){return Cw(e,t,[1,1],!1)}function Gf(e,t){return Cw(e,t,[2,2],!0,"valid")}function Ise(e,t){function n(o,l,c){let u=e(o),p=u.length/(l*c*c);if(cw(p))throw new Error(`depth has to be an integer: ${p}, weights.length: ${u.length}, numFilters: ${l}, filterSize: ${c}`);return D(()=>Ue(Aa(u,[l,p,c,c]),[2,3,1,0]))}function a(o,l,c,u){let p=n(o,l,c),d=nt(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/bias`}),{filters:p,bias:d}}function r(o,l){let c=nt(e(o)),u=nt(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 FC(e){let{extractWeights:t,getRemainingWeights:n}=vn(e),a=[],{extractConvLayerParams:r,extractResidualLayerParams:s}=Ise(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(Ea(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 Nse(e,t){let n=Hn(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 $C(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Nse(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"}),!uw(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 xn(e,t),{params:x,paramMappings:t}}function Va(e,t){let n=AC(e,t.conv1);return n=_w(n,t.conv2),n=Z(n,e),n=Ye(n),n}function Xp(e,t){let n=Gf(e,t.conv1);n=_w(n,t.conv2);let a=Jn(e,2,2,"valid"),r=xt(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=xt(o);n=Qe([n,l],1);let c=[...n.shape];c[2]=1;let u=xt(c);n=Qe([n,u],2)}return a=s?Qe([a,r],3):a,n=Z(a,n),n=Ye(n),n}var ho=class extends tn{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return D(()=>{let a=pe(t.toBatchTensor(150,!0),"float32"),s=ka(a,[122.782,117.001,104.298]).div(he(256)),i=Gf(s,n.conv32_down);i=$t(i,3,2,"valid"),i=Va(i,n.conv32_1),i=Va(i,n.conv32_2),i=Va(i,n.conv32_3),i=Xp(i,n.conv64_down),i=Va(i,n.conv64_1),i=Va(i,n.conv64_2),i=Va(i,n.conv64_3),i=Xp(i,n.conv128_down),i=Va(i,n.conv128_1),i=Va(i,n.conv128_2),i=Xp(i,n.conv256_down),i=Va(i,n.conv256_1),i=Va(i,n.conv256_2),i=Xp(i,n.conv256_down_out);let o=i.mean([1,2]);return ze(o,n.fc)})}async forward(t){return this.forwardInput(await yt(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 yt(t),a=D(()=>ht(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 $C(t)}extractParams(t){return FC(t)}};function DC(e){let t=new ho;return t.extractWeights(e),t}function Yp(e,t){return{...e,...{descriptor:t}}}function MC(e){return typeof e.age=="number"}function Jp(e,t){return{...e,...{age:t}}}function RC(e){return(e.gender===dr.MALE||e.gender===dr.FEMALE)&&_u(e.genderProbability)}function Zp(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function Tse(e,t){function n(l,c){let u=Aa(e(3*3*l),[3,3,l,1]),p=nt(e(l)),d=nt(e(l)),h=nt(e(l)),m=nt(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=Aa(e(l*c*u*u),[u,u,l,c]),m=nt(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"),$=a(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),F=a(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),O=a(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),W=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:$,class_predictor:F},box_predictor_5:{box_encoding_predictor:O,class_predictor:W}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function PC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:s}=Tse(n,t),i=r(),o=s(),c={extra_dim:kh(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 Sse(e,t){let n=Hn(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 OC(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=Sse(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!$r(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 xn(e,t),{params:s,paramMappings:t}}function Ia(e,t,n){return D(()=>{let a=Ft(e,t.filters,n,"same");return a=Z(a,t.batch_norm_offset),Xt(a,0,6)})}var Cse=.0010000000474974513;function _se(e,t,n){return D(()=>{let a=vr(e,t.filters,n,"same");return a=xr(a,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Cse),Xt(a,0,6)})}function Ese(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function LC(e,t){return D(()=>{let n,a=Ia(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=Ese(o);a=_se(a,s.depthwise_conv,l),a=Ia(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 Ase(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 zC(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=Ase(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 Fse(e){let t=ht(Ue(e,[1,0])),n=[ge(t[2],t[0]),ge(t[3],t[1])],a=[Z(t[0],we(n[0],he(2))),Z(t[1],we(n[1],he(2)))];return{sizes:n,centers:a}}function $se(e,t){let{sizes:n,centers:a}=Fse(e),r=ht(Ue(t,[1,0])),s=we(L(hn(we(r[2],he(5))),n[0]),he(2)),i=Z(L(we(r[0],he(10)),n[0]),a[0]),o=we(L(hn(we(r[3],he(5))),n[1]),he(2)),l=Z(L(we(r[1],he(10)),n[1]),a[1]);return Ue(Dt([ge(i,s),ge(l,o),Z(i,s),Z(l,o)]),[1,0])}function BC(e,t,n){return D(()=>{let a=e.shape[0],r=$se(q(Xa(n.extra_dim,[a,1,1]),[-1,4]),q(e,[-1,4]));r=q(r,[a,r.shape[0]/a,4]);let s=ma(We(t,[0,0,1],[-1,-1,-1])),i=We(s,[0,0,0],[-1,-1,1]);i=q(i,[a,i.shape[1]]);let o=ht(r),l=ht(i);return{boxes:o,scores:l}})}function mo(e,t){return D(()=>{let n=e.shape[0],a=q(uo(e,t.box_encoding_predictor),[n,-1,1,4]),r=q(uo(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:a,classPrediction:r}})}function WC(e,t,n){return D(()=>{let a=Ia(e,n.conv_0,[1,1]),r=Ia(a,n.conv_1,[2,2]),s=Ia(r,n.conv_2,[1,1]),i=Ia(s,n.conv_3,[2,2]),o=Ia(i,n.conv_4,[1,1]),l=Ia(o,n.conv_5,[2,2]),c=Ia(l,n.conv_6,[1,1]),u=Ia(c,n.conv_7,[2,2]),p=mo(t,n.box_predictor_0),d=mo(e,n.box_predictor_1),h=mo(r,n.box_predictor_2),m=mo(i,n.box_predictor_3),f=mo(l,n.box_predictor_4),g=mo(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 sa=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 Ns=class extends tn{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return D(()=>{let a=pe(t.toBatchTensor(512,!1),"float32"),r=ge(L(a,he(.007843137718737125)),he(1)),s=LC(r,n.mobilenetv1),{boxPredictions:i,classPredictions:o}=WC(s.out,s.conv11,n.prediction_layer);return BC(i,o,n.output_layer)})}async forward(t){return this.forwardInput(await yt(t))}async locateFaces(t,n={}){let{maxResults:a,minConfidence:r}=new sa(n),s=await yt(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=zC(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($=>$*g),[T,C]=[Math.max(0,y[v][1]),Math.min(1,y[v][3])].map($=>$*f);return new bt(u[v],new ro(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 OC(t)}extractParams(t){return PC(t)}};function Ew(e){let t=new Ns;return t.extractWeights(e),t}function VC(e){return Ew(e)}var Aw=class extends Ns{};var UC=.4,GC=[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)],HC=[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)],jC=[117.001,114.697,97.404],qC="tiny_yolov2_model",KC="tiny_yolov2_separable_conv_model";var Hf=e=>typeof e=="number";function jf(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(!Hf(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=>Hf(t.x)&&Hf(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(Hf)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Ou(e){return D(()=>{let t=L(e,he(.10000000149011612));return Z(Ye(ge(e,t)),t)})}function Rr(e,t){return D(()=>{let n=ta(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Ft(n,t.conv.filters,[1,1],"valid"),n=ge(n,t.bn.sub),n=L(n,t.bn.truediv),n=Z(n,t.conv.bias),Ou(n)})}function Pr(e,t){return D(()=>{let n=ta(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Pi(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=Z(n,t.bias),Ou(n)})}function Dse(e,t){let n=Mu(e,t);function a(i,o){let l=nt(e(i)),c=nt(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=Ru(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}}function XC(e,t,n,a){let{extractWeights:r,getRemainingWeights:s}=vn(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=Dse(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"),$=c(f,g,"conv4"),F=c(g,y,"conv5"),O=b?c(y,b,"conv6"):void 0,W=v?c(b,v,"conv7"):void 0,V=o(v||b||y,5*n,1,"conv8");u={conv0:x,conv1:N,conv2:T,conv3:C,conv4:$,conv5:F,conv6:O,conv7:W,conv8:V}}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"),$=l(f,g,"conv4"),F=l(g,y,"conv5"),O=l(y,b,"conv6"),W=l(b,v,"conv7"),V=o(v,5*n,1,"conv8");u={conv0:x,conv1:N,conv2:T,conv3:C,conv4:$,conv5:F,conv6:O,conv7:W,conv8:V}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:u,paramMappings:i}}function Mse(e,t){let n=Hn(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=Pu(n);return{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function YC(e,t){let n=[],{extractConvParams:a,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}=Mse(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 xn(e,n),{params:i,paramMappings:n}}var Ua=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 Fw=class extends tn{constructor(t){super("TinyYolov2");jf(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=Rr(t,n.conv0);return a=$t(a,[2,2],[2,2],"same"),a=Rr(a,n.conv1),a=$t(a,[2,2],[2,2],"same"),a=Rr(a,n.conv2),a=$t(a,[2,2],[2,2],"same"),a=Rr(a,n.conv3),a=$t(a,[2,2],[2,2],"same"),a=Rr(a,n.conv4),a=$t(a,[2,2],[2,2],"same"),a=Rr(a,n.conv5),a=$t(a,[2,2],[1,1],"same"),a=Rr(a,n.conv6),a=Rr(a,n.conv7),uo(a,n.conv8,"valid",!1)}runMobilenet(t,n){let a=this.config.isFirstLayerConv2d?Ou(uo(t,n.conv0,"valid",!1)):Pr(t,n.conv0);return a=$t(a,[2,2],[2,2],"same"),a=Pr(a,n.conv1),a=$t(a,[2,2],[2,2],"same"),a=Pr(a,n.conv2),a=$t(a,[2,2],[2,2],"same"),a=Pr(a,n.conv3),a=$t(a,[2,2],[2,2],"same"),a=Pr(a,n.conv4),a=$t(a,[2,2],[2,2],"same"),a=Pr(a,n.conv5),a=$t(a,[2,2],[1,1],"same"),a=n.conv6?Pr(a,n.conv6):a,a=n.conv7?Pr(a,n.conv7):a,uo(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=pe(t.toBatchTensor(n,!1),"float32");return r=this.config.meanRgb?ka(r,this.config.meanRgb):r,r=r.div(he(256)),this.config.withSeparableConvs?this.runMobilenet(r,a):this.runTinyYolov2(r,a)})}async forward(t,n){return this.forwardInput(await yt(t),n)}async detect(t,n={}){let{inputSize:a,scoreThreshold:r}=new Ua(n),s=await yt(t),i=await this.forwardInput(s,a),o=D(()=>ht(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 If(u.map(g=>g.rescale(a)),p,this.config.iouThreshold,!0).map(g=>new Dr(p[g],d[g],h[g],u[g],l))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return YC(t,this.config)}extractParams(t){let n=this.config.filterSizes||Fw.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 XC(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?_a(y.slice([0,0,0,5],[c,c,u,this.config.classes.length]),3):he(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=Eu(f[y][b][v][0]);if(!a||x>a){let N=(b+Eu(g[y][b][v][0]))/c*o,T=(y+Eu(g[y][b][v][1]))/c*l,C=Math.exp(g[y][b][v][2])*this.config.anchors[v].x/c*o,$=Math.exp(g[y][b][v][3])*this.config.anchors[v].y/c*l,F=N-C/2,O=T-$/2,W={row:y,col:b,anchor:v},{classScore:V,label:H}=this.withClassScores?await this.extractPredictedClass(h,W):{classScore:1,label:0};m.push({box:new ao(F,O,F+C,O+$),score:x,classScore:x*V,label:H,...W})}}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)}},Lu=Fw;Lu.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var fo=class extends Lu{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:UC,classes:["face"],...t?{anchors:HC,meanRgb:jC}:{anchors:GC,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?KC:qC}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function JC(e,t=!0){let n=new fo(t);return n.extractWeights(e),n}var Qp=class extends Ua{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var ia=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function go(e,t,n,a,r=({alignedRect:s})=>s){let s=e.map(l=>Is(l)?r(l):l.detection),i=a||(t instanceof z?await lo(t,s):await oo(t,s)),o=await n(i);return i.forEach(l=>l instanceof z&&l.dispose()),o}async function zu(e,t,n,a,r){return go([e],t,async s=>n(s[0]),a,r)}var ZC=.4,QC=[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)],e_=[117.001,114.697,97.404];var yo=class extends Lu{constructor(){let t={withSeparableConvs:!0,iouThreshold:ZC,classes:["face"],anchors:QC,meanRgb:e_,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 et={ssdMobilenetv1:new Ns,tinyFaceDetector:new yo,tinyYolov2:new fo,faceLandmark68Net:new po,faceLandmark68TinyNet:new Kp,faceRecognitionNet:new ho,faceExpressionNet:new Gp,ageGenderNet:new jp},$w=(e,t)=>et.ssdMobilenetv1.locateFaces(e,t),t_=(e,t)=>et.tinyFaceDetector.locateFaces(e,t),n_=(e,t)=>et.tinyYolov2.locateFaces(e,t),Dw=e=>et.faceLandmark68Net.detectLandmarks(e),a_=e=>et.faceLandmark68TinyNet.detectLandmarks(e),r_=e=>et.faceRecognitionNet.computeFaceDescriptor(e),s_=e=>et.faceExpressionNet.predictExpressions(e),i_=e=>et.ageGenderNet.predictAgeAndGender(e),Mw=e=>et.ssdMobilenetv1.load(e),o_=e=>et.tinyFaceDetector.load(e),l_=e=>et.tinyYolov2.load(e),u_=e=>et.faceLandmark68Net.load(e),c_=e=>et.faceLandmark68TinyNet.load(e),p_=e=>et.faceRecognitionNet.load(e),d_=e=>et.faceExpressionNet.load(e),h_=e=>et.ageGenderNet.load(e),m_=Mw,f_=$w,g_=Dw;var Rw=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},Vu=class extends Rw{async run(){let t=await this.parentTask,n=await go(t,this.input,async a=>Promise.all(a.map(r=>et.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return t.map((a,r)=>Hp(a,n[r]))}withAgeAndGender(){return new Bu(this,this.input)}},Uu=class extends Rw{async run(){let t=await this.parentTask;if(!t)return;let n=await zu(t,this.input,a=>et.faceExpressionNet.predictExpressions(a),this.extractedFaces);return Hp(t,n)}withAgeAndGender(){return new Wu(this,this.input)}},vo=class extends Vu{withAgeAndGender(){return new bo(this,this.input)}withFaceDescriptors(){return new Or(this,this.input)}},wo=class extends Uu{withAgeAndGender(){return new xo(this,this.input)}withFaceDescriptor(){return new Lr(this,this.input)}};var Pw=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},Bu=class extends Pw{async run(){let t=await this.parentTask,n=await go(t,this.input,async a=>Promise.all(a.map(r=>et.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return t.map((a,r)=>{let{age:s,gender:i,genderProbability:o}=n[r];return Jp(Zp(a,i,o),s)})}withFaceExpressions(){return new Vu(this,this.input)}},Wu=class extends Pw{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:a,genderProbability:r}=await zu(t,this.input,s=>et.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return Jp(Zp(t,a,r),n)}withFaceExpressions(){return new Uu(this,this.input)}},bo=class extends Bu{withFaceExpressions(){return new vo(this,this.input)}withFaceDescriptors(){return new Or(this,this.input)}},xo=class extends Wu{withFaceExpressions(){return new wo(this,this.input)}withFaceDescriptor(){return new Lr(this,this.input)}};var ed=class extends ia{constructor(t,n){super();this.parentTask=t;this.input=n}},Or=class extends ed{async run(){let t=await this.parentTask;return(await go(t,this.input,a=>Promise.all(a.map(r=>et.faceRecognitionNet.computeFaceDescriptor(r))),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}))).map((a,r)=>Yp(t[r],a))}withFaceExpressions(){return new vo(this,this.input)}withAgeAndGender(){return new bo(this,this.input)}},Lr=class extends ed{async run(){let t=await this.parentTask;if(!t)return;let n=await zu(t,this.input,a=>et.faceRecognitionNet.computeFaceDescriptor(a),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}));return Yp(t,n)}withFaceExpressions(){return new wo(this,this.input)}withAgeAndGender(){return new xo(this,this.input)}};var td=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.useTinyLandmarkNet=a}get landmarkNet(){return this.useTinyLandmarkNet?et.faceLandmark68TinyNet:et.faceLandmark68Net}},nd=class extends td{async run(){let t=await this.parentTask,n=t.map(s=>s.detection),a=this.input instanceof z?await lo(this.input,n):await oo(this.input,n),r=await Promise.all(a.map(s=>this.landmarkNet.detectLandmarks(s)));return a.forEach(s=>s instanceof z&&s.dispose()),t.map((s,i)=>co(s,r[i]))}withFaceExpressions(){return new vo(this,this.input)}withAgeAndGender(){return new bo(this,this.input)}withFaceDescriptors(){return new Or(this,this.input)}},ad=class extends td{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,a=this.input instanceof z?await lo(this.input,[n]):await oo(this.input,[n]),r=await this.landmarkNet.detectLandmarks(a[0]);return a.forEach(s=>s instanceof z&&s.dispose()),co(t,r)}withFaceExpressions(){return new wo(this,this.input)}withAgeAndGender(){return new xo(this,this.input)}withFaceDescriptor(){return new Lr(this,this.input)}};var rd=class extends ia{constructor(t,n=new sa){super();this.input=t;this.options=n}},Gu=class extends rd{async run(){let{input:t,options:n}=this,a=n instanceof Qp?r=>et.tinyFaceDetector.locateFaces(r,n):n instanceof sa?r=>et.ssdMobilenetv1.locateFaces(r,n):n instanceof Ua?r=>et.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=>bs({},a)))})}withFaceLandmarks(t=!1){return new nd(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new Vu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Bu(this.runAndExtendWithFaceDetections(),this.input)}},sd=class extends rd{async run(){let t=await new Gu(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?bs({},n):void 0)})}withFaceLandmarks(t=!1){return new ad(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new Uu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Wu(this.runAndExtendWithFaceDetection(),this.input)}};function y_(e,t=new sa){return new sd(e,t)}function id(e,t=new sa){return new Gu(e,t)}async function Ow(e,t){return id(e,new sa(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function b_(e,t={}){return id(e,new Ua(t)).withFaceLandmarks().withFaceDescriptors()}var x_=Ow;function qf(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 od=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 ur)return i;if(i instanceof Float32Array)return new ur(s(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new ur(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=>qf(a,t)).reduce((a,r)=>a+r,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:a})=>new Au(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 Au("unknown",n.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(a=>ur.fromJSON(a));return new od(n,t.distanceThreshold)}};function v_(e){let t=new yo;return t.extractWeights(e),t}function Lw(e,t){let{width:n,height:a}=new un(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=>Lw(r,{width:n,height:a}));if(Is(e)){let r=e.detection.forSize(n,a),s=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return co(bs(e,r),s)}return Wa(e)?bs(e,e.detection.forSize(n,a)):e instanceof Gn||e instanceof bt?e.forSize(n,a):e}var Pse=typeof process!="undefined",Ose=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",w_={faceapi:wC,node:Pse,browser:Ose};return Rse;})();
|
|
/**
|
|
* @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.js.map
|