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 tE=Object.create,bd=Object.defineProperty,nE=Object.getPrototypeOf,aE=Object.prototype.hasOwnProperty,rE=Object.getOwnPropertyNames,sE=Object.getOwnPropertyDescriptor;var e0=e=>bd(e,"__esModule",{value:!0});var iE=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Ju=(e,t)=>{for(var n in t)bd(e,n,{get:t[n],enumerable:!0})},oE=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of rE(t))!aE.call(e,a)&&a!=="default"&&bd(e,a,{get:()=>t[a],enumerable:!(n=sE(t,a))||n.enumerable});return e},lE=e=>oE(e0(bd(e!=null?tE(nE(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var eC=iE((fre,Z2)=>{e0(fre);Ju(fre,{isNodejs:()=>gre});function gre(){return typeof global=="object"&&!0&&typeof Z2!="undefined"&&typeof process!="undefined"&&!!process.version}});var Lre={};Ju(Lre,{AgeGenderNet:()=>Dp,BoundingBox:()=>ao,Box:()=>it,ComposableTask:()=>ia,ComputeAllFaceDescriptorsTask:()=>Rr,ComputeFaceDescriptorsTaskBase:()=>Wp,ComputeSingleFaceDescriptorTask:()=>Mr,DetectAllFaceLandmarksTask:()=>Up,DetectAllFacesTask:()=>Wu,DetectFaceLandmarksTaskBase:()=>Vp,DetectFacesTaskBase:()=>Hp,DetectSingleFaceLandmarksTask:()=>Gp,DetectSingleFaceTask:()=>jp,Dimensions:()=>un,FACE_EXPRESSION_LABELS:()=>$f,FaceDetection:()=>mt,FaceDetectionNet:()=>Dw,FaceExpressionNet:()=>Ap,FaceExpressions:()=>Ar,FaceLandmark68Net:()=>co,FaceLandmark68TinyNet:()=>Mp,FaceLandmarkNet:()=>Ew,FaceLandmarks:()=>jn,FaceLandmarks5:()=>fw,FaceLandmarks68:()=>so,FaceMatch:()=>Cu,FaceMatcher:()=>Kp,FaceRecognitionNet:()=>po,Gender:()=>cr,LabeledBox:()=>_u,LabeledFaceDescriptors:()=>or,NetInput:()=>ur,NeuralNetwork:()=>Zt,ObjectDetection:()=>Fr,Point:()=>De,PredictedBox:()=>gw,Rect:()=>ro,SsdMobilenetv1:()=>Ns,SsdMobilenetv1Options:()=>sa,TinyFaceDetector:()=>go,TinyFaceDetectorOptions:()=>Bp,TinyYolov2:()=>mo,TinyYolov2Options:()=>Ba,allFaces:()=>i_,allFacesSsdMobilenetv1:()=>Bw,allFacesTinyYolov2:()=>s_,awaitMediaLoaded:()=>bf,bufferToImage:()=>xf,computeFaceDescriptor:()=>HC,createCanvas:()=>ks,createCanvasFromMedia:()=>Fu,createFaceDetectionNet:()=>EC,createFaceRecognitionNet:()=>vC,createSsdMobilenetv1:()=>$w,createTinyFaceDetector:()=>o_,createTinyYolov2:()=>LC,detectAllFaces:()=>qp,detectFaceLandmarks:()=>Pw,detectFaceLandmarksTiny:()=>GC,detectLandmarks:()=>a_,detectSingleFace:()=>r_,draw:()=>Rf,env:()=>tt,euclideanDistance:()=>Lf,extendWithAge:()=>Lp,extendWithFaceDescriptor:()=>Op,extendWithFaceDetection:()=>bs,extendWithFaceExpressions:()=>$p,extendWithFaceLandmarks:()=>uo,extendWithGender:()=>zp,extractFaceTensors:()=>oo,extractFaces:()=>io,fetchImage:()=>tC,fetchJson:()=>kf,fetchNetWeights:()=>nC,fetchOrThrow:()=>Is,getContext2dOrThrow:()=>bn,getMediaDimensions:()=>ws,imageTensorToCanvas:()=>vf,imageToSquare:()=>wf,inverseSigmoid:()=>Q2,iou:()=>df,isMediaElement:()=>Sp,isMediaLoaded:()=>Eu,isWithAge:()=>wC,isWithFaceDetection:()=>La,isWithFaceExpressions:()=>Df,isWithFaceLandmarks:()=>Ts,isWithGender:()=>kC,loadAgeGenderModel:()=>e_,loadFaceDetectionModel:()=>t_,loadFaceExpressionModel:()=>ZC,loadFaceLandmarkModel:()=>YC,loadFaceLandmarkTinyModel:()=>JC,loadFaceRecognitionModel:()=>QC,loadSsdMobilenetv1Model:()=>Ow,loadTinyFaceDetectorModel:()=>KC,loadTinyYolov2Model:()=>XC,loadWeightMap:()=>Tf,locateFaces:()=>n_,matchDimensions:()=>aC,minBbox:()=>hf,nets:()=>Qe,nonMaxSuppression:()=>mf,normalize:()=>wa,padToSquare:()=>ff,predictAgeAndGender:()=>qC,recognizeFaceExpressions:()=>jC,resizeResults:()=>Ww,resolveInput:()=>xs,shuffleArray:()=>J2,sigmoid:()=>Su,ssdMobilenetv1:()=>Mw,tf:()=>xd,tinyFaceDetector:()=>VC,tinyYolov2:()=>UC,toNetInput:()=>ht,utils:()=>uf,validateConfig:()=>Of,version:()=>l_});var xd={};Ju(xd,{Abs:()=>Po,Acos:()=>Oo,Acosh:()=>Lo,AdadeltaOptimizer:()=>qh,AdagradOptimizer:()=>Kh,AdamOptimizer:()=>Xh,AdamaxOptimizer:()=>Yh,Add:()=>Hr,AddN:()=>As,All:()=>Sd,Any:()=>Cd,ArgMax:()=>$s,ArgMin:()=>nc,Asin:()=>zo,Asinh:()=>Bo,Atan:()=>Wo,Atan2:()=>Uo,Atanh:()=>Vo,AvgPool:()=>Ds,AvgPool3D:()=>ac,AvgPool3DGrad:()=>Ed,AvgPoolGrad:()=>_d,BackendWasm:()=>X2,BatchMatMul:()=>Rs,BatchToSpaceND:()=>rc,Bincount:()=>Fd,BroadcastTo:()=>m0,Callback:()=>KI,CallbackList:()=>j1,Cast:()=>Ms,Ceil:()=>Ps,ClipByValue:()=>jr,Complex:()=>Ad,ComplexAbs:()=>sc,Concat:()=>Go,Conv2D:()=>Os,Conv2DBackpropFilter:()=>$d,Conv2DBackpropInput:()=>Ls,Conv3D:()=>ic,Conv3DBackpropFilterV2:()=>Dd,Conv3DBackpropInputV2:()=>Rd,Cos:()=>zs,Cosh:()=>Ho,CropAndResize:()=>jo,Cumsum:()=>Bs,CustomCallback:()=>K1,DataStorage:()=>kd,DenseBincount:()=>Md,DepthToSpace:()=>qo,DepthwiseConv2dNative:()=>Ws,DepthwiseConv2dNativeBackpropFilter:()=>Pd,DepthwiseConv2dNativeBackpropInput:()=>Od,Diag:()=>Ld,Dilation2D:()=>oc,Dilation2DBackpropFilter:()=>Bd,Dilation2DBackpropInput:()=>zd,ENV:()=>ry,EarlyStopping:()=>YI,Elu:()=>Ko,EluGrad:()=>Wd,Environment:()=>d0,Equal:()=>Yo,Erf:()=>Xo,Exp:()=>Us,ExpandDims:()=>Jo,Expm1:()=>Qo,FFT:()=>Vd,Fill:()=>lc,FlipLeftRight:()=>Zo,Floor:()=>Gs,FloorDiv:()=>Hs,FromPixels:()=>nh,FusedBatchNorm:()=>js,FusedConv2D:()=>Ti,FusedDepthwiseConv2D:()=>Ni,GatherNd:()=>tl,GatherV2:()=>el,GraphModel:()=>ST,Greater:()=>nl,GreaterEqual:()=>qs,History:()=>q1,IFFT:()=>Ud,Identity:()=>Ks,Imag:()=>Gd,InputSpec:()=>Xt,IsFinite:()=>al,IsInf:()=>rl,IsNan:()=>sl,KernelBackend:()=>Zu,LRN:()=>pc,LRNGrad:()=>jd,LayerVariable:()=>W1,LayersModel:()=>Tr,LeakyRelu:()=>Xs,Less:()=>il,LessEqual:()=>ol,LinSpace:()=>Hd,Log:()=>Ys,Log1p:()=>ll,LogSoftmax:()=>f0,LogicalAnd:()=>ul,LogicalNot:()=>uc,LogicalOr:()=>cc,Max:()=>Js,MaxPool:()=>Zs,MaxPool3D:()=>dc,MaxPool3DGrad:()=>Kd,MaxPoolGrad:()=>qd,MaxPoolWithArgmax:()=>Xd,Maximum:()=>Qs,Mean:()=>ei,Min:()=>ti,Minimum:()=>ni,MirrorPad:()=>hc,Mod:()=>cl,MomentumOptimizer:()=>Jh,Multinomial:()=>Yd,Multiply:()=>ai,Neg:()=>pl,NonMaxSuppressionV3:()=>hl,NonMaxSuppressionV4:()=>ml,NonMaxSuppressionV5:()=>fl,NotEqual:()=>dl,OP_SCOPE_SUFFIX:()=>S0,OneHot:()=>ri,OnesLike:()=>gl,Optimizer:()=>wr,Pack:()=>yl,PadV2:()=>si,Pool:()=>QE,Pow:()=>ii,Prelu:()=>oi,Prod:()=>bl,RMSPropOptimizer:()=>Qh,RNN:()=>nr,Range:()=>mc,Rank:()=>py,Real:()=>Jd,RealDiv:()=>Vs,Reciprocal:()=>xl,Reduction:()=>mn,Relu:()=>li,Relu6:()=>ci,Reshape:()=>vl,ResizeBilinear:()=>ui,ResizeBilinearGrad:()=>Zd,ResizeNearestNeighbor:()=>fc,ResizeNearestNeighborGrad:()=>Qd,Reverse:()=>pi,RotateWithOffset:()=>Rl,Round:()=>di,Rsqrt:()=>hi,SGDOptimizer:()=>Uc,ScatterNd:()=>wl,Select:()=>kl,Selu:()=>Il,Sequential:()=>su,Sigmoid:()=>fi,Sign:()=>Sl,Sin:()=>mi,Sinh:()=>Nl,Slice:()=>Tl,Softmax:()=>bi,Softplus:()=>Cl,SpaceToBatchND:()=>gc,SparseToDense:()=>eh,SplitV:()=>_l,Sqrt:()=>gi,Square:()=>yc,SquaredDifference:()=>xi,Step:()=>Kr,StridedSlice:()=>El,Sub:()=>vi,Sum:()=>yi,SymbolicTensor:()=>Aa,Tan:()=>Fl,Tanh:()=>wi,Tensor:()=>Ee,TensorBuffer:()=>Ot,Tile:()=>qr,TopK:()=>Al,Transpose:()=>ki,Unique:()=>th,Unpack:()=>$l,UnsortedSegmentSum:()=>bc,Variable:()=>Xr,ZerosLike:()=>Dl,_FusedMatMul:()=>Ii,abs:()=>Lt,acos:()=>Py,acosh:()=>Oy,add:()=>J,addN:()=>lk,all:()=>yh,any:()=>Ec,argMax:()=>Fc,argMin:()=>Ly,asin:()=>zy,asinh:()=>By,atan:()=>Wy,atan2:()=>Vy,atanh:()=>Uy,avgPool:()=>Zn,avgPool3d:()=>jy,backend:()=>ok,backend_util:()=>_,basicLSTMCell:()=>C$,batchNorm:()=>br,batchNorm2d:()=>dk,batchNorm3d:()=>hk,batchNorm4d:()=>mk,batchToSpaceND:()=>$c,bincount:()=>fk,booleanMaskAsync:()=>AM,broadcastTo:()=>Dc,browser:()=>Ei,buffer:()=>Le,callbacks:()=>b4,cast:()=>ue,ceil:()=>qy,clipByValue:()=>qt,clone:()=>Zr,complex:()=>Yr,concat:()=>Je,concat1d:()=>gk,concat2d:()=>yk,concat3d:()=>bk,concat4d:()=>xk,constraints:()=>m1,conv1d:()=>xh,conv2d:()=>Ft,conv2dTranspose:()=>vh,conv3d:()=>Xy,conv3dTranspose:()=>X$,copyRegisteredKernels:()=>tF,cos:()=>Rc,cosh:()=>wh,cosineWindow:()=>wb,cumsum:()=>kh,customGrad:()=>Ka,data:()=>_T,denseBincount:()=>wk,deprecationWarn:()=>My,depthToSpace:()=>Yy,depthwiseConv2d:()=>ns,deregisterOp:()=>v4,device_util:()=>uh,diag:()=>aD,dilation2d:()=>Jy,disableDeprecationWarnings:()=>zA,dispose:()=>Ae,disposeVariables:()=>BA,div:()=>xe,divNoNan:()=>Qy,dot:()=>kk,dropout:()=>Uk,elu:()=>Gl,enableDebugMode:()=>LA,enableProdMode:()=>OA,enclosingPowerOfTwo:()=>Gk,engine:()=>Ha,env:()=>ee,equal:()=>as,erf:()=>Zy,exp:()=>hn,expandDims:()=>Mn,expm1:()=>eb,eye:()=>tb,fft:()=>Wc,fill:()=>Cn,findBackend:()=>qA,findBackendFactory:()=>KA,floor:()=>Hl,floorDiv:()=>gh,fused:()=>is,gather:()=>$i,gatherND:()=>Vk,gather_util:()=>_y,getBackend:()=>HA,getGradient:()=>ly,getKernel:()=>ah,getKernelsForBackend:()=>rh,grad:()=>$D,grads:()=>DD,greater:()=>ha,greaterEqual:()=>rs,ifft:()=>Jl,imag:()=>Ih,image:()=>Ja,inTopKAsync:()=>VM,initializers:()=>w1,input:()=>R1,io:()=>Ht,irfft:()=>Lh,isFinite:()=>Ik,isInf:()=>Tk,isNaN:()=>Nk,keep:()=>jt,kernel_impls:()=>Qa,layers:()=>D1,leakyRelu:()=>Mc,less:()=>Th,lessEqual:()=>Di,linalg:()=>n1,linspace:()=>Sk,loadGraphModel:()=>xV,loadLayersModel:()=>LW,localResponseNormalization:()=>nb,log:()=>Pn,log1p:()=>Nh,logSigmoid:()=>_k,logSoftmax:()=>Ch,logSumExp:()=>sb,logicalAnd:()=>ma,logicalNot:()=>Pc,logicalOr:()=>_h,logicalXor:()=>$k,losses:()=>aO,matMul:()=>ze,math:()=>V0,max:()=>ea,maxPool:()=>At,maxPool3d:()=>ib,maxPoolWithArgmax:()=>Dk,maximum:()=>Xa,mean:()=>St,memory:()=>mh,metrics:()=>HI,min:()=>ql,minimum:()=>Kl,mirrorPad:()=>ob,mod:()=>lb,model:()=>PW,models:()=>jI,moments:()=>Eh,movingAverage:()=>RM,mul:()=>L,multiRNNCell:()=>lR,multinomial:()=>Rk,neg:()=>Nt,nextFrame:()=>Zh,norm:()=>Vh,notEqual:()=>Mi,oneHot:()=>Bl,ones:()=>Ya,onesLike:()=>On,op:()=>P,outerProduct:()=>hR,pad:()=>ta,pad1d:()=>gR,pad2d:()=>bR,pad3d:()=>vR,pad4d:()=>kR,pool:()=>Mk,pow:()=>xr,prelu:()=>Lc,print:()=>P0,prod:()=>Fh,profile:()=>WA,rand:()=>AR,randomGamma:()=>MR,randomNormal:()=>Pk,randomUniform:()=>Xl,range:()=>Ah,ready:()=>GA,real:()=>zc,reciprocal:()=>pb,registerBackend:()=>fh,registerCallbackConstructor:()=>zW,registerGradient:()=>g0,registerKernel:()=>vc,registerOp:()=>x4,regularizers:()=>qI,relu:()=>qe,relu6:()=>$h,removeBackend:()=>jA,reshape:()=>U,reverse:()=>Ln,reverse1d:()=>GR,reverse2d:()=>jR,reverse3d:()=>KR,reverse4d:()=>YR,rfft:()=>Vc,round:()=>db,rsqrt:()=>Dh,scalar:()=>pe,scatterND:()=>Wk,scatter_util:()=>Ey,selu:()=>Rh,separableConv2d:()=>Pi,sequential:()=>OW,serialization:()=>re,setBackend:()=>UA,setPlatform:()=>XA,setWasmPath:()=>ore,setWasmPaths:()=>lre,setdiff1dAsync:()=>Ok,sigmoid:()=>da,sign:()=>hb,signal:()=>nO,sin:()=>Mh,sinh:()=>Ph,slice:()=>We,slice1d:()=>Oh,slice2d:()=>mb,slice3d:()=>Yl,slice4d:()=>Bc,slice_util:()=>dn,softmax:()=>Na,softplus:()=>jl,spaceToBatchND:()=>Oc,sparseToDense:()=>vb,spectral:()=>tO,split:()=>zn,sqrt:()=>an,square:()=>lt,squaredDifference:()=>zh,squeeze:()=>ss,stack:()=>$t,step:()=>Ql,stridedSlice:()=>fb,sub:()=>me,sum:()=>Se,sumOutType:()=>lh,tan:()=>gb,tanh:()=>Ul,tensor:()=>Jn,tensor1d:()=>Ze,tensor2d:()=>Sa,tensor3d:()=>dh,tensor4d:()=>Ca,tensor5d:()=>kM,tensor6d:()=>IM,tensor_util:()=>Ta,test_util:()=>ak,tidy:()=>D,tile:()=>qa,time:()=>VA,topk:()=>yb,train:()=>Li,transpose:()=>Ve,truncatedNormal:()=>Bh,unique:()=>Wh,unregisterGradient:()=>eF,unregisterKernel:()=>ZE,unsortedSegmentSum:()=>bb,unstack:()=>ut,upcastType:()=>pa,util:()=>w,valueAndGrad:()=>RD,valueAndGrads:()=>MD,variable:()=>Lk,variableGrads:()=>Ck,version:()=>fee,version_converter:()=>CT,version_core:()=>ik,version_layers:()=>Im,version_wasm:()=>ure,where:()=>Sn,whereAsync:()=>xb,zeros:()=>xt,zerosLike:()=>Ge});var uE=Object.create,vd=Object.defineProperty,cE=Object.getPrototypeOf,pE=Object.prototype.hasOwnProperty,dE=Object.getOwnPropertyNames,hE=Object.getOwnPropertyDescriptor,mE=e=>vd(e,"__esModule",{value:!0}),pn=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Oe=(e,t)=>{for(var n in t)vd(e,n,{get:t[n],enumerable:!0})},fE=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of dE(t))!pE.call(e,a)&&a!=="default"&&vd(e,a,{get:()=>t[a],enumerable:!(n=hE(t,a))||n.enumerable});return e},Do=e=>fE(mE(vd(e!=null?uE(cE(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),gE=pn(()=>{}),yE=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)}),bE=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)}),xE=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)}),vE=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)}),wE=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=[],x=128;for(d===(d|0)?(m=d,d=null):(d=d+"\0",m=0,x=Math.max(x,d.length)),f=0,g=-32;g<x;++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)}),kE=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)}),IE=pn(()=>{}),TE=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,S){var A=[];T=T==!0?{entropy:!0}:T||{};var $=b(y(T.entropy?[N,v(n)]:N==null?x():N,3),A),R=new f(A),B=function(){for(var V=R.g(i),W=c,G=0;V<u;)V=(V+G)*s,W*=s,G=R.g(1);for(;V>=p;)V/=2,W/=2,G>>>=1;return(V+G)/W};return B.int32=function(){return R.g(4)|0},B.quick=function(){return R.g(4)/4294967296},B.double=B,b(v(R.S),n),(T.pass||S||function(V,W,G,H){return H&&(H.S&&g(H,R),V.state=function(){return g(R,{})}),G?(a[l]=V,W):V})(B,$,"global"in T?T.global:this==a,T.state)}a["seed"+l]=m;function f(N){var T,S=N.length,A=this,$=0,R=A.i=A.j=0,B=A.S=[];for(S||(N=[S++]);$<s;)B[$]=$++;for($=0;$<s;$++)B[$]=B[R=d&R+N[$%S]+(T=B[$])],B[R]=T;(A.g=function(V){for(var W,G=0,H=A.i,X=A.j,q=A.S;V--;)W=q[H=d&H+1],G=G*s+q[d&(q[H]=q[X=d&X+W])+(q[X]=W)];return A.i=H,A.j=X,G})(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 S=[],A=typeof N,$;if(T&&A=="object")for($ in N)try{S.push(y(N[$],T-1))}catch(R){}return S.length?S:A=="string"?N:N+"\0"}function b(N,T){for(var S=N+"",A,$=0;$<S.length;)T[d&$]=d&(A^=T[d&$]*19)+S.charCodeAt($++);return v(T)}function x(){try{var N;return h&&(N=h.randomBytes)?N=N(s):(N=new Uint8Array(s),(r.crypto||r.msCrypto).getRandomValues(N)),v(N)}catch(A){var T=r.navigator,S=T&&T.plugins;return[+new Date,r,S,r.screen,v(n)]}}function v(N){return String.fromCharCode.apply(0,N)}if(b(a.random(),n),typeof t=="object"&&t.exports){t.exports=m;try{h=IE()}catch(N){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)}),wd=pn((e,t)=>{var n=yE(),a=bE(),r=xE(),s=vE(),i=wE(),o=kE(),l=TE();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),NE=pn(()=>{}),Qu=pn(()=>{}),SE=pn(()=>{}),CE=pn(()=>{}),_E=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 Z.buffer!=Be&&tn(Z.buffer),wn}function i(){return Z.buffer!=Be&&tn(Z.buffer),It}function o(){return Z.buffer!=Be&&tn(Z.buffer),kn}function l(){return Z.buffer!=Be&&tn(Z.buffer),Xn}function c(){return Z.buffer!=Be&&tn(Z.buffer),cn}var u=typeof r!="undefined"?r:{},p,d;u.ready=new Promise(function(I,C){p=I,d=C});var h={},m;for(m in u)u.hasOwnProperty(m)&&(h[m]=u[m]);var f=[],g="./this.program",y=function(I,C){throw C},b=!1,x=!1,v=!1,N=!1;b=typeof window=="object",x=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",N=!b&&!v&&!x;var T=u.ENVIRONMENT_IS_PTHREAD||!1;T&&(Be=u.buffer);var S="";function A(I){return u.locateFile?u.locateFile(I,S):S+I}var $,R,B,V,W,G;if(v){x?S=Qu().dirname(S)+"/":S=__dirname+"/",$=function(I,C){return W||(W=require("fs")),G||(G=Qu()),I=G.normalize(I),W.readFileSync(I,C?null:"utf8")},B=function(I){var C=$(I,!0);return C.buffer||(C=new Uint8Array(C)),fe(C.buffer),C},process.argv.length>1&&(g=process.argv[1].replace(/\\/g,"/")),f=process.argv.slice(2),process.on("uncaughtException",function(I){if(!(I instanceof Yu))throw I}),process.on("unhandledRejection",hr),y=function(I){process.exit(I)},u.inspect=function(){return"[Emscripten Module object]"};var H;try{H=SE()}catch(I){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),I}global.Worker=H.Worker}else N?(typeof read!="undefined"&&($=function(I){return read(I)}),B=function(I){var C;return typeof readbuffer=="function"?new Uint8Array(readbuffer(I)):(C=read(I,"binary"),fe(typeof C=="object"),C)},typeof scriptArgs!="undefined"?f=scriptArgs:typeof arguments!="undefined"&&(f=arguments),typeof quit=="function"&&(y=function(I){quit(I)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(b||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof a!="undefined"&&a&&(S=a),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",v?($=function(I,C){return W||(W=require("fs")),G||(G=Qu()),I=G.normalize(I),W.readFileSync(I,C?null:"utf8")},B=function(I){var C=$(I,!0);return C.buffer||(C=new Uint8Array(C)),fe(C.buffer),C}):($=function(I){var C=new XMLHttpRequest;return C.open("GET",I,!1),C.send(null),C.responseText},x&&(B=function(I){var C=new XMLHttpRequest;return C.open("GET",I,!1),C.responseType="arraybuffer",C.send(null),new Uint8Array(C.response)}),R=function(I,C,O){var j=new XMLHttpRequest;j.open("GET",I,!0),j.responseType="arraybuffer",j.onload=function(){if(j.status==200||j.status==0&&j.response){C(j.response);return}O()},j.onerror=O,j.send(null)}),V=function(I){document.title=I});v&&typeof performance=="undefined"&&(global.performance=CE().performance);var X=u.print||console.log.bind(console),q=u.printErr||console.warn.bind(console);for(m in h)h.hasOwnProperty(m)&&(u[m]=h[m]);h=null,u.arguments&&(f=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(y=u.quit);var te=Atomics.load,Q=Atomics.store,se=Atomics.compareExchange,ne;u.wasmBinary&&(ne=u.wasmBinary);var ie=u.noExitRuntime||!0;typeof WebAssembly!="object"&&hr("no native wasm support detected");var Z,de,oe=!1,ge;function fe(I,C){I||hr("Assertion failed: "+C)}function we(I){var C=u["_"+I];return fe(C,"Cannot call unknown function "+I+", make sure it is exported"),C}function Te(I,C,O,j,he){var le={string:function(Nn){var $o=0;if(Nn!=null&&Nn!==0){var Zw=(Nn.length<<2)+1;$o=Eo(Zw),at(Nn,$o,Zw)}return $o},array:function(Nn){var $o=Eo(Nn.length);return Xe(Nn,$o),$o}};function ce(Nn){return C==="string"?Fe(Nn):C==="boolean"?Boolean(Nn):Nn}var be=we(I),rt=[],Ut=0;if(j)for(var Mt=0;Mt<j.length;Mt++){var Vr=le[O[Mt]];Vr?(Ut===0&&(Ut=Xu()),rt[Mt]=Vr(j[Mt])):rt[Mt]=j[Mt]}var Ao=be.apply(null,rt);return Ao=ce(Ao),Ut!==0&&_o(Ut),Ao}function _e(I,C,O,j){O=O||[];var he=O.every(function(ce){return ce==="number"}),le=C!=="string";return le&&he&&!j?we(I):function(){return Te(I,C,O,arguments,j)}}function Re(I,C,O){for(var j=C+O,he="";!(C>=j);){var le=I[C++];if(!le)return he;if(!(le&128)){he+=String.fromCharCode(le);continue}var ce=I[C++]&63;if((le&224)==192){he+=String.fromCharCode((le&31)<<6|ce);continue}var be=I[C++]&63;if((le&240)==224?le=(le&15)<<12|ce<<6|be:le=(le&7)<<18|ce<<12|be<<6|I[C++]&63,le<65536)he+=String.fromCharCode(le);else{var rt=le-65536;he+=String.fromCharCode(55296|rt>>10,56320|rt&1023)}}return he}function Fe(I,C){return I?Re(i(),I,C):""}function nt(I,C,O,j){if(!(j>0))return 0;for(var he=O,le=O+j-1,ce=0;ce<I.length;++ce){var be=I.charCodeAt(ce);if(be>=55296&&be<=57343){var rt=I.charCodeAt(++ce);be=65536+((be&1023)<<10)|rt&1023}if(be<=127){if(O>=le)break;C[O++]=be}else if(be<=2047){if(O+1>=le)break;C[O++]=192|be>>6,C[O++]=128|be&63}else if(be<=65535){if(O+2>=le)break;C[O++]=224|be>>12,C[O++]=128|be>>6&63,C[O++]=128|be&63}else{if(O+3>=le)break;C[O++]=240|be>>18,C[O++]=128|be>>12&63,C[O++]=128|be>>6&63,C[O++]=128|be&63}}return C[O]=0,O-he}function at(I,C,O){return nt(I,i(),C,O)}function ot(I){for(var C=0,O=0;O<I.length;++O){var j=I.charCodeAt(O);j>=55296&&j<=57343&&(j=65536+((j&1023)<<10)|I.charCodeAt(++O)&1023),j<=127?++C:j<=2047?C+=2:j<=65535?C+=3:C+=4}return C}function Xe(I,C){s().set(I,C)}function ft(I,C){return I%C>0&&(I+=C-I%C),I}var Be,wn,It,Kn,en,kn,Xn,Rn,cn;function tn(I){Be=I,u.HEAP8=wn=new Int8Array(I),u.HEAP16=Kn=new Int16Array(I),u.HEAP32=kn=new Int32Array(I),u.HEAPU8=It=new Uint8Array(I),u.HEAPU16=en=new Uint16Array(I),u.HEAPU32=Xn=new Uint32Array(I),u.HEAPF32=Rn=new Float32Array(I),u.HEAPF64=cn=new Float64Array(I)}var Wa=u.INITIAL_MEMORY||16777216;if(T)Z=u.wasmMemory,Be=u.buffer;else if(u.wasmMemory)Z=u.wasmMemory;else if(Z=new WebAssembly.Memory({initial:Wa/65536,maximum:2147483648/65536,shared:!0}),!(Z.buffer instanceof SharedArrayBuffer))throw q("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),v&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Z&&(Be=Z.buffer),Wa=Be.byteLength,tn(Be);var oa,la=[],Pr=[],pr=[],Or=[],wo=[],Ia=!1,Xp=!1;T||Pr.push({func:function(){pd()}}),T&&(Ia=!0);function zf(){if(!T){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)Qp(u.preRun.shift());Io(la)}}function Yp(){Ia=!0,Io(Pr)}function Bf(){T||Io(pr)}function Jp(){T||(Xp=!0)}function In(){if(!T){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Wf(u.postRun.shift());Io(wo)}}function Qp(I){la.unshift(I)}function Wf(I){wo.unshift(I)}var dr=0,Lr=null,Ss=null;function Vf(I){fe(!T,"addRunDependency cannot be used in a pthread worker"),dr++,u.monitorRunDependencies&&u.monitorRunDependencies(dr)}function Uf(I){if(dr--,u.monitorRunDependencies&&u.monitorRunDependencies(dr),dr==0&&(Lr!==null&&(clearInterval(Lr),Lr=null),Ss)){var C=Ss;Ss=null,C()}}u.preloadedImages={},u.preloadedAudios={};function hr(I){u.onAbort&&u.onAbort(I),T&&console.error("Pthread aborting at "+new Error().stack),I+="",q(I),oe=!0,ge=1,I="abort("+I+"). Build with -s ASSERTIONS=1 for more info.";var C=new WebAssembly.RuntimeError(I);throw d(C),C}function Zp(I,C){return String.prototype.startsWith?I.startsWith(C):I.indexOf(C)===0}var ko="data:application/octet-stream;base64,";function ed(I){return Zp(I,ko)}var Gf="file://";function td(I){return Zp(I,Gf)}var Tn="tfjs-backend-wasm-threaded-simd.wasm";ed(Tn)||(Tn=A(Tn));function Hf(I){try{if(I==Tn&&ne)return new Uint8Array(ne);if(B)return B(I);throw"both async and sync fetching of the wasm failed"}catch(C){hr(C)}}function nd(){if(!ne&&(b||x)){if(typeof fetch=="function"&&!td(Tn))return fetch(Tn,{credentials:"same-origin"}).then(function(I){if(!I.ok)throw"failed to load wasm binary file at '"+Tn+"'";return I.arrayBuffer()}).catch(function(){return Hf(Tn)});if(R)return new Promise(function(I,C){R(Tn,function(O){I(new Uint8Array(O))},C)})}return Promise.resolve().then(function(){return Hf(Tn)})}function jf(){var I={a:Pg};function C(ce,be){var rt=ce.exports;if(u.asm=rt,oa=u.asm.F,de=be,!T){var Ut=ke.unusedWorkers.length;ke.unusedWorkers.forEach(function(Mt){ke.loadWasmModuleToWorker(Mt,function(){--Ut||Uf("wasm-instantiate")})})}}T||Vf("wasm-instantiate");function O(ce){C(ce.instance,ce.module)}function j(ce){return nd().then(function(be){return WebAssembly.instantiate(be,I)}).then(ce,function(be){q("failed to asynchronously prepare wasm: "+be),hr(be)})}function he(){return!ne&&typeof WebAssembly.instantiateStreaming=="function"&&!ed(Tn)&&!td(Tn)&&typeof fetch=="function"?fetch(Tn,{credentials:"same-origin"}).then(function(ce){var be=WebAssembly.instantiateStreaming(ce,I);return be.then(O,function(rt){return q("wasm streaming compile failed: "+rt),q("falling back to ArrayBuffer instantiation"),j(O)})}):j(O)}if(u.instantiateWasm)try{var le=u.instantiateWasm(I,C);return le}catch(ce){return q("Module.instantiateWasm callback failed with error: "+ce),!1}return he().catch(d),{}}var ad={8991:function(I,C){setTimeout(function(){qw(I,C)},0)}};function qf(){ke.initRuntime()}function Io(I){for(;I.length>0;){var C=I.shift();if(typeof C=="function"){C(u);continue}var O=C.func;typeof O=="number"?C.arg===void 0?oa.get(O)():oa.get(O)(C.arg):O(C.arg===void 0?null:C.arg)}}function To(I,C){if(I<=0||I>s().length||I&!0||C<0)return-28;if(C==0)return 0;C>=2147483647&&(C=Infinity);var O=Atomics.load(o(),Fo>>2),j=0;if(O==I){var he=Atomics.compareExchange(o(),Fo>>2,O,0);if(he==O&&(--C,j=1,C<=0))return 1}var le=Atomics.notify(o(),I>>2,C);if(le>=0)return le+j;throw"Atomics.notify returned an unexpected value "+le}u._emscripten_futex_wake=To;function Kf(I){if(T)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in killThread!";o()[I+12>>2]=0;var C=ke.pthreads[I];C.worker.terminate(),ke.freeThreadData(C),ke.runningWorkers.splice(ke.runningWorkers.indexOf(C.worker),1),C.worker.pthread=void 0}function Xf(I){if(T)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in cancelThread!";var C=ke.pthreads[I];C.worker.postMessage({cmd:"cancel"})}function Yf(I){if(T)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in cleanupThread!";o()[I+12>>2]=0;var C=ke.pthreads[I];if(C){var O=C.worker;ke.returnWorkerToPool(O)}}var ke={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var I=8,C=0;C<I;++C)ke.allocateUnusedWorker()},initRuntime:function(){for(var I=_s(228),C=0;C<228/4;++C)l()[I/4+C]=0;o()[I+12>>2]=I;var O=I+152;o()[O>>2]=O;for(var j=_s(512),C=0;C<128;++C)l()[j/4+C]=0;Atomics.store(l(),I+100>>2,j),Atomics.store(l(),I+40>>2,I),gd(I,!x,1),jw(I)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;ke.threadExitHandlers.length>0;)ke.threadExitHandlers.pop()();T&&Co()&&Hw()},threadExit:function(I){var C=Co();C&&(Atomics.store(l(),C+4>>2,I),Atomics.store(l(),C+0>>2,1),Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),ke.runExitHandlers(),To(C+0,2147483647),gd(0,0,0),T&&postMessage({cmd:"exit"}))},threadCancel:function(){ke.runExitHandlers();var I=Co();Atomics.store(l(),I+4>>2,-1),Atomics.store(l(),I+0>>2,1),To(I+0,2147483647),gd(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var I in ke.pthreads){var C=ke.pthreads[I];C&&C.worker&&ke.returnWorkerToPool(C.worker)}ke.pthreads={};for(var O=0;O<ke.unusedWorkers.length;++O){var j=ke.unusedWorkers[O];j.terminate()}ke.unusedWorkers=[];for(var O=0;O<ke.runningWorkers.length;++O){var j=ke.runningWorkers[O],C=j.pthread;ke.freeThreadData(C),j.terminate()}ke.runningWorkers=[]},freeThreadData:function(I){if(I){if(I.threadInfoStruct){var C=o()[I.threadInfoStruct+100>>2];o()[I.threadInfoStruct+100>>2]=0,Ku(C),Ku(I.threadInfoStruct)}I.threadInfoStruct=0,I.allocatedOwnStack&&I.stackBase&&Ku(I.stackBase),I.stackBase=0,I.worker&&(I.worker.pthread=null)}},returnWorkerToPool:function(I){ke.runWithoutMainThreadQueuedCalls(function(){delete ke.pthreads[I.pthread.threadInfoStruct],ke.unusedWorkers.push(I),ke.runningWorkers.splice(ke.runningWorkers.indexOf(I),1),ke.freeThreadData(I.pthread),I.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(I){o()[Qw>>2]=0;try{I()}finally{o()[Qw>>2]=1}},receiveObjectTransfer:function(I){},loadWasmModuleToWorker:function(I,C){I.onmessage=function(O){var j=O.data,he=j.cmd;if(I.pthread&&(ke.currentProxiedOperationCallerThread=I.pthread.threadInfoStruct),j.targetThread&&j.targetThread!=Co()){var le=ke.pthreads[j.targetThread];le?le.worker.postMessage(O.data,j.transferList):console.error('Internal error! Worker sent a message "'+he+'" to target pthread '+j.targetThread+", but that thread no longer exists!"),ke.currentProxiedOperationCallerThread=void 0;return}if(he==="processQueuedMainThreadWork")Jg();else if(he==="spawnThread")ud(O.data);else if(he==="cleanupThread")Yf(j.thread);else if(he==="killThread")Kf(j.thread);else if(he==="cancelThread")Xf(j.thread);else if(he==="loaded")I.loaded=!0,C&&C(I),I.runPthread&&(I.runPthread(),delete I.runPthread);else if(he==="print")X("Thread "+j.threadId+": "+j.text);else if(he==="printErr")q("Thread "+j.threadId+": "+j.text);else if(he==="alert")alert("Thread "+j.threadId+": "+j.text);else if(he==="exit"){var ce=I.pthread&&Atomics.load(l(),I.pthread.threadInfoStruct+64>>2);ce&&ke.returnWorkerToPool(I)}else if(he==="exitProcess")try{eE(j.returnCode)}catch(be){if(be instanceof Yu)return;throw be}else he==="cancelDone"?ke.returnWorkerToPool(I):he==="objectTransfer"?ke.receiveObjectTransfer(O.data):O.data.target==="setimmediate"?I.postMessage(O.data):q("worker sent an unknown command "+he);ke.currentProxiedOperationCallerThread=void 0},I.onerror=function(O){q("pthread sent an error! "+O.filename+":"+O.lineno+": "+O.message)},v&&(I.on("message",function(O){I.onmessage({data:O})}),I.on("error",function(O){I.onerror(O)}),I.on("exit",function(O){})),I.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||a,wasmMemory:Z,wasmModule:de})},allocateUnusedWorker:function(){var I=A("tfjs-backend-wasm-threaded-simd.worker.js");ke.unusedWorkers.push(new Worker(I))},getNewWorker:function(){return ke.unusedWorkers.length==0&&(ke.allocateUnusedWorker(),ke.loadWasmModuleToWorker(ke.unusedWorkers[0])),ke.unusedWorkers.length>0?ke.unusedWorkers.pop():null},busySpinWait:function(I){for(var C=performance.now()+I;performance.now()<C;);}};function Jf(I,C){Yw(I,C),_o(I)}u.establishStackSpace=Jf;function Qf(){return ie}u.getNoExitRuntime=Qf;function Zf(I,C){return oa.get(I)(C)}u.invokeEntryPoint=Zf;function eg(I,C,O,j){hr("Assertion failed: "+Fe(I)+", at: "+[C?Fe(C):"unknown filename",O,j?Fe(j):"unknown function"])}function tg(I,C){var O=_main(I,C)}var Cs;v?Cs=function(){var I=process.hrtime();return I[0]*1e3+I[1]/1e6}:T?Cs=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?Cs=dateNow:Cs=function(){return performance.now()};function ng(I){return o()[Uw()>>2]=I,I}function ag(I,C){if(T)return zr(1,1,I,C)}function rg(I,C){if(I==C)postMessage({cmd:"processQueuedMainThreadWork"});else if(T)postMessage({targetThread:I,cmd:"processThreadQueue"});else{var O=ke.pthreads[I],j=O&&O.worker;if(!j)return;j.postMessage({cmd:"processThreadQueue"})}return 1}function sg(){hr()}function ig(I,C,O){var j=pg(C,O);return ad[I].apply(null,j)}function og(I,C){}function lg(I,C,O){if(I<=0||I>s().length||I&!0)return-28;if(b){if(Atomics.load(o(),I>>2)!=C)return-6;for(var j=performance.now(),he=j+O,le=Atomics.exchange(o(),Fo>>2,I);;){if(j=performance.now(),j>he)return le=Atomics.exchange(o(),Fo>>2,0),-73;if(le=Atomics.exchange(o(),Fo>>2,0),le==0)break;if(Jg(),Atomics.load(o(),I>>2)!=C)return-6;le=Atomics.exchange(o(),Fo>>2,I)}return 0}else{var ce=Atomics.wait(o(),I>>2,C,O);if(ce==="timed-out")return-73;if(ce==="not-equal")return-6;if(ce==="ok")return 0;throw"Atomics.wait returned an unexpected value "+ce}}function ug(I,C,O){i().copyWithin(I,C,C+O)}function cg(){return v?require("os").cpus().length:navigator.hardwareConcurrency}function zr(I,C){for(var O=arguments.length-2,j=Xu(),he=O,le=Eo(he*8),ce=le>>3,be=0;be<O;be++){var rt=arguments[2+be];c()[ce+be]=rt}var Ut=Xw(I,he,le,C);return _o(j),Ut}var Vu=[],Uu=[];function pg(I,C){Uu.length=0;var O;for(C>>=2;O=i()[I++];){var j=O<105;j&&C&1&&C++,Uu.push(j?c()[C++>>1]:o()[C]),++C}return Uu}function dg(I,C,O){Vu.length=C;for(var j=O>>3,he=0;he<C;he++)Vu[he]=c()[j+he];var le=I<0,ce=le?ad[-I-1]:Mg[I];return ce.apply(null,Vu)}function hg(){return i().length}function mg(I){try{return Z.grow(I-Be.byteLength+65535>>>16),tn(Z.buffer),1}catch(C){}}function fg(I){var C=hg();if(I<=C)return!1;var O=2147483648;if(I>O)return!1;for(var j=1;j<=4;j*=2){var he=C*(1+.2/j);he=Math.min(he,I+100663296);var le=Math.min(O,ft(Math.max(I,he),65536)),ce=mg(le);if(ce)return!0}return!1}var Pe={inEventHandler:0,removeAllEventListeners:function(){for(var I=Pe.eventHandlers.length-1;I>=0;--I)Pe._removeHandler(I);Pe.eventHandlers=[],Pe.deferredCalls=[]},registerRemoveEventListeners:function(){Pe.removeEventListenersRegistered||(Or.push(Pe.removeAllEventListeners),Pe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(I,C,O){function j(ce,be){if(ce.length!=be.length)return!1;for(var rt in ce)if(ce[rt]!=be[rt])return!1;return!0}for(var he in Pe.deferredCalls){var le=Pe.deferredCalls[he];if(le.targetFunction==I&&j(le.argsList,O))return}Pe.deferredCalls.push({targetFunction:I,precedence:C,argsList:O}),Pe.deferredCalls.sort(function(ce,be){return ce.precedence<be.precedence})},removeDeferredCalls:function(I){for(var C=0;C<Pe.deferredCalls.length;++C)Pe.deferredCalls[C].targetFunction==I&&(Pe.deferredCalls.splice(C,1),--C)},canPerformEventHandlerRequests:function(){return Pe.inEventHandler&&Pe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(Pe.canPerformEventHandlerRequests())for(var I=0;I<Pe.deferredCalls.length;++I){var C=Pe.deferredCalls[I];Pe.deferredCalls.splice(I,1),--I,C.targetFunction.apply(null,C.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(I,C){for(var O=0;O<Pe.eventHandlers.length;++O)Pe.eventHandlers[O].target==I&&(!C||C==Pe.eventHandlers[O].eventTypeString)&&Pe._removeHandler(O--)},_removeHandler:function(I){var C=Pe.eventHandlers[I];C.target.removeEventListener(C.eventTypeString,C.eventListenerFunc,C.useCapture),Pe.eventHandlers.splice(I,1)},registerOrRemoveHandler:function(I){var C=function(j){++Pe.inEventHandler,Pe.currentEventHandler=I,Pe.runDeferredCalls(),I.handlerFunc(j),Pe.runDeferredCalls(),--Pe.inEventHandler};if(I.callbackfunc)I.eventListenerFunc=C,I.target.addEventListener(I.eventTypeString,C,I.useCapture),Pe.eventHandlers.push(I),Pe.registerRemoveEventListeners();else for(var O=0;O<Pe.eventHandlers.length;++O)Pe.eventHandlers[O].target==I.target&&Pe.eventHandlers[O].eventTypeString==I.eventTypeString&&Pe._removeHandler(O--)},queueEventHandlerOnThread_iiii:function(I,C,O,j,he){var le=Xu(),ce=Eo(12);o()[ce>>2]=O,o()[ce+4>>2]=j,o()[ce+8>>2]=he,Qg(0,I,637534208,C,j,ce),_o(le)},getTargetThreadForEventCallback:function(I){switch(I){case 1:return 0;case 2:return ke.currentProxiedOperationCallerThread;default:return I}},getNodeNameForTarget:function(I){return I?I==window?"#window":I==screen?"#screen":I&&I.nodeName?I.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function gg(I){var C=ot(I)+1,O=_s(C);return at(I,O,C),O}function yg(I,C,O,j){var he=Xu(),le=Eo(12),ce=0;C&&(ce=gg(C)),o()[le>>2]=ce,o()[le+4>>2]=O,o()[le+8>>2]=j,Qg(0,I,657457152,0,ce,le),_o(he)}function bg(I,C,O,j){C=C?Fe(C):"",yg(I,C,O,j)}function xg(I){return I>2?Fe(I):I}var vg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function wg(I){I=xg(I);var C=vg[I]||(typeof document!="undefined"?document.querySelector(I):void 0);return C}function Gu(I){return wg(I)}function rd(I,C,O){var j=Gu(I);if(!j)return-4;if(j.canvasSharedPtr&&(o()[j.canvasSharedPtr>>2]=C,o()[j.canvasSharedPtr+4>>2]=O),j.offscreenCanvas||!j.controlTransferredOffscreen){j.offscreenCanvas&&(j=j.offscreenCanvas);var he=!1;if(j.GLctxObject&&j.GLctxObject.GLctx){var le=j.GLctxObject.GLctx.getParameter(2978);he=le[0]===0&&le[1]===0&&le[2]===j.width&&le[3]===j.height}j.width=C,j.height=O,he&&j.GLctxObject.GLctx.viewport(0,0,C,O)}else if(j.canvasSharedPtr){var ce=o()[j.canvasSharedPtr+8>>2];return bg(ce,I,C,O),1}else return-4;return 0}function sd(I,C,O){return T?zr(2,1,I,C,O):rd(I,C,O)}function kg(I,C,O){var j=Gu(I);return j?rd(I,C,O):sd(I,C,O)}function Ig(I){}function Tg(I,C){}function Ng(I){var C=I.getExtension("ANGLE_instanced_arrays");if(C)return I.vertexAttribDivisor=function(O,j){C.vertexAttribDivisorANGLE(O,j)},I.drawArraysInstanced=function(O,j,he,le){C.drawArraysInstancedANGLE(O,j,he,le)},I.drawElementsInstanced=function(O,j,he,le,ce){C.drawElementsInstancedANGLE(O,j,he,le,ce)},1}function Sg(I){var C=I.getExtension("OES_vertex_array_object");if(C)return I.createVertexArray=function(){return C.createVertexArrayOES()},I.deleteVertexArray=function(O){C.deleteVertexArrayOES(O)},I.bindVertexArray=function(O){C.bindVertexArrayOES(O)},I.isVertexArray=function(O){return C.isVertexArrayOES(O)},1}function Cg(I){var C=I.getExtension("WEBGL_draw_buffers");if(C)return I.drawBuffers=function(O,j){C.drawBuffersWEBGL(O,j)},1}function _g(I){return!!(I.multiDrawWebgl=I.getExtension("WEBGL_multi_draw"))}var et={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(I){et.lastError||(et.lastError=I)},getNewId:function(I){for(var C=et.counter++,O=I.length;O<C;O++)I[O]=null;return C},getSource:function(I,C,O,j){for(var he="",le=0;le<C;++le){var ce=j?o()[j+le*4>>2]:-1;he+=Fe(o()[O+le*4>>2],ce<0?void 0:ce)}return he},createContext:function(I,C){var O=I.getContext("webgl",C);if(!O)return 0;var j=et.registerContext(O,C);return j},registerContext:function(I,C){var O=_s(8);o()[O+4>>2]=Co();var j={handle:O,attributes:C,version:C.majorVersion,GLctx:I};return I.canvas&&(I.canvas.GLctxObject=j),et.contexts[O]=j,(typeof C.enableExtensionsByDefault=="undefined"||C.enableExtensionsByDefault)&&et.initExtensions(j),O},makeContextCurrent:function(I){return et.currentContext=et.contexts[I],u.ctx=Br=et.currentContext&&et.currentContext.GLctx,!(I&&!Br)},getContext:function(I){return et.contexts[I]},deleteContext:function(I){et.currentContext===et.contexts[I]&&(et.currentContext=null),typeof Pe=="object"&&Pe.removeAllHandlersOnTarget(et.contexts[I].GLctx.canvas),et.contexts[I]&&et.contexts[I].GLctx.canvas&&(et.contexts[I].GLctx.canvas.GLctxObject=void 0),Ku(et.contexts[I].handle),et.contexts[I]=null},initExtensions:function(I){if(I||(I=et.currentContext),!I.initExtensionsDone){I.initExtensionsDone=!0;var C=I.GLctx;Ng(C),Sg(C),Cg(C),C.disjointTimerQueryExt=C.getExtension("EXT_disjoint_timer_query"),_g(C);var O=C.getSupportedExtensions()||[];O.forEach(function(j){j.indexOf("lose_context")<0&&j.indexOf("debug")<0&&C.getExtension(j)})}},populateUniformTable:function(I){for(var C=et.programs[I],O=et.programInfos[I]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},j=O.uniforms,he=Br.getProgramParameter(C,35718),le=0;le<he;++le){var ce=Br.getActiveUniform(C,le),be=ce.name;O.maxUniformLength=Math.max(O.maxUniformLength,be.length+1),be.slice(-1)=="]"&&(be=be.slice(0,be.lastIndexOf("[")));var rt=Br.getUniformLocation(C,be);if(rt){var Ut=et.getNewId(et.uniforms);j[be]=[ce.size,Ut],et.uniforms[Ut]=rt;for(var Mt=1;Mt<ce.size;++Mt){var Vr=be+"["+Mt+"]";rt=Br.getUniformLocation(C,Vr),Ut=et.getNewId(et.uniforms),et.uniforms[Ut]=rt}}}}},Eg=["default","low-power","high-performance"];function Fg(I,C){var O=C>>2,j=o()[O+(24>>2)],he={alpha:!!o()[O+(0>>2)],depth:!!o()[O+(4>>2)],stencil:!!o()[O+(8>>2)],antialias:!!o()[O+(12>>2)],premultipliedAlpha:!!o()[O+(16>>2)],preserveDrawingBuffer:!!o()[O+(20>>2)],powerPreference:Eg[j],failIfMajorPerformanceCaveat:!!o()[O+(28>>2)],majorVersion:o()[O+(32>>2)],minorVersion:o()[O+(36>>2)],enableExtensionsByDefault:o()[O+(40>>2)],explicitSwapControl:o()[O+(44>>2)],proxyContextToMainThread:o()[O+(48>>2)],renderViaOffscreenBackBuffer:o()[O+(52>>2)]},le=Gu(I);if(!le||he.explicitSwapControl)return 0;var ce=et.createContext(le,he);return ce}function Ag(I,C){return Fg(I,C)}var No={mappings:{},buffers:[null,[],[]],printChar:function(I,C){var O=No.buffers[I];C===0||C===10?((I===1?X:q)(Re(O,0)),O.length=0):O.push(C)},varargs:void 0,get:function(){No.varargs+=4;var I=o()[No.varargs-4>>2];return I},getStr:function(I){var C=Fe(I);return C},get64:function(I,C){return I}};function id(I){return T?zr(3,1,I):0}function od(I,C,O,j,he){if(T)return zr(4,1,I,C,O,j,he)}function ld(I,C,O,j){if(T)return zr(5,1,I,C,O,j);for(var he=0,le=0;le<O;le++){for(var ce=o()[C+le*8>>2],be=o()[C+(le*8+4)>>2],rt=0;rt<be;rt++)No.printChar(I,i()[ce+rt]);he+=be}return o()[j>>2]=he,0}function $g(I){var C=ke.threadExitHandlers.pop();I&&C()}function Dg(I,C){ke.threadExitHandlers.push(function(){oa.get(I)(C)})}function ud(I){if(T)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var C=ke.getNewWorker();if(C.pthread!==void 0)throw"Internal error!";if(!I.pthread_ptr)throw"Internal error, no pthread ptr!";ke.runningWorkers.push(C);for(var O=_s(128*4),j=0;j<128;++j)o()[O+j*4>>2]=0;var he=I.stackBase+I.stackSize,le=ke.pthreads[I.pthread_ptr]={worker:C,stackBase:I.stackBase,stackSize:I.stackSize,allocatedOwnStack:I.allocatedOwnStack,threadInfoStruct:I.pthread_ptr},ce=le.threadInfoStruct>>2;Atomics.store(l(),ce+(64>>2),I.detached),Atomics.store(l(),ce+(100>>2),O),Atomics.store(l(),ce+(40>>2),le.threadInfoStruct),Atomics.store(l(),ce+(80>>2),I.stackSize),Atomics.store(l(),ce+(76>>2),he),Atomics.store(l(),ce+(104>>2),I.stackSize),Atomics.store(l(),ce+(104+8>>2),he),Atomics.store(l(),ce+(104+12>>2),I.detached);var be=Gw(),rt=be+40;Atomics.store(l(),ce+(172>>2),rt),C.pthread=le;var Ut={cmd:"run",start_routine:I.startRoutine,arg:I.arg,threadInfoStruct:I.pthread_ptr,stackBase:I.stackBase,stackSize:I.stackSize};C.runPthread=function(){Ut.time=performance.now(),C.postMessage(Ut,I.transferList)},C.loaded&&(C.runPthread(),delete C.runPthread)}function Rg(I,C,O,j){if(typeof SharedArrayBuffer=="undefined")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!I)return q("pthread_create called with a null thread pointer!"),28;var he=[],le=0;if(T&&(he.length===0||le))return Kw(687865856,I,C,O,j);if(le)return le;var ce=0,be=0,rt=0;C&&C!=-1?(ce=o()[C>>2],ce+=81920,be=o()[C+8>>2],rt=o()[C+12>>2]!==0):ce=2097152;var Ut=be==0;Ut?be=Jw(16,ce):(be-=ce,fe(be>0));for(var Mt=_s(228),Vr=0;Vr<228>>2;++Vr)l()[(Mt>>2)+Vr]=0;o()[I>>2]=Mt,o()[Mt+12>>2]=Mt;var Ao=Mt+152;o()[Ao>>2]=Ao;var Nn={stackBase:be,stackSize:ce,allocatedOwnStack:Ut,detached:rt,startRoutine:O,pthread_ptr:Mt,arg:j,transferList:he};return T?(Nn.cmd="spawnThread",postMessage(Nn,he)):ud(Nn),0}function cd(I){if(T)return zr(6,1,I);switch(I){case 30:return 16384;case 85:var C=2147483648;return C/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return ng(28),-1}T||ke.initMainThreadBlock();var Br,Mg=[null,ag,sd,id,od,ld,cd],Pg={e:eg,r:tg,x:rg,b:sg,y:ig,j:og,c:lg,d:To,f:Cs,p:ug,z:cg,u:dg,q:fg,v:kg,i:Ig,t:Tg,w:Ag,m:id,n:od,g:ld,o:qf,a:Z||u.wasmMemory,k:$g,l:Dg,h:Rg,s:cd},Vw=jf(),pd=u.___wasm_call_ctors=function(){return(pd=u.___wasm_call_ctors=u.asm.A).apply(null,arguments)},Og=u._init=function(){return(Og=u._init=u.asm.B).apply(null,arguments)},Lg=u._register_tensor=function(){return(Lg=u._register_tensor=u.asm.C).apply(null,arguments)},zg=u._dispose_data=function(){return(zg=u._dispose_data=u.asm.D).apply(null,arguments)},Bg=u._dispose=function(){return(Bg=u._dispose=u.asm.E).apply(null,arguments)},Wg=u._Abs=function(){return(Wg=u._Abs=u.asm.G).apply(null,arguments)},Vg=u._Add=function(){return(Vg=u._Add=u.asm.H).apply(null,arguments)},Ug=u._AddN=function(){return(Ug=u._AddN=u.asm.I).apply(null,arguments)},Gg=u._ArgMax=function(){return(Gg=u._ArgMax=u.asm.J).apply(null,arguments)},Hg=u._AvgPool=function(){return(Hg=u._AvgPool=u.asm.K).apply(null,arguments)},jg=u._BatchMatMul=function(){return(jg=u._BatchMatMul=u.asm.L).apply(null,arguments)},qg=u._Ceil=function(){return(qg=u._Ceil=u.asm.M).apply(null,arguments)},Kg=u._ClipByValue=function(){return(Kg=u._ClipByValue=u.asm.N).apply(null,arguments)},Xg=u._Conv2D=function(){return(Xg=u._Conv2D=u.asm.O).apply(null,arguments)},dd=u._Conv2DBackpropInput=function(){return(dd=u._Conv2DBackpropInput=u.asm.P).apply(null,arguments)},hd=u._Cos=function(){return(hd=u._Cos=u.asm.Q).apply(null,arguments)},Hu=u._CropAndResize=function(){return(Hu=u._CropAndResize=u.asm.R).apply(null,arguments)},So=u._Cumsum=function(){return(So=u._Cumsum=u.asm.S).apply(null,arguments)},Yg=u._DepthToSpace=function(){return(Yg=u._DepthToSpace=u.asm.T).apply(null,arguments)},ju=u._DepthwiseConv2dNative=function(){return(ju=u._DepthwiseConv2dNative=u.asm.U).apply(null,arguments)},K=u._Equal=function(){return(K=u._Equal=u.asm.V).apply(null,arguments)},ae=u._Exp=function(){return(ae=u._Exp=u.asm.W).apply(null,arguments)},Ne=u._FlipLeftRight=function(){return(Ne=u._FlipLeftRight=u.asm.X).apply(null,arguments)},Ye=u._Floor=function(){return(Ye=u._Floor=u.asm.Y).apply(null,arguments)},_t=u._FloorDiv=function(){return(_t=u._FloorDiv=u.asm.Z).apply(null,arguments)},yt=u._FusedBatchNorm=function(){return(yt=u._FusedBatchNorm=u.asm._).apply(null,arguments)},Ue=u._FusedConv2D=function(){return(Ue=u._FusedConv2D=u.asm.$).apply(null,arguments)},He=u._FusedDepthwiseConv2D=function(){return(He=u._FusedDepthwiseConv2D=u.asm.aa).apply(null,arguments)},nn=u._Gather=function(){return(nn=u._Gather=u.asm.ba).apply(null,arguments)},mr=u._GatherNd=function(){return(mr=u._GatherNd=u.asm.ca).apply(null,arguments)},fr=u._Greater=function(){return(fr=u._Greater=u.asm.da).apply(null,arguments)},md=u._GreaterEqual=function(){return(md=u._GreaterEqual=u.asm.ea).apply(null,arguments)},qu=u._LeakyRelu=function(){return(qu=u._LeakyRelu=u.asm.fa).apply(null,arguments)},Yn=u._Less=function(){return(Yn=u._Less=u.asm.ga).apply(null,arguments)},Wr=u._LessEqual=function(){return(Wr=u._LessEqual=u.asm.ha).apply(null,arguments)},fd=u._Log=function(){return(fd=u._Log=u.asm.ia).apply(null,arguments)},u_=u._LogicalAnd=function(){return(u_=u._LogicalAnd=u.asm.ja).apply(null,arguments)},c_=u._Max=function(){return(c_=u._Max=u.asm.ka).apply(null,arguments)},p_=u._MaxPool=function(){return(p_=u._MaxPool=u.asm.la).apply(null,arguments)},d_=u._Maximum=function(){return(d_=u._Maximum=u.asm.ma).apply(null,arguments)},h_=u._Mean=function(){return(h_=u._Mean=u.asm.na).apply(null,arguments)},m_=u._Min=function(){return(m_=u._Min=u.asm.oa).apply(null,arguments)},f_=u._Minimum=function(){return(f_=u._Minimum=u.asm.pa).apply(null,arguments)},g_=u._Multiply=function(){return(g_=u._Multiply=u.asm.qa).apply(null,arguments)},y_=u._Neg=function(){return(y_=u._Neg=u.asm.ra).apply(null,arguments)},b_=u._NonMaxSuppressionV3=function(){return(b_=u._NonMaxSuppressionV3=u.asm.sa).apply(null,arguments)},x_=u._NonMaxSuppressionV4=function(){return(x_=u._NonMaxSuppressionV4=u.asm.ta).apply(null,arguments)},v_=u._NonMaxSuppressionV5=function(){return(v_=u._NonMaxSuppressionV5=u.asm.ua).apply(null,arguments)},w_=u._NotEqual=function(){return(w_=u._NotEqual=u.asm.va).apply(null,arguments)},k_=u._OneHot=function(){return(k_=u._OneHot=u.asm.wa).apply(null,arguments)},I_=u._PadV2=function(){return(I_=u._PadV2=u.asm.xa).apply(null,arguments)},T_=u._Pow=function(){return(T_=u._Pow=u.asm.ya).apply(null,arguments)},N_=u._Prelu=function(){return(N_=u._Prelu=u.asm.za).apply(null,arguments)},S_=u._Prod=function(){return(S_=u._Prod=u.asm.Aa).apply(null,arguments)},C_=u._RealDiv=function(){return(C_=u._RealDiv=u.asm.Ba).apply(null,arguments)},__=u._Relu=function(){return(__=u._Relu=u.asm.Ca).apply(null,arguments)},E_=u._Relu6=function(){return(E_=u._Relu6=u.asm.Da).apply(null,arguments)},F_=u._ResizeBilinear=function(){return(F_=u._ResizeBilinear=u.asm.Ea).apply(null,arguments)},A_=u._Reverse=function(){return(A_=u._Reverse=u.asm.Fa).apply(null,arguments)},$_=u._RotateWithOffset=function(){return($_=u._RotateWithOffset=u.asm.Ga).apply(null,arguments)},D_=u._Round=function(){return(D_=u._Round=u.asm.Ha).apply(null,arguments)},R_=u._Rsqrt=function(){return(R_=u._Rsqrt=u.asm.Ia).apply(null,arguments)},M_=u._ScatterNd=function(){return(M_=u._ScatterNd=u.asm.Ja).apply(null,arguments)},P_=u._SelectV2=function(){return(P_=u._SelectV2=u.asm.Ka).apply(null,arguments)},O_=u._Sigmoid=function(){return(O_=u._Sigmoid=u.asm.La).apply(null,arguments)},L_=u._Sin=function(){return(L_=u._Sin=u.asm.Ma).apply(null,arguments)},z_=u._Softmax=function(){return(z_=u._Softmax=u.asm.Na).apply(null,arguments)},B_=u._Sqrt=function(){return(B_=u._Sqrt=u.asm.Oa).apply(null,arguments)},W_=u._Square=function(){return(W_=u._Square=u.asm.Pa).apply(null,arguments)},V_=u._SquaredDifference=function(){return(V_=u._SquaredDifference=u.asm.Qa).apply(null,arguments)},U_=u._Step=function(){return(U_=u._Step=u.asm.Ra).apply(null,arguments)},G_=u._StridedSlice=function(){return(G_=u._StridedSlice=u.asm.Sa).apply(null,arguments)},H_=u._Sub=function(){return(H_=u._Sub=u.asm.Ta).apply(null,arguments)},j_=u._Sum=function(){return(j_=u._Sum=u.asm.Ua).apply(null,arguments)},q_=u._Tanh=function(){return(q_=u._Tanh=u.asm.Va).apply(null,arguments)},K_=u._Tile=function(){return(K_=u._Tile=u.asm.Wa).apply(null,arguments)},X_=u._TopK=function(){return(X_=u._TopK=u.asm.Xa).apply(null,arguments)},Y_=u._Transpose=function(){return(Y_=u._Transpose=u.asm.Ya).apply(null,arguments)},J_=u.__FusedMatMul=function(){return(J_=u.__FusedMatMul=u.asm.Za).apply(null,arguments)},_s=u._malloc=function(){return(_s=u._malloc=u.asm._a).apply(null,arguments)},Ku=u._free=function(){return(Ku=u._free=u.asm.$a).apply(null,arguments)},Uw=u.___errno_location=function(){return(Uw=u.___errno_location=u.asm.ab).apply(null,arguments)},Gw=u._emscripten_get_global_libc=function(){return(Gw=u._emscripten_get_global_libc=u.asm.bb).apply(null,arguments)},Co=u._pthread_self=function(){return(Co=u._pthread_self=u.asm.cb).apply(null,arguments)},Hw=u.___pthread_tsd_run_dtors=function(){return(Hw=u.___pthread_tsd_run_dtors=u.asm.db).apply(null,arguments)},Jg=u._emscripten_main_thread_process_queued_calls=function(){return(Jg=u._emscripten_main_thread_process_queued_calls=u.asm.eb).apply(null,arguments)},Q_=u._emscripten_current_thread_process_queued_calls=function(){return(Q_=u._emscripten_current_thread_process_queued_calls=u.asm.fb).apply(null,arguments)},jw=u._emscripten_register_main_browser_thread_id=function(){return(jw=u._emscripten_register_main_browser_thread_id=u.asm.gb).apply(null,arguments)},qw=u.__emscripten_do_dispatch_to_thread=function(){return(qw=u.__emscripten_do_dispatch_to_thread=u.asm.hb).apply(null,arguments)},Kw=u._emscripten_sync_run_in_main_thread_4=function(){return(Kw=u._emscripten_sync_run_in_main_thread_4=u.asm.ib).apply(null,arguments)},Xw=u._emscripten_run_in_main_runtime_thread_js=function(){return(Xw=u._emscripten_run_in_main_runtime_thread_js=u.asm.jb).apply(null,arguments)},Qg=u.__emscripten_call_on_thread=function(){return(Qg=u.__emscripten_call_on_thread=u.asm.kb).apply(null,arguments)},Z_=u._emscripten_tls_init=function(){return(Z_=u._emscripten_tls_init=u.asm.lb).apply(null,arguments)},gd=u.__emscripten_thread_init=function(){return(gd=u.__emscripten_thread_init=u.asm.mb).apply(null,arguments)},Xu=u.stackSave=function(){return(Xu=u.stackSave=u.asm.nb).apply(null,arguments)},_o=u.stackRestore=function(){return(_o=u.stackRestore=u.asm.ob).apply(null,arguments)},Eo=u.stackAlloc=function(){return(Eo=u.stackAlloc=u.asm.pb).apply(null,arguments)},Yw=u._emscripten_stack_set_limits=function(){return(Yw=u._emscripten_stack_set_limits=u.asm.qb).apply(null,arguments)},Jw=u._memalign=function(){return(Jw=u._memalign=u.asm.rb).apply(null,arguments)},Qw=u.__emscripten_allow_main_runtime_queued_calls=9880,Fo=u.__emscripten_main_thread_futex=11368;u.cwrap=_e,u.PThread=ke,u.PThread=ke,u.wasmMemory=Z,u.ExitStatus=Yu;var yd;function Yu(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}Ss=function I(){yd||Zg(),yd||(Ss=I)};function Zg(I){if(I=I||f,dr>0)return;if(T){p(u),postMessage({cmd:"loaded"});return}if(zf(),dr>0)return;function C(){yd||(yd=!0,u.calledRun=!0,!oe&&(Yp(),Bf(),p(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),In()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),C()},1)):C()}u.run=Zg;function eE(I,C){if(!(C&&ie&&I===0)){if(!C&&T)throw postMessage({cmd:"exitProcess",returnCode:I}),new Yu(I);ie||(ke.terminateAllThreads(),ge=I,Jp(),u.onExit&&u.onExit(I),oe=!0),y(I,new Yu(I))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return T&&(ie=!1,ke.initWorker()),Zg(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}),EE=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;s.ready=new Promise(function(K,ae){i=K,o=ae});var l={},c;for(c in s)s.hasOwnProperty(c)&&(l[c]=s[c]);var u=[],p="./this.program",d=function(K,ae){throw ae},h=!1,m=!1,f=!1,g=!1;h=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!f&&!m;var y="";function b(K){return s.locateFile?s.locateFile(K,y):y+K}var x,v,N,T,S,A;f?(m?y=Qu().dirname(y)+"/":y=__dirname+"/",x=function(K,ae){return S||(S=require("fs")),A||(A=Qu()),K=A.normalize(K),S.readFileSync(K,ae?null:"utf8")},N=function(K){var ae=x(K,!0);return ae.buffer||(ae=new Uint8Array(ae)),X(ae.buffer),ae},process.argv.length>1&&(p=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(K){if(!(K instanceof Yg))throw K}),process.on("unhandledRejection",Ia),d=function(K){process.exit(K)},s.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(K){return read(K)}),N=function(K){var ae;return typeof readbuffer=="function"?new Uint8Array(readbuffer(K)):(ae=read(K,"binary"),X(typeof ae=="object"),ae)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(d=function(K){quit(K)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||m)&&(m?y=self.location.href:typeof document!="undefined"&&document.currentScript&&(y=document.currentScript.src),a&&(y=a),y.indexOf("blob:")!==0?y=y.substr(0,y.lastIndexOf("/")+1):y="",x=function(K){var ae=new XMLHttpRequest;return ae.open("GET",K,!1),ae.send(null),ae.responseText},m&&(N=function(K){var ae=new XMLHttpRequest;return ae.open("GET",K,!1),ae.responseType="arraybuffer",ae.send(null),new Uint8Array(ae.response)}),v=function(K,ae,Ne){var Ye=new XMLHttpRequest;Ye.open("GET",K,!0),Ye.responseType="arraybuffer",Ye.onload=function(){if(Ye.status==200||Ye.status==0&&Ye.response){ae(Ye.response);return}Ne()},Ye.onerror=Ne,Ye.send(null)},T=function(K){document.title=K});var $=s.print||console.log.bind(console),R=s.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(s[c]=l[c]);l=null,s.arguments&&(u=s.arguments),s.thisProgram&&(p=s.thisProgram),s.quit&&(d=s.quit);var B;s.wasmBinary&&(B=s.wasmBinary);var V=s.noExitRuntime||!0;typeof WebAssembly!="object"&&Ia("no native wasm support detected");var W,G=!1,H;function X(K,ae){K||Ia("Assertion failed: "+ae)}function q(K){var ae=s["_"+K];return X(ae,"Cannot call unknown function "+K+", make sure it is exported"),ae}function te(K,ae,Ne,Ye,_t){var yt={string:function(Yn){var Wr=0;if(Yn!=null&&Yn!==0){var fd=(Yn.length<<2)+1;Wr=Hu(fd),de(Yn,Wr,fd)}return Wr},array:function(Yn){var Wr=Hu(Yn.length);return oe(Yn,Wr),Wr}};function Ue(Yn){return ae==="string"?ie(Yn):ae==="boolean"?Boolean(Yn):Yn}var He=q(K),nn=[],mr=0;if(Ye)for(var fr=0;fr<Ye.length;fr++){var md=yt[Ne[fr]];md?(mr===0&&(mr=dd()),nn[fr]=md(Ye[fr])):nn[fr]=Ye[fr]}var qu=He.apply(null,nn);return qu=Ue(qu),mr!==0&&hd(mr),qu}function Q(K,ae,Ne,Ye){Ne=Ne||[];var _t=Ne.every(function(Ue){return Ue==="number"}),yt=ae!=="string";return yt&&_t&&!Ye?q(K):function(){return te(K,ae,Ne,arguments,Ye)}}var se=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ne(K,ae,Ne){for(var Ye=ae+Ne,_t=ae;K[_t]&&!(_t>=Ye);)++_t;if(_t-ae>16&&K.subarray&&se)return se.decode(K.subarray(ae,_t));for(var yt="";ae<_t;){var Ue=K[ae++];if(!(Ue&128)){yt+=String.fromCharCode(Ue);continue}var He=K[ae++]&63;if((Ue&224)==192){yt+=String.fromCharCode((Ue&31)<<6|He);continue}var nn=K[ae++]&63;if((Ue&240)==224?Ue=(Ue&15)<<12|He<<6|nn:Ue=(Ue&7)<<18|He<<12|nn<<6|K[ae++]&63,Ue<65536)yt+=String.fromCharCode(Ue);else{var mr=Ue-65536;yt+=String.fromCharCode(55296|mr>>10,56320|mr&1023)}}return yt}function ie(K,ae){return K?ne(Te,K,ae):""}function Z(K,ae,Ne,Ye){if(!(Ye>0))return 0;for(var _t=Ne,yt=Ne+Ye-1,Ue=0;Ue<K.length;++Ue){var He=K.charCodeAt(Ue);if(He>=55296&&He<=57343){var nn=K.charCodeAt(++Ue);He=65536+((He&1023)<<10)|nn&1023}if(He<=127){if(Ne>=yt)break;ae[Ne++]=He}else if(He<=2047){if(Ne+1>=yt)break;ae[Ne++]=192|He>>6,ae[Ne++]=128|He&63}else if(He<=65535){if(Ne+2>=yt)break;ae[Ne++]=224|He>>12,ae[Ne++]=128|He>>6&63,ae[Ne++]=128|He&63}else{if(Ne+3>=yt)break;ae[Ne++]=240|He>>18,ae[Ne++]=128|He>>12&63,ae[Ne++]=128|He>>6&63,ae[Ne++]=128|He&63}}return ae[Ne]=0,Ne-_t}function de(K,ae,Ne){return Z(K,Te,ae,Ne)}function oe(K,ae){we.set(K,ae)}function ge(K,ae){return K%ae>0&&(K+=ae-K%ae),K}var fe,we,Te,_e,Re,Fe,nt,at,ot;function Xe(K){fe=K,s.HEAP8=we=new Int8Array(K),s.HEAP16=_e=new Int16Array(K),s.HEAP32=Fe=new Int32Array(K),s.HEAPU8=Te=new Uint8Array(K),s.HEAPU16=Re=new Uint16Array(K),s.HEAPU32=nt=new Uint32Array(K),s.HEAPF32=at=new Float32Array(K),s.HEAPF64=ot=new Float64Array(K)}var ft=s.INITIAL_MEMORY||16777216,Be,wn=[],It=[],Kn=[],en=[],kn=!1;It.push({func:function(){nd()}});function Xn(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)Wa(s.preRun.shift());Lr(wn)}function Rn(){kn=!0,Lr(It)}function cn(){Lr(Kn)}function tn(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)oa(s.postRun.shift());Lr(en)}function Wa(K){wn.unshift(K)}function oa(K){en.unshift(K)}var la=0,Pr=null,pr=null;function Or(K){la++,s.monitorRunDependencies&&s.monitorRunDependencies(la)}function wo(K){if(la--,s.monitorRunDependencies&&s.monitorRunDependencies(la),la==0&&(Pr!==null&&(clearInterval(Pr),Pr=null),pr)){var ae=pr;pr=null,ae()}}s.preloadedImages={},s.preloadedAudios={};function Ia(K){s.onAbort&&s.onAbort(K),K+="",R(K),G=!0,H=1,K="abort("+K+"). Build with -s ASSERTIONS=1 for more info.";var ae=new WebAssembly.RuntimeError(K);throw o(ae),ae}function Xp(K,ae){return String.prototype.startsWith?K.startsWith(ae):K.indexOf(ae)===0}var zf="data:application/octet-stream;base64,";function Yp(K){return Xp(K,zf)}var Bf="file://";function Jp(K){return Xp(K,Bf)}var In="tfjs-backend-wasm.wasm";Yp(In)||(In=b(In));function Qp(K){try{if(K==In&&B)return new Uint8Array(B);if(N)return N(K);throw"both async and sync fetching of the wasm failed"}catch(ae){Ia(ae)}}function Wf(){if(!B&&(h||m)){if(typeof fetch=="function"&&!Jp(In))return fetch(In,{credentials:"same-origin"}).then(function(K){if(!K.ok)throw"failed to load wasm binary file at '"+In+"'";return K.arrayBuffer()}).catch(function(){return Qp(In)});if(v)return new Promise(function(K,ae){v(In,function(Ne){K(new Uint8Array(Ne))},ae)})}return Promise.resolve().then(function(){return Qp(In)})}function dr(){var K={a:Tn};function ae(Ue,He){var nn=Ue.exports;s.asm=nn,W=s.asm.g,Xe(W.buffer),Be=s.asm.m,wo("wasm-instantiate")}Or("wasm-instantiate");function Ne(Ue){ae(Ue.instance)}function Ye(Ue){return Wf().then(function(He){return WebAssembly.instantiate(He,K)}).then(Ue,function(He){R("failed to asynchronously prepare wasm: "+He),Ia(He)})}function _t(){return!B&&typeof WebAssembly.instantiateStreaming=="function"&&!Yp(In)&&!Jp(In)&&typeof fetch=="function"?fetch(In,{credentials:"same-origin"}).then(function(Ue){var He=WebAssembly.instantiateStreaming(Ue,K);return He.then(Ne,function(nn){return R("wasm streaming compile failed: "+nn),R("falling back to ArrayBuffer instantiation"),Ye(Ne)})}):Ye(Ne)}if(s.instantiateWasm)try{var yt=s.instantiateWasm(K,ae);return yt}catch(Ue){return R("Module.instantiateWasm callback failed with error: "+Ue),!1}return _t().catch(o),{}}function Lr(K){for(;K.length>0;){var ae=K.shift();if(typeof ae=="function"){ae(s);continue}var Ne=ae.func;typeof Ne=="number"?ae.arg===void 0?Be.get(Ne)():Be.get(Ne)(ae.arg):Ne(ae.arg===void 0?null:ae.arg)}}function Ss(){Ia()}function Vf(K,ae,Ne){Te.copyWithin(K,ae,ae+Ne)}function Uf(){return Te.length}function hr(K){try{return W.grow(K-fe.byteLength+65535>>>16),Xe(W.buffer),1}catch(ae){}}function Zp(K){var ae=Uf(),Ne=2147483648;if(K>Ne)return!1;for(var Ye=1;Ye<=4;Ye*=2){var _t=ae*(1+.2/Ye);_t=Math.min(_t,K+100663296);var yt=Math.min(Ne,ge(Math.max(K,_t),65536)),Ue=hr(yt);if(Ue)return!0}return!1}var ko={mappings:{},buffers:[null,[],[]],printChar:function(K,ae){var Ne=ko.buffers[K];ae===0||ae===10?((K===1?$:R)(ne(Ne,0)),Ne.length=0):Ne.push(ae)},varargs:void 0,get:function(){ko.varargs+=4;var K=Fe[ko.varargs-4>>2];return K},getStr:function(K){var ae=ie(K);return ae},get64:function(K,ae){return K}};function ed(K){return 0}function Gf(K,ae,Ne,Ye,_t){}function td(K,ae,Ne,Ye){for(var _t=0,yt=0;yt<Ne;yt++){for(var Ue=Fe[ae+yt*8>>2],He=Fe[ae+(yt*8+4)>>2],nn=0;nn<He;nn++)ko.printChar(K,Te[Ue+nn]);_t+=He}return Fe[Ye>>2]=_t,0}var Tn={a:Ss,d:Vf,e:Zp,f:ed,c:Gf,b:td},Hf=dr(),nd=s.___wasm_call_ctors=function(){return(nd=s.___wasm_call_ctors=s.asm.h).apply(null,arguments)},jf=s._init=function(){return(jf=s._init=s.asm.i).apply(null,arguments)},ad=s._register_tensor=function(){return(ad=s._register_tensor=s.asm.j).apply(null,arguments)},qf=s._dispose_data=function(){return(qf=s._dispose_data=s.asm.k).apply(null,arguments)},Io=s._dispose=function(){return(Io=s._dispose=s.asm.l).apply(null,arguments)},To=s._Abs=function(){return(To=s._Abs=s.asm.n).apply(null,arguments)},Kf=s._Add=function(){return(Kf=s._Add=s.asm.o).apply(null,arguments)},Xf=s._AddN=function(){return(Xf=s._AddN=s.asm.p).apply(null,arguments)},Yf=s._ArgMax=function(){return(Yf=s._ArgMax=s.asm.q).apply(null,arguments)},ke=s._AvgPool=function(){return(ke=s._AvgPool=s.asm.r).apply(null,arguments)},Jf=s._BatchMatMul=function(){return(Jf=s._BatchMatMul=s.asm.s).apply(null,arguments)},Qf=s._Ceil=function(){return(Qf=s._Ceil=s.asm.t).apply(null,arguments)},Zf=s._ClipByValue=function(){return(Zf=s._ClipByValue=s.asm.u).apply(null,arguments)},eg=s._Conv2D=function(){return(eg=s._Conv2D=s.asm.v).apply(null,arguments)},tg=s._Conv2DBackpropInput=function(){return(tg=s._Conv2DBackpropInput=s.asm.w).apply(null,arguments)},Cs=s._Cos=function(){return(Cs=s._Cos=s.asm.x).apply(null,arguments)},ng=s._CropAndResize=function(){return(ng=s._CropAndResize=s.asm.y).apply(null,arguments)},ag=s._Cumsum=function(){return(ag=s._Cumsum=s.asm.z).apply(null,arguments)},rg=s._DepthToSpace=function(){return(rg=s._DepthToSpace=s.asm.A).apply(null,arguments)},sg=s._DepthwiseConv2dNative=function(){return(sg=s._DepthwiseConv2dNative=s.asm.B).apply(null,arguments)},ig=s._Equal=function(){return(ig=s._Equal=s.asm.C).apply(null,arguments)},og=s._Exp=function(){return(og=s._Exp=s.asm.D).apply(null,arguments)},lg=s._FlipLeftRight=function(){return(lg=s._FlipLeftRight=s.asm.E).apply(null,arguments)},ug=s._Floor=function(){return(ug=s._Floor=s.asm.F).apply(null,arguments)},cg=s._FloorDiv=function(){return(cg=s._FloorDiv=s.asm.G).apply(null,arguments)},zr=s._FusedBatchNorm=function(){return(zr=s._FusedBatchNorm=s.asm.H).apply(null,arguments)},Vu=s._FusedConv2D=function(){return(Vu=s._FusedConv2D=s.asm.I).apply(null,arguments)},Uu=s._FusedDepthwiseConv2D=function(){return(Uu=s._FusedDepthwiseConv2D=s.asm.J).apply(null,arguments)},pg=s._Gather=function(){return(pg=s._Gather=s.asm.K).apply(null,arguments)},dg=s._GatherNd=function(){return(dg=s._GatherNd=s.asm.L).apply(null,arguments)},hg=s._Greater=function(){return(hg=s._Greater=s.asm.M).apply(null,arguments)},mg=s._GreaterEqual=function(){return(mg=s._GreaterEqual=s.asm.N).apply(null,arguments)},fg=s._LeakyRelu=function(){return(fg=s._LeakyRelu=s.asm.O).apply(null,arguments)},Pe=s._Less=function(){return(Pe=s._Less=s.asm.P).apply(null,arguments)},gg=s._LessEqual=function(){return(gg=s._LessEqual=s.asm.Q).apply(null,arguments)},yg=s._Log=function(){return(yg=s._Log=s.asm.R).apply(null,arguments)},bg=s._LogicalAnd=function(){return(bg=s._LogicalAnd=s.asm.S).apply(null,arguments)},xg=s._Max=function(){return(xg=s._Max=s.asm.T).apply(null,arguments)},vg=s._MaxPool=function(){return(vg=s._MaxPool=s.asm.U).apply(null,arguments)},wg=s._Maximum=function(){return(wg=s._Maximum=s.asm.V).apply(null,arguments)},Gu=s._Mean=function(){return(Gu=s._Mean=s.asm.W).apply(null,arguments)},rd=s._Min=function(){return(rd=s._Min=s.asm.X).apply(null,arguments)},sd=s._Minimum=function(){return(sd=s._Minimum=s.asm.Y).apply(null,arguments)},kg=s._Multiply=function(){return(kg=s._Multiply=s.asm.Z).apply(null,arguments)},Ig=s._Neg=function(){return(Ig=s._Neg=s.asm._).apply(null,arguments)},Tg=s._NonMaxSuppressionV3=function(){return(Tg=s._NonMaxSuppressionV3=s.asm.$).apply(null,arguments)},Ng=s._NonMaxSuppressionV4=function(){return(Ng=s._NonMaxSuppressionV4=s.asm.aa).apply(null,arguments)},Sg=s._NonMaxSuppressionV5=function(){return(Sg=s._NonMaxSuppressionV5=s.asm.ba).apply(null,arguments)},Cg=s._NotEqual=function(){return(Cg=s._NotEqual=s.asm.ca).apply(null,arguments)},_g=s._OneHot=function(){return(_g=s._OneHot=s.asm.da).apply(null,arguments)},et=s._PadV2=function(){return(et=s._PadV2=s.asm.ea).apply(null,arguments)},Eg=s._Pow=function(){return(Eg=s._Pow=s.asm.fa).apply(null,arguments)},Fg=s._Prelu=function(){return(Fg=s._Prelu=s.asm.ga).apply(null,arguments)},Ag=s._Prod=function(){return(Ag=s._Prod=s.asm.ha).apply(null,arguments)},No=s._RealDiv=function(){return(No=s._RealDiv=s.asm.ia).apply(null,arguments)},id=s._Relu=function(){return(id=s._Relu=s.asm.ja).apply(null,arguments)},od=s._Relu6=function(){return(od=s._Relu6=s.asm.ka).apply(null,arguments)},ld=s._ResizeBilinear=function(){return(ld=s._ResizeBilinear=s.asm.la).apply(null,arguments)},$g=s._Reverse=function(){return($g=s._Reverse=s.asm.ma).apply(null,arguments)},Dg=s._RotateWithOffset=function(){return(Dg=s._RotateWithOffset=s.asm.na).apply(null,arguments)},ud=s._Round=function(){return(ud=s._Round=s.asm.oa).apply(null,arguments)},Rg=s._Rsqrt=function(){return(Rg=s._Rsqrt=s.asm.pa).apply(null,arguments)},cd=s._ScatterNd=function(){return(cd=s._ScatterNd=s.asm.qa).apply(null,arguments)},Br=s._SelectV2=function(){return(Br=s._SelectV2=s.asm.ra).apply(null,arguments)},Mg=s._Sigmoid=function(){return(Mg=s._Sigmoid=s.asm.sa).apply(null,arguments)},Pg=s._Sin=function(){return(Pg=s._Sin=s.asm.ta).apply(null,arguments)},Vw=s._Softmax=function(){return(Vw=s._Softmax=s.asm.ua).apply(null,arguments)},pd=s._Sqrt=function(){return(pd=s._Sqrt=s.asm.va).apply(null,arguments)},Og=s._Square=function(){return(Og=s._Square=s.asm.wa).apply(null,arguments)},Lg=s._SquaredDifference=function(){return(Lg=s._SquaredDifference=s.asm.xa).apply(null,arguments)},zg=s._Step=function(){return(zg=s._Step=s.asm.ya).apply(null,arguments)},Bg=s._StridedSlice=function(){return(Bg=s._StridedSlice=s.asm.za).apply(null,arguments)},Wg=s._Sub=function(){return(Wg=s._Sub=s.asm.Aa).apply(null,arguments)},Vg=s._Sum=function(){return(Vg=s._Sum=s.asm.Ba).apply(null,arguments)},Ug=s._Tanh=function(){return(Ug=s._Tanh=s.asm.Ca).apply(null,arguments)},Gg=s._Tile=function(){return(Gg=s._Tile=s.asm.Da).apply(null,arguments)},Hg=s._TopK=function(){return(Hg=s._TopK=s.asm.Ea).apply(null,arguments)},jg=s._Transpose=function(){return(jg=s._Transpose=s.asm.Fa).apply(null,arguments)},qg=s.__FusedMatMul=function(){return(qg=s.__FusedMatMul=s.asm.Ga).apply(null,arguments)},Kg=s._malloc=function(){return(Kg=s._malloc=s.asm.Ha).apply(null,arguments)},Xg=s._free=function(){return(Xg=s._free=s.asm.Ia).apply(null,arguments)},dd=s.stackSave=function(){return(dd=s.stackSave=s.asm.Ja).apply(null,arguments)},hd=s.stackRestore=function(){return(hd=s.stackRestore=s.asm.Ka).apply(null,arguments)},Hu=s.stackAlloc=function(){return(Hu=s.stackAlloc=s.asm.La).apply(null,arguments)};s.cwrap=Q;var So;function Yg(K){this.name="ExitStatus",this.message="Program terminated with exit("+K+")",this.status=K}pr=function K(){So||ju(),So||(pr=K)};function ju(K){if(K=K||u,la>0||(Xn(),la>0))return;function ae(){So||(So=!0,s.calledRun=!0,!G&&(Rn(),cn(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),tn()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),ae()},1)):ae()}if(s.run=ju,s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();return ju(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}),FE=1e-7,AE=1e-4,kd=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}},Zu=class{refCount(e){return ua("refCount")}incRef(e){return ua("incRef")}timerAvailable(){return!0}time(e){return ua("time")}read(e){return ua("read")}readSync(e){return ua("readSync")}numDataIds(){return ua("numDataIds")}disposeData(e,t){return ua("disposeData")}write(e,t,n){return ua("write")}move(e,t,n,a,r){return ua("move")}memory(){return ua("memory")}floatPrecision(){return ua("floatPrecision")}epsilon(){return this.floatPrecision()===32?FE:AE}dispose(){return ua("dispose")}};function ua(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 t0(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 $E(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,a,r,s=0;for(;n>0;)s=Math.random()*n|0,n--,a=e[n],r=t[n],e[n]=e[s],t[n]=t[s],e[s]=a,t[s]=r}function ec(e,t,n){return Math.max(e,Math.min(t,n))}function DE(e){return e%2==0?e:e+1}function RE(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function ME(e,t){let n=Math.random();return t*n+(1-n)*e}function PE(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 F(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function on(e,t,n=""){F(gr(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Es(e){F(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Fs(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||ln(e)&&!n)for(let a=0;a<e.length;++a)Fs(e[a],t,n);else t.push(e);return t}function Pt(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function OE(e){return e.length===0}function gr(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gt(e){return e%1==0}function LE(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 zE(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function BE(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return t0(t),t}function tc(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function WE(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 VE(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 ca(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),F(e.every(a=>a>=-n&&a<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),F(e.every(a=>Gt(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function n0(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:ca(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 a0(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 r0(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 s0(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 i0(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function UE(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 ey(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 o0(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 l0(e){return typeof e=="boolean"}function u0(e){return typeof e=="number"}function Id(e){return Array.isArray(e)?Id(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":u0(e)?"float32":Ur(e)?"string":l0(e)?"bool":"float32"}function Gr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Td(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Ro(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 c0(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]=c0(e+o*i,s,n)}return a}function Mo(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 c0(0,e,t)}function ty(e,t){let n=Nd(e,t);for(let a=0;a<n.length;a++)n[a]=1;return n}function Nd(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 GE(e,t){let n=e.reduce((a,r)=>a*r,1);if(t==null||t==="float32")return Mo(e,new Float32Array(n));if(t==="int32")return Mo(e,new Int32Array(n));if(t==="bool")return Mo(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ny(e){e.forEach(t=>{F(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function HE(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 jE(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 ay(e){return e&&e.then&&typeof e.then=="function"}var p0="tfjsflags",d0=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(ay(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=qE(this.global.location.search);p0 in e&&e[p0].split(",").forEach(t=>{let[n,a]=t.split(":");this.urlFlags[n]=KE(n,a)})}};function qE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(XE(t,a[0],a[1]),a.join("="))),t}function XE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function KE(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function ee(){return ry}var ry=null;function YE(e){ry=e}var sy;function h0(){if(sy==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");sy=e}return sy}function JE(){let e=h0();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function iy(e,t){let n=JE();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var Po="Abs",Oo="Acos",Lo="Acosh",Hr="Add",As="AddN",Sd="All",Cd="Any",$s="ArgMax",nc="ArgMin",zo="Asin",Bo="Asinh",Wo="Atan",Vo="Atanh",Uo="Atan2",Ds="AvgPool",_d="AvgPoolGrad",ac="AvgPool3D",Ed="AvgPool3DGrad",Rs="BatchMatMul",rc="BatchToSpaceND",Fd="Bincount",m0="BroadcastTo",Ms="Cast",Ps="Ceil",jr="ClipByValue",Ad="Complex",sc="ComplexAbs",Go="Concat",Os="Conv2D",$d="Conv2DBackpropFilter",Ls="Conv2DBackpropInput",ic="Conv3D",Dd="Conv3DBackpropFilterV2",Rd="Conv3DBackpropInputV2",zs="Cos",Ho="Cosh",Bs="Cumsum",jo="CropAndResize",Md="DenseBincount",qo="DepthToSpace",Ws="DepthwiseConv2dNative",Pd="DepthwiseConv2dNativeBackpropFilter",Od="DepthwiseConv2dNativeBackpropInput",Ld="Diag",oc="Dilation2D",zd="Dilation2DBackpropInput",Bd="Dilation2DBackpropFilter",Vs="RealDiv",Ko="Elu",Wd="EluGrad",Xo="Erf",Yo="Equal",Us="Exp",Jo="ExpandDims",Qo="Expm1",Vd="FFT",lc="Fill",Zo="FlipLeftRight",Gs="Floor",Hs="FloorDiv",js="FusedBatchNorm",el="GatherV2",tl="GatherNd",nl="Greater",qs="GreaterEqual",Ks="Identity",Ud="IFFT",Gd="Imag",al="IsFinite",rl="IsInf",sl="IsNan",Xs="LeakyRelu",il="Less",ol="LessEqual",Hd="LinSpace",Ys="Log",ll="Log1p",ul="LogicalAnd",uc="LogicalNot",cc="LogicalOr",f0="LogSoftmax",pc="LRN",jd="LRNGrad",Js="Max",Qs="Maximum",Zs="MaxPool",qd="MaxPoolGrad",dc="MaxPool3D",Kd="MaxPool3DGrad",Xd="MaxPoolWithArgmax",ei="Mean",ti="Min",ni="Minimum",hc="MirrorPad",cl="Mod",Yd="Multinomial",ai="Multiply",pl="Neg",dl="NotEqual",hl="NonMaxSuppressionV3",ml="NonMaxSuppressionV4",fl="NonMaxSuppressionV5",gl="OnesLike",ri="OneHot",yl="Pack",si="PadV2",QE="Pool",ii="Pow",oi="Prelu",bl="Prod",mc="Range",Jd="Real",xl="Reciprocal",li="Relu",vl="Reshape",fc="ResizeNearestNeighbor",Qd="ResizeNearestNeighborGrad",ui="ResizeBilinear",Zd="ResizeBilinearGrad",ci="Relu6",pi="Reverse",di="Round",hi="Rsqrt",wl="ScatterNd",kl="Select",Il="Selu",Tl="Slice",mi="Sin",Nl="Sinh",Sl="Sign",fi="Sigmoid",Cl="Softplus",gi="Sqrt",yi="Sum",gc="SpaceToBatchND",_l="SplitV",bi="Softmax",xi="SquaredDifference",yc="Square",vi="Sub",eh="SparseToDense",El="StridedSlice",Fl="Tan",wi="Tanh",qr="Tile",Al="TopK",ki="Transpose",th="Unique",$l="Unpack",bc="UnsortedSegmentSum",Dl="ZerosLike",Kr="Step",nh="FromPixels",Rl="RotateWithOffset",Ii="_FusedMatMul",Ti="FusedConv2D",Ni="FusedDepthwiseConv2D",Ml=iy("kernelRegistry",()=>new Map),xc=iy("gradRegistry",()=>new Map);function ah(e,t){let n=oy(e,t);return Ml.get(n)}function ly(e){return xc.get(e)}function rh(e){let t=Ml.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 vc(e){let{kernelName:t,backendName:n}=e,a=oy(t,n);Ml.has(a)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Ml.set(a,e)}function g0(e){let{kernelName:t}=e;xc.has(t)&&ee().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),xc.set(t,e)}function ZE(e,t){let n=oy(e,t);if(!Ml.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ml.delete(n)}function eF(e){if(!xc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);xc.delete(e)}function tF(e,t){rh(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});vc(a)})}function oy(e,t){return`${t}_${e}`}var w={};Oe(w,{arraysEqual:()=>gr,assert:()=>F,assertNonNegativeIntegerDimensions:()=>ny,assertNonNull:()=>Es,assertShapesMatch:()=>on,bytesFromStringArray:()=>o0,bytesPerElement:()=>ey,checkConversionForErrors:()=>s0,clamp:()=>ec,computeStrides:()=>Ro,createScalarValue:()=>nF,createShuffledIndices:()=>BE,decodeString:()=>ih,distSquared:()=>PE,encodeString:()=>kc,fetch:()=>aF,flatten:()=>Fs,getArrayFromDType:()=>r0,getTypedArrayFromDType:()=>a0,hasEncodingLoss:()=>UE,indexToLoc:()=>jE,inferDtype:()=>Id,inferFromImplicitShape:()=>VE,isBoolean:()=>l0,isFunction:()=>Gr,isInt:()=>Gt,isNumber:()=>u0,isPromise:()=>ay,isScalarShape:()=>OE,isString:()=>Ur,isTypedArray:()=>ln,isValidDtype:()=>i0,locToIndex:()=>HE,makeOnesTypedArray:()=>ty,makeZerosNestedTypedArray:()=>GE,makeZerosTypedArray:()=>Nd,nearestDivisor:()=>Td,nearestLargerEven:()=>DE,now:()=>wc,parseAxisParam:()=>ca,randUniform:()=>ME,repeatedTry:()=>WE,rightPad:()=>tc,shuffle:()=>t0,shuffleCombo:()=>$E,sizeFromShape:()=>Pt,sizeToSquarishShape:()=>zE,squeezeShape:()=>n0,sum:()=>RE,tanh:()=>LE,toNestedArray:()=>Mo,toTypedArray:()=>sh});function nF(e,t){return t==="string"?kc(e):sh([e],t)}function rF(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function sh(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Fs(e)),ee().getBool("DEBUG")&&s0(e,t),rF(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 wc(){return ee().platform.now()}function aF(e,t){return ee().platform.fetch(e,t)}function kc(e,t="utf-8"){return t=t||"utf-8",ee().platform.encode(e,t)}function ih(e,t="utf-8"){return t=t||"utf-8",ee().platform.decode(e,t)}var oF=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new iF)}profileKernel(e,t,n){let a,r=()=>{a=n()},s,i=wc();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:wc()-i})}if(ee().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<a.length;o++){let l=a[o];l.data().then(c=>{sF(c,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function sF(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 iF=class{logKernelProfile(e,t,n,a,r,s){let i=typeof a=="number"?tc(`${a}ms`,9):a.error,o=tc(e,25),l=t.rank,c=t.size,u=tc(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 lF(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 uF(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(!gr(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 y0=20,Ic=3,uy=7;function pF(e,t,n,a){let r=Ro(t),s=cF(e,t,n,r),i=t.length,o=oh(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 cF(e,t,n,a){let r=Pt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Nc(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],Tc(l[u+p],0,n).length)}return i}function Tc(e,t,n){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(uy))} + ${parseFloat(e[1].toFixed(uy))}j`:Ur(e)?a=`'${e}'`:n==="bool"?a=b0(e):a=parseFloat(e.toFixed(uy)).toString(),tc(a,t)}function b0(e){return e===0?"false":"true"}function oh(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=Nc(e);return[Tc(f[0],0,n)]}return n==="bool"?[b0(e[0])]:[e[0].toString()]}if(l===1){if(o>y0){let g=Ic*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o-Ic)*i,o*i));return n==="complex64"&&(y=Nc(y),b=Nc(b)),["["+y.map((x,v)=>Tc(x,r[v],n)).join(", ")+", ..., "+b.map((x,v)=>Tc(x,r[o-Ic+v],n)).join(", ")+"]"]}let f=n==="complex64"?Nc(e):Array.from(e);return["["+f.map((g,y)=>Tc(g,r[y],n)).join(", ")+"]"]}let c=t.slice(1),u=a.slice(1),p=a[0]*i,d=[];if(o>y0){for(let f=0;f<Ic;f++){let g=f*p,y=g+p;d.push(...oh(e.slice(g,y),c,n,u,r,!1))}d.push("...");for(let f=o-Ic;f<o;f++){let g=f*p,y=g+p;d.push(...oh(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(...oh(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 Nc(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ot=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Pt(e),n!=null){let a=n.length;F(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||r0(t,this.size),this.strides=Ro(e)}set(e,...t){t.length===0&&(t=[0]),F(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Va().makeTensor(this.values,this.shape,this.dtype)}},Va=null,Pl=null,dF=null;function hF(e){Va=e}function mF(e){Pl=e}function fF(e){dF=e}var Ee=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Pt(e),this.strides=Ro(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 Pl.buffer(this.shape,this.dtype,e)}bufferSync(){return Pl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Mo(this.shape,e)}arraySync(){return Mo(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Va().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>ih(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Va().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>ih(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Va().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Va().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Pl.print(this,e)}clone(){return this.throwIfDisposed(),Pl.clone(this)}toString(e=!1){let t=this.dataSync();return pF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Pl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Va().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Y(){return iy("Tensor",()=>Ee)}Y();var Xr=class extends Ee{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(!gr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Va().disposeTensor(this),this.dataId=e.dataId,Va().incRef(this,null)}dispose(){Va().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Xr,Symbol.hasInstance,{value:e=>e instanceof Ee&&e.assign!=null&&e.assign instanceof Function});var Ta={};Oe(Ta,{assertTypesMatch:()=>x0,getTensorsInContainer:()=>cy,isTensorInList:()=>gF,makeTypesMatch:()=>Tt});var py;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(py||(py={}));var dy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(dy||(dy={}));var hy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(hy||(hy={}));var my;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(my||(my={}));var fy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(fy||(fy={}));var yF={float32:my,int32:dy,bool:hy,complex64:fy};function pa(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return yF[e][t]}function lh(e){return pa(e,"int32")}function Tt(e,t){if(e.dtype===t.dtype)return[e,t];let n=pa(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function x0(e,t){F(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function gF(e,t){return t.some(n=>n.id===e.id)}function cy(e){let t=[],n=new Set;return v0(e,t,n),t}function v0(e,t,n){if(e==null)return;if(e instanceof Ee){t.push(e);return}if(!bF(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),v0(s,t,n))}}function bF(e){return Array.isArray(e)||typeof e=="object"}function gy(e){return e.kernelName!=null}var w0=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()}},Sc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new w0}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 oF(this.backendInstance),!0}setupRegisteredKernels(){rh(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){rh(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 Zu)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(a<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(s.stack||s.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:a,asyncInit:r}=this.initializeBackend(n);if(r||a)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),a=n.backend,r=this.readSync(t),s=a.refCount(t);a.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let a;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,n){e();try{let a=n();return t(),a}catch(a){throw t(),a}}nextTensorId(){return Sc.nextTensorId++}nextVariableId(){return Sc.nextVariableId++}clone(e){let t=M.runKernel(Ks,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return M.runKernel(Ms,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(ah(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let a=this.backend.numDataIds(),r=0;n.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],a=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=gy(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(gy(e)){let{kernelName:h,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=ah(h,this.backendName);F(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let b=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,b);let x=b.map(v=>{if(v.rank!=null)return v;let{dataId:N,shape:T,dtype:S}=v;return this.makeTensorFromDataId(N,T,S)});if(a){let v=this.getTensorsForGradient(h,m,x);n=this.saveTensorsForBackwardMode(v)}return x}}else{let{forwardFunc:h}=e,m=f=>{!a||(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>h(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:c,attrs:u}=e,p=gy(e)?null:e.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(d=this.profiler.profileKernel(l,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs)}),a&&this.addTapeNode(l,c,t,p,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=ly(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(F(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=n.filter((l,c)=>s[c]);return i.concat(o)}return[]}makeTensor(e,t,n,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let r=e;n==="string"&&Ur(e[0])&&(r=e.map(o=>kc(o)));let s=a.write(r,t,n),i=new Ee(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=o0(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r=new Ee(t,n,e,this.nextTensorId());return this.trackTensor(r,a),r}makeVariable(e,t=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let r=new 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}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*ey(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Xr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*ey(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,a,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=ly(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((c,u)=>{if(c==null){let p=n[u],d=Nd(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=cy(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(F(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));F(r instanceof Ee,()=>"The result y returned by f() must be a tensor.");let s=lF(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?xF(r.shape):n,uF(i,s,l=>this.tidy(l),vF);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 F(Gr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{F(t.every(i=>i instanceof Ee),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};t.forEach((i,o)=>{a[o]=i});let r=(i,o)=>(n=e(...t,o),F(n.value instanceof Ee,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),F(Gr(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s=(i,o)=>{let l=n.gradFunc(i,o),c=Array.isArray(l)?l:[l];F(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),F(c.every(p=>p instanceof Ee),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((p,d)=>{u[d]=()=>p}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=wc(),n=await this.backend.time(e);return n.wallMs=wc()-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 w0;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}};Sc.nextTensorId=0;Sc.nextVariableId=0;function xF(e){let t=ty(Pt(e),"float32");return M.makeTensor(t,e,"float32")}function k0(){let e=h0();if(e._tfengine==null){let t=new d0(e);e._tfengine=new Sc(t)}return YE(e._tfengine.ENV),hF(()=>e._tfengine),e._tfengine}var M=k0();function vF(e,t){let n={a:e,b:t};return M.runKernel(Hr,n)}var uh={};Oe(uh,{isBrowser:()=>I0,isMobile:()=>wF});function kF(){return typeof navigator!="undefined"&&navigator!=null}function wF(){if(kF()){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 I0(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Ua=ee();Ua.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Ua.registerFlag("IS_BROWSER",()=>I0());Ua.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Ua.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Ua.registerFlag("PROD",()=>!1);Ua.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ua.getBool("DEBUG"));Ua.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Ua.registerFlag("IS_TEST",()=>!1);Ua.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);function Ga(e,t){let n=e;if(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)&&ee().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&T0(e,a,[]),a}function T0(e,t,n){if(n=n||[],!Array.isArray(e)&&!ln(e)){F(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}F(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),F(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)T0(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(e,t,n,a="numeric"){if(e instanceof Ee)return N0(a,e.dtype,t,n),e;let r=Id(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=Ga(e,r);!ln(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?sh(e,r):Fs(e,[],!0);return M.makeTensor(i,s,r)}function Cc(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>E(r,`${t}[${s}]`,n,a))}var S0="__op";function P(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+S0;let r=(...s)=>{M.startScope(n);try{let i=a(...s);return ay(i)&&console.error("Cannot return a Promise inside of tidy."),M.endScope(i),i}catch(i){throw M.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function IF(e,t){let n=E(e,"real","complex"),a=E(t,"imag","complex");on(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return M.runKernel(Ad,r)}var Yr=P({complex_:IF});function Jr(e,t,n,a){if(a==null&&(a=Id(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){ny(t);let r=Pt(t),s=Pt(n);F(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i<n.length;++i){let o=n[i],l=i===n.length-1?o!==Pt(t.slice(i)):!0;F(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"?sh(e,a):Fs(e,[],!0),M.makeTensor(e,t,a)}function Jn(e,t,n){let a=Ga(e,n);return Jr(e,t,a,n)}var yy={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},ch=4;async function NF(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)+ch*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+=ch,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:TF(s),specs:n}}function C0(e,t){let n={},a,r=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,c=Pt(l),u;if("quantization"in s){let p=s.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let d=yy[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=SF()),u=a(m);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(o==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);u=new Int32Array(m.length);for(let f=0;f<m.length;f++){let g=m[f];u[f]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=c*d}else if(o==="string"){let p=Pt(s.shape);u=[];for(let d=0;d<p;d++){let h=new Uint32Array(e.slice(r,r+ch))[0];r+=ch;let m=new Uint8Array(e.slice(r,r+h));u.push(m),r+=h}}else{let p=yy[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=Jn(h,l,"float32"),g=Jn(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]=Jn(u,l,o))}return n}function TF(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 by=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function _0(e){return by?Buffer.byteLength(e):new Blob([e]).size}function CF(e){if(by)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 _F(e){if(by){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 xy(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 E0(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 _c(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:_0(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:_0(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function EF(){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 FF(){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 AF(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function SF(){let e=EF(),t=FF(),n=AF();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i<a.length;i++){let o=a[i],l=e[n[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var Et=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Et.instance==null&&(Et.instance=new Et),Et.instance}static registerSaveRouter(e){Et.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Et.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Et.getHandlers(e,"save")}static getLoadHandlers(e,t){return Et.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?Et.getInstance().loadRouters:Et.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},$F=e=>Et.registerSaveRouter(e),DF=e=>Et.registerLoadRouter(e),RF=e=>Et.getSaveHandlers(e),MF=(e,t)=>Et.getLoadHandlers(e,t),vy="tensorflowjs",wy=1,Si="models_store",Qr="model_info_store";function F0(){if(!ee().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ky(e){let t=e.result;t.createObjectStore(Si,{keyPath:"modelPath"}),t.createObjectStore(Qr,{keyPath:"modelPath"})}var Ci=class{constructor(e){if(this.indexedDB=F0(),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(vy,wy);r.onupgradeneeded=()=>ky(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(Si,"readonly"),o=i.objectStore(Si).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=_c(t),o=s.transaction(Qr,"readwrite"),l=o.objectStore(Qr),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),u;c.onsuccess=()=>{u=s.transaction(Si,"readwrite");let p=u.objectStore(Si).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});p.onsuccess=()=>n({modelArtifactsInfo:i}),p.onerror=d=>{l=o.objectStore(Qr);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)})}};Ci.URL_SCHEME="indexeddb://";var A0=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ci.URL_SCHEME)?PF(e.slice(Ci.URL_SCHEME.length)):null;Et.registerSaveRouter(A0);Et.registerLoadRouter(A0);function PF(e){return new Ci(e)}function OF(e){return e.startsWith(Ci.URL_SCHEME)?e.slice(Ci.URL_SCHEME.length):e}var LF=class{constructor(){this.indexedDB=F0()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(vy,wy);n.onupgradeneeded=()=>ky(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(Qr,"readonly"),s=r.objectStore(Qr).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=OF(e),new Promise((t,n)=>{let a=this.indexedDB.open(vy,wy);a.onupgradeneeded=()=>ky(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(Qr,"readwrite"),i=s.objectStore(Qr),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(Si,"readwrite");let p=l.objectStore(Si).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)})}},yr="/",Ol="tensorflowjs_models",$0="info",zF="model_topology",BF="weight_specs",WF="weight_data",VF="model_metadata";function D0(e){return{info:[Ol,e,$0].join(yr),topology:[Ol,e,zF].join(yr),weightSpecs:[Ol,e,BF].join(yr),weightData:[Ol,e,WF].join(yr),modelMetadata:[Ol,e,VF].join(yr)}}function UF(e){let t=e.split(yr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(yr)}function GF(e){return e.startsWith(_i.URL_SCHEME)?e.slice(_i.URL_SCHEME.length):e}var _i=class{constructor(e){if(!ee().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=D0(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=_c(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,CF(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=_F(s),t}};_i.URL_SCHEME="localstorage://";var R0=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(_i.URL_SCHEME)?HF(e.slice(_i.URL_SCHEME.length)):null;Et.registerSaveRouter(R0);Et.registerLoadRouter(R0);function HF(e){return new _i(e)}var jF=class{constructor(){F(ee().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),F(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Ol+yr,n=yr+$0;for(let a=0;a<this.LS.length;++a){let r=this.LS.key(a);if(r.startsWith(t)&&r.endsWith(n)){let s=UF(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=GF(e);let t=D0(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}},Ll="://",Qn=class{constructor(){this.managers={}}static getInstance(){return Qn.instance==null&&(Qn.instance=new Qn),Qn.instance}static registerManager(e,t){F(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Ll)&&(e=e.slice(0,e.indexOf(Ll))),F(e.length>0,()=>"scheme must not be an empty string.");let n=Qn.getInstance();F(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 ph(e){if(e.indexOf(Ll)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Qn.getSchemes().join(",")}`);return{scheme:e.split(Ll)[0],path:e.split(Ll)[1]}}async function M0(e,t,n=!1){F(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=Et.getLoadHandlers(e);F(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),F(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=Et.getSaveHandlers(t);F(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),F(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=ph(e).scheme,l=ph(e).path,c=o===ph(e).scheme,u=await r.load();n&&c&&await Qn.getManager(o).removeModel(l);let p=await i.save(u);return n&&!c&&await Qn.getManager(o).removeModel(l),p.modelArtifactsInfo}async function qF(){let e=Qn.getSchemes(),t={};for(let n of e){let a=await Qn.getManager(n).listModels();for(let r in a){let s=n+Ll+r;t[s]=a[r]}}return t}async function KF(e){let t=ph(e);return Qn.getManager(t.scheme).removeModel(t.path)}async function XF(e,t){return M0(e,t,!1)}async function YF(e,t){return M0(e,t,!0)}var JF=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(ee().get("IS_BROWSER")){ee().setPlatform("browser",new JF);try{Qn.registerManager(_i.URL_SCHEME,new jF)}catch(e){}try{Qn.registerManager(Ci.URL_SCHEME,new LF)}catch(e){}}var QF={importFetch:()=>gE()},Iy,ZF=class{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return ee().global.fetch!=null?ee().global.fetch(e,t):(Iy==null&&(Iy=QF.importFetch()),Iy(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};ee().get("IS_NODE")&&ee().setPlatform("node",new ZF);function Le(e,t="float32",n){return t=t||"float32",ny(e),new Ot(e,t,n)}function eA(e,t){let n=E(e,"x","cast");if(!i0(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let a={x:n},r={dtype:t};return M.runKernel(Ms,a,r)}var ue=P({cast_:eA});function tA(e){let t={x:E(e,"x","clone","string_or_numeric")};return M.runKernel(Ks,t)}var Zr=P({clone_:tA});function P0(e,t=!1){console.log(e.toString(t))}k0();var nA={buffer:Le,cast:ue,clone:Zr,print:P0};mF(nA);var Ht={};Oe(Ht,{browserFiles:()=>aA,browserHTTPRequest:()=>sA,concatenateArrayBuffers:()=>xy,copyModel:()=>XF,decodeWeights:()=>C0,encodeWeights:()=>NF,fromMemory:()=>iA,getLoadHandlers:()=>MF,getModelArtifactsInfoForJSON:()=>_c,getSaveHandlers:()=>RF,http:()=>Ny,isHTTPScheme:()=>Ty,listModels:()=>qF,loadWeights:()=>rA,moveModel:()=>YF,registerLoadRouter:()=>DF,registerSaveRouter:()=>$F,removeModel:()=>KF,weightsLoaderFactory:()=>O0,withSaveHandler:()=>oA});var lA="model",uA=".json",cA=".weights.bin";function L0(e){return new Promise(t=>setTimeout(t)).then(e)}var zl=class{constructor(e){if(!ee().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(zl.URL_SCHEME)&&(e=e.slice(zl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=lA),this.modelTopologyFileName=e+uA,this.weightDataFileName=e+cA}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 L0(()=>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 L0(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:_c(e)}}}};zl.URL_SCHEME="downloads://";var pA=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 x={modelTopology:o,weightSpecs:u,weightData:xy(d),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(x.signature=i.signature),i.userDefinedMetadata!=null&&(x.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(x.modelInitializer=i.modelInitializer),n(x)}},f.onerror=g=>a(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(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=>E0(s.name)),r={};for(let s of e)s.paths.forEach(i=>{let o=E0(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}},hA=e=>ee().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zl.URL_SCHEME)?dA(e.slice(zl.URL_SCHEME.length)):null;Et.registerSaveRouter(hA);function dA(e="model"){return new zl(e)}function aA(e){return new pA(e)}function z0(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){F(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,c){F(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),F(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),F(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(s))}async function B0(e,t){t==null&&(t={});let n=t.fetchFunc==null?ee().platform.fetch:t.fetchFunc,a=e.map(c=>n(c,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await z0(a,t.onProgress,r,s)).map(c=>c.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await z0(i,t.onProgress,o,l)}async function rA(e,t="",n,a){return O0(r=>B0(r,{requestInit:a}))(e,t,n)}function O0(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=yy[y]*Pt(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:b})};a!=null?a.forEach((v,N)=>{v===g.name&&(x(),i[N]=!0)}):x(),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 x=0;x<m;x++)f+=u[d+x].byteLength;let g=new ArrayBuffer(f),y=new Uint8Array(g),b=0;for(let x=0;x<m;x++){let v=new Uint8Array(u[d+x]);y.set(v,b),b+=v.byteLength}s[h].forEach(x=>{let v=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),N=C0(v,[x.manifestEntry]);for(let T in N)p[T]=N[T]}),d+=m}),p}}var mA="application/octet-stream",fA="application/json",Sy=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?(F(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=ee().platform.fetch,F(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&F(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:fA}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:mA}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:_c(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]=gA(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 B0(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,xy(l)]}};Sy.URL_SCHEME_REGEX=/^https?:\/\//;function gA(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function Ty(e){return e.match(Sy.URL_SCHEME_REGEX)!=null}var W0=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>Ty(a)):n=Ty(e),n)return Ny(e,t)}return null};Et.registerSaveRouter(W0);Et.registerLoadRouter(W0);function Ny(e,t){return new Sy(e,t)}function sA(e,t){return Ny(e,t)}var Cy=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},yA=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function iA(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Cy(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 Cy({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 Cy({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function oA(e){return new yA(e)}var V0={};Oe(V0,{confusionMatrix:()=>bA});function xA(e,t,n=!1,a=!1){let r=E(e,"a","matMul"),s=E(t,"b","matMul");[r,s]=Tt(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return M.runKernel(Rs,i,o)}var ze=P({matMul_:xA});function vA(e,t,n=1,a=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let r={indices:E(e,"indices","oneHot","int32")},s={depth:t,onValue:n,offValue:a};return M.runKernel(ri,r,s)}var Bl=P({oneHot_:vA});function wA(e,t){let n=E(e,"x","transpose");if(t==null&&(t=n.shape.map((s,i)=>i).reverse()),F(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(s=>{F(s>=0&&s<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let a={x:n},r={perm:t};return M.runKernel(ki,a,r)}var Ve=P({transpose_:wA});function kA(e,t,n){let a=E(e,"labels","confusionMatrix"),r=E(t,"predictions","confusionMatrix");F(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),F(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),F(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),F(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.`),F(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=Bl(ue(a,"int32"),n),i=Bl(ue(r,"int32"),n),o=Ve(s),l=ze(o,i);return ue(l,"int32")}var bA=P({confusionMatrix_:kA}),Ei={};Oe(Ei,{fromPixels:()=>TA,toPixels:()=>IA});function dh(e,t,n){if(Es(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=Ga(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Jr(e,t,a,n)}var Wl;function NA(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(ah(nh,M.backendName)!=null){let d={pixels:e},h={numChannels:t};return M.runKernel(nh,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)&&(Wl==null&&(Wl=document.createElement("canvas").getContext("2d")),Wl.canvas.width=l,Wl.canvas.height=c,Wl.drawImage(e,0,0,l,c),u=Wl.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 dh(p,[c,l,t],"int32")}async function IA(e,t){let n=E(e,"img","toPixels");if(!(e instanceof Ee)){let c=n;n=ue(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 TA=P({fromPixels_:NA}),_y={};Oe(_y,{prepareAndValidate:()=>U0});function U0(e,t){let n=e.shape.length,a=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(Pt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let p=0;p<r.length-1;++p)i*=r[p];let o=e.shape,l=r.slice();l.pop();let c=1;for(let p=s;p<n;++p)c*=o[p],l.push(o[p]);let u=[...Ro(e.shape).map(p=>p/c),1].slice(0,s);return[l,i,c,u]}var Ey={};Oe(Ey,{calculateShapes:()=>G0,validateInput:()=>Ay,validateUpdateShape:()=>Fy});function Fy(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 Ay(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}`)}Fy(n,t,e)}function G0(e,t,n){let a=t.shape.length,r=a>1?t.shape[a-1]:1,s=n.length,i=1;for(let p=r;p<s;++p)i*=n[p];let o=r<1?1:r,l=Pt(t.shape)/o,c=[...Ro(n.slice(0,r)),1],u=Pt(n);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:c,outputSize:u}}var dn={};Oe(dn,{assertParamsValid:()=>SA,computeFlatOffset:()=>_A,computeOutShape:()=>H0,getNormalizedAxes:()=>q0,isSliceContinous:()=>CA,maskToAxes:()=>hh,parseSliceParams:()=>Z0,sliceInfo:()=>EA,startForAxis:()=>J0,startIndicesWithElidedDims:()=>K0,stopForAxis:()=>Q0,stopIndicesWithElidedDims:()=>X0,stridesForAxis:()=>Y0,stridesWithElidedDims:()=>j0});function SA(e,t,n){let a=e.shape.length;F(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),F(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)F(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 hh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function H0(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 j0(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 ek(e,t,n){return n<=e?n:n-(t-1)}function tk(e,t){let n=[];for(let a=0;a<e;a++)n.push(t+a);return n}function q0(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=K0(i,h,m,a,e),p=X0(o,h,m,r,e),d=j0(s,h,m,e)}else for(let h=0;h<c;h++)u[h]=J0(i,a,s,e,h,l),p[h]=Q0(o,r,s,e,h,l),d[h]=Y0(s,h,l);return{begin:u,end:p,strides:d}}function K0(e,t,n,a,r){let s=[...r],i=tk(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=ek(t,n,o),c=a[l];e&1<<l&&(c=0),s[o]=c}return s}function X0(e,t,n,a,r){let s=[...r],i=tk(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=ek(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]=ec(0,s[o],r[o])}return s}function Y0(e,t,n){let a=e[t];return(n&1<<t||a==null)&&(a=1),a}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.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=ec(0,i,l-1),i}function Q0(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=ec(0,i,l):i=ec(-1,i,l-1),i}function CA(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 _A(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=>{F(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:(F(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 EA(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=hh(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=hh(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}=q0(f,d,h,c,u,p,r,s,i);c=g,u=y,p=b;let x=hh(l);x.forEach(T=>{u[T]=c[T]+1,p[T]=1});let v=H0(c,u,p),N=v.filter((T,S)=>x.indexOf(S)===-1);return{nonStrided:p.every(T=>T===1),$begin:c,$end:u,$strides:p,size:v,newShape:f,outShape:N}}var re={};Oe(re,{Serializable:()=>nk,SerializationMap:()=>Fi,registerClass:()=>es});var nk=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){F(e.className!=null,()=>"Class being registered does not have the static className property defined."),F(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),F(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Fi.register(e)}var ak={};Oe(ak,{TEST_EPSILON_FLOAT16:()=>rk,encodeStrings:()=>sk,expectArrayBuffersEqual:()=>MA,expectArraysClose:()=>FA,expectArraysEqual:()=>$A,expectNumbersClose:()=>DA,expectPromiseToFail:()=>AA,expectValuesInRange:()=>RA,testEpsilon:()=>$y});var PA=.001,rk=.1;function FA(e,t,n){return n==null&&(n=$y()),Dy(e,t,(a,r)=>Ry(a,r,n))}function $y(){return M.backend.floatPrecision()===32?PA:rk}function Dy(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=Ga(e),o=Ga(t);if(!gr(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=ln(e)?e:Fs(e),s=ln(t)?t:Fs(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 AA(e,t){e().then(()=>t.fail(),()=>t())}function $A(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])?Dy(e,n,(a,r)=>a==r):Dy(e,t,(a,r)=>Ry(a,r,0))}function DA(e,t,n){if(n==null&&(n=$y()),!Ry(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ry(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function RA(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 MA(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function sk(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?sk(n):e[t]=kc(n)}return e}var ik="3.2.0";function OA(){ee().set("PROD",!0)}function LA(){ee().set("DEBUG",!0)}function zA(){ee().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function My(e){ee().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}fF(My);function BA(){M.disposeVariables()}function Ha(){return M}function mh(){return M.memory()}function WA(e){return M.profile(e)}function D(e,t){return M.tidy(e,t)}function Ae(e){cy(e).forEach(t=>t.dispose())}function jt(e){return M.keep(e)}function VA(e){return M.time(e)}function UA(e){return M.setBackend(e)}function GA(){return M.ready()}function HA(){return M.backendName}function jA(e){M.removeBackend(e)}function qA(e){return M.findBackend(e)}function KA(e){return M.findBackendFactory(e)}function fh(e,t,n=1){return M.registerBackend(e,t,n)}function ok(){return M.backend}function XA(e,t){ee().setPlatform(e,t)}function YA(e,t){let n=E(e,"a","add"),a=E(t,"b","add");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(Hr,r)}var J=P({add_:YA});function JA(e,t){let n=E(e,"a","floorDiv"),a=E(t,"b","floorDiv");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(Hs,r)}var gh=P({floorDiv_:JA});function QA(e,t){let n=E(e,"a","div"),a=E(t,"b","div");if([n,a]=Tt(n,a),n.dtype==="int32"&&a.dtype==="int32")return gh(n,a);let r={a:n,b:a},s={};return M.runKernel(Vs,r,s)}var xe=P({div_:QA});function ZA(e,t){let n=E(e,"a","mul"),a=E(t,"b","mul");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(ai,r)}var L=P({mul_:ZA});function e$(e){let t=E(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return M.runKernel(sc,n)}else{let n={x:t};return M.runKernel(Po,n)}}var Lt=P({abs_:e$});function t$(e){let t={x:E(e,"x","acos")};return M.runKernel(Oo,t)}var Py=P({acos_:t$});function n$(e){let t={x:E(e,"x","acosh")};return M.runKernel(Lo,t)}var Oy=P({acosh_:n$});function a$(e){F(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),F(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>E(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!gr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return M.runKernel(As,a)}var lk=P({addN_:a$});function r$(e,t=null,n=!1){let a={x:E(e,"x","all","bool")},r={axis:t,keepDims:n};return M.runKernel(Sd,a,r)}var yh=P({all_:r$});function s$(e,t=null,n=!1){let a={x:E(e,"x","any","bool")},r={axis:t,keepDims:n};return M.runKernel(Cd,a,r)}var Ec=P({any_:s$});function i$(e,t=0){let n={x:E(e,"x","argMax")},a={axis:t};return M.runKernel($s,n,a)}var Fc=P({argMax_:i$});function o$(e,t=0){let n={x:E(e,"x","argMin")},a={axis:t};return M.runKernel(nc,n,a)}var Ly=P({argMin_:o$});function l$(e){let t={x:E(e,"x","asin")};return M.runKernel(zo,t)}var zy=P({asin_:l$});function u$(e){let t={x:E(e,"x","asinh")};return M.runKernel(Bo,t)}var By=P({asinh_:u$});function c$(e){let t={x:E(e,"x","atan")};return M.runKernel(Wo,t)}var Wy=P({atan_:c$});function p$(e,t){let n=E(e,"a","atan2"),a=E(t,"b","atan2");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(Uo,r)}var Vy=P({atan2_:p$});function d$(e){let t={x:E(e,"x","atanh")};return M.runKernel(Vo,t)}var Uy=P({atanh_:d$});function h$(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=uk(r);return Ac(e,o,n,s,a,null,null,l)}function ck(e,t,n,a,r,s,i="channelsLast"){let[o,l]=bh(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 Ac(e,c,n,a,r,s,!1,i)}function m$(e,t,n,a,r,s,i="NDHWC"){let[o,l,c]=Gy(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 pk(e,u,n,a,r,!1,p,s)}function Ac(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]=bh(n),[y,b]=bh(a),x=Vl(d,y),v=Vl(h,b),{padInfo:N,outHeight:T,outWidth:S}=f$(r,c,u,f,g,x,v,s,o),A=i?m*p:m,$;return o==="channelsFirst"?$=[l,A,T,S]:o==="channelsLast"&&($=[l,T,S,A]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:p,outHeight:T,outWidth:S,outChannels:A,padInfo:N,strideHeight:f,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:b,inShape:e,outShape:$,filterShape:t}}function pk(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,x]=Gy(n),[v,N,T]=Gy(a),S=Vl(h,v),A=Vl(m,N),$=Vl(f,T),{padInfo:R,outDepth:B,outHeight:V,outWidth:W}=g$(r,c,u,p,y,b,x,S,A,$,o),G=s?g*d:g,H;return i==="channelsFirst"?H=[l,G,B,V,W]:i==="channelsLast"&&(H=[l,B,V,W,G]),{batchSize:l,dataFormat:i,inDepth:c,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:V,outWidth:W,outChannels:G,padInfo:R,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:S,effectiveFilterHeight:A,effectiveFilterWidth:$,dilationDepth:v,dilationHeight:N,dilationWidth:T,inShape:e,outShape:H,filterShape:t}}function y$(e,t,n,a,r){a==null&&(a=Hy(e,t,n));let s=e[0],i=e[1],o=Ai((s-t+2*a)/n+1,r),l=Ai((i-t+2*a)/n+1,r);return[o,l]}function b$(e,t,n,a,r,s){r==null&&(r=Hy(e,t,a));let i=e[0],o=e[1],l=e[2],c=Ai((i-t+2*r)/a+1,s),u=Ai((o-t+2*r)/a+1,s),p=Ai((l-t+2*r)/a+1,s);return[c,u,p,n]}function Hy(e,t,n,a=1){let r=Vl(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function bh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Gy(e){return typeof e=="number"?[e,e,e]:e}function Vl(e,t){return t<=1?e:e+(e-1)*(t-1)}function f$(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=y$([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=Ai((t-s+d+h)/a+1,o),p=Ai((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:p}}function g$(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=b$([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),x=f-b,v=Math.floor(g/2),N=g-v,T=Math.floor(y/2),S=y-T;p={top:v,bottom:N,left:T,right:S,front:b,back:x,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 Ai(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 ts(e){let[t,n,a]=bh(e);return t===1&&n===1&&a===1}function ja(e,t){return ts(e)||ts(t)}function uk(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function x$(e,t){let n={x:E(e,"x","reshape","string_or_numeric")},a={shape:t};return M.runKernel(vl,n,a)}var U=P({reshape_:x$});function v$(e,t,n,a,r){let s=E(e,"x","avgPool","float32"),i=1;F(ja(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),F(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),r!=null&&F(Gt(a),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r},p=M.runKernel(Ds,c,u);return p=ue(p,s.dtype),l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Zn=P({avgPool_:v$});function w$(e,t,n,a,r,s="NDHWC"){let i=E(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),F(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),F(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&F(Gt(a),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},p=M.runKernel(ac,c,u);return p=ue(p,o.dtype),l?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var jy=P({avgPool3d_:w$});function k$(e,t=0){F(e.length>=1,()=>"Pass at least one tensor to concat");let n=Cc(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 Zr(n[0]);let a=n,r={axis:t};return M.runKernel(Go,a,r)}var Je=P({concat_:k$});function I$(e){let t={x:E(e,"x","sigmoid")};return M.runKernel(fi,t)}var da=P({sigmoid_:I$});function T$(e,t,n){let a=E(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return M.runKernel(Tl,r,s)}var We=P({slice_:T$});function N$(e){let t={x:E(e,"x","tanh")};return M.runKernel(wi,t)}var Ul=P({tanh_:N$});function S$(e,t,n,a,r,s){let i=E(e,"forgetBias","basicLSTMCell"),o=E(t,"lstmKernel","basicLSTMCell"),l=E(n,"lstmBias","basicLSTMCell"),c=E(a,"data","basicLSTMCell"),u=E(r,"c","basicLSTMCell"),p=E(s,"h","basicLSTMCell"),d=Je([c,p],1),h=ze(d,o),m=J(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],b=We(m,[0,0],y),x=We(m,[0,g],y),v=We(m,[0,g*2],y),N=We(m,[0,g*3],y),T=J(L(da(b),Ul(x)),L(u,da(J(i,v)))),S=L(Ul(T),da(N));return[T,S]}var C$=P({basicLSTMCell_:S$});function _$(e,t,n){let a=E(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);F(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),F(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),F(a.shape[0]%r==0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return M.runKernel(rc,s,i)}var $c=P({batchToSpaceND_:_$});function E$(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function F$(e,t,n,a,r,s){s==null&&(s=.001);let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;a!=null&&(u=E(a,"offset","batchNorm")),F(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),F(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),F(c==null||o.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:E$(i),scale:c,offset:u,mean:o,variance:l},d={varianceEpsilon:s},h=M.runKernel(js,p,d);return U(h,i.shape)}var br=P({batchNorm_:F$});function A$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),F(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),F(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),F(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&F(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&F(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),br(i,o,l,u,c,s)}var dk=P({batchNorm2d_:A$});function $$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),F(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),F(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),F(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&F(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&F(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),br(i,o,l,u,c,s)}var hk=P({batchNorm3d_:$$});function D$(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),c;r!=null&&(c=E(r,"scale","batchNorm"));let u;return a!=null&&(u=E(a,"offset","batchNorm")),F(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),F(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),F(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&F(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&F(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),br(i,o,l,u,c,s)}var mk=P({batchNorm4d_:D$});function R$(e,t,n){let a=E(e,"x","bincount"),r=E(t,"weights","bincount");F(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),F(n>=0,()=>`size must be non-negative, but got ${n}.`),F(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return M.runKernel(Fd,s,i)}var fk=P({bincount_:R$});function M$(e,t){let n=E(e,"broadcastTo","x"),a=n.shape;if(t.some(l=>!(l>0)||l%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){let l=n.shape.slice();for(;l.length<t.length;)l.unshift(1);n=U(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 Zr(n);let i={x:n},o={reps:s};return M.runKernel(qr,i,o)}var Dc=P({broadcastTo_:M$});function P$(e){let t={x:E(e,"x","ceil")};return M.runKernel(Ps,t)}var qy=P({ceil_:P$});function O$(e,t,n){let a=E(e,"x","clipByValue");F(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:a},s={clipValueMin:t,clipValueMax:n};return M.runKernel(jr,r,s)}var qt=P({clipByValue_:O$});function L$(e){return Je(e,0)}var gk=P({concat1d_:L$});function z$(e,t){return Je(e,t)}var yk=P({concat2d_:z$});function B$(e,t){return Je(e,t)}var bk=P({concat3d_:B$});function W$(e,t){return Je(e,t)}var xk=P({concat4d_:W$});function V$(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","conv2d"),l=E(t,"filter","conv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),F(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),F(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&F(Gt(a),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let p=r==="NHWC"?c.shape[3]:c.shape[1];F(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),F(ja(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let d={x:c,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=M.runKernel(Os,d,h);return u?U(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ft=P({conv2d_:V$});function U$(e,t,n,a,r="NWC",s=1,i){let o=E(e,"x","conv1d"),l=E(t,"filter","conv1d"),c=o,u=!1;o.rank===2&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1]])),F(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),F(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&F(Gt(a),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),F(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),F(ja(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),F(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let p=U(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=U(c,[c.shape[0],1,c.shape[1],c.shape[2]]),h=Ft(d,p,[1,n],a,"NHWC",[1,s],i);return u?U(h,[h.shape[2],h.shape[3]]):U(h,[h.shape[0],h.shape[2],h.shape[3]])}var xh=P({conv1d_:U$});function G$(e,t,n,a,r,s="NHWC",i){F(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=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),F(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),F(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),F(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];F(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),F(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),i!=null&&F(Gt(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let d={dy:l,filter:n},h={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=M.runKernel(Ls,d,h);return c?U(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ky=P({conv2DBackpropInput_:G$});function H$(e,t,n,a,r,s){let i=E(e,"x","conv2dTranspose"),o=E(t,"filter","conv2dTranspose");return Ky(n,i,o,a,r,"NHWC",s)}var vh=P({conv2dTranspose_:H$});function j$(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=E(e,"x","conv3d"),o=E(t,"filter","conv3d"),l=i,c=!1;i.rank===4&&(c=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),F(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),F(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),F(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),F(ja(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),F(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:o},p={strides:n,pad:a,dataFormat:r,dilations:s},d=M.runKernel(ic,u,p);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Xy=P({conv3d_:j$});function q$(e,t,n,a,r){F(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=U(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];F(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),F(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),F(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),F(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),F(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:i,filter:n},p={pad:r,strides:a,inputShape:s},d=M.runKernel(Rd,u,p);return o?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var vk=P({conv3DBackpropInput_:q$});function K$(e,t,n,a,r){let s=E(e,"x","conv3dTranspose"),i=E(t,"filter","conv3dTranspose");return vk(n,s,i,a,r)}var X$=P({conv3dTranspose_:K$});function Y$(e){let t={x:E(e,"x","cos")};return M.runKernel(zs,t)}var Rc=P({cos_:Y$});function J$(e){let t={x:E(e,"x","cosh")};return M.runKernel(Ho,t)}var wh=P({cosh_:J$});function Q$(e,t=0,n=!1,a=!1){let r={x:E(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return M.runKernel(Bs,r,s)}var kh=P({cumsum_:Q$});function Z$(e,t,n,a=!1){let r=E(e,"x","denseBincount"),s=E(t,"weights","denseBincount");F(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),F(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),F(n>=0,()=>`size must be non-negative, but got ${n}.`),F(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return M.runKernel(Md,i,o)}var wk=P({denseBincount_:Z$});function eD(e,t,n="NHWC"){let a=E(e,"x","depthToSpace"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];F(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${r} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),F(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),F(i%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return M.runKernel(qo,o,l)}var Yy=P({depthToSpace_:eD});function tD(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","depthwiseConv2d"),l=E(t,"filter","depthwiseConv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),F(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),F(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),F(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&&F(Gt(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let p={x:c,filter:l},d={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},h=M.runKernel(Ws,p,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var ns=P({depthwiseConv2d_:tD});function nD(e){let t={x:E(e,"x","diag")};return M.runKernel(Ld,t)}var aD=P({diag_:nD});function rD(e,t,n,a,r=[1,1],s="NHWC"){let i=E(e,"x","dilation2d"),o=E(t,"filter","dilation2d");F(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),F(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),F(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,c=!1;i.rank===3&&(l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=!0);let u={x:l,filter:o},p={strides:n,pad:a,dilations:r},d=M.runKernel(oc,u,p);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Jy=P({dilation2d_:rD});function sD(e,t){let n=e.length,a=[];for(let r=0;r<n;r++){let s=n-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&a.unshift(s)}return a}function zt(e,t){let n=[];for(let a=0;a<t.length;a++){let r=e[e.length-a-1],s=t.length-a-1,i=t[s];(r==null||r===1&&i>1)&&n.unshift(s)}return n}function bt(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 iD(e,t){let n=E(e,"a","equal"),a=E(t,"b","equal");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Yo,r)}var as=P({equal_:iD});function oD(e,t,n){let a=E(t,"a","where"),r=E(n,"b","where"),s=E(e,"condition","where","bool"),i=bt(a.shape,r.shape),o=Dc(a,i),l=Dc(r,i);s.rank===1&&F(s.shape[0]===a.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),s.rank!==1&&on(s.shape,l.shape,"Error in where: ");let c={condition:s,t:o,e:l};return M.runKernel(kl,c)}var Sn=P({where_:oD});function lD(e){let t={x:E(e,"x","zerosLike")};return M.runKernel(Dl,t)}var Ge=P({zerosLike_:lD});function uD(e,t){let n=E(e,"a","div"),a=E(t,"b","div");[n,a]=Tt(n,a);let r=xe(n,a),s=Ge(r),i=as(a,s);return Sn(i,s,r)}var Qy=P({divNoNan_:uD});function cD(e,t){let n=E(e,"t1","dot"),a=E(t,"t2","dot");F((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(F(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=U(n,[1,-1]),o=U(a,[-1,1]),l=ze(i,o);return U(l,[])}else if(n.rank===1&&a.rank===2){let i=U(n,[1,-1]),o=U(a,[a.shape[0],a.shape[1]]),l=ze(i,o);return U(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=U(a,[-1,1]),o=ze(n,i);return U(o,[o.size])}else{let i=U(a,[a.shape[0],a.shape[1]]);return ze(n,i)}}var kk=P({dot_:cD});function pD(e){let t={x:E(e,"x","elu")};return M.runKernel(Ko,t)}var Gl=P({elu_:pD});function dD(e){let t=E(e,"x","erf");F(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ue(t,"float32"));let n={x:t};return M.runKernel(Xo,n)}var Zy=P({erf_:dD});function hD(e){let t={x:E(e,"x","exp")};return M.runKernel(Us,t)}var hn=P({exp_:hD});function mD(e,t=0){let n=E(e,"x","expandDims","string_or_numeric");F(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return M.runKernel(Jo,a,r)}var Mn=P({expandDims_:mD});function fD(e){let t={x:E(e,"x","expm1")};return M.runKernel(Qo,t)}var eb=P({expm1_:fD});function gD(e,t){let n=E(e,"x","tile","string_or_numeric");F(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return M.runKernel(qr,a,r)}var qa=P({tile_:gD});function yD(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=U(r.toTensor(),[e,t]);if(n==null)return i;if(n.length===1)return qa(Mn(i,0),[n[0],1,1]);if(n.length===2)return qa(Mn(Mn(i,0),0),[n[0],n[1],1,1]);if(n.length===3)return qa(Mn(Mn(Mn(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 tb=P({eye_:yD});function Cn(e,t,n){let a={shape:e,value:t,dtype:n};return M.runKernel(lc,{},a)}function bD(e){let t={x:E(e,"x","floor")};return M.runKernel(Gs,t)}var Hl=P({floor_:bD});function xD(e,t,n=0,a=0){let r=E(e,"x","gather"),s=E(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:n,batchDims:a};return M.runKernel(el,i,o)}var $i=P({gather_:xD});function vD(e,t){let n=E(e,"a","greater"),a=E(t,"b","greater");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(nl,r)}var ha=P({greater_:vD});function wD(e,t){let n=E(e,"a","greaterEqual"),a=E(t,"b","greaterEqual");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(qs,r)}var rs=P({greaterEqual_:wD});function kD(e){let t={input:E(e,"input","imag")};return M.runKernel(Gd,t)}var Ih=P({imag_:kD});function ID(e){let t={x:E(e,"x","isFinite")};return M.runKernel(al,t)}var Ik=P({isFinite_:ID});function TD(e){let t={x:E(e,"x","isInf")};return M.runKernel(rl,t)}var Tk=P({isInf_:TD});function ND(e){let t={x:E(e,"x","isNaN")};return M.runKernel(sl,t)}var Nk=P({isNaN_:ND});function SD(e,t=.2){let n={x:E(e,"x","leakyRelu")},a={alpha:t};return M.runKernel(Xs,n,a)}var Mc=P({leakyRelu_:SD});function CD(e,t){let n=E(e,"a","less"),a=E(t,"b","less");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(il,r)}var Th=P({less_:CD});function _D(e,t){let n=E(e,"a","lessEqual"),a=E(t,"b","lessEqual");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(ol,r)}var Di=P({lessEqual_:_D});function Sk(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let a={start:e,stop:t,num:n};return M.runKernel(Hd,{},a)}function ED(e,t=5,n=1,a=1,r=.5){let s=E(e,"x","localResponseNormalization");F(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),F(Gt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=U(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},c={depthRadius:t,bias:n,alpha:a,beta:r},u=M.runKernel(pc,l,c);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var nb=P({localResponseNormalization_:ED});function FD(e){let t={x:E(e,"x","log")};return M.runKernel(Ys,t)}var Pn=P({log_:FD});function AD(e){let t={x:E(e,"x","log1p")};return M.runKernel(ll,t)}var Nh=P({log1p_:AD});function $D(e){return F(Gr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=E(t,"x","tf.grad","string_or_numeric"),r=n!=null?E(n,"dy","tf.grad"):null;return M.tidy(()=>{let{value:s,grads:i}=M.gradients(()=>e(a),[a],r);return r!=null&&on(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Sh(i),i[0]})}}function DD(e){return F(Gr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{F(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=Cc(t,"args","tf.grads","string_or_numeric"),r=n!=null?E(n,"dy","tf.grads"):null;return M.tidy(()=>{let{value:s,grads:i}=M.gradients(()=>e(...a),a,r);return r!=null&&on(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sh(i),i})}}function RD(e){return F(Gr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{F(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),F(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=M.gradients(()=>e(t),[t],n);return Sh(a),{grad:a[0],value:r}}}function MD(e){return F(Gr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{F(Array.isArray(t)&&t.every(r=>r instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),F(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=M.gradients(()=>e(...t),t,n);return n!=null&&on(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sh(a.grads),a}}function Ck(e,t){F(Gr(e),()=>"The f passed in variableGrads(f) must be a function"),F(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 M.registeredVariables)t.push(M.registeredVariables[c])}let a=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),F(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=M.gradients(e,t,null,s);F(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()."),F(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((c,u)=>{o[u]!=null&&(l[c.name]=o[u])}),a!=null&&a.forEach(c=>l[c.name]=null),{value:i,grads:l}}function Ka(e){return M.customGrad(e)}function Sh(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 PD(e){let t={x:E(e,"x","neg")};return M.runKernel(pl,t)}var Nt=P({neg_:PD});function OD(e){let t={x:E(e,"x","softplus")};return M.runKernel(Cl,t)}var jl=P({softplus_:OD});function LD(e){let t=E(e,"x","logSigmoid");return Ka(n=>({value:Nt(jl(Nt(n))),gradFunc:a=>L(a,da(Nt(n)))}))(t)}var _k=P({logSigmoid_:LD});function zD(e,t=null,n=!1){let a={x:E(e,"x","max")},r={reductionIndices:t,keepDims:n};return M.runKernel(Js,a,r)}var ea=P({max_:zD});function BD(e,t){let n=E(e,"a","sub"),a=E(t,"b","sub");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(vi,r)}var me=P({sub_:BD});function WD(e,t=null,n=!1){let a=E(e,"x","sum");a.dtype==="bool"&&(a=ue(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return M.runKernel(yi,r,s)}var Se=P({sum_:WD});function VD(e,t=-1){let n=E(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Ka((a,r)=>{let s=!0,i=ea(a,t,!0),o=me(a,i),l=me(ue(o,"float32"),Pn(Se(hn(o),t,s)));return r([l]),{value:l,gradFunc:(c,u)=>{let[p]=u,d=!0,h=hn(p);return me(c,L(Se(c,t,d),h))}}})(n)}var Ch=P({logSoftmax_:VD});function ab(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Ek(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 Fk(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 Ri(e,t){let n=t.map(a=>1);return Ek(e,n,t)}function UD(e,t,n){F(ab(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ak(e,t){if(ab(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 rb(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function GD(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function HD(e,t=null,n=!1){let a=E(e,"x","logSumExp"),r=ca(t,a.shape),s=ea(a,r,!0),i=me(a,s),o=hn(i),l=Se(o,r),c=Pn(l),u=J(U(s,c.shape),c);if(n){let p=Ri(u.shape,r);return U(u,p)}return u}var sb=P({logSumExp_:HD});function jD(e,t){let n=E(e,"a","logicalAnd","bool"),a=E(t,"b","logicalAnd","bool");bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(ul,r)}var ma=P({logicalAnd_:jD});function qD(e){let t={x:E(e,"x","logicalNot","bool")};return M.runKernel(uc,t)}var Pc=P({logicalNot_:qD});function KD(e,t){let n=E(e,"a","logicalOr","bool"),a=E(t,"b","logicalOr","bool");bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(cc,r)}var _h=P({logicalOr_:KD});function XD(e,t){let n=E(e,"a","logicalXor","bool"),a=E(t,"b","logicalXor","bool");return bt(n.shape,a.shape),ma(_h(e,t),Pc(ma(e,t)))}var $k=P({logicalXor_:XD});function YD(e,t,n,a,r){let s=E(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),F(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),F(ja(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&F(Gt(a),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r},p=M.runKernel(Zs,c,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var At=P({maxPool_:YD});function JD(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=E(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),F(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),F(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&F(Gt(a),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},p=M.runKernel(dc,c,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var ib=P({maxPool3d_:JD});function QD(e,t,n,a,r=!1){let s={x:E(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=M.runKernel(Xd,s,i);return{result:o[0],indexes:o[1]}}var Dk=P({maxPoolWithArgmax_:QD});function ZD(e,t){let n=E(e,"a","maximum"),a=E(t,"b","maximum");[n,a]=Tt(n,a),n.dtype==="bool"&&(n=ue(n,"int32"),a=ue(a,"int32")),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(Qs,r)}var Xa=P({maximum_:ZD});function eR(e,t=null,n=!1){let a={x:E(e,"x","mean")},r={axis:t,keepDims:n};return M.runKernel(ei,a,r)}var St=P({mean_:eR});function tR(e,t=null,n=!1){let a={x:E(e,"x","min")},r={axis:t,keepDims:n};return M.runKernel(ti,a,r)}var ql=P({min_:tR});function nR(e,t){let n=E(e,"a","minimum"),a=E(t,"b","minimum");[n,a]=Tt(n,a),n.dtype==="bool"&&(n=ue(n,"int32"),a=ue(a,"int32")),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(ni,r)}var Kl=P({minimum_:nR});function aR(e,t,n){F(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=E(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");F(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++)F(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),F(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return M.runKernel(hc,i,s)}var ob=P({mirrorPad_:aR});function rR(e,t){let n=E(e,"a","mod"),a=E(t,"b","mod");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(cl,r)}var lb=P({mod_:rR});function sR(e){let t=E(e,"x","square"),n={};return M.runKernel("Square",{x:t},n)}var lt=P({square_:sR});function iR(e,t=null,n=!1){e=E(e,"x","moments");let a=ca(t,e.shape),r=St(e,a,n),s=r.shape;n||(s=Ri(r.shape,a));let i=lt(me(ue(e,"float32"),U(r,s))),o=St(i,a,n);return{mean:r,variance:o}}var Eh=P({moments_:iR});function oR(e,t,n,a){let r=E(t,"data","multiRNNCell"),s=Cc(n,"c","multiRNNCell"),i=Cc(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 lR=P({multiRNNCell_:oR});function uR(e,t,n,a=!1){let r=E(e,"logits","multinomial"),s=r.size,i=r.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?U(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},c=M.runKernel(Yd,o,l);return i===1?U(c,[c.size]):c}var Rk=P({multinomial_:uR});function cR(e,t){let n=E(e,"a","notEqual"),a=E(t,"b","notEqual");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a};return M.runKernel(dl,r)}var Mi=P({notEqual_:cR});function xt(e,t="float32"){if(t==="complex64"){let a=xt(e,"float32"),r=xt(e,"float32");return Yr(a,r)}let n=Nd(Pt(e),t);return M.makeTensor(n,e,t)}function Ya(e,t="float32"){if(t==="complex64"){let a=Ya(e,"float32"),r=xt(e,"float32");return Yr(a,r)}let n=ty(Pt(e),t);return M.makeTensor(n,e,t)}function pR(e){let t={x:E(e,"x","onesLike")};return M.runKernel(gl,t)}var On=P({onesLike_:pR});function dR(e,t){let n=E(e,"v1","outerProduct"),a=E(t,"v2","outerProduct");F(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=U(n,[-1,1]),s=U(a,[1,-1]);return ze(r,s)}var hR=P({outerProduct_:dR});function mR(e,t,n=0){let a=E(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return M.runKernel(si,s,r)}var ta=P({pad_:mR});function fR(e,t,n=0){return F(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ta(e,[t],n)}var gR=P({pad1d_:fR});function yR(e,t,n=0){return F(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 bR=P({pad2d_:yR});function xR(e,t,n=0){return F(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 vR=P({pad3d_:xR});function wR(e,t,n=0){return F(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 kR=P({pad4d_:wR});function IR(e,t,n){let a=E(e,"x","spaceToBatchND");F(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),F(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),F(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]==0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return M.runKernel(gc,r,s)}var Oc=P({spaceToBatchND_:IR});function SR(e,t,n,a,r,s){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let i=E(e,"x","maxPool"),o=i,l=!1;i.rank===3&&(l=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),F(ja(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let c=ck(o.shape,t,s,r,a),u=[c.dilationHeight,c.dilationWidth],p;a==="same"?p=NR([c.filterHeight,c.filterWidth],u):p=[[0,0],[0,0]];let d=u[0]===1&&u[1]===1,[h,m]=TR([c.inHeight,c.inWidth],u,p),f=d?a:"valid",g=d?o:Oc(o,u,h),y=(n==="avg"?()=>Zn(g,t,s,f):()=>At(g,t,s,f))(),b=d?y:$c(y,u,m);return l?U(b,[b.shape[1],b.shape[2],b.shape[3]]):b}function TR(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 NR(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 Mk=P({pool_:SR});function CR(e,t){let n=E(e,"base","pow"),a=E(t,"exp","pow");[n,a]=Tt(n,a);let r={a:n,b:a};return M.runKernel(ii,r)}var xr=P({pow_:CR});function _R(e,t){let n=E(e,"x","prelu"),a=E(t,"alpha","prelu"),r={x:n,alpha:a};return M.runKernel(oi,r)}var Lc=P({prelu_:_R});function ER(e,t=null,n=!1){let a=E(e,"x","prod");a.dtype==="bool"&&(a=ue(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return M.runKernel(bl,r,s)}var Fh=P({prod_:ER});function FR(e,t,n){let a=Pt(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s<a;s++)r[s]=t();return M.makeTensor(r,e,n)}var AR=P({rand_:FR}),ub=Do(wd()),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}},$R=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)}},DR=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 RR(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 $R(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 MR=P({randomGamma_:RR});function PR(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 Pk=P({randomNormal_:PR});function OR(e,t=0,n=1,a="float32",r){let s=Le(e,a),i=new DR(t,n,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Xl=P({randomUniform_:OR});function Ah(e,t,n=1,a="float32"){if(n===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:n,dtype:a};return M.runKernel(mc,{},r)}function LR(e){let t={input:E(e,"input","real")};return M.runKernel(Jd,t)}var zc=P({real_:LR});function zR(e){let t={x:E(e,"x","reciprocal")};return M.runKernel(xl,t)}var pb=P({reciprocal_:zR});function BR(e){let t={x:E(e,"x","relu")};return M.runKernel(li,t)}var qe=P({relu_:BR});function WR(e){let t={x:E(e,"x","relu6")};return M.runKernel(ci,t)}var $h=P({relu6_:WR});function VR(e,t){let n={x:E(e,"x","reverse")},a={dims:t};return M.runKernel(pi,n,a)}var Ln=P({reverse_:VR});function UR(e){let t=E(e,"x","reverse");return F(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Ln(t,0)}var GR=P({reverse1d_:UR});function HR(e,t){let n=E(e,"x","reverse");return F(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Ln(n,t)}var jR=P({reverse2d_:HR});function qR(e,t){let n=E(e,"x","reverse");return F(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Ln(n,t)}var KR=P({reverse3d_:qR});function XR(e,t){let n=E(e,"x","reverse");return F(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Ln(n,t)}var YR=P({reverse4d_:XR});function JR(e){let t={x:E(e,"x","round")};return M.runKernel(di,t)}var db=P({round_:JR});function QR(e){let t={x:E(e,"x","rsqrt")};return M.runKernel(hi,t)}var Dh=P({rsqrt_:QR});function pe(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 ZR(e){let t={x:E(e,"x","selu")};return M.runKernel(Il,t)}var Rh=P({selu_:ZR});function eM(e,t,n,a,r,s=[1,1],i="NHWC"){let o=E(e,"x","separableConv2d"),l=E(t,"depthwiseFilter","separableConv2d"),c=E(n,"pointwiseFilter","separableConv2d"),u=o,p=!1;if(o.rank===3&&(p=!0,u=U(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");F(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),F(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),F(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),F(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),F(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];F(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=ns(u,l,a,r,i,s),f=Ft(m,c,1,"valid",i);return p?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Pi=P({separableConv2d_:eM});async function tM(e,t){let n=E(e,"x","setdiff1d"),a=E(t,"y","setdiff1d");F(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),F(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),F(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let u=0;u<r.length;u++)i.has(r[u])||o++;let l=new Ot([o],n.dtype),c=new Ot([o],"int32");for(let u=0,p=0;u<r.length;u++)i.has(r[u])||(l.values[p]=r[u],c.values[p]=u,p++);return[l.toTensor(),c.toTensor()]}var Ok=tM;function nM(e){let t={x:E(e,"x","sign")};return M.runKernel(Sl,t)}var hb=P({sign_:nM});function aM(e){let t={x:E(e,"x","sin")};return M.runKernel(mi,t)}var Mh=P({sin_:aM});function rM(e){let t={x:E(e,"x","sinh")};return M.runKernel(Nl,t)}var Ph=P({sinh_:rM});function sM(e,t,n){let a=E(e,"x","slice1d");return F(a.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),We(a,[t],[n])}var Oh=P({slice1d_:sM});function iM(e,t,n){let a=E(e,"x","slice2d");return F(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var mb=P({slice2d_:iM});function oM(e,t,n){let a=E(e,"x","slice3d");return F(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var Yl=P({slice3d_:oM});function lM(e,t,n){let a=E(e,"x","slice4d");return F(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),We(a,t,n)}var Bc=P({slice4d_:lM});function uM(e,t=-1){let n=E(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let a={logits:n},r={dim:t};return M.runKernel(bi,a,r)}var Na=P({softmax_:uM});function cM(e){F(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return M.runKernel(Vd,t)}var Wc=P({fft_:cM});function pM(e){F(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return M.runKernel(Ud,t)}var Jl=P({ifft_:pM});function dM(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=U(e,[n,t]);a=Jl(r)}else{let r=[n,2*(t-1)],s=U(zc(e),[n,t]),i=U(Ih(e),[n,t]),o=Ln(We(s,[0,1],[n,t-2]),1),l=L(Ln(We(i,[0,1],[n,t-2]),1),pe(-1)),c=Je([s,o],1),u=Je([i,l],1),p=U(Yr(c,u),[r[0],r[1]]);a=Jl(p)}if(a=zc(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=U(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var Lh=P({irfft_:dM});function hM(e,t,n=0){let a={x:E(e,"x","split")},r={numOrSizeSplits:t,axis:n};return M.runKernel(_l,a,r)}var zn=P({split_:hM});function mM(e,t){F(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=Je([e,xt(m)],e.shape.length-1),n=t}else r=e;let s=Ge(r),i=U(Yr(r,s),[a,n]),o=Wc(i),l=Math.floor(n/2)+1,c=zc(o),u=Ih(o),p=zn(c,[l,n-l],c.shape.length-1),d=zn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,U(Yr(p[0],d[0]),h)}var Vc=P({rfft_:mM});function fM(e){let t={x:E(e,"x","sqrt")};return M.runKernel(gi,t)}var an=P({sqrt_:fM});function gM(e,t){let n=E(e,"a","squaredDifference"),a=E(t,"b","squaredDifference");[n,a]=Tt(n,a),bt(n.shape,a.shape);let r={a:n,b:a},s={};return M.runKernel(xi,r,s)}var zh=P({squaredDifference_:gM});function yM(e,t){let n=E(e,"x","squeeze");return U(n,n0(n.shape,t).newShape)}var ss=P({squeeze_:yM});function bM(e,t=0){let n=Cc(e,"tensors","stack","string_or_numeric");F(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&F(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return M.runKernel(yl,a,r)}var $t=P({stack_:bM});function xM(e,t=0){let n={x:E(e,"x","step")},a={alpha:t};return M.runKernel(Kr,n,a)}var Ql=P({step_:xM});function vM(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let c={x:E(e,"x","stridedSlice")},u={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return M.runKernel(El,c,u)}var fb=P({stridedSlice_:vM});function wM(e){let t={x:E(e,"x","tan")};return M.runKernel(Fl,t)}var gb=P({tan_:wM});function Ze(e,t){Es(e);let n=Ga(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Jr(e,null,n,t)}function Sa(e,t,n){if(Es(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=Ga(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Jr(e,t,a,n)}function Ca(e,t,n){if(Es(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=Ga(e,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Jr(e,t,a,n)}function kM(e,t,n){if(Es(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=Ga(e,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Jr(e,t,a,n)}function IM(e,t,n){if(Es(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=Ga(e,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,Jr(e,t,a,n)}function TM(e,t=1,n=!0){let a=E(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=M.runKernel(Al,s,i);return{values:o,indices:l}}var yb=P({topk_:TM});function NM(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 Bh=P({truncatedNormal_:NM});function SM(e,t=0){let n=E(e,"x","unique","string_or_numeric");F(n.rank>0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=M.runKernel(th,a,r);return{values:s,indices:i}}var Wh=P({unique_:SM});function CM(e,t,n){let a=E(e,"x","unsortedSegmentSum"),r=E(t,"segmentIds","unsortedSegmentSum","int32");F(Gt(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return M.runKernel(bc,s,i)}var bb=P({unsortedSegmentSum_:CM});function _M(e,t=0){let n=E(e,"x","unstack","string_or_numeric");F(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return M.runKernel($l,a,r)}var ut=P({unstack_:_M});function Lk(e,t=!0,n,a){return M.makeVariable(e,t,n,a)}function zk(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 EM(e){let t=E(e,"condition","whereAsync","bool"),n=await t.data(),a=zk(t.shape,n);return e!==t&&t.dispose(),a}var xb=EM;async function FM(e,t,n){let a=E(e,"tensor","boolMask"),r=E(t,"mask","boolMask","bool"),s=n==null?0:n,i=r.rank,o=a.shape;F(i>0,()=>"mask cannot be scalar"),on(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f<s+i;f++)l*=o[f];let c=o.slice(0,s).concat([l],o.slice(s+i)),u=U(a,c),p=U(r,[-1]),d=await xb(p),h=ss(d,[1]),m=$i(u,h,s);return e!==a&&a.dispose(),t!==r&&r.dispose(),h.dispose(),u.dispose(),p.dispose(),d.dispose(),m}var AM=FM;function $M(e,t="euclidean",n=null,a=!1){e=E(e,"x","norm");let r=Bk(e,t,n),s=r.shape;if(a){let i=ca(n,e.shape);s=Ri(r.shape,i)}return U(r,s)}function Bk(e,t,n=null){if(e.rank===0)return Lt(e);if(e.rank!==1&&n===null)return Bk(U(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return Se(Lt(e),n);if(t===Infinity)return ea(Lt(e),n);if(t===-Infinity)return ql(Lt(e),n);if(t==="euclidean"||t===2)return an(Se(xr(Lt(e),pe(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(Se(Lt(e),n[0]),n[1]-1);if(t===Infinity)return ea(Se(Lt(e),n[1]),n[0]);if(t===-Infinity)return ql(Se(Lt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return an(Se(lt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var Vh=P({norm_:$M});function DM(e,t,n,a,r=!0){let s=E(e,"v","movingAverage"),i=E(t,"x","movingAverage"),o=E(n,"decay","movingAverage");x0(s,i),F(gr(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=pe(1),c=me(l,o),u=L(me(i,s),c);if(r){F(a!=null,()=>"When using zeroDebias: true, step is required.");let p=E(a,"step","movingAverage");u=xe(u,me(l,xr(o,p)))}return J(s,u)}var RM=P({movingAverage_:DM});function MM(e,t,n){let a=E(e,"indices","scatterND","int32"),r=E(t,"updates","scatterND");Ay(r,a,n);let s={indices:a,updates:r},i={shape:n};return M.runKernel(wl,s,i)}var Wk=P({scatterND_:MM});function PM(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 OM(e,t,n,a=0){let r=E(e,"sparseIndices","sparseToDense","int32"),s=E(t,"sparseValues","sparseToDense"),i=E(a,"defaultValue","sparseToDense",s.dtype);PM(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return M.runKernel(eh,o,l)}var vb=P({sparseToDense_:OM});function LM(e,t){let n=E(t,"indices","gatherND","int32"),a={params:E(e,"x","gatherND"),indices:n};return M.runKernel(tl,a)}var Vk=P({gatherND_:LM});function zM(e,t){if(t==null)return e.shape.slice();if(gr(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 BM(e,t,n,a){let r=E(e,"x","dropout");if(F(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.`),F(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ee?r.clone():r;let s=zM(r,n),i=1-t,o=xe(Hl(J(Xl(s,0,1,"float32",a),i)),i);return L(r,o)}var Uk=P({dropout_:BM});function Gk(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 Ze(r,"float32")}async function WM(e,t,n=1){let a=E(e,"predictions","inTopK"),r=E(t,"targets","inTopK");F(a.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),F(a.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${r.rank}`),on(a.shape.slice(0,a.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];F(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=a0("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(),Jn(u,r.shape,"bool")}var VM=WM,is={};Oe(is,{conv2d:()=>UM,depthwiseConv2d:()=>GM,matMul:()=>HM});function jM(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),F(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),F(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),F(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];F(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),F(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),i!=null&&F(Gt(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let p={x:o,dy:l},d={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return M.runKernel($d,p,d)}var kb=P({conv2DBackpropFilter_:jM});function Uh(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,Ql(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Gh(e,t){let n=t,a=zt(e.shape,t.shape);return a.length>0&&(n=Se(n,a)),U(n,e.shape)}function Hh(e,t,n,a){if(t==="linear")return e;if(t==="relu")return qe(e);if(t==="elu")return Gl(e);if(t==="relu6")return $h(e);if(t==="prelu")return Lc(e,n);if(t==="leakyrelu")return Mc(e,a);throw new Error(`Unknown fused activation ${t}.`)}var jh=(e,t)=>!(e>0)||t==="linear";function qM({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",jh(M.state.gradientDepth,l)===!1){let N=Ft(e,t,n,a,r,s,i);return o!=null&&(N=J(N,o)),Hh(N,l,c,u)}let p=E(e,"x","conv2d"),d=E(t,"filter","conv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=U(p,[1,p.shape[0],p.shape[1],p.shape[2]])),F(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),F(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),i!=null&&F(Gt(a),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),F(h.shape[3]===d.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${d.shape[2]}.`),F(ja(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),F(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let f=Ac(h.shape,d.shape,n,s,a,i),g;o!=null&&(g=E(o,"bias","fused conv2d"),[g]=Tt(g,p),bt(f.outShape,g.shape));let y;c!=null&&(y=E(c,"prelu weights","fused conv2d"));let b=(N,T)=>{let[S,A,$,R]=T,B=Uh(N,$,l);F(ts(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let V=Ky(A.shape,B,S,n,a),W=kb(A,B,S.shape,n,a),G=[V,W];if(R!=null){let H=Gh(R,B);G.push(H)}return G},x={x:h,filter:d,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Ka((N,T,S)=>{let A=M.runKernel(Ti,x,v);return S([T,N,A]),m&&(A=U(A,[A.shape[1],A.shape[2],A.shape[3]])),{value:A,gradFunc:b}})(h,d):Ka((N,T,S,A)=>{let $=M.runKernel(Ti,x,v);return A([T,N,$,S]),m&&($=U($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d,g)}var UM=P({fusedConv2d_:qM});function KM(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:o,dy:l},u={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return M.runKernel(Pd,c,u)}var Hk=P({depthwiseConv2dNativeBackpropFilter_:KM});function XM(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:o,filter:n},u={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},p=M.runKernel(Od,c,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var jk=P({depthwiseConv2dNativeBackpropInput_:XM});function YM({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(jh(M.state.gradientDepth,l)===!1){let N=ns(e,t,n,a,r,s,i);return o!=null&&(N=J(N,o)),Hh(N,l,c,u)}let p=E(e,"x","depthwiseConv2d"),d=E(t,"filter","depthwiseConv2d"),h=p,m=!1;p.rank===3&&(m=!0,h=U(p,[1,p.shape[0],p.shape[1],p.shape[2]])),F(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),F(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),F(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]),F(ja(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&F(Gt(a),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${a}.`);let f=Ac(h.shape,d.shape,n,s,a,i,!0),g;o!=null&&(g=E(o,"bias","fused conv2d"),[g]=Tt(g,p),bt(f.outShape,g.shape));let y;c!=null&&(y=E(c,"prelu weights","fused depthwiseConv2d"));let b=(N,T)=>{F(ts(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[S,A,$,R]=T,B=Uh(N,$,l),V=jk(A.shape,B,S,n,a,s,i),W=Hk(A,B,S.shape,n,a,s,i);if(R!=null){let G=Gh(g,B);return[V,W,G]}return[V,W]},x={x:h,filter:d,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Ka((N,T,S)=>{let A=M.runKernel(Ni,x,v);return S([T,N,A]),m&&(A=U(A,[A.shape[1],A.shape[2],A.shape[3]])),{value:A,gradFunc:b}})(h,d):Ka((N,T,S,A)=>{let $=M.runKernel(Ni,x,v);return A([T,N,$,S]),m&&($=U($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(h,d,g)}var GM=P({fusedDepthwiseConv2d_:YM});function JM({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(jh(M.state.gradientDepth,s)===!1){let R=ze(e,t,n,a);return r!=null&&(R=J(R,r)),Hh(R,s,i,o)}let l=E(e,"a","fused matMul"),c=E(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=Pt(m),y=Pt(f);F(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}.`),F(gr(m,f),()=>`Error in fused matMul: outer dimensions (${m}) and (${f}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),F(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]),x=n?U(l,[g,u,d]):U(l,[g,d,u]),v=a?U(c,[y,h,p]):U(c,[y,p,h]),N;r!=null&&(N=E(r,"bias","fused matMul"),[N]=Tt(N,l),bt(b,N.shape));let T;i!=null&&(T=E(i,"prelu weights","fused matMul"));let S=(R,B)=>{let[V,W,G,H]=B,X=Uh(U(R,G.shape),G,s),q,te;if(!n&&!a?(q=ze(X,W,!1,!0),te=ze(V,X,!0,!1)):!n&&a?(q=ze(X,W,!1,!1),te=ze(X,V,!0,!1)):n&&!a?(q=ze(W,X,!1,!0),te=ze(V,X,!1,!1)):(q=ze(W,X,!0,!0),te=ze(X,V,!0,!0)),r!=null){let Q=Gh(H,X);return[q,te,Q]}else return[q,te]},A={a:x,b:v,bias:N,preluActivationWeights:T},$={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?Ka((R,B,V)=>{let W=M.runKernel(Ii,A,$);return V([R,B,W]),{value:U(W,b),gradFunc:S}})(x,v):Ka((R,B,V,W)=>{let G=M.runKernel(Ii,A,$);return W([R,B,G,V]),{value:U(G,b),gradFunc:S}})(x,v,N)}var HM=P({fusedMatMul_:JM});function QM(e){return wb(e,.54,.46)}var ZM=P({hammingWindow_:QM});function eP(e){return wb(e,.5,.5)}var qk=P({hannWindow_:eP});function tP(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=Je([We(e,s,t-o),Cn([o],r)]);i.push(l),s+=n}return i.length===0?Sa([],[0,t]):U(Je(i),[i.length,t])}var Kk=P({frame_:tP});function nP(e,t,n,a,r=qk){a==null&&(a=Gk(t));let s=Kk(e,t,n),i=L(s,r(t)),o=[];for(let l=0;l<s.shape[0];l++)o.push(Vc(We(i,[l,0],[1,t]),a));return Je(o)}var aP=P({stft_:nP});function rP(e,t,n,a,r="bilinear",s=0){let i=E(e,"image","cropAndResize"),o=E(t,"boxes","cropAndResize","float32"),l=E(n,"boxInd","cropAndResize","int32"),c=o.shape[0];F(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),F(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`),F(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`),F(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),F(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),F(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:i,boxes:o,boxInd:l},p={method:r,extrapolationValue:s,cropSize:a};return M.runKernel(jo,u,p)}var sP=P({cropAndResize_:rP});function iP(e){let t=E(e,"image","flipLeftRight","float32");F(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return M.runKernel(Zo,n,{})}var oP=P({flipLeftRight_:iP});function lP(e,t,n=0,a=.5){let r=E(e,"image","rotateWithOffset","float32");F(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return M.runKernel(Rl,s,i)}var uP=P({rotateWithOffset_:lP});function Zl(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),F(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),F(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),F(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),F(t.rank===1,()=>"scores must be a 1D tensor"),F(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),F(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function cP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppression"),i=E(t,"scores","nonMaxSuppression"),o=Zl(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return M.runKernel(hl,{boxes:s,scores:i},l)}var pP=P({nonMaxSuppression_:cP});function hP(e,t,n){let a=dP(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function dP(e,t,n){return fP(e,t,n||mP)}function mP(e,t){return e>t?1:e<t?-1:0}function fP(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 Xk(e,t,n,a,r){return Ib(e,t,n,a,r,0)}function Yk(e,t,n,a,r,s){return Ib(e,t,n,a,r,0,!1,s,!0)}function Jk(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(Qk);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:x}=g;if(y<r)break;let v=!1;for(let N=p.length-1;N>=x;--N){let T=gP(e,b,p[N]);if(T>=a){v=!0;break}if(g.score=g.score*yP(a,u,T),g.score<=r)break}g.suppressBeginIndex=p.length,v||(g.score===y?(p.push(b),d.push(g.score)):g.score>r&&hP(c,g,Qk))}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 gP(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),x=Math.max(y-f,0)*Math.max(b-g,0);return x/(h+m-x)}function yP(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function Qk(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function bP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppressionAsync"),i=E(t,"scores","nonMaxSuppressionAsync"),o=Zl(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}=Xk(c,u,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),Ze(p,"int32")}var xP=bP;function vP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=Zl(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let c={boxes:i,scores:o},u={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},p=M.runKernel(fl,c,u);return{selectedIndices:p[0],selectedScores:p[1]}}var wP=P({nonMaxSuppressionWithScore_:vP});async function kP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=Zl(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}=Jk(u,p,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ze(d,"int32"),selectedScores:Ze(h)}}var IP=kP;function TP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=Zl(i,o,n,a,r,null),c=l.maxOutputSize,u=l.iouThreshold,p=l.scoreThreshold,d={boxes:i,scores:o},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:p,padToMaxOutputSize:s},m=M.runKernel(ml,d,h);return{selectedIndices:m[0],validOutputs:m[1]}}var NP=P({nonMaxSuppressionPadded_:TP});async function SP(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=Zl(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}=Yk(d,h,c,u,p,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ze(m,"int32"),validOutputs:pe(f,"int32")}}var CP=SP;function _P(e,t,n=!1,a=!1){let r=E(e,"images","resizeBilinear");F(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),F(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),F(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=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=M.runKernel(ui,o,l);return i?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Zk=P({resizeBilinear_:_P});function EP(e,t,n=!1,a=!1){let r=E(e,"images","resizeNearestNeighbor");F(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),F(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),F(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),F(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=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},c=M.runKernel(fc,o,l);return i?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var e1=P({resizeNearestNeighbor_:EP});function FP(e,t,n){F(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),F(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let a=E(e,"a","bandPart");F(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=U(Ah(0,s,1,"int32"),[-1,1]),l=Ah(0,i,1,"int32"),c=me(o,l),u=ma(Di(c,pe(+t,"int32")),rs(c,pe(-n,"int32"))),p=xt([s,i],a.dtype);return U($t(ut(U(a,[-1,s,i])).map(d=>Sn(u,d,p))),r)}var AP=P({bandPart_:FP});function $P(e){let t;if(Array.isArray(e)){t=!1,F(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)F(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=zn(e,e.shape[0],0).map(r=>ss(r,[0]));F(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r<e.length;++r)n.push(M.tidy(()=>{let s=a[r];if(r>0)for(let i=0;i<r;++i){let o=L(Se(L(n[i],s)),n[i]);s=me(s,o)}return xe(s,Vh(s,"euclidean"))}));return t?$t(n,0):n}var DP=P({gramSchmidt_:$P});function RP(e,t=!1){if(F(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return t1(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),a=ut(U(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[c,u]=t1(l,t);r.push(c),s.push(u)});let i=U($t(r,0),e.shape),o=U($t(s,0),e.shape);return[i,o]}}function t1(e,t=!1){return M.tidy(()=>{F(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=tb(n),s=Zr(e),i=Sa([[1]],[1,1]),o=Zr(i),l=n>=a?a:n;for(let c=0;c<l;++c){let u=s,p=o,d=r;[o,s,r]=M.tidy(()=>{let h=We(s,[c,c],[n-c,1]),m=Vh(h),f=We(s,[c,c],[1,1]),g=Sn(ha(f,0),Sa([[-1]]),Sa([[1]])),y=me(f,L(g,m)),b=xe(h,y);b.shape[0]===1?o=Zr(i):o=Je([i,We(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let x=Nt(xe(ze(g,y),m)),v=We(s,[c,0],[n-c,a]),N=L(x,o),T=Ve(o);if(c===0)s=me(v,ze(N,ze(T,v)));else{let $=me(v,ze(N,ze(T,v)));s=Je([We(s,[0,0],[c,a]),$],0)}let S=Ve(N),A=We(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=me(A,ze(ze(A,o),S));else{let $=me(A,ze(ze(A,o),S));r=Je([We(r,[0,0],[n,c]),$],1)}return[o,s,r]}),Ae([u,p,d])}return!t&&n>a&&(r=We(r,[0,0],[n,a]),s=We(s,[0,0],[a,a])),[r,s]})}var MP=P({qr_:RP}),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 PP(e,t,n=mn.SUM_BY_NONZERO_WEIGHTS){let a=E(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=E(t,"weights","computeWeightedLoss"));let s=r==null?a:L(a,r);if(n===mn.NONE)return s;if(n===mn.SUM)return Se(s);if(n===mn.MEAN){if(r==null)return St(s);{let i=a.size/r.size,o=xe(Se(s),Se(r));return i>1?xe(o,pe(i)):o}}if(n===mn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return xe(Se(s),pe(a.size));{let i=L(r,Ya(a.shape)),o=ue(Se(Mi(i,pe(0))),"float32");return xe(Se(s),o)}}throw Error(`Unknown reduction: ${n}`)}var vr=P({computeWeightedLoss_:PP});function OP(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","absoluteDifference"),s=E(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=E(n,"weights","absoluteDifference")),on(r.shape,s.shape,"Error in absoluteDifference: ");let o=Lt(me(r,s));return vr(o,i,a)}var LP=P({absoluteDifference_:OP});function zP(e,t,n,a,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","cosineDistance"),i=E(t,"predictions","cosineDistance"),o=null;a!=null&&(o=E(a,"weights","cosineDistance")),on(s.shape,i.shape,"Error in cosineDistance: ");let l=pe(1),c=me(l,Se(L(s,i),n,!0));return vr(c,o,r)}var BP=P({cosineDistance_:zP});function WP(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","hingeLoss"),s=E(t,"predictions","hingeLoss"),i=null;n!=null&&(i=E(n,"weights","hingeLoss")),on(r.shape,s.shape,"Error in hingeLoss: ");let o=pe(1);r=me(L(pe(2),r),o);let l=qe(me(o,L(r,s)));return vr(l,i,a)}var VP=P({hingeLoss_:WP});function UP(e,t,n,a=1,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","huberLoss"),i=E(t,"predictions","huberLoss"),o=null;n!=null&&(o=E(n,"weights","huberLoss")),on(s.shape,i.shape,"Error in huberLoss: ");let l=pe(a),c=Lt(me(i,s)),u=Kl(c,l),p=me(c,u),d=J(L(pe(.5),lt(u)),L(l,p));return vr(d,o,r)}var GP=P({huberLoss_:UP});function HP(e,t,n,a=1e-7,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","logLoss"),i=E(t,"predictions","logLoss"),o=null;n!=null&&(o=E(n,"weights","logLoss")),on(s.shape,i.shape,"Error in logLoss: ");let l=pe(1),c=pe(a),u=Nt(L(s,Pn(J(i,c)))),p=L(me(l,s),Pn(J(me(l,i),c))),d=me(u,p);return vr(d,o,r)}var jP=P({logLoss_:HP});function qP(e,t,n,a=mn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","meanSquaredError"),s=E(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=E(n,"weights","meanSquaredError")),on(r.shape,s.shape,"Error in meanSquaredError: ");let o=zh(r,s);return vr(o,i,a)}var KP=P({meanSquaredError_:qP});function XP(e,t){let n=E(e,"labels","sigmoidCrossEntropyWithLogits"),a=E(t,"logits","sigmoidCrossEntropyWithLogits");on(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=qe(a),s=L(a,n),i=Nh(hn(Nt(Lt(a))));return J(me(r,s),i)}function YP(e,t,n,a=0,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"multiClassLabels","sigmoidCrossEntropy"),i=E(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","sigmoidCrossEntropy")),on(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let c=pe(a),u=pe(1),p=pe(.5);s=J(L(s,me(u,c)),L(p,c))}let l=XP(s,i);return vr(l,o,r)}var JP=P({sigmoidCrossEntropy_:YP});function QP(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Ka((a,r,s)=>{let i=sb(r,[n],!0),o=me(ue(r,"float32"),i);s([a,o]);let l=Nt(L(o,a));return{value:Se(l,[n]),gradFunc:(c,u)=>{let[p,d]=u,h=Ri(c.shape,[n]);return[L(U(c,h),me(ue(p,"float32"),hn(d))),L(U(c,h),me(hn(d),ue(p,"float32")))]}}})(e,t)}function ZP(e,t,n,a=0,r=mn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"onehotLabels","softmaxCrossEntropy"),i=E(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","softmaxCrossEntropy")),on(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let c=pe(a),u=pe(1),p=pe(s.shape[1]);s=J(L(s,me(u,c)),xe(c,p))}let l=QP(s,i);return vr(l,o,r)}var eO=P({softmaxCrossEntropy_:ZP}),tO={fft:Wc,ifft:Jl,rfft:Vc,irfft:Lh},nO={hammingWindow:ZM,hannWindow:qk,frame:Kk,stft:aP},Ja={flipLeftRight:oP,resizeNearestNeighbor:e1,resizeBilinear:Zk,rotateWithOffset:uP,cropAndResize:sP,nonMaxSuppression:pP,nonMaxSuppressionAsync:xP,nonMaxSuppressionWithScore:wP,nonMaxSuppressionWithScoreAsync:IP,nonMaxSuppressionPadded:NP,nonMaxSuppressionPaddedAsync:CP},n1={bandPart:AP,gramSchmidt:DP,qr:MP},aO={absoluteDifference:LP,computeWeightedLoss:vr,cosineDistance:BP,hingeLoss:VP,huberLoss:GP,logLoss:jP,meanSquaredError:KP,sigmoidCrossEntropy:JP,softmaxCrossEntropy:eO},wr=class extends nk{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 Ae(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 Ck(e,t)}dispose(){this.iterations_!=null&&Ae(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:pe(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(wr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var qh=class extends wr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:D(()=>Ge(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;D(()=>{let l=J(L(i,this.rho),L(lt(s),1-this.rho)),c=L(xe(an(J(o,this.epsilon)),an(J(i,this.epsilon))),s),u=J(L(o,this.rho),L(lt(c),1-this.rho));i.assign(l),o.assign(u);let p=J(L(c,-this.learningRate),a);a.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ae(this.accumulatedGrads.map(e=>e.variable)),Ae(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)}};qh.className="Adadelta";es(qh);var Kh=class extends wr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t];if(this.accumulatedGrads[n]==null){let i=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:D(()=>Cn(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=J(s,lt(r));s.assign(i);let o=J(L(xe(r,an(J(i,M.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ae(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)}};Kh.className="Adagrad";es(Kh);var Xh=class extends wr{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=pe(t).variable(),this.accBeta2=pe(n).variable()}),a==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=me(1,this.accBeta1),a=me(1,this.accBeta2);t.forEach((r,s)=>{let i=M.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:D(()=>Ge(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:D(()=>Ge(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[s].variable,u=this.accumulatedSecondMoment[s].variable,p=J(L(c,this.beta1),L(l,1-this.beta1)),d=J(L(u,this.beta2),L(lt(l),1-this.beta2)),h=xe(p,n),m=xe(d,a);c.assign(p),u.assign(d);let f=J(L(xe(h,J(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&&Ae(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ae(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(xr(this.beta1,this.iterations_+1)),this.accBeta2.assign(xr(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)}};Xh.className="Adam";es(Xh);var Yh=class extends wr{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=pe(0).variable(),this.accBeta1=pe(t).variable()}),a==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);D(()=>{let n=me(1,this.accBeta1),a=xe(-this.learningRate,J(L(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=M.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Ge(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:Ge(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[s].variable,u=this.accumulatedWeightedInfNorm[s].variable,p=J(L(c,this.beta1),L(l,1-this.beta1)),d=L(u,this.beta2),h=Lt(l),m=Xa(d,h);c.assign(p),u.assign(m);let f=J(L(xe(a,n),xe(p,J(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(J(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ae(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ae(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)}};Yh.className="Adamax";es(Yh);var Uc=class extends wr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=M.registeredVariables[t];D(()=>{let s=J(L(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=jt(pe(-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)}};Uc.className="SGD";es(Uc);var Jh=class extends Uc{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=pe(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t];if(this.accumulations[n]==null){let i=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:D(()=>Ge(a).variable(i))}}let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&D(()=>{let i,o=J(L(this.m,r),s);this.useNesterov?i=J(L(this.c,J(s,L(o,this.m))),a):i=J(L(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ae(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)}};Jh.className="Momentum";es(Jh);var Qh=class extends wr{constructor(e,t=.9,n=0,a=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=M.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=M.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:D(()=>Ge(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:D(()=>Ge(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;D(()=>{let l=J(L(i,this.decay),L(lt(s),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[n].variable,u=J(L(c,this.decay),L(s,1-this.decay)),p=xe(L(s,this.learningRate),an(me(l,J(lt(u),this.epsilon)))),d=J(L(o,this.momentum),p);i.assign(l),c.assign(u),o.assign(d);let h=me(a,d);a.assign(h)}else{let c=J(L(i,this.decay),L(lt(s),1-this.decay)),u=J(L(o,this.momentum),xe(L(s,this.learningRate),an(J(c,this.epsilon))));i.assign(c),o.assign(u);let p=me(a,u);a.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ae(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ae(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ae(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)}};Qh.className="RMSProp";es(Qh);var Oi=class{static sgd(e){return new Uc(e)}static momentum(e,t,n=!1){return new Jh(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new Qh(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new Xh(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new qh(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new Yh(e,t,n,a,r)}static adagrad(e,t=.1){return new Kh(e,t)}},Li={sgd:Oi.sgd,momentum:Oi.momentum,adadelta:Oi.adadelta,adagrad:Oi.adagrad,rmsprop:Oi.rmsprop,adamax:Oi.adamax,adam:Oi.adam},rO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Zh(){return new Promise(e=>rO(()=>e()))}var _={};Oe(_,{ERF_A1:()=>fO,ERF_A2:()=>gO,ERF_A3:()=>yO,ERF_A4:()=>bO,ERF_A5:()=>xO,ERF_P:()=>mO,PARALLELIZE_THRESHOLD:()=>Tb,SELU_SCALE:()=>r1,SELU_SCALEALPHA:()=>a1,applyActivation:()=>Hh,assertAndGetBroadcastShape:()=>bt,assertAxesAreInnerMostDims:()=>UD,assertParamsConsistent:()=>sO,assignToTypedArray:()=>CO,axesAreInnerMostDims:()=>ab,calculateShapes:()=>G0,combineLocations:()=>Ek,complexWithEvenIndex:()=>TO,complexWithOddIndex:()=>NO,computeConv2DInfo:()=>Ac,computeConv3DInfo:()=>pk,computeDefaultPad:()=>Hy,computeDilation2DInfo:()=>h$,computeOptimalWindowSize:()=>oO,computeOutAndReduceShapes:()=>Fk,computeOutShape:()=>iO,computePool2DInfo:()=>ck,computePool3DInfo:()=>m$,convertConv2DDataFormat:()=>uk,eitherStridesOrDilationsAreOne:()=>ja,expandShapeToKeepDim:()=>Ri,exponent:()=>EO,exponents:()=>_O,fromStringArrayToUint8:()=>$O,fromUint8ToStringArray:()=>AO,getAxesPermutation:()=>Ak,getBroadcastDims:()=>sD,getComplexWithIndex:()=>SO,getFusedBiasGradient:()=>Gh,getFusedDyActivation:()=>Uh,getImageCenter:()=>lO,getInnerMostAxes:()=>GD,getPermuted:()=>cO,getReductionAxes:()=>zt,getReshaped:()=>uO,getReshapedPermuted:()=>pO,getSliceBeginCoords:()=>dO,getSliceSize:()=>hO,getUndoAxesPermutation:()=>rb,log:()=>wO,mergeRealAndImagArrays:()=>kO,prepareAndValidate:()=>U0,prepareSplitSize:()=>FO,segment_util:()=>s1,shouldFuse:()=>jh,slice_util:()=>dn,splitRealAndImagArrays:()=>IO,tupleValuesAreOne:()=>ts,upcastType:()=>pa,validateInput:()=>Ay,validateUpdateShape:()=>Fy,warn:()=>vO});function sO(e,t){let n=e[0].length;e.forEach((r,s)=>{F(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),F(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++)F(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 iO(e,t){let n=e[0].slice();for(let a=1;a<e.length;a++)n[t]+=e[a][t];return n}var Tb=30;function oO(e){return e<=Tb?e:Td(e,Math.floor(Math.sqrt(e)))}function lO(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function uO(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 cO(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 pO(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 dO(e,t){let n=[0];for(let a=0;a<t;++a)n.push(e[a][0]);return n}function hO(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 a1=1.7580993408473768,r1=1.0507009873554805,mO=.3275911,fO=.254829592,gO=-.284496736,yO=1.421413741,bO=-1.453152027,xO=1.061405429;function vO(...e){ee().getBool("IS_TEST")||console.warn(...e)}function wO(...e){ee().getBool("IS_TEST")||console.log(...e)}function kO(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 IO(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 TO(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 NO(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 SO(e,t){let n=e[t*2],a=e[t*2+1];return{real:n,imag:a}}function CO(e,t,n,a){e[a*2]=t,e[a*2+1]=n}function _O(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 EO(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 FO(e,t,n=0){let a=[];if(typeof t=="number")F(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);F(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}F(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 s1={};Oe(s1,{collectGatherOpShapeInfo:()=>MO,computeOutShape:()=>RO,segOpComputeOptimalWindowSize:()=>DO});function DO(e,t){let n=!1,a;for(e<=Tb?(a=e,n=!0):a=Td(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=Td(e,a+1);return a}function RO(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 MO(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 AO(e){try{return e.map(t=>ih(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function $O(e){return e.map(t=>kc(t))}var Qa={};Oe(Qa,{nonMaxSuppressionV3Impl:()=>Xk,nonMaxSuppressionV4Impl:()=>Yk,nonMaxSuppressionV5Impl:()=>Jk,whereImpl:()=>zk});var i1={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Ql(ue(n,"float32"),-1))}}},PO={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=lt(ue(n,"float32")),r=an(me(pe(1),a));return Nt(xe(e,r))}}}},OO={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=an(me(lt(ue(n,"float32")),1));return xe(e,a)}}}},LO={kernelName:Hr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=e,i=zt(n.shape,r);return i.length>0&&(s=Se(s,i)),U(s,n.shape)},b:()=>{let s=e,i=zt(a.shape,r);return i.length>0&&(s=Se(s,i)),U(s,a.shape)}}}},zO={kernelName:As,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},BO={kernelName:$s,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},WO={kernelName:nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},VO={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,an(me(pe(1),lt(ue(n,"float32")))))}}},UO={kernelName:Bo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=an(J(pe(1),lt(ue(n,"float32"))));return xe(e,a)}}}},GO={kernelName:Uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=J(lt(n),lt(a)),i=L(e,xe(a,s)),o=zt(n.shape,r);return o.length>0&&(i=Se(i,o)),U(i,n.shape)},b:()=>{let s=J(lt(n),lt(a)),i=Nt(L(e,xe(n,s))),o=zt(a.shape,r);return o.length>0&&(i=Se(i,o)),U(i,a.shape)}}}},HO={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,J(lt(ue(n,"float32")),1))}}},jO={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,me(pe(1),lt(ue(n,"float32"))))}}};function qO(e,t,n,a,r,s){let i=E(e,"dy","avgPool3dGrad"),o=E(t,"input","avgPool3dGrad"),l=i,c=o,u=!1;o.rank===4&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),F(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),F(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),s!=null&&F(Gt(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let p={dy:l,input:c},d={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=M.runKernel(Ed,p,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var KO=P({avgPool3dGrad_:qO}),XO={kernelName:ac,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>KO(e,a,r,s,i,o)}}};function YO(e,t,n,a,r){let s=E(e,"dy","avgPoolGrad"),i=E(t,"input","avgPoolGrad");F(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=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),F(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),F(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let u={dy:l,input:o},p={filterSize:n,strides:a,pad:r},d=M.runKernel(_d,u,p);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var JO=P({avgPoolGrad_:YO}),QO={kernelName:Ds,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>JO(e,a,r,s,i)}}},ZO={kernelName:Rs,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)}}},eL={kernelName:rc,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>Oc(e,a,r)}}},tL={kernelName:m0,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:()=>Se(e,o,!0)}}},nL={kernelName:Ms,gradFunc:e=>({x:()=>e.clone()})},aL={kernelName:Ps,gradFunc:e=>({x:()=>Ge(e)})},rL={kernelName:jr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>Sn(ma(rs(a,r),Di(a,s)),e,Ge(e))}}},sL={kernelName:sc,inputsToSave:["x"],gradFunc:i1.gradFunc},iL={kernelName:Go,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=ca(r,t[0].shape)[0],i=a.map(o=>o[s]);return zn(e,i,s).map(o=>()=>o)}},oL={kernelName:Os,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return F(ts(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Ky(a.shape,e,r,i,o,l),filter:()=>kb(a,e,r.shape,i,o,l)}}},lL={kernelName:Ls,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 uL(e,t,n,a,r){let s=e;e.rank===4&&(s=U(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),F(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),F(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),F(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),F(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),F(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);let o={x:s,dy:i},l={strides:a,pad:r,filterShape:n};return M.runKernel(Dd,o,l)}var cL=P({conv3DBackpropFilter_:uL}),pL={kernelName:ic,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;F(ts(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:()=>vk(i.shape,e,o,r,s),filter:()=>cL(i,e,o.shape,r,s)}}},dL={kernelName:zs,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Nt(Mh(ue(n,"float32"))),e)}}},hL={kernelName:Ho,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Ph(ue(n,"float32")),e)}}},mL={kernelName:Bs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=Ak([r],a.rank),l=kh(e,r,s,!i);return o!=null&&(l=Ve(l,o)),l}}}},fL={kernelName:Ws,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;F(ts(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,c]=t;return F(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),F(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),F(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]}.`),F(ja(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),i!=null&&F(Gt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`),{x:()=>jk(l.shape,e,c,r,s,a,i),filter:()=>Hk(l,e,c.shape,r,s,a,i)}}},gL={kernelName:oc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,s={x:a,filter:r,dy:e},i={x:a,filter:r,dy:e};return{x:()=>M.runKernel(zd,s,n),filter:()=>M.runKernel(Bd,i,n)}}},yL={kernelName:Ko,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>M.runKernel(Wd,a)}}},bL={kernelName:Xo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(hn(Nt(lt(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,a)}}},xL={kernelName:Us,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},vL={kernelName:Jo,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>U(e,n.shape)}}},wL={kernelName:Qo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,hn(n))}}},kL={kernelName:Gs,gradFunc:e=>({x:()=>Ge(e)})},IL={kernelName:Hs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=xe(e,ue(a,"float32")),i=zt(n.shape,r);return i.length>0?U(Se(s,i),n.shape):s},b:()=>{let s=L(e,ue(n,"float32")),i=zt(a.shape,r);i.length>0&&(s=U(Se(s,i),a.shape));let o=lt(a);return Nt(xe(s,ue(o,"float32")))}}}},TL={kernelName:js,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?pe(1):o,c=zt(s.shape,r.shape),u=[];if(s.rank===1){for(let f=0;f<r.shape.length-1;++f)u.push(r.shape[f]);u.push(1)}let p=me(r,s),d=L(e,l),h=Dh(J(i,pe(a))),m=L(L(L(h,h),h),pe(-.5));return{x:()=>s.rank===1?U(L(L(e,qa(U(h,[1,1,1,s.shape[0]]),u)),l),r.shape):U(L(L(e,h),l),r.shape),mean:()=>{let f=L(L(h,pe(-1)),d);return s.rank===1&&(f=Se(f,c)),U(f,s.shape)},variance:()=>{let f=L(L(m,p),d);return s.rank===1&&(f=Se(f,c)),U(f,s.shape)},scale:()=>{let f=L(p,h),g=L(e,f);return s.rank===1&&(g=Se(g,c)),U(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=Se(f,c)),U(f,s.shape)}}}},NL={kernelName:el,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=ca(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=o1(0,u),m=o1(u+1,u+1+d),f=l1([c,[l],p]),g=U(e,f),y=U(r,[l]),b=l1([[u],h,m]),x=Ve(g,b),v=bb(x,y,a.shape[i]),N=rb(b);return v=Ve(v,N),v},indices:()=>r}}};function o1(e,t){let n=[];for(let a=e;a<t;++a)n.push(a);return n}function l1(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 SL={kernelName:qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>Ge(n),b:()=>Ge(a)}}},CL={kernelName:Ks,gradFunc:e=>({x:()=>ue(e,"float32")})},_L={kernelName:al,gradFunc:e=>({x:()=>Ge(e)})},EL={kernelName:rl,gradFunc:e=>({x:()=>Ge(e)})},FL={kernelName:sl,gradFunc:e=>({x:()=>Ge(e)})},AL={kernelName:Xs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=ha(a,0);return{x:()=>Sn(s,e,L(e,r))}}},$L={kernelName:ll,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,J(n,1))}}},DL={kernelName:Ys,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,ue(n,"float32"))}}},RL={kernelName:f0,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=!0,i=hn(a);return me(e,L(Se(e,r,s),i))}}}};function ML(e,t,n,a=5,r=1,s=1,i=.5){let o={x:e,y:t,dy:n},l={depthRadius:a,bias:r,alpha:s,beta:i};return M.runKernel(jd,o,l)}var PL=P({localResponseNormalizationBackprop_:ML}),OL={kernelName:pc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>PL(a,r,e,s,i,o,l)}}};function u1(e,t,n,a){return t.rank<n.rank&&(t=U(t,Ri(t.shape,a))),e.rank<n.rank&&(e=U(e,Ri(e.shape,a))),{x:()=>L(e,ue(as(n,t),e.dtype))}}var c1={kernelName:Js,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=ca(r,s.shape),l=u1(e,i,s,o);return{x:()=>l.x()}}},LL={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,ue(rs(n,a),"float32")),b:()=>L(e,ue(Th(n,a),"float32"))}}};function zL(e,t,n,a,r,s,i){let o=E(e,"dy","maxPool3dGrad"),l=E(t,"input","maxPool3dGrad"),c=E(n,"output","maxPool3dGrad"),u=o,p=l,d=c,h=!1;l.rank===4&&(h=!0,u=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),p=U(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=U(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),F(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),F(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),F(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),i!=null&&F(Gt(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let m={dy:u,input:p,output:d},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=M.runKernel(Kd,m,f);return h?U(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var BL=P({maxPool3dGrad_:zL}),WL={kernelName:dc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>BL(e,a,r,s,i,o,l)}}};function VL(e,t,n,a,r,s,i){let o=E(e,"dy","maxPoolGrad"),l=E(t,"input","maxPoolGrad"),c=E(n,"output","maxPoolGrad");F(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),F(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),F(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),i!=null&&F(Gt(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let u={dy:o,input:l,output:c},p={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return M.runKernel(qd,u,p)}var UL=P({maxPoolGrad_:VL}),GL={kernelName:Zs,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>UL(e,a,r,s,i,o)}}},HL={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=ca(r,a.shape),i=Fk(a.shape,s)[1],o=Pt(i);return{x:()=>{let l=a.shape.slice();s.forEach(u=>{l[u]=1});let c=U(e,l);return xe(L(c,Ya(a.shape,"float32")),o)}}}},jL={kernelName:ti,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=ca(r,s.shape),l=u1(e,i,s,o);return{x:()=>l.x()}}},qL={kernelName:ni,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>L(e,ue(Di(n,a),"float32")),b:()=>L(e,ue(ha(n,a),"float32"))}}},KL={kernelName:hc,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)}}},XL={kernelName:cl,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=zt(n.shape,r);return s.length>0?U(Se(e,s),n.shape):e},b:()=>{let s=L(e,Nt(Hl(xe(n,a)))),i=zt(a.shape,r);return i.length>0?U(Se(s,i),a.shape):s}}}},YL={kernelName:ai,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=L(e,ue(a,"float32")),i=zt(n.shape,r);return i.length>0?U(Se(s,i),n.shape):s},b:()=>{let s=L(e,ue(n,"float32")),i=zt(a.shape,r);return i.length>0?U(Se(s,i),a.shape):s}}}},JL={kernelName:pl,gradFunc:e=>({x:()=>Nt(e)})},QL={kernelName:ri,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>xt(n.shape,"float32")}}},ZL={kernelName:gl,gradFunc:e=>({x:()=>Ge(e)})},e3={kernelName:yl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return ut(e,a).map(r=>()=>r)}},p1={kernelName:si,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)}}},t3={kernelName:ii,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=bt(s.shape,i.shape);return{a:()=>{let l=ue(i,"float32"),c=L(e,L(l,xr(s,me(l,pe(1))))),u=zt(s.shape,o);return u.length>0&&(c=Se(c,u)),U(c,s.shape)},b:()=>{let l=ha(s,0),c=Sn(l,Pn(s),Ge(s)),u=L(e,L(r,c)),p=zt(i.shape,o);return p.length>0&&(u=Se(u,p)),U(u,i.shape)}}}},n3={kernelName:oi,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=ha(n,0);return{x:()=>Sn(r,e,L(e,a)),alpha:()=>{let s=Sn(r,Ge(e),L(e,n)),i=zt(a.shape,e.shape);return i.length>0&&(s=Se(s,i)),U(s,a.shape)}}}},a3={kernelName:Vs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=xe(e,ue(a,"float32")),i=zt(n.shape,r);return i.length>0?U(Se(s,i),n.shape):s},b:()=>{let s=L(e,ue(n,"float32")),i=zt(a.shape,r);i.length>0&&(s=U(Se(s,i),a.shape));let o=lt(a);return Nt(xe(s,ue(o,"float32")))}}}},r3={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,Nt(lt(n)))}}},s3={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=L(Di(n,6),Ql(n));return{x:()=>L(e,ue(a,"float32"))}}},i3={kernelName:li,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ue(Ql(n),"float32"))}}},o3={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>U(e,n.shape)}}},l3={kernelName:ui,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>M.runKernel(Zd,r,n)}}},u3={kernelName:fc,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>M.runKernel(Qd,r,n)}}},c3={kernelName:pi,gradFunc:(e,t,n)=>{let{dims:a}=n,r=ca(a,e.shape);return{x:()=>Ln(e,r)}}},p3={kernelName:di,gradFunc:e=>({x:()=>Ge(e)})},d3={kernelName:hi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Nt(xe(e,L(xr(n,1.5),2)))}}},h3={kernelName:kl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>ue(Ge(n),"float32"),t:()=>L(e,ue(n,e.dtype)),e:()=>L(e,ue(Pc(n),e.dtype))}}},m3={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=ha(n,pe(0)),r=pe(a1),s=pe(r1),i=L(e,s),o=L(L(e,r),hn(ue(n,"float32")));return Sn(a,i,o)}}}},f3={kernelName:fi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,me(pe(1),n)))}}},g3={kernelName:Sl,gradFunc:e=>({x:()=>Ge(e)})},y3={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Rc(ue(n,"float32")),e)}}},b3={kernelName:Nl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(wh(ue(n,"float32")),e)}}},x3={kernelName:Tl,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)}}},v3={kernelName:bi,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=L(e,a);return{logits:()=>me(i,L(Se(i,[r],s),a))}}},w3={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,da(n))}}},d1={kernelName:gc,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>$c(e,a,r)}}},h1={kernelName:_l,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>Je(e,a)}}},k3={kernelName:gi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,L(an(ue(n,"float32")),2))}}},I3={kernelName:yc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(ue(n,"float32"),2))}}},T3={kernelName:xi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=pe(2);return{a:()=>L(e,L(r,me(n,a))),b:()=>L(e,L(r,me(a,n)))}}},N3={kernelName:Kr,gradFunc:e=>({x:()=>Ge(e)})},S3={kernelName:vi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=bt(n.shape,a.shape);return{a:()=>{let s=e,i=zt(n.shape,r);return i.length>0&&(s=Se(s,i)),U(s,n.shape)},b:()=>{let s=e,i=zt(a.shape,r);return i.length>0&&(s=Se(s,i)),U(Nt(s),a.shape)}}}},C3={kernelName:yi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;ca(s,a.shape).forEach(l=>{r[l]=1});let i=U(e,r),o=L(i,Ya(a.shape,"float32"));return{x:()=>o}}},_3={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>xe(e,lt(Rc(n)))}}},E3={kernelName:wi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(me(pe(1),lt(n)),e)}}},F3={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=J(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=J(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=J(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=J(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}}}},A3={kernelName:ki,gradFunc:(e,t,n)=>{let a=n,{perm:r}=a,s=rb(r);return{x:()=>Ve(e,s)}}},$3={kernelName:$l,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>$t(e,r)}}},R3={kernelName:bc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>D3(e,n)}}};function D3(e,t){let n=Xa(t,Ge(t)),a=$i(e,n),r=rs(t,pe(0,"int32")),s=a.rank-r.rank;for(let o=0;o<s;++o)r=Mn(r,o+1);r=ma(r,Ya(a.shape,"bool"));let i=Ge(a);return Sn(r,a,i)}var M3={kernelName:Dl,gradFunc:e=>({x:()=>Ge(e)})},P3=[i1,PO,OO,LO,zO,BO,WO,VO,UO,GO,HO,jO,XO,QO,ZO,eL,tL,nL,aL,rL,sL,iL,lL,oL,pL,dL,hL,mL,fL,gL,a3,yL,bL,xL,vL,wL,IL,kL,TL,NL,SL,CL,_L,EL,FL,AL,$L,DL,RL,OL,c1,c1,LL,WL,GL,HL,jL,qL,KL,XL,YL,JL,QL,ZL,e3,p1,p1,t3,n3,r3,s3,i3,o3,l3,u3,c3,p3,d3,h3,m3,f3,g3,y3,b3,x3,v3,w3,d1,d1,h1,h1,k3,T3,I3,N3,S3,C3,_3,E3,F3,A3,$3,R3,M3];for(let e of P3)g0(e);Y().prototype.abs=function(){return this.throwIfDisposed(),Lt(this)};Y().prototype.acos=function(){return this.throwIfDisposed(),Py(this)};Y().prototype.acosh=function(){return this.throwIfDisposed(),Oy(this)};Y().prototype.add=function(e){return this.throwIfDisposed(),J(this,e)};Y().prototype.all=function(e,t){return this.throwIfDisposed(),yh(this,e,t)};Y().prototype.any=function(e,t){return this.throwIfDisposed(),Ec(this,e,t)};Y().prototype.argMax=function(e){return this.throwIfDisposed(),Fc(this,e)};Y().prototype.argMin=function(e){return this.throwIfDisposed(),Ly(this,e)};Y().prototype.asScalar=function(){return this.throwIfDisposed(),F(this.size===1,()=>"The array must have only 1 element."),U(this,[])};Y().prototype.asType=function(e){return this.throwIfDisposed(),ue(this,e)};Y().prototype.as1D=function(){return this.throwIfDisposed(),U(this,[this.size])};Y().prototype.as2D=function(e,t){return this.throwIfDisposed(),U(this,[e,t])};Y().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),U(this,[e,t,n])};Y().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),U(this,[e,t,n,a])};Y().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),U(this,[e,t,n,a,r])};Y().prototype.asin=function(){return this.throwIfDisposed(),zy(this)};Y().prototype.asinh=function(){return this.throwIfDisposed(),By(this)};Y().prototype.atan=function(){return this.throwIfDisposed(),Wy(this)};Y().prototype.atan2=function(e){return this.throwIfDisposed(),Vy(this,e)};Y().prototype.atanh=function(){return this.throwIfDisposed(),Uy(this)};Y().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),Zn(this,e,t,n,a)};Y().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),$c(this,e,t)};Y().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),br(this,e,t,n,a,r)};Y().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Dc(this,e)};Y().prototype.cast=function(e){return this.throwIfDisposed(),ue(this,e)};Y().prototype.ceil=function(){return this.throwIfDisposed(),qy(this)};Y().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),qt(this,e,t)};Y().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ee&&(e=[e]),Je([this,...e],t)};Y().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),xh(this,e,t,n,a,r,s)};Y().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),vh(this,e,t,n,a,r)};Y().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Ft(this,e,t,n,a,r,s)};Y().prototype.cos=function(){return this.throwIfDisposed(),Rc(this)};Y().prototype.cosh=function(){return this.throwIfDisposed(),wh(this)};Y().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),kh(this,e,t,n)};Y().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Yy(this,e,t)};Y().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),ns(this,e,t,n,a,r,s)};Y().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),Jy(this,e,t,n,a,r)};Y().prototype.divNoNan=function(e){return this.throwIfDisposed(),Qy(this,e)};Y().prototype.div=function(e){return this.throwIfDisposed(),xe(this,e)};Y().prototype.dot=function(e){return this.throwIfDisposed(),kk(this,e)};Y().prototype.elu=function(){return this.throwIfDisposed(),Gl(this)};Y().prototype.equal=function(e){return this.throwIfDisposed(),as(this,e)};Y().prototype.erf=function(){return this.throwIfDisposed(),Zy(this)};Y().prototype.exp=function(){return this.throwIfDisposed(),hn(this)};Y().prototype.expandDims=function(e){return this.throwIfDisposed(),Mn(this,e)};Y().prototype.expm1=function(){return this.throwIfDisposed(),eb(this)};Y().prototype.fft=function(){return this.throwIfDisposed(),Wc(this)};Y().prototype.flatten=function(){return this.throwIfDisposed(),U(this,[this.size])};Y().prototype.floor=function(){return this.throwIfDisposed(),Hl(this)};Y().prototype.floorDiv=function(e){return this.throwIfDisposed(),gh(this,e)};Y().prototype.gather=function(e,t){return this.throwIfDisposed(),$i(this,e,t)};Y().prototype.greaterEqual=function(e){return this.throwIfDisposed(),rs(this,e)};Y().prototype.greater=function(e){return this.throwIfDisposed(),ha(this,e)};Y().prototype.ifft=function(){return this.throwIfDisposed(),Jl(this)};Y().prototype.irfft=function(){return this.throwIfDisposed(),Lh(this)};Y().prototype.isFinite=function(){return this.throwIfDisposed(),Ik(this)};Y().prototype.isInf=function(){return this.throwIfDisposed(),Tk(this)};Y().prototype.isNaN=function(){return this.throwIfDisposed(),Nk(this)};Y().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Mc(this,e)};Y().prototype.lessEqual=function(e){return this.throwIfDisposed(),Di(this,e)};Y().prototype.less=function(e){return this.throwIfDisposed(),Th(this,e)};Y().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),nb(this,e,t,n,a)};Y().prototype.logSigmoid=function(){return this.throwIfDisposed(),_k(this)};Y().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Ch(this,e)};Y().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),sb(this,e,t)};Y().prototype.log=function(){return this.throwIfDisposed(),Pn(this)};Y().prototype.log1p=function(){return this.throwIfDisposed(),Nh(this)};Y().prototype.logicalAnd=function(e){return this.throwIfDisposed(),ma(this,e)};Y().prototype.logicalNot=function(){return this.throwIfDisposed(),Pc(this)};Y().prototype.logicalOr=function(e){return this.throwIfDisposed(),_h(this,e)};Y().prototype.logicalXor=function(e){return this.throwIfDisposed(),$k(this,e)};Y().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),ze(this,e,t,n)};Y().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),At(this,e,t,n,a)};Y().prototype.max=function(e,t){return this.throwIfDisposed(),ea(this,e,t)};Y().prototype.maximum=function(e){return this.throwIfDisposed(),Xa(this,e)};Y().prototype.mean=function(e,t){return this.throwIfDisposed(),St(this,e,t)};Y().prototype.min=function(e,t){return this.throwIfDisposed(),ql(this,e,t)};Y().prototype.minimum=function(e){return this.throwIfDisposed(),Kl(this,e)};Y().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),ob(this,e,t)};Y().prototype.mod=function(e){return this.throwIfDisposed(),lb(this,e)};Y().prototype.mul=function(e){return this.throwIfDisposed(),L(this,e)};Y().prototype.neg=function(){return this.throwIfDisposed(),Nt(this)};Y().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Vh(this,e,t,n)};Y().prototype.notEqual=function(e){return this.throwIfDisposed(),Mi(this,e)};Y().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Bl(this,e,t,n)};Y().prototype.onesLike=function(){return this.throwIfDisposed(),On(this)};Y().prototype.pad=function(e,t){return this.throwIfDisposed(),ta(this,e,t)};Y().prototype.pool=function(e,t,n,a,r){return this.throwIfDisposed(),Mk(this,e,t,n,a,r)};Y().prototype.pow=function(e){return this.throwIfDisposed(),xr(this,e)};Y().prototype.prelu=function(e){return this.throwIfDisposed(),Lc(this,e)};Y().prototype.prod=function(e,t){return this.throwIfDisposed(),Fh(this,e,t)};Y().prototype.reciprocal=function(){return this.throwIfDisposed(),pb(this)};Y().prototype.relu=function(){return this.throwIfDisposed(),qe(this)};Y().prototype.relu6=function(){return this.throwIfDisposed(),$h(this)};Y().prototype.reshapeAs=function(e){return this.throwIfDisposed(),U(this,e.shape)};Y().prototype.reshape=function(e){return this.throwIfDisposed(),U(this,e)};Y().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),Zk(this,e,t,n)};Y().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),e1(this,e,t,n)};Y().prototype.reverse=function(e){return this.throwIfDisposed(),Ln(this,e)};Y().prototype.rfft=function(){return this.throwIfDisposed(),Vc(this)};Y().prototype.round=function(){return this.throwIfDisposed(),db(this)};Y().prototype.rsqrt=function(){return this.throwIfDisposed(),Dh(this)};Y().prototype.selu=function(){return this.throwIfDisposed(),Rh(this)};Y().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Pi(this,e,t,n,a,r,s)};Y().prototype.sigmoid=function(){return this.throwIfDisposed(),da(this)};Y().prototype.sign=function(){return this.throwIfDisposed(),hb(this)};Y().prototype.sin=function(){return this.throwIfDisposed(),Mh(this)};Y().prototype.sinh=function(){return this.throwIfDisposed(),Ph(this)};Y().prototype.slice=function(e,t){return this.throwIfDisposed(),We(this,e,t)};Y().prototype.softmax=function(e){return this.throwIfDisposed(),Na(this,e)};Y().prototype.softplus=function(){return this.throwIfDisposed(),jl(this)};Y().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Oc(this,e,t)};Y().prototype.split=function(e,t){return this.throwIfDisposed(),zn(this,e,t)};Y().prototype.sqrt=function(){return this.throwIfDisposed(),an(this)};Y().prototype.square=function(){return this.throwIfDisposed(),lt(this)};Y().prototype.squaredDifference=function(e){return this.throwIfDisposed(),zh(this,e)};Y().prototype.squeeze=function(e){return this.throwIfDisposed(),ss(this,e)};Y().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Ee?[this,e]:[this,...e];return $t(n,t)};Y().prototype.step=function(e){return this.throwIfDisposed(),Ql(this,e)};Y().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),fb(this,e,t,n,a,r,s,i,o)};Y().prototype.sub=function(e){return this.throwIfDisposed(),me(this,e)};Y().prototype.sum=function(e,t){return this.throwIfDisposed(),Se(this,e,t)};Y().prototype.tan=function(){return this.throwIfDisposed(),gb(this)};Y().prototype.tanh=function(){return this.throwIfDisposed(),Ul(this)};Y().prototype.tile=function(e){return this.throwIfDisposed(),qa(this,e)};Y().prototype.toBool=function(){return this.throwIfDisposed(),ue(this,"bool")};Y().prototype.toFloat=function(){return this.throwIfDisposed(),ue(this,"float32")};Y().prototype.toInt=function(){return this.throwIfDisposed(),ue(this,"int32")};Y().prototype.topk=function(e,t){return this.throwIfDisposed(),yb(this,e,t)};Y().prototype.transpose=function(e){return this.throwIfDisposed(),Ve(this,e)};Y().prototype.unique=function(e){return this.throwIfDisposed(),Wh(this,e)};Y().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),bb(this,e,t)};Y().prototype.unstack=function(e){return this.throwIfDisposed(),ut(this,e)};Y().prototype.where=function(e,t){return this.throwIfDisposed(),Sn(e,this,t)};Y().prototype.zerosLike=function(){return this.throwIfDisposed(),Ge(this)};var m1={};Oe(m1,{maxNorm:()=>O3,minMaxNorm:()=>B3,nonNeg:()=>z3,unitNorm:()=>L3});var Nb;function Bt(){return Nb==null&&(Nb=ok().epsilon()),Nb}function _a(){return"channelsLast"}var kr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,kr.prototype)}},Ea=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ea.prototype)}},z=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,z.prototype)}},$e=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,$e.prototype)}},f1=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,f1.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 Za(e,t){if(!e)throw new f1(t)}function g1(e,t){let n=0;for(let a of e)a===t&&n++;return n}function _n(e){return e.length===1?e[0]:e}function gt(e){return Array.isArray(e)?e:[e]}function Ir(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 fa={};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 Gc(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 fa)i=fa[s];else if(i=t[s],i==null)throw new z(`Unknown ${a}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new z(`${a}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in fa?[o,l]=fa.className:i in t&&([o,l]=t[i]),o==null)throw new z(`Unknown ${a}: ${i}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let c={};for(let h of Object.keys(fa))c[h]=fa[h];for(let h of Object.keys(n))c[h]=n[h];let u=s.config;u.customObjects=c;let p=Object.assign({},fa);for(let h of Object.keys(n))fa[h]=n[h];Cb(s.config);let d=l(o,s.config,n,r);return fa=Object.assign({},p),d}else{let c=Object.assign({},fa);for(let p of Object.keys(n))fa[p]=n[p];let u=new o(s.config);return fa=Object.assign({},c),u}}}function W3(e,t){return e<t?-1:e>t?1:0}function em(e,t){return-1*W3(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 V3(e){if(e==null)throw new z(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Wi(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new z(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function _b(e,t,n=0,a=Infinity){return Za(n>=0),Za(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function Kt(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>Kt(n,`element ${a+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${y1(e)}.`)}function y1(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>y1(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function U3(e,t){let n=w.now(),a;return(...r)=>{let s=w.now();return s-n<t||(n=s,a=e(...r)),a}}function b1(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Eb(e,t){return D(()=>an(Se(L(e,e),t,!0)))}var Hc=class extends re.Serializable{getConfig(){return{}}},Fb=class extends Hc{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=qt(t,0,this.maxValue);return L(e,xe(n,J(Bt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Fb.className="MaxNorm";re.registerClass(Fb);var Ab=class extends Hc{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>xe(e,J(Bt(),Eb(e,this.axis))))}getConfig(){return{axis:this.axis}}};Ab.className="UnitNorm";re.registerClass(Ab);var $b=class extends Hc{apply(e){return qe(e)}};$b.className="NonNeg";re.registerClass($b);var Db=class extends Hc{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=J(L(this.rate,qt(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,xe(n,J(Bt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Db.className="MinMaxNorm";re.registerClass(Db);var x1={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Wt(e){return Sb(e)}function v1(e,t={}){return Gc(e,re.SerializationMap.getMap().classNameMap,t,"constraint")}function Vt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in x1?x1[e]:e,config:{}};return v1(t)}else return e instanceof Hc?e:v1(e)}function O3(e){return new Fb(e)}function L3(e){return new Ab(e)}function z3(){return new $b}function B3(e){return new Db(e)}var w1={};Oe(w1,{constant:()=>j3,glorotNormal:()=>Z3,glorotUniform:()=>Q3,heNormal:()=>ez,heUniform:()=>tz,identity:()=>Y3,leCunNormal:()=>nz,leCunUniform:()=>az,ones:()=>H3,orthogonal:()=>rz,randomNormal:()=>K3,randomUniform:()=>q3,truncatedNormal:()=>X3,varianceScaling:()=>J3,zeros:()=>G3});var sz=["channelsFirst","channelsLast"],iz=["nearest","bilinear"],oz=["valid","same","causal"],lz=["max","avg"],uz=["sum","mul","concat","ave"],eu=new Map;function Dt(e){Wi(sz,"DataFormat",e)}function cz(e){Wi(iz,"InterpolationFormat",e)}function na(e){Wi(oz,"PaddingMode",e)}function k1(e){Wi(lz,"PoolMode",e)}var jc=[],I1="/";function Vi(e,t){jc.push(e);try{let n=t();return jc.pop(),n}catch(n){throw jc.pop(),n}}function pz(){return jc.length===0?"":jc.join(I1)+I1}function N1(e){if(!T1(e))throw new Error("Not a valid tensor name: '"+e+"'");return pz()+e}function S1(e){if(!T1(e))throw new Error("Not a valid tensor name: '"+e+"'");eu.has(e)||eu.set(e,0);let t=eu.get(e);if(eu.set(e,eu.get(e)+1),t>0){let n=`${e}_${t}`;return eu.set(n,1),n}else return e}var dz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function T1(e){return!!e.match(dz)}function hz(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 C1(e){return e=Array.isArray(e)?new Float32Array(e):e,Ze(e)}function tu(e){return ql(C1(e)).dataSync()[0]}function us(e){return ea(C1(e)).dataSync()[0]}function Fa(e,t){if(t<e)throw new z(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let a=e;a<t;++a)n.push(a);return n}function qc(e,t){return e.asType(t)}function Kc(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 mz(e,t){return D(()=>{if(e.shape.length!==2)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Kc(e,1);return Rb(n,[1,t,1])})}function fz(e){let t=[ls(e.shape)];return e.reshape(t)}function gz(e){if(e.rank<=1)throw new z(`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 Oh(e,t,n);case 2:return mb(e,[t,0],[n,e.shape[1]]);case 3:return Yl(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Bc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return We(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return We(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Mb(e,t,n){return D(()=>{switch(e.rank){case 1:return Oh(e,t,n);case 2:return mb(e,[0,t],[e.shape[0],n]);case 3:return Yl(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Bc(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function tm(e,t,n,a){return D(()=>{switch(e.rank){case 1:return Oh(e,t,n);case 2:switch(a){case 1:return Ui(e,t,n);case 2:return Mb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return Ui(e,t,n);case 2:return Yl(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Mb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return Ui(e,t,n);case 2:return Bc(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Bc(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Mb(e,t,n);default:throw new z(`The axis is not within the rank of the tensor ${a}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function 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),Je(e,t)}function _1(e,t){switch(e.rank){case 1:return gk([e,t]);case 2:return yk([e,t],0);case 3:return bk([e,t],0);case 4:return xk([e,t],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Rb(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new z(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return qa(e,t)}function nm(e,t=0,n=1,a,r){return Pk(e,t,n,a,r)}function er(e,t,n,a){if(e.rank<2||t.rank<2)throw new $e(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(r!==s)throw new $e(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){let r=!1,s=!1;return is.matMul({a:e,b:t,transposeA:r,transposeB:s,bias:a?Ob(e.rank,a,_a()):null,activation:n})}else{let r=e.shape.slice(),s=r.pop();e=e.reshape([-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),c=[...i,o],u=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=t.transpose(u).reshape([l,-1]);let p=[...r,...c],d=!1,h=!1;return is.matMul({a:e,b:t,transposeA:d,transposeB:h,bias:a?Ob(e.rank,a,_a()):null,activation:n}).reshape(p)}}function E1(e,t,n){return D(()=>(Array.isArray(t)?t=Ze(t,"int32"):t=t.toInt(),$i(e,t,n)))}function Xc(e){return L(e,e)}function Ob(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new z(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1,1,1]):t.reshape([1,a[3],a[0],a[1],a[2]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,1,1,a[0]]):t.reshape([1].concat(a))}else if(e===4){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1,1]):t.reshape([1,a[2],a[0],a[1]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,1,a[0]]):t.reshape([1].concat(a))}else if(e===3){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1]):t.reshape([1,a[1],a[0]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,a[0]]):t.reshape([1].concat(a))}else if(e<3)return t;throw new z(`Unsupported input rank by biasAdd: ${t.rank}`)}function tr(e,t,n){return D(()=>(n==null&&(n=_a()),Dt(n),e.add(Ob(e.rank,t,n))))}function yz(e,t=1){if(t!==1)throw new $e(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Gl(e)}function bz(e){return D(()=>xe(e,Lt(e).add(1)))}function F1(e,t,n,a){return D(()=>Uk(e,t,n,a))}function xz(e){return D(()=>{let t=J(.5,L(.2,e));return qt(t,0,1)})}function Yc(e,t,n=!1){return n?e():t()}var vz=["fanIn","fanOut","fanAvg"],wz=["normal","uniform","truncatedNormal"];function kz(e){Wi(vz,"FanMode",e)}function Iz(e){Wi(wz,"Distribution",e)}var ga=class extends re.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Lb=class extends ga{apply(e,t){return xt(e,t)}};Lb.className="Zeros";re.registerClass(Lb);var am=class extends ga{apply(e,t){return Ya(e,t)}};am.className="Ones";re.registerClass(am);var zb=class extends ga{constructor(e){super();if(typeof e!="object")throw new z(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new z(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return D(()=>L(pe(this.value),Ya(e,t)))}getConfig(){return{value:this.value}}};zb.className="Constant";re.registerClass(zb);var Bb=class extends ga{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 Xl(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 ga{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 nm(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 ga{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 Bh(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 ga{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return D(()=>{if(e.length!==2||e[0]!==e[1])throw new z("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,tb(e[0]))})}getConfig(){return{gain:this.gain}}};Ub.className="Identity";re.registerClass(Ub);function Tz(e,t="channelsLast"){let n,a;if(Dt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=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 En=class extends ga{constructor(e){super();if(e.scale<0)throw new z(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,kz(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Iz(this.distribution),this.seed=e.seed}apply(e,t){let n=Tz(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 Bh(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Xl(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};En.className="VarianceScaling";re.registerClass(En);var rm=class extends En{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return En.className}};rm.className="GlorotUniform";re.registerClass(rm);var sm=class extends En{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return En.className}};sm.className="GlorotNormal";re.registerClass(sm);var im=class extends En{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return En.className}};im.className="HeNormal";re.registerClass(im);var om=class extends En{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return En.className}};om.className="HeUniform";re.registerClass(om);var lm=class extends En{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return En.className}};lm.className="LeCunNormal";re.registerClass(lm);var um=class extends En{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return En.className}};um.className="LeCunNormal";re.registerClass(um);var Gb=class extends ga{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=nm(n,0,1,"float32"),r=n1.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 A1={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 $1(e,t={}){return Gc(e,re.SerializationMap.getMap().classNameMap,t,"initializer")}function Ct(e){return Sb(e)}function vt(e){if(typeof e=="string"){let t=e in A1?A1[e]:e;if(t==="GlorotNormal")return new sm;if(t==="GlorotUniform")return new rm;if(t==="HeNormal")return new im;if(t==="HeUniform")return new om;if(t==="LeCunNormal")return new lm;if(t==="LeCunUniform")return new um;{let n={};return n.className=t,n.config={},$1(n)}}else return e instanceof ga?e:$1(e)}function G3(){return new Lb}function H3(){return new am}function j3(e){return new zb(e)}function q3(e){return new Bb(e)}function K3(e){return new Wb(e)}function X3(e){return new Vb(e)}function Y3(e){return new Ub(e)}function J3(e){return new En(e)}function Q3(e){return new rm(e)}function Z3(e){return new sm(e)}function ez(e){return new im(e)}function tz(e){return new om(e)}function nz(e){return new lm(e)}function az(e){return new um(e)}function rz(e){return new Gb(e)}var D1={};Oe(D1,{Layer:()=>je,RNN:()=>nr,RNNCell:()=>Jc,activation:()=>Bz,add:()=>Xz,alphaDropout:()=>$B,average:()=>Yz,averagePooling1d:()=>Hb,averagePooling2d:()=>jb,averagePooling3d:()=>qb,avgPool1d:()=>sB,avgPool2d:()=>oB,avgPool3d:()=>uB,avgPooling1d:()=>iB,avgPooling2d:()=>lB,avgPooling3d:()=>cB,batchNormalization:()=>nB,bidirectional:()=>TB,concatenate:()=>Jz,conv1d:()=>$z,conv2d:()=>Dz,conv2dTranspose:()=>Rz,conv3d:()=>Mz,convLstm2d:()=>vB,convLstm2dCell:()=>wB,cropping2D:()=>Oz,dense:()=>Wz,depthwiseConv2d:()=>zz,dot:()=>tB,dropout:()=>Vz,elu:()=>Sz,embedding:()=>Kz,flatten:()=>Gz,gaussianDropout:()=>AB,gaussianNoise:()=>FB,globalAveragePooling1d:()=>pB,globalAveragePooling2d:()=>dB,globalMaxPool1d:()=>SB,globalMaxPool2d:()=>CB,globalMaxPooling1d:()=>M1,globalMaxPooling2d:()=>P1,gru:()=>mB,gruCell:()=>fB,input:()=>R1,inputLayer:()=>Nz,layerNormalization:()=>aB,leakyReLU:()=>_z,lstm:()=>gB,lstmCell:()=>yB,masking:()=>DB,maxPool1d:()=>_B,maxPool2d:()=>EB,maxPooling1d:()=>O1,maxPooling2d:()=>L1,maxPooling3d:()=>hB,maximum:()=>Qz,minimum:()=>Zz,multiply:()=>eB,permute:()=>qz,prelu:()=>Ez,reLU:()=>Cz,repeatVector:()=>Hz,reshape:()=>jz,rnn:()=>kB,separableConv2d:()=>Pz,simpleRNN:()=>bB,simpleRNNCell:()=>xB,softmax:()=>Fz,spatialDropout1d:()=>Uz,stackedRNNCells:()=>IB,thresholdedReLU:()=>Az,timeDistributed:()=>NB,upSampling2d:()=>Lz,zeroPadding2d:()=>rB});var RB=0;function z1(){return RB++}var cm={};function pm(e=""){return e in cm||(cm[e]=0),cm[e]+=1,e+cm[e].toString()}function Kb(e){return Array.isArray(e)&&Array.isArray(e[0])}function dm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Me(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new z(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function ct(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new z(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function hm(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 B1="Variable",W1=class{constructor(e,t="float32",n=B1,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=z1(),n=n==null?B1:n,this.originalName=N1(n),this.name=S1(this.originalName),this.trainable_=a,this.constraint=r,this.val=Lk(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),MB(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 MB(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 Xt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},Aa=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=z1(),s!=null&&(this.originalName=N1(s),this.name=S1(this.originalName)),this.rank=t.length}},PB=0,mm=class{constructor(e,t){this.callArgs=t,this.id=PB++,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}}},OB=0,je=class extends re.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=OB++,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=Ir(n)+"_"+pm(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Ea(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new z(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return _n(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return _n(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new kr(`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 kr(`Layer ${this.name} is not connected, no input to return.`);return _n(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new kr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new kr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return _n(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=gt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=gt(this.inputSpec);if(e.length!==t.length)throw new z(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let a=e[n],r=t[n];if(r==null)continue;let s=a.rank;if(r.ndim!=null&&s!==r.ndim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${s}`);if(r.maxNDim!=null&&s>r.maxNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${s}`);if(r.minNDim!=null&&s<r.minNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${s}.`);if(r.dtype!=null&&a.dtype!==r.dtype)throw new z(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${a.dtype}.`);if(r.axes){let i=a.shape;for(let o in r.axes){let l=Number(o),c=r.axes[o],u=l>=0?i[l]:i[i.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${i}.`)}}if(r.shape!=null)for(let i=0;i<r.shape.length;++i){let o=r.shape[i],l=a.shape[i];if(o!=null&&l!=null&&o!==l)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${a.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let n=gt(e),a=!0;for(let s of n)if(!(s instanceof Aa)){a=!1;break}let r=!0;for(let s of n)if(s instanceof Aa){r=!1;break}if(a===r)throw new z("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 gt(e))s.push(i.shape);this.build(_n(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=gt(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=_n(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=LB(e),i=this.computeOutputShape(s),o,l=zB(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 Aa(l,c,this,gt(e),t,this.name,u)):o=new Aa(l,i,this,gt(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 kr(`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 kr(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Ea(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return hm(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 z(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],a=Xb(t);for(let r=0;r<a.length;++r){let s=a[r],i=t[r],o=e[r];if(!w.arraysEqual(s.shape,o.shape))throw new z(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}Yb(n)})}addWeight(e,t,n,a,r,s,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new z(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(a=vt("zeros"));let o=a.apply(t,n),l=new W1(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=gt(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=gt(e);t=gt(t),n=gt(n),a=gt(a),r=dm(r),s=dm(s);let l=[],c=[],u=[];for(let p of o)l.push(p.sourceLayer),c.push(p.nodeIndex),u.push(p.tensorIndex);new mm({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 LB(e){e=gt(e);let t=[];for(let n of e)t.push(n.shape);return _n(t)}function zB(e){return"float32"}function V1(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=V1(i,o,l);for(let u of c)r.indexOf(u)===-1&&r.push(u)}return r}}}var nu=class extends je{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:pm("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let a=new Aa(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new mm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new z(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};nu.className="InputLayer";re.registerClass(nu);function U1(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;return n==null&&(n="float32"),new nu({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];Ae(a)}}function G1(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var H1;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(H1||(H1={}));var BB=125,au=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){}},j1=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)}},WB=class extends au{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(()=>J(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(xe(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),jt(t[n])}))}},q1=class extends au{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]}},K1=class extends au{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=BB),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");w.isNumber(this.yieldEvery)&&(this.maybeWait=U3(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(Zh()),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(Zh()),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(Zh()):w.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 X1(e,t){return e==null&&(e={}),e instanceof au?[e]:Array.isArray(e)&&e[0]instanceof au?e:gt(e).map(n=>new K1(n,t))}var ya=class{constructor(){}static registerCallbackConstructor(e,t){w.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),ya.checkForDuplicate(t),ya.constructors[e]==null&&(ya.constructors[e]=[]),ya.constructors[e].push(t)}static checkForDuplicate(e){for(let t in ya.constructors)ya.constructors[+t].forEach(n=>{if(n===e)throw new z("Duplicate callback constructor.")})}static clear(){ya.constructors={}}static createCallbacks(e){let t=[];for(let n in ya.constructors){let a=+n;e>=a&&t.push(...ya.constructors[a])}return t.map(n=>new n)}};ya.constructors={};function Y1(e,t,n,a,r,s,i,o,l){let c=new q1,u=[new WB,...ya.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let p=new j1(u);return p.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:p,history:c}}function $a(e,t={},n=!1){return Gc(e,re.SerializationMap.getMap().classNameMap,t,"layer",n)}function fm(e,t){return D(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));let n=Se(Xc(e),t,!0),a=Cn(n.shape,Bt()),r=an(Xa(n,a));return xe(e,r)})}function Gi(e,t){return D(()=>St(Xc(me(t,e)),-1))}function gm(e,t){return D(()=>St(Lt(me(t,e)),-1))}function ru(e,t){return D(()=>{let n=me(e,t),a=qt(Lt(e),Bt(),Number.MAX_VALUE),r=Lt(xe(n,a));return L(100,St(r,-1))})}function VB(e,t){return D(()=>{let n=qt(t,Bt(),Number.MAX_VALUE),a=Pn(J(1,n)),r=qt(e,Bt(),Number.MAX_VALUE),s=Pn(J(1,r));return St(Xc(me(a,s)),-1)})}function UB(e,t){return D(()=>{let n=Xa(0,me(1,L(e,t)));return St(Xc(n),-1)})}function GB(e,t){return D(()=>{let n=Xa(0,me(1,L(e,t)));return St(n,-1)})}function HB(e,t){return D(()=>{let n=Se(L(e,t),-1),a=ea(L(me(1,e),t),-1);return Xa(0,J(1,me(a,n)))})}function jB(e,t){return D(()=>{let n=Math.log(2),a=me(t,e),r=me(J(a,jl(L(-2,a))),n);return St(r,-1)})}function Qc(e,t,n=!1){return D(()=>{if(n)t=Na(t);else{let a=Se(t,t.shape.length-1,!0);t=xe(t,a)}return t=qt(t,Bt(),1-Bt()),Nt(Se(L(e.toFloat(),Pn(t)),t.shape.length-1))})}function ym(e,t,n=!1){return D(()=>{let a=Hl(fz(e)).toInt();t=qt(t,Bt(),1-Bt());let r=t.shape,s=Bl(a,r[r.length-1]).reshape(r);return Qc(s,t,n)})}function qB(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return D(()=>{let n=t.relu(),a=t.abs().neg();return n.sub(t.mul(e)).add(a.exp().log1p())})}function bm(e,t){return D(()=>{let n;return n=qt(t,Bt(),1-Bt()),n=Pn(xe(n,me(1,n))),St(qB(e,n),-1)})}function KB(e,t){return D(()=>{let n=qt(e,Bt(),1),a=qt(t,Bt(),1);return Se(L(e,Pn(xe(n,a))),-1)})}function XB(e,t){return D(()=>{let n=Pn(J(Bt(),t));return St(me(t,L(e,n)),-1)})}function Jb(e,t){return D(()=>{let n=fm(e,-1),a=fm(t,-1),r=L(n,a);return Nt(Se(r,-1))})}var xm={meanSquaredError:Gi,meanAbsoluteError:gm,meanAbsolutePercentageError:ru,meanSquaredLogarithmicError:VB,squaredHinge:UB,hinge:GB,categoricalHinge:HB,logcosh:jB,categoricalCrossentropy:Qc,sparseCategoricalCrossentropy:ym,binaryCrossentropy:bm,kullbackLeiblerDivergence:KB,poisson:XB,cosineProximity:Jb};function Qb(e){if(typeof e=="string"){if(e in xm)return xm[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new z(t)}else return e}function Zb(e,t){return D(()=>{let n=L(.5,On(t)),a=qc(ha(t,n),e.dtype);return St(as(e,a),-1)})}function ex(e,t){return D(()=>qc(as(Fc(e,-1),Fc(t,-1)),"float32"))}function J1(e,t){return D(()=>ma(e.equal(1),t.equal(1)).sum().cast("float32"))}function YB(e,t){return D(()=>ma(e.equal(1),t.equal(0)).sum().cast("float32"))}function JB(e,t){return D(()=>ma(e.equal(0),t.equal(1)).sum().cast("float32"))}function Q1(e,t){return D(()=>{let n=J1(e,t),a=JB(e,t),r=n.add(a);return Sn(ha(r,0),n.div(r),0).cast("float32")})}function QB(e,t){return D(()=>{let n=J1(e,t),a=YB(e,t),r=n.add(a);return Sn(ha(r,0),n.div(r),0).cast("float32")})}function Z1(e,t){return bm(e,t)}function eI(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)),as(e,t).asType("float32")}var ZB=Gi,eW=Gi,tW=gm,nW=gm,aW=ru,rW=ru,tx=Qc,sW=Jb,tI=ym,vm={binaryAccuracy:Zb,categoricalAccuracy:ex,precision:Q1,categoricalCrossentropy:tx,sparseCategoricalCrossentropy:tI,mse:ZB,MSE:eW,mae:tW,MAE:nW,mape:aW,MAPE:rW,cosine:sW};function iW(e){if(typeof e=="string"&&e in vm)return vm[e];if(typeof e!="string"&&e!=null)return e;throw new z(`Unknown metric ${e}`)}function wm(e){if(Za(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(xm))if(xm[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(vm))if(vm[n]===e){t=n;break}return t!==void 0?t:e.name}}function oW(e){let t={Adagrad:()=>Li.adagrad(.01),Adadelta:()=>Li.adadelta(1,.95,Bt()),Adam:()=>Li.adam(.001,.9,.999,Bt()),Adamax:()=>Li.adamax(.002,.9,.999,Bt(),0),RMSProp:()=>Li.rmsprop(.001,.9,0,Bt()),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 z(`Unknown Optimizer ${e}`)}var nI=1*1024*1024;function aI(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>nI&&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 <= ${nI}.`)}}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 dW(e,t,n,a=console.log){let r=uW(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)),km(s,n,a),a("=".repeat(t));let o=e.layers;for(let u=0;u<o.length;++u)r?cW(o[u],n,a):pW(o[u],n,i,a),a((u===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=lW(e),c=hm(e.nonTrainableWeights);a(`Total params: ${l+c}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${c}`),a("_".repeat(t))}function lW(e){let t;return e.collectedTrainableWeights!=null?t=hm(e.collectedTrainableWeights):t=hm(e.trainableWeights),t}function uW(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 km(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 cW(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()];km(i,t,n)}function pW(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];km(c,t,a);for(let u=1;u<s.length;++u)km(["","","",s[u]],t,a)}function rI(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Zc(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];rI(t,r,s)?n.push(s):n.push(Zc(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]=Zc(r,s)}}return n}}function ax(e,t){if(e==null)return null;if(typeof e=="string")return Ir(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];rI(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=Ir(a);(a==="name"||a==="className")&&typeof r=="string"?n[s]=r:n[s]=ax(r,a)}return n}}var Im="3.2.0";function hW(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ue(t,e.dtype)}catch(n){throw new z(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var 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]=hW(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new z(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Aa){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Aa){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Ae(this.id2Mask)}},rx={},sI={};function ep(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=mW(i,t);p=m.sorted,d=m.recipientCounts,rx[u]=p,sI[u]=d}p=rx[u],d={},r||Object.assign(d,sI[u]);let h=new Hi(t);for(let m=0;m<p.length;++m){if(a!=null){let $=mh().numTensors;$>a.maxNumTensors&&(a.maxNumTensors=$),$<a.minNumTensors&&(a.minNumTensors=$)}let f=p[m],g=f.sourceLayer;if(g instanceof nu)continue;let y=[],b=[],x=[],v=!1;for(let $ of f.inputs){let R=h.getValue($),B=h.getMask($);y.push(R),b.push(B),B!=null&&(v=!0),r||(d[$.name]--,d[$.name]===0&&!t.hasKey($)&&o.indexOf($.name)===-1&&!R.isDisposed&&$.sourceLayer.stateful!==!0&&x.push(R))}v&&(n=n||{},n.mask=b[0]);let N=gt(g.apply(y,n)),T=null;g.supportsMasking&&(T=g.computeMask(y,b));let S=fW(f),A=Array.isArray(S)?S:[S];for(let $=0;$<A.length;++$){h.hasKey(A[$])||h.add(A[$],N[$],Array.isArray(T)?T[0]:T);let R=o.indexOf(A[$].name);R!==-1&&(l[R]=N[$])}r||Ae(x)}return h.disposeMasks(),s?l:l[0]}function mW(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=iI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=iI(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:gW(a)}}function gW(e){let t={};for(let n in e)t[n]=e[n].size;return t}function iI(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 fW(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;a<e.sourceLayer.inboundNodes.length;++a)for(let r of e.sourceLayer.inboundNodes[a].outputTensors)if(r.id===e.id){n=a;break}t=e.sourceLayer.getOutputAt(n)}return t}var ar=class extends je{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=pm(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 z(`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,x=y.nodeIndex,v=y.tensorIndex;this.outputLayers.push(b),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(v)}for(let y of this.inputs){let b=y.sourceLayer,x=y.nodeIndex,v=y.tensorIndex;Za(x===0,"input layer has >1 nodes"),Za(v===0,"input layer has >1 tensors"),this.inputLayers.push(b),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(v)}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 nu))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,x,v,N,T)=>{(v==null||N==null||T==null)&&(v=y.sourceLayer,N=y.nodeIndex,T=y.tensorIndex);let S=v.inboundNodes[N];if(x.indexOf(S)!==-1)throw new Ea(`The tensor ${y.name} at layer "${v.name}" is part of a cycle.`);if(b.indexOf(S)!==-1)return;this.containerNodes.add(ar.nodeKey(v,N)),v.id in s||(s[v.id]=Object.keys(s).length),x.indexOf(S)===-1&&x.push(S);let A=S.inboundLayers.length;for(let $=0;$<A;$++){let R=S.inputTensors[$],B=S.inboundLayers[$],V=S.nodeIndices[$],W=S.tensorIndices[$];o(R,b,x,B,V,W)}for(b.push(S);x.indexOf(S)>=0;)x.splice(x.indexOf(S),1);i.push(S)},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],x=a[y.outboundLayer.id]==null?0:a[y.outboundLayer.id];b=Math.max(b,x),a[y.outboundLayer.id]=b,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=b;for(let v=0;v<y.inboundLayers.length;v++){let N=y.inboundLayers[v],T=y.nodeIndices[v],S=N.inboundNodes[T],A=t[S.id]==null?0:t[S.id];t[S.id]=Math.max(b+1,A),n[S.id]=S}}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(em);this.layers=[];for(let y of h){let b=d[y];b.sort((x,v)=>{let N=s[x.id],T=s[v.id];return N<T?-1:N>T?1:0});for(let x of b)x instanceof ar&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=d,h=Object.keys(p).map(y=>parseInt(y,10)).sort(em);let m=this.inputs.slice(),f=[];for(let y of h)for(let b of p[y]){let x=b.outboundLayer;if(x!=null){for(let v of b.inputTensors)if(m.indexOf(v)===-1)throw new Ea(`Graph disconnected: cannot obtain value for tensor ${v} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(let v of b.outputTensors)m.push(v);f.push(x.name)}}this.nodesByDepth=p;let g=this.layers.map(y=>y.name);for(let y of g){let b=g.filter(x=>x===y).length;if(b!==1)throw new Ea(`The name "${y}" is used ${b} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new mm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new z("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},a=0;for(let s of this.layers)for(let i of s.weights){if(n[i.originalName]!=null)throw new z(`Duplicate weight name: ${i.originalName}`);n[i.originalName]=i,a++}let r=[];for(let s in e){let i=s;if(n[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(n[i]!=null)r.push([n[i],e[s]]);else if(t)throw new z(`Provided weight data has no target variable: ${s}`);delete n[i]}if(t){let s=[];for(let i in n)s.push(i);if(s.length>0)throw new z(`${s.length} of ${a} weights are not set: ${s}`)}Yb(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Im}`,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=gt(e);let n=new Hi;for(let a=0;a<this.inputs.length;++a)n.add(this.inputs[a],e[a]);return ep(this.outputs,n,t)})}computeMask(e,t){return D(()=>{e=gt(e);let n;return t==null?n=zi(null,e.length):n=gt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=dm(e);if(t.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;i<t.length;i++){let o=this.inputLayers[i],l=t[i],c=o.name+"_0_0";n[c]=l}let a=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(em);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}`,x=n[b];u.push(x)}let p=c.computeOutputShape(_n(u)),d=dm(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];Za(o in n),r.push(n[o])}return _n(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(em);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[x,v]=h[0];m.mask==null&&(m.mask=v),y=gt(u.call(x,m)),b=gt(u.computeMask(x,v)),f=[x],g=[v]}else f=h.map(x=>x[0]),g=h.map(x=>x[1]),m.mask==null&&(m.mask=g),y=gt(u.call(f,m)),b=gt(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 x=0;x<d.length;++x){let v=d[x],N=y[x],T=b[x];n[v.id]=[N,T]}}}}let r=[],s=[],i=[];for(let o of this.outputs){Za(o.id in n,`Could not compute output ${o.name} : ${o.id}`);let[l,c]=n[o.id];i.push(l.shape),r.push(l),s.push(c)}return[r,s,i]}buildNodeConversionMap(e){let t={},n;for(let a of this.layers){n=a instanceof ar?1:0;for(let r=0;r<a.inboundNodes.length;r++){let s=ar.nodeKey(a,r);this.containerNodes.has(s)&&(t[s]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new z(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new z("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new z(`No such layer: ${e}`)}calculateLosses(){return D(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let a=ar.nodeKey(t,n);this.containerNodes.has(a)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let s of this.layers){let i=s.getClassName(),o=s.getConfig(),l=[];for(let u=0;u<s.inboundNodes.length;u++){let p=s.inboundNodes[u],d=ar.nodeKey(s,u),h={};if(this.containerNodes.has(d)){if(p.callArgs)try{JSON.stringify(p.callArgs),h=p.callArgs}catch(m){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${p.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(p.inboundLayers.length>0){let m=[];for(let f=0;f<p.inboundLayers.length;f++){let g=p.inboundLayers[f],y=p.nodeIndices[f],b=p.tensorIndices[f],x=ar.nodeKey(g,y),v=t[x];v==null&&(v=0),m.push([g.name,v,b,h])}l.push(m)}}}let c={};c.name=s.name,c.className=i,c.config=o,c.inboundNodes=l,n.push(c)}e.layers=n;let a=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=ar.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.inputLayersTensorIndices[s];a.push([i.name,c,u])}e.inputLayers=a;let r=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=ar.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.outputLayersTensorIndices[s];r.push([i.name,c,u])}return e.outputLayers=r,e}static fromConfig(e,t,n={},a=!1){let r={},s={};function i(f,g){f.name in s?s[f.name].push(g):s[f.name]=[g]}function o(f,g){let y=[],b;for(let x of g){let v=x[0],N=x[1],T=x[2];if(b=x[3]==null?{}:x[3],!(v in r)){i(f,g);return}let S=r[v];if(S.inboundNodes.length<=N){i(f,g);return}let A=S.inboundNodes[N];y.push(A.outputTensors[T])}y.length>0&&f.apply(_n(y),b)}function l(f){let g=f.name,y=$a(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),r[g]=y,f.inboundNodes.forEach(b=>{if(!(b instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${b}`);i(y,b)})}let c=t.name,u=t.layers;for(let f of u)l(f);for(;!V3(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];Za(g in r);let x=r[g].inboundNodes[y].outputTensors;p.push(x[b])}let m=t.outputLayers;for(let f of m){let g=f[0],y=f[1],b=f[2];Za(g in r);let x=r[g].inboundNodes[y].outputTensors;d.push(x[b])}return new e({inputs:p,outputs:d,name:c})}get stateful(){if(this._stateful)throw new z("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){D(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function yW(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 oI(e,t){return yW(e,t,"classWeight")}async function lI(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());Ae(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])}),Ze(i,"float32")}else return null}function bW(e,t){return L(e,t)}var xW=32;function cI(e,t){let n,a,r=t;n=r.xs,a=r.ys,w.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=uI("input",e.inputNames,n),i=uI("output",e.outputNames,a),o=s[0].shape[0];w.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)w.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)w.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function uI(e,t,n){if(n instanceof Ee)return[n];if(Array.isArray(n))return w.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let a=[];for(let r of t){if(n[r]==null)throw new z(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function vW(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 kW(e,t,n){let a=n.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),w.assert(!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}`),w.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,s,i;if(r)if(pI(n.validationData))w.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=vW(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=X1(n.callbacks,n.yieldEvery),p=n.verbose==null?1:n.verbose,{callbackList:d,history:h}=Y1(u,p,n.epochs,null,null,wW(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 x=await f.next();if(a&&x.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(x.value!=null){let{xs:v,ys:N}=cI(e,x.value),T={};T.batch=b,T.size=v[0].shape[0],await d.onBatchBegin(b,T);let S=[];if(n.classWeight!=null){let R=oI(n.classWeight,e.outputNames);for(let B=0;B<R.length;++B)S.push(await lI(N[B],null,R[B]))}let A=v.concat(N).concat(S),$=o(A);Ae(A);for(let R=0;R<l.length;++R){let B=l[R],V=$[R];T[B]=V,jt(V)}await d.onBatchEnd(b,T),G1(T),b++,y++}if(a?y>=n.batchesPerEpoch:x.done){if(r){let v;pI(n.validationData)?v=gt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):v=gt(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?xW:n.validationBatchSize,verbose:0}));for(let N=0;N<e.metricsNames.length;++N)g[`val_${e.metricsNames[N]}`]=v[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 wW(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function pI(e){return typeof e.iterator=="function"}function IW(e){return typeof e.next=="function"}async function TW(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.");w.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=IW(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}=cI(e,c.value),d=u.concat(p),h=D(()=>r(d));if(Ae(d),l===0)for(let f=0;f<h.length;++f)s.push(pe(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(()=>J(s[f],L(m,g))),l>0&&Ae(y)}Ae(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]=xe(s[c],o),Ae(u)}return _n(s)}function sx(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function tp(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)):E1(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 NW(e,t,n,a,r,s,i,o,l,c,u,p,d,h,m){r==null&&(r=32),s==null&&(s=1),u==null&&(u=!0),d==null&&(d=0);let f=!1;if(l!=null&&c!=null&&(f=!0),m!=null&&(f=!0,h==null))throw new z("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),y;g!=null&&(y=Fa(0,g)),i==null&&(i=1);let{callbackList:b,history:x}=Y1(o,i,s,d,g,h,r,f,p);b.setModel(e),e.history=x,await b.onTrainBegin(),e.stopTraining_=!1;for(let v=d;v<s;++v){await b.onEpochBegin(v);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&&w.shuffle(y);let T=Ze(y),S=ox(g,r);for(let A=0;A<S.length;++A){let $={};if(await b.onBatchBegin(A,$),D(()=>{let R=S[A][0],B=S[A][1],V=Ui(T,R,B-R);$.batch=A,$.size=B-R;let W=ix(n,V),G=t(W);for(let H=0;H<a.length;++H){let X=a[H],q=G[H];$[X]=q,jt(q)}if(A===S.length-1&&f){let H=e.testLoop(l,c,r);for(let X=0;X<a.length;++X){let q=a[X],te=H[X];jt(te),N["val_"+q]=te}}}),await b.onBatchEnd(A,$),G1($),e.stopTraining_)break}T.dispose()}if(await b.onEpochEnd(v,N),e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}async function SW(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 z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);let T=!0,S=await e.standardizeUserData(i,o,null,null,T,p);l=S[0],c=S[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)),S=r[0].shape[0];l=tp(r,T,S),r=tp(r,0,T),c=tp(s,T,S),s=tp(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(),x,v;m?(e.makeTestFunction(),x=e.testFunction,v=b.slice().concat(b.map(T=>"val_"+T))):(x=null,f=[],v=b.slice());let N=X1(a.callbacks,a.yieldEvery);return await NW(e,y,g,b,p,a.epochs,a.verbose,N,x,f,a.shuffle,v,a.initialEpoch,null,null)}finally{e.isTraining=!1,ji(r,t),ji(s,n),ji(l,i),ji(c,o),u!=null&&Ae(u)}}function dI(e){let t=[];e instanceof Ee&&(e=[e]);for(let n=0;n<e.length;++n){let a=e[n];if(a.rank===1)t.push(Kc(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 Ee)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 Ee)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 CW(e){return e instanceof Ee}function lx(e){return Array.isArray(e)}function hI(e){return!CW(e)&&!lx(e)}function mI(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(hI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new z(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(hI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new z(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(lx(e)){if(e=e,e.length!==t.length)throw new z(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(e=e,t.length>1)throw new z(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=dI(s),n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new z(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let c=o.shape[l],u=n[i][l];if(u!=null&&u>=0&&c!==u)throw new z(`Error when checking ${r}: expected ${t[i]} to have shape [${n[i]}], but got array with shape [${o.shape}].`)}}return s}function _W(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 z(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(r.length>1)throw new z(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&r.length>0&&!w.arraysEqual(a,r))throw new z(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${r[0]} target sample(s).`)}function EW(e,t,n){let a=[Gi,bm,Qc];for(let r=0;r<e.length;++r){let s=e[r],i=t[r],o=n[r];if(i!=null){if(i===Qc&&s.shape[s.shape.length-1]===1)throw new z(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(a.indexOf(i)!==-1){let l=s.shape.slice(1),c=o.slice(1);for(let u=0;u<l.length;++u){let p=l[u],d=c[u];if(d!=null&&p!==d)throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function fI(e,t,n,a=!0,r=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new z(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new z(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new z(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let c=o.shape[l],u=n[i][l];if(u!=null&&u!==c)throw new z(`Error when checking ${r}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function FW(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 AW="layers-model",Tr=class extends ar{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new z("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");dW(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=oW(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof wr))throw new z("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new z(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(Qb(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new z(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(s=>Qb(s))}else{let s=Qb(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=FW(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]===bm?["accuracy","acc"].indexOf(d)!==-1?u=Zb:["crossentropy","ce"].indexOf(d)!==-1&&(u=Z1):this.lossFunctions[s]===ym?["accuracy","acc"].indexOf(d)!==-1?u=eI:["crossentropy","ce"].indexOf(d)!==-1&&(u=tI):["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=iW(d),c=l+wm(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 _n(l)}finally{ji(s[0],e),ji(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),TW(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new z(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new z(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new z("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new Hi;if(e instanceof Ee&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new z(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new z(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=ep(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 z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return D(()=>{let a=this.checkNumSamples(e);if(n)throw new $e("Verbose predictLoop() is not implemented yet.");let r=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=tp(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 ep(this.outputs,p)}).forEach((o,l)=>s[l].push(o));return _n(s.map(i=>Je(i,0)))})}predict(e,t={}){let n=dI(e);fI(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){fI(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,a){if(this.optimizer_==null)throw new Ea("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===ym?r.push(i.slice(0,i.length-1).concat([1])):r.push(i)}if(e=mI(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=mI(t,this.feedOutputNames,r,!1,"target"),_W(e,t,null),EW(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!=0)throw new z(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,a,r=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,r,s);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let c=oI(a,this.outputNames);l=[];for(let u=0;u<c.length;++u)l.push(await lI(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=Ze(Fa(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(pe(0));for(let f=0;f<m.length;++f){let g=m[f];i[f]=J(i[f],L(p-u,g))}}for(let c=0;c<i.length;++c)i[c]=xe(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;g1(e,a)>1&&(r+=`_${g1(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=ep(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=bW(m,r[h]));let f=St(m);t.push(f),h===0?d=m:d=J(d,m)}for(let h=0;h<this.metricsTensors.length;++h){let m;if(this.outputs.length>1&&h<this.outputs.length)m=t[h];else{let f=this.metricsTensors[h][0],g=this.metricsTensors[h][1];m=St(f(a[g],p[g]))}jt(m),s.push(m)}return d=St(d),this.calculateLosses().forEach(h=>{d=J(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=ep(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let c=this.lossFunctions[l],u=St(c(r[l],o[l]));l===0?n=u:n=J(n,u),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let c=this.metricsTensors[l][0],u=this.metricsTensors[l][1],p=St(c(r[u],o[u]));t.push(p)}return t})}async fit(e,t,n={}){return SW(this,e,t,n)}async fitDataset(e,t){return kW(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 Ae(s),_n(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=mh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-mh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Ir(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=>Ir(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]=Ir(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[Ir(wm(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Ir(wm(e)));{let e={};for(let t in this.metrics)e[t]=Ir(wm(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=Zc(e.optimizer_config),n=$a(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=Ht.getSaveHandlers(e);if(i.length===0)throw new z(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new z(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Ht.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:AW,generatedBy:`TensorFlow.js tfjs-layers v${Im}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Ht.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=Ht.concatenateArrayBuffers([n.data,o])}if(this.userDefinedMetadata!=null){let i=!0;aI(this.userDefinedMetadata,this.name,i),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){aI(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Tr.className="Model";re.registerClass(Tr);var gI=class extends Tr{};gI.className="Functional";re.registerClass(gI);async function $W(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=Zc(n),r=$a(a,t);if(e.weightsManifest!=null){let s=await Ht.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(o=>o.originalName)),i={};for(let o of r.weights)i[o.originalName]=s[o.originalName];r.loadWeights(i),Ae(s)}return r}async function RW(e,t){if(t==null&&(t={}),typeof e=="string"){let n=Ht.getLoadHandlers(e,t);if(n.length===0)n.push(Ht.browserHTTPRequest(e,t));else if(n.length>1)throw new z(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return DW(e,void 0,t)}async function DW(e,t,n){if(n==null&&(n={}),e.load==null)throw new z("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),r=a.modelTopology;r.model_config!=null&&(r=r.model_config);let s=n.strict==null?!0:n.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=$a(Zc(r),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=MW(a.weightData,a.weightSpecs);o.loadWeights(c,s),o.optimizer!=null&&u.length>0&&await o.optimizer.setWeights(u),Ae(c),Ae(u.map(p=>p.tensor))}return o}function MW(e,t){let n=Ht.decodeWeights(e,t),a={},r=[];return t.forEach(s=>{s.group==="optimizer"?r.push({name:s.name,tensor:n[s.name]}):a[s.name]=n[s.name]}),{modelWeights:a,optimizerWeights:r}}var su=class extends Tr{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:pm("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof su||e instanceof Tr,n;if(t){if(n=e,n.outputs.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new z("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=U1({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(a)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new z(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=V1(this.outputs[0])}this.inboundNodes=[],new mm({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(ct(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 Tr({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Ea("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Ea("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Ea("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Ea("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},a=!1){let r,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new z("Legacy serialization format not supported yet.");r=t}else w.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof su))throw new $e(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=$a(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new z("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new z("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}};su.className="Sequential";re.registerClass(su);function PW(e){return new Tr(e)}function OW(e){return new su(e)}function LW(e,t){return t==null&&(t={}),RW(e,t)}function R1(e){return U1(e)}function zW(e,t){ya.registerCallbackConstructor(e,t)}var Bn=class extends re.Serializable{getConfig(){return{}}},yI=class extends Bn{apply(e,t=1){return yz(e,t)}};yI.className="elu";re.registerClass(yI);var bI=class extends Bn{apply(e){return Rh(e)}};bI.className="selu";re.registerClass(bI);var xI=class extends Bn{apply(e){return qe(e)}};xI.className="relu";re.registerClass(xI);var vI=class extends Bn{apply(e){return D(()=>Kl(6,qe(e)))}};vI.className="relu6";re.registerClass(vI);var wI=class extends Bn{apply(e){return e}};wI.className="linear";re.registerClass(wI);var kI=class extends Bn{apply(e){return da(e)}};kI.className="sigmoid";re.registerClass(kI);var II=class extends Bn{apply(e){return xz(e)}};II.className="hardSigmoid";re.registerClass(II);var TI=class extends Bn{apply(e){return jl(e)}};TI.className="softplus";re.registerClass(TI);var NI=class extends Bn{apply(e){return bz(e)}};NI.className="softsign";re.registerClass(NI);var SI=class extends Bn{apply(e){return Ul(e)}};SI.className="tanh";re.registerClass(SI);var ux=class extends Bn{apply(e,t=-1){return Na(e,t)}};ux.className="softmax";re.registerClass(ux);var CI=class extends Bn{apply(e,t=-1){return Ch(e,t)}};CI.className="logSoftmax";re.registerClass(CI);var _I=class extends Bn{apply(e,t=1){return D(()=>da(e.mul(t)).mul(e))}};_I.className="swish";re.registerClass(_I);function ps(e){return e.getClassName()}function cx(e,t={}){return Gc(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 Bn?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 EI=class extends re.Serializable{},np=class extends EI{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=J(t,Se(L(this.l1,Lt(e))))),this.hasL2&&(t=J(t,Se(L(this.l2,Xc(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};np.className="L1L2";re.registerClass(np);function BW(e){return px(e),new np({l1:e!=null?e.l1:null,l2:0})}function WW(e){return px(e),new np({l2:e!=null?e.l2:null,l1:0})}var FI={l1l2:"L1L2"};function pt(e){return Sb(e)}function AI(e,t={}){return Gc(e,re.SerializationMap.getMap().classNameMap,t,"regularizer")}function wt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in FI?FI[e]:e,config:{}};return AI(t)}else return e instanceof EI?e:AI(e)}var dx=class extends je{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Me(e);let n=qe(e);return this.maxValue!=null&&(n=qt(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};dx.className="ReLU";re.registerClass(dx);var hx=class extends je{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Me(e);return Mc(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 je{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=vt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=wt(e.alphaRegularizer),this.alphaConstraint=Vt(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=ct(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a<e.length;++a)n[a]=e[a];this.inputSpec=[new Xt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Me(e),Lc(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Ct(this.alphaInitializer),alphaRegularizer:pt(this.alphaRegularizer),alphaConstraint:Wt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};mx.className="PReLU";re.registerClass(mx);var fx=class extends je{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new $e(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Me(e);return Gl(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 je{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Me(e);return n.mul(qc(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 je{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=Me(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};yx.className="Softmax";re.registerClass(yx);function iu(e,t,n){if(typeof e=="number")return zi(e,t);if(e.length!==t)throw new z(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){let r=e[a];if(!hz(r))throw new z(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`)}return e}function Da(e,t,n,a,r=1){if(e==null)return e;let s=t+(t-1)*(r-1),i;return n==="same"?i=e:i=e-s+1,Math.floor((i+a-1)/a)}function Tm(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 z(`Unsupport padding mode: ${a}.`);return e}function bx(e,t){return D(()=>(Dt(t),t==="channelsFirst"?Ve(e,[0,2,3,1]):e))}function $I(e,t){return D(()=>(Dt(t),t==="channelsFirst"?Ve(e,[0,2,3,4,1]):e))}function VW(e,t,n,a=1,r="valid",s,i=1){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.shape.length!==3)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=Ve(e,[0,2,1])),r==="causal")throw new $e("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=xh(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=tr(o,n)),o})}function DI(e,t,n,a=[1,1],r="valid",s,i,o=null){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.rank!==3&&e.rank!==4)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=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=Ve(l,[0,3,1,2])),l})}function UW(e,t,n,a=[1,1,1],r="valid",s,i){return D(()=>{if(s==null&&(s=_a()),Dt(s),e.rank!==4&&e.rank!==5)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=$I(e,s);if(r==="causal")throw new $e("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Xy(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=tr(o,n)),s==="channelsFirst"&&(o=Ve(o,[0,4,1,2,3])),o})}var xx=class extends je{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,Kt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new $e(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=iu(t.kernelSize,e,"kernelSize"),this.strides=iu(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,Dt(this.dataFormat),this.activation=ds(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=vt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Vt(t.biasConstraint),this.biasRegularizer=wt(t.biasRegularizer),this.activityRegularizer=wt(t.activityRegularizer),this.dilationRate=iu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new z(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new z(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Za("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!_b(e.kernelSize,"number",1,3))throw new z(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:ps(this.activation),useBias:this.useBias,biasInitializer:Ct(this.biasInitializer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),biasConstraint:Wt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},ap=class extends xx{constructor(e,t){super(e,t);this.kernel=null,ap.verifyArgs(t),this.filters=t.filters,Kt(this.filters,"filters"),this.kernelInitializer=vt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Vt(t.kernelConstraint),this.kernelRegularizer=wt(t.kernelRegularizer)}build(e){e=ct(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],a=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return D(()=>{e=Me(e);let n,a=this.bias==null?null:this.bias.read(),r=b1(this.activation.getClassName());if(r!=null&&this.rank===2)n=DI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=VW(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=DI(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=UW(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=ct(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r<n.length;++r){let s=Da(n[r],this.kernelSize[r],this.padding,this.strides[r],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[r]);t.push(s)}let a=[e[0]];return this.dataFormat==="channelsLast"?(a=a.concat(t),a.push(this.filters)):(a.push(this.filters),a=a.concat(t)),a}getConfig(){let e={filters:this.filters,kernelInitializer:Ct(this.kernelInitializer),kernelRegularizer:pt(this.kernelRegularizer),kernelConstraint:Wt(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},rp=class extends ap{constructor(e){super(2,e);rp.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 z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};rp.className="Conv2D";re.registerClass(rp);var Nm=class extends ap{constructor(e){super(3,e);Nm.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Nm.className="Conv3D";re.registerClass(Nm);var vx=class extends rp{constructor(e){super(e);if(this.inputSpec=[new Xt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ct(e),e.length!==4)throw new z("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Xt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{let n=Me(e);if(n.shape.length!==4)throw new z(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],c=this.kernelSize[0],u=this.kernelSize[1],p=this.strides[0],d=this.strides[1],h=Tm(o,p,c,this.padding),m=Tm(l,d,u,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=Ve(n,[0,2,3,1]));let g=vh(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Ve(g,[0,3,1,2])),this.bias!=null&&(g=tr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=ct(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]=Tm(t[a],o,s,this.padding),t[r]=Tm(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};vx.className="Conv2DTranspose";re.registerClass(vx);var RI=class extends ap{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new z("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new z(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=vt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=wt(t.depthwiseRegularizer),this.depthwiseConstraint=Vt(t.depthwiseConstraint),this.pointwiseInitializer=vt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=wt(t.pointwiseRegularizer),this.pointwiseConstraint=Vt(t.pointwiseConstraint)}build(e){if(e=ct(e),e.length<this.rank+2)throw new z(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new z(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],a=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let i=0;i<this.rank;++i)r.push(1);r.push(n*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Xt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return D(()=>{e=Me(e);let n;if(this.rank===1)throw new $e("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ve(e,[0,2,3,1])),n=Pi(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=tr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Ve(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ct(this.depthwiseInitializer),e.pointwiseInitializer=Ct(this.pointwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.pointwiseRegularizer=pt(this.pointwiseRegularizer),e.depthwiseConstraint=Wt(this.depthwiseConstraint),e.pointwiseConstraint=Wt(this.pointwiseConstraint),e}};RI.className="SeparableConv";var wx=class extends RI{constructor(e){super(2,e)}};wx.className="SeparableConv2D";re.registerClass(wx);var Sm=class extends ap{constructor(e){super(1,e);Sm.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 z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};Sm.className="Conv1D";re.registerClass(Sm);var kx=class extends je{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return D(()=>{if(e=Me(e),this.dataFormat==="channelsLast"){let n=tm(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return tm(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=tm(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return tm(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 je{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,cz(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return D(()=>{let n=Me(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=Ve(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 Ve(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 GW(e,t,n=[1,1],a="valid",r,s){return D(()=>{r==null&&(r=_a()),Dt(r);let i=bx(e,r);if(e.rank!==4)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=ns(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=Ve(i,[0,3,1,2])),i})}var Tx=class extends xx{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=vt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Vt(e.depthwiseConstraint),this.depthwiseRegularizer=wt(e.depthwiseRegularizer)}build(e){if(e=ct(e),e.length<4)throw new z(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new z(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],a=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return D(()=>{e=Me(e);let n=GW(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=tr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=ct(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Da(t,this.kernelSize[0],this.padding,this.strides[0]),s=Da(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,r,s]:[e[0],r,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ct(this.depthwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.depthwiseConstraint=Wt(this.depthwiseRegularizer),e}};Tx.className="DepthwiseConv2D";re.registerClass(Tx);function MI(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new z("When inputs is an array, neither initialState or constants should be provided");a!=null&&(n=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(s){return s==null||Array.isArray(s)?s:[s]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function PI(e,t,n,a=!1,r,s,i=!1,o=!1){return D(()=>{let l=t.shape.length;if(l<3)throw new z(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(Fa(2,l));if(t=Ve(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=Mn(r,-1)),r=Ve(r,c)),a&&(t=Ln(t,0),r!=null&&(r=Ln(r,0)));let u=[],p,d=n,h=t.shape[0],m=ut(t),f;r!=null&&(f=ut(r));for(let y=0;y<h;++y){let b=m[y],x=D(()=>e(b,d));if(r==null)p=x[0],d=x[1];else{let v=D(()=>{let N=f[y],T=On(N).sub(N),S=x[0].mul(N).add(d[0].mul(T)),A=d.map(($,R)=>x[1][R].mul(N).add($.mul(T)));return{output:S,newStates:A}});p=v.output,d=v.newStates}o&&u.push(p)}let g;return o&&(g=$t(u,1)),[p,g,d]})}var nr=class extends je{constructor(e){super(e);let t;if(e.cell==null)throw new z("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Cm({cells:e.cell}):t=e.cell,t.stateSize==null)throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Xt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Fa(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 Xt({shape:[n,null,...a]});let r=[e[0]].concat(e.slice(2));if(t!=null)throw new $e("Constants support is not implemented in RNN yet.");this.cell.build(r);let s;if(Array.isArray(this.cell.stateSize)?s=this.cell.stateSize:s=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),s))throw new z(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=s.map(i=>new Xt({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new kr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>xt([n,a])):this.states_=[xt([n,this.cell.stateSize])];else if(e==null)Ae(this.states_),this.keptStates!=null&&(Ae(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 z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):Ae(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(!w.arraysEqual(r.shape,i))throw new z(`State ${a} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${r.shape}`);this.states_[a]=r}}this.states_=this.states_.map(a=>jt(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=MI(e,n,a,this.numConstants);e=r.inputs,n=r.initialState,a=r.constants;let s=[],i=[];if(n!=null){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(let o of n)this.stateSpec.push(new Xt({shape:o.shape}));i=i.concat(this.stateSpec)}if(a!=null&&(t.constants=a,s=s.concat(a),this.numConstants=a.length),s[0]instanceof Aa){let o=[e].concat(s),l=this.inputSpec.concat(i),c=this.inputSpec;this.inputSpec=l;let u=super.apply(o,t);return this.inputSpec=c,u}else return super.apply(e,t)}call(e,t){return D(()=>{let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;e=Me(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==s)throw new z(`RNN Layer has ${s} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:a},o=PI((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=Se(t,[1,2]),t=Kc(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Rb(t,[1,n]):t):this.cell.stateSize>1?[Rb(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===nr.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let a=t.cell,r=$a(a,n);return new e(Object.assign(t,{cell:r}))}};nr.className="RNN";re.registerClass(nr);var Jc=class extends je{},_m=class extends Jc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Kt(this.units,"units"),this.activation=ds(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=vt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=vt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=vt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=wt(e.kernelRegularizer),this.recurrentRegularizer=wt(e.recurrentRegularizer),this.biasRegularizer=wt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=tu([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=tu([1,us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ct(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return D(()=>{if(e=e,e.length!==2)throw new z(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=hs({ones:()=>On(e),rate:this.dropout,training:a})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>On(n),rate:this.recurrentDropout,training:a}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=er(L(e,s),this.kernel.read()):r=er(e,this.kernel.read()),this.bias!=null&&(r=tr(r,this.bias.read())),i!=null&&(n=L(n,i));let o=J(r,er(n,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ps(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};_m.className="SimpleRNNCell";re.registerClass(_m);var Nx=class extends nr{constructor(e){e.cell=new _m(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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)}};Nx.className="SimpleRNN";re.registerClass(Nx);var Em=class extends Jc{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new z("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Kt(this.units,"units"),this.activation=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=vt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=vt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=vt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=wt(e.kernelRegularizer),this.recurrentRegularizer=wt(e.recurrentRegularizer),this.biasRegularizer=wt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=tu([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=tu([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=ct(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return D(()=>{if(e=e,e.length!==2)throw new z(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,a=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=hs({ones:()=>On(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>On(a),rate:this.recurrentDropout,training:n,count:3}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=L(e,r[0]));let c=er(e,this.kernel.read());this.useBias&&(c=tr(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,s[0]));let u=this.recurrentKernel.read(),[p,d]=zn(u,[2*this.units,this.units],u.rank-1),h=er(a,p),[m,f,g]=zn(c,3,c.rank-1),[y,b]=zn(h,2,h.rank-1);i=this.recurrentActivation.apply(J(m,y)),o=this.recurrentActivation.apply(J(f,b));let x=er(L(o,a),d);l=this.activation.apply(J(g,x));let v=J(L(i,a),L(J(1,Nt(i)),l));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ps(this.activation),recurrentActivation:ps(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Em.className="GRUCell";re.registerClass(Em);var Sx=class extends nr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Em(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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 sp=class extends Jc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Kt(this.units,"units"),this.activation=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=vt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=vt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=vt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=wt(e.kernelRegularizer),this.recurrentRegularizer=wt(e.recurrentRegularizer),this.biasRegularizer=wt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=tu([1,us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=tu([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=ct(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 ga{apply(i,o){let l=r.apply([s]),c=new am().apply([s]),u=r.apply([s*2]);return _1(_1(l,c),u)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return D(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=hs({ones:()=>On(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=hs({ones:()=>On(a),rate:this.recurrentDropout,training:n,count:4}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,c,u;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let p=er(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,i[0])),p=J(p,er(a,this.recurrentKernel.read())),this.useBias&&(p=tr(p,this.bias.read()));let[d,h,m,f]=zn(p,4,p.rank-1);o=this.recurrentActivation.apply(d),l=this.recurrentActivation.apply(h),c=J(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:Ct(this.kernelInitializer),recurrentInitializer:Ct(this.recurrentInitializer),biasInitializer:Ct(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),recurrentConstraint:Wt(this.recurrentConstraint),biasConstraint:Wt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};sp.className="LSTMCell";re.registerClass(sp);var Cx=class extends nr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new sp(e),super(e)}call(e,t){return D(()=>{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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 Cm=class extends Jc{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($a(r,n));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return 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)}};Cm.className="StackedRNNCells";re.registerClass(Cm);function hs(e){let{ones:t,rate:n,training:a=!1,count:r=1}=e,s=()=>F1(t(),n),i=()=>Yc(s,t,a);return!r||r<=1?jt(i().clone()):Array(r).fill(void 0).map(i).map(o=>jt(o.clone()))}var HW=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},OI=class extends nr{constructor(e){if(e.unroll)throw new $e("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new $e("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Xt({ndim:5})]}call(e,t){return D(()=>{if(this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new z("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return D(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=xt(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){D(()=>{if(!this.stateful)throw new kr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)];if(n[0]==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>xt(r)):this.states_=[xt(r)];else if(e==null)Ae(this.states_),this.keptStates!=null&&(Ae(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 z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Ae(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=r;if(!w.arraysEqual(i.shape,o))throw new z(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>jt(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:a,padding:r,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],c=e[o?4:3],u=Da(l,a[0],r,s[0],i[0]),p=Da(c,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,u,p]:[u,p,n]]}};OI.className="ConvRNN2D";var Fm=class extends sp{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super(Object.assign({},e,{units:t}));this.filters=t,Kt(this.filters,"filters"),this.kernelSize=iu(n,2,"kernelSize"),this.kernelSize.forEach(o=>Kt(o,"kernelSize")),this.strides=iu(a||1,2,"strides"),this.strides.forEach(o=>Kt(o,"strides")),this.padding=r||"valid",na(this.padding),this.dataFormat=s||"channelsLast",Dt(this.dataFormat),this.dilationRate=iu(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>Kt(o,"dilationRate"))}build(e){var t;e=ct(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new z(`The channel dimension of the input should be defined. Found ${e[n]}`);let a=e[n],r=4,s=this.kernelSize.concat([a,this.filters*r]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;o=new(t=class extends ga{apply(u,p){let d=l.apply([c]),h=Ya([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 z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,a=e[0],r=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=hs({ones:()=>On(a),rate:this.dropout,training:n,count:i}));let o=this.dropoutMask,l=(Q,se,ne)=>!se||!se[ne]?Q:L(se[ne],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:()=>On(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,[x,v,N,T]=zn(this.kernel.read(),i,b),[S,A,$,R]=this.useBias?zn(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,x,S,this.padding),u=this.inputConv(u,v,A,this.padding),p=this.inputConv(p,N,$,this.padding),d=this.inputConv(d,T,R,this.padding);let[B,V,W,G]=zn(this.recurrentKernel.read(),i,b);m=this.recurrentConv(m,B),f=this.recurrentConv(f,V),g=this.recurrentConv(g,W),y=this.recurrentConv(y,G);let H=this.recurrentActivation.apply(J(c,m)),X=this.recurrentActivation.apply(J(u,f)),q=J(L(X,s),L(H,this.activation.apply(J(p,g)))),te=L(this.recurrentActivation.apply(J(d,y)),this.activation.apply(q));return[te,te,q]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=HW(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?tr(r,n,this.dataFormat):r}recurrentConv(e,t){return Ft(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Fm.className="ConvLSTM2DCell";re.registerClass(Fm);var _x=class extends OI{constructor(e){let t=new Fm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};_x.className="ConvLSTM2D";re.registerClass(_x);var Am=class extends je{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let a=0;a<this.noiseShape.length;++a)n.push(this.noiseShape[a]==null?t[a]:this.noiseShape[a]);return n}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,r=this.getNoiseShape(n);return Yc(()=>F1(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()}};Am.className="Dropout";re.registerClass(Am);var Ex=class extends Am{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 Fx=class extends je{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Kt(this.units,"units"),this.activation=ds(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=vt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=vt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Vt(e.kernelConstraint),this.biasConstraint=Vt(e.biasConstraint),this.kernelRegularizer=wt(e.kernelRegularizer),this.biasRegularizer=wt(e.biasRegularizer),this.activityRegularizer=wt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=ct(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=ct(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e),a=b1(this.activation.getClassName()),r;return a!=null?r=er(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=er(n,this.kernel.read()),this.bias!=null&&(r=tr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:ps(this.activation),useBias:this.useBias,kernelInitializer:Ct(this.kernelInitializer),biasInitializer:Ct(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:Wt(this.kernelConstraint),biasConstraint:Wt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Fx.className="Dense";re.registerClass(Fx);var Ax=class extends je{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=ct(e);for(let t of e.slice(1))if(t==null)throw new z(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ls(e,1)]}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r<n.rank;++r)a.push(r);a.push(1),n=n.transpose(a)}return gz(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Ax.className="Flatten";re.registerClass(Ax);var $x=class extends je{constructor(e){super(e);this.supportsMasking=!0,this.activation=ds(e.activation)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(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 je{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return D(()=>(e=Me(e),mz(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 Rx=class extends je{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",a=t.slice(),r=1,s=null;for(let o=0;o<a.length;++o){let l=a[o];if(this.isUnknown(l))if(s===null)s=o;else throw new z("Can only specifiy one unknown dimension.");else r*=l}let i=ls(e);if(s!==null){if(r===0||i%r!=0)throw new z(n);a[s]=i/r}else if(i!==r)throw new z(n);return a}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e),a=n.shape,r=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return n.reshape(r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};Rx.className="Reshape";re.registerClass(Rx);var Mx=class extends je{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=Fa(1,e.dims.length+1);if(!w.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Xt({ndim:this.dims.length+1})]}computeOutputShape(e){e=ct(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return Ve(Me(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Mx.className="Permute";re.registerClass(Mx);var Px=class extends je{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Me(e),a=-1;return Ec(Mi(n,this.maskValue),a)}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e),a=-1,r=!0,s=Ec(Mi(n,this.maskValue),a,r);return n.mul(s.asType(n.dtype))})}};Px.className="Masking";re.registerClass(Px);var Ox=class extends je{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(gt(e.inputLength))}this.inputDim=e.inputDim,Kt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Kt(this.outputDim,"outputDim"),this.embeddingsInitializer=vt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=wt(e.embeddingsRegularizer),this.activityRegularizer=wt(e.activityRegularizer),this.embeddingsConstraint=Vt(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return D(()=>this.maskZero?(e=Me(e),Mi(e,Ge(e))):null)}computeOutputShape(e){if(e=ct(e),this.inputLength==null)return[...e,this.outputDim];let t=gt(this.inputLength);if(t.length!==e.length-1)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a<t.length;++a){let r=t[a],s=e[a+1];if(r!=null&&s!=null&&r!==s)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);r==null&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);return n.dtype!=="int32"&&(n=qc(n,"int32")),E1(this.embeddings.read(),n.as1D()).reshape(ct(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ct(this.embeddingsInitializer),embeddingsRegularizer:pt(this.embeddingsRegularizer),activityRegularizer:pt(this.activityRegularizer),embeddingsConstraint:Wt(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 je{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new $e}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let a=0;a<t.length;++a){let r=e[e.length-t.length+a],s=t[a];if(r==null||s==null||r<0||s<0)n.push(null);else if(r===1)n.push(s);else if(s===1)n.push(r);else{if(r!==s)throw new z("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[ct(e)]),e=e,e.length<2)throw new z(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let r of e)r!=null&&r[0]!==null&&t.push(r[0]);if(t=os(t),t.length>1)throw new z(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}let a=e.map(r=>r.length);e.indexOf(null)===-1&&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=Kc(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=Ve(d,[1,0]),d=d.reshape(p),n.push(d),r=!0}else if(l>1){let c=Fa(1,l).concat([0]);n.push(Ve(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=Ve(s.reshape([-1,c]),[1,0]).reshape(u)}else if(i>1){let o=[i-1].concat(Fa(0,i-1));s=Ve(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 z("`mask` should be an Array");if(!Array.isArray(e))throw new z("`inputs` should be an Array");if(t.length!==e.length)throw new z(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:Mn(a,0));let n=t[0];for(let a=1;a<t.length-1;++a)n=ma(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=J(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=J(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=Xa(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=Kl(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 z("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let a of e)if(a!=null){t=!1;break}if(t)return;let n=[];for(let a=0;a<e.length;++a){let r=e[a].slice();r.splice(this.axis,1);let s=!1;for(let i of n)if(w.arraysEqual(i,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return D(()=>Pb(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new z("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),a=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[a]==null||r[a]==null){n[a]=null;break}n[a]+=r[a]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new z("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new z("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new z(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return D(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s<e.length;++s)t[s]==null?a.push(On(e[s]).asType("bool")):t[s].rank<e[s].rank?a.push(Mn(t[s],-1)):a.push(t[s]);let r=Je(a,this.axis);return yh(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 ip(e,t){for(;e<0;)e+=t;return e}function jW(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(w.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),w.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new $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){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new $e("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);if(t[a[0]]!==n[a[1]])throw new z(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new z(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((r,s)=>ip(r,e[s].shape.length)):a=[ip(this.axes,t.shape.length),ip(this.axes,n.shape.length)],this.normalize&&(t=fm(t,a[0]),n=fm(n,a[1])),jW(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[ip(this.axes,e.length),ip(this.axes,t.length)],n}computeOutputShape(e){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new $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 je{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);return Yc(()=>nm(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Hx.className="GaussianNoise";re.registerClass(Hx);var jx=class extends je{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return D(()=>{this.invokeCallHook(e,t);let n=Me(e);return this.rate>0&&this.rate<1?Yc(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return n.mul(nm(n.shape,1,a))},()=>n,t.training||!1):n})}};jx.className="GaussianDropout";re.registerClass(jx);var qx=class extends je{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Me(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return D(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Yc(()=>{let a=Me(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=rs(Xl(n),this.rate);o=qc(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,c=-l*i*this.rate;return a.mul(o).add(o.add(-1).mul(i)).mul(l).add(c)},()=>Me(e),t.training||!1)}return e})}};qx.className="AlphaDropout";re.registerClass(qx);function op(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=dk(e,t,n,a,r,s);else if(e.rank===3)i=hk(e,t,n,a,r,s);else if(e.rank===4)i=mk(e,t,n,a,r,s);else throw new $e(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function qW(e,t,n,a,r=.001){return D(()=>{let s=Eh(e,a),i=s.mean,o=s.variance;return[op(e,i,o,n,t,r),i,o]})}function KW(e,t,n,a,r=.001){return D(()=>{let s=Eh(e,a),i=s.mean,o=s.variance,l=[];for(let h of Fa(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[op(e,c,u,d,p,r),i,o]})}function XW(e,t,n,a,r=.001){return w.arraysEqual(a.slice().sort(),Fa(0,e.rank-1))?qW(e,t,n,a,r):KW(e,t,n,a,r)}var Kx=class extends je{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=vt(e.betaInitializer||"zeros"),this.gammaInitializer=vt(e.gammaInitializer||"ones"),this.movingMeanInitializer=vt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=vt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Vt(e.betaConstraint),this.gammaConstraint=Vt(e.gammaConstraint),this.betaRegularizer=wt(e.betaRegularizer),this.gammaRegularizer=wt(e.gammaRegularizer)}build(e){e=ct(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new z(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Xt({ndim:e.length,axes:{[t]:n}})];let a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return D(()=>{let n=t.training==null?!1:t.training,a=Me(e),r=a.shape,s=r.length,i=Fa(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=!w.arraysEqual(c,Fa(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,x=this.scale?this.gamma.read().reshape(l):null;return op(a,g,y,b,x,this.epsilon)}else return op(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]=XW(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,y,b)=>{D(()=>{let x=1-b,v=g.read(),N=v.sub(y).mul(x);g.write(v.sub(N))})};return(()=>{f(this.movingMean,h,this.momentum),f(this.movingVariance,m,this.momentum)})(),d})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ct(this.betaInitializer),gammaInitializer:Ct(this.gammaInitializer),movingMeanInitializer:Ct(this.movingMeanInitializer),movingVarianceInitializer:Ct(this.movingVarianceInitializer),betaRegularizer:pt(this.betaRegularizer),gammaRegularizer:pt(this.gammaRegularizer),betaConstraint:Wt(this.betaConstraint),gammaConstraint:Wt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Kx.className="BatchNormalization";re.registerClass(Kx);var Xx=class extends je{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=vt(e.betaInitializer||"zeros"),this.gammaInitializer=vt(e.gammaInitializer||"ones"),this.betaRegularizer=wt(e.betaRegularizer),this.gammaRegularizer=wt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=ct(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=Me(e),a=n.shape,r=a.length;return D(()=>{let s=!0,{mean:i,variance:o}=Eh(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),op(n,i,o,p,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ct(this.betaInitializer),gammaInitializer:Ct(this.gammaInitializer),betaRegularizer:pt(this.betaRegularizer),gammaRegularizer:pt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Xx.className="LayerNormalization";re.registerClass(Xx);function YW(e,t,n){return D(()=>{if(e.rank!==4)throw new z(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=_a()),n!=="channelsLast"&&n!=="channelsFirst")throw new z(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return n==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],ta(e,a)})}var Yx=class extends je{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?_a():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new z(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new z(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new z(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Xt({ndim:4})]}computeOutputShape(e){e=ct(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(()=>YW(Me(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 $m(e,t,n,a,r,s){return D(()=>{Dt(r),k1(s),na(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=_a()),s==null&&(s="max"),e=bx(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=At(e,t,n,o):i=Zn(e,t,n,o),r==="channelsFirst"&&(i=Ve(i,[0,3,1,2])),i})}function LI(e,t,n,a,r,s){return D(()=>{Dt(r),k1(s),na(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=_a()),s==null&&(s="max"),e=$I(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=ib(e,t,n,o):i=jy(e,t,n,o),r==="channelsFirst"&&(i=Ve(i,[0,4,1,2,3])),i})}var zI=class extends je{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Kt(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,na(this.padding),this.inputSpec=[new Xt({ndim:3})]}computeOutputShape(e){e=ct(e);let t=Da(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return D(()=>{this.invokeCallHook(e,t),e=Kc(Me(e),2);let n=this.poolingFunction(Me(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 zI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),$m(e,t,n,a,r,"max")}};Jx.className="MaxPooling1D";re.registerClass(Jx);var Qx=class extends zI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),$m(e,t,n,a,r,"avg")}};Qx.className="AveragePooling1D";re.registerClass(Qx);var BI=class extends je{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new z(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Kt(this.poolSize,"poolSize"),Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),na(this.padding),this.inputSpec=[new Xt({ndim:4})]}computeOutputShape(e){e=ct(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Da(t,this.poolSize[0],this.padding,this.strides[0]),n=Da(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return D(()=>(this.invokeCallHook(e,t),this.poolingFunction(Me(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Zx=class extends BI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),$m(e,t,n,a,r,"max")}};Zx.className="MaxPooling2D";re.registerClass(Zx);var ev=class extends BI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),$m(e,t,n,a,r,"avg")}};ev.className="AveragePooling2D";re.registerClass(ev);var WI=class extends je{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new z(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Kt(this.poolSize,"poolSize"),Kt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),na(this.padding),this.inputSpec=[new Xt({ndim:5})]}computeOutputShape(e){e=ct(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Da(t,this.poolSize[0],this.padding,this.strides[0]),n=Da(n,this.poolSize[1],this.padding,this.strides[1]),a=Da(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,a]:[e[0],t,n,a,e[4]]}call(e,t){return D(()=>(this.invokeCallHook(e,t),this.poolingFunction(Me(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},tv=class extends WI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),LI(e,t,n,a,r,"max")}};tv.className="MaxPooling3D";re.registerClass(tv);var nv=class extends WI{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Dt(r),na(a),LI(e,t,n,a,r,"avg")}};nv.className="AveragePooling3D";re.registerClass(nv);var VI=class extends je{constructor(e){super(e);this.inputSpec=[new Xt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new $e}},av=class extends VI{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Me(e);return St(n,1)})}};av.className="GlobalAveragePooling1D";re.registerClass(av);var rv=class extends VI{constructor(e){super(e||{})}call(e,t){return D(()=>{let n=Me(e);return ea(n,1)})}};rv.className="GlobalMaxPooling1D";re.registerClass(rv);var UI=class extends je{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Dt(this.dataFormat),this.inputSpec=[new Xt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new $e}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},sv=class extends UI{call(e,t){return D(()=>{let n=Me(e);return this.dataFormat==="channelsLast"?St(n,[1,2]):St(n,[2,3])})}};sv.className="GlobalAveragePooling2D";re.registerClass(sv);var iv=class extends UI{call(e,t){return D(()=>{let n=Me(e);return this.dataFormat==="channelsLast"?ea(n,[1,2]):ea(n,[2,3])})}};iv.className="GlobalMaxPooling2D";re.registerClass(iv);var GI=class extends je{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let a=t.layer,r=$a(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},ov=class extends GI{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=ct(e),e.length<3)throw new z(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=ct(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return D(()=>(e=Me(e),PI((n,a)=>[Me(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ov.className="TimeDistributed";re.registerClass(ov);function JW(e){Wi(uz,"BidirectionalMergeMode",e)}var QW="concat",lv=class extends GI{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=$a(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=$a(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?QW:e.mergeMode,JW(this.mergeMode),e.weights)throw new $e("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,a,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,a=[n]):this.mergeMode==null?a=[n,n.slice()]:a=[n],this.returnState?this.mergeMode==null?a.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):_n(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=MI(e,n,a,this.numConstants);if(e=r.inputs,n=r.initialState,a=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(n!=null){let l=n.length;if(l%2>0)throw new z("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);let c=n.map(u=>new Xt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),i.push(...c)}if(a!=null)throw new $e("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Aa;for(let l of s)if(l instanceof Aa!==o)throw new z("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),c=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=c;let p=super.apply(l,t);return this.inputSpec=u,p}else return super.apply(e,t)}call(e,t){return D(()=>{let n=t.initialState,a,r;if(n==null)a=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let o=n.slice(0,n.length/2),l=n.slice(n.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(r.slice(1))),a=a[0],r=r[0]),this.returnSequences&&(r=Ln(r,1));let i;return this.mergeMode==="concat"?i=Pb([a,r]):this.mergeMode==="sum"?i=J(a,r):this.mergeMode==="ave"?i=L(.5,J(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=$a(t.layer);if(delete t.layer,t.numConstants!=null)throw new $e("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};lv.className="Bidirectional";re.registerClass(lv);function Nz(e){return new nu(e)}function Sz(e){return new fx(e)}function Cz(e){return new dx(e)}function _z(e){return new hx(e)}function Ez(e){return new mx(e)}function Fz(e){return new yx(e)}function Az(e){return new gx(e)}function $z(e){return new Sm(e)}function Dz(e){return new rp(e)}function Rz(e){return new vx(e)}function Mz(e){return new Nm(e)}function Pz(e){return new wx(e)}function Oz(e){return new kx(e)}function Lz(e){return new Ix(e)}function zz(e){return new Tx(e)}function Bz(e){return new $x(e)}function Wz(e){return new Fx(e)}function Vz(e){return new Am(e)}function Uz(e){return new Ex(e)}function Gz(e){return new Ax(e)}function Hz(e){return new Dx(e)}function jz(e){return new Rx(e)}function qz(e){return new Mx(e)}function Kz(e){return new Ox(e)}function Xz(e){return new Lx(e)}function Yz(e){return new Bx(e)}function Jz(e){return new Ux(e)}function Qz(e){return new Wx(e)}function Zz(e){return new Vx(e)}function eB(e){return new zx(e)}function tB(e){return new Gx(e)}function nB(e){return new Kx(e)}function aB(e){return new Xx(e)}function rB(e){return new Yx(e)}function Hb(e){return new Qx(e)}function sB(e){return Hb(e)}function iB(e){return Hb(e)}function jb(e){return new ev(e)}function oB(e){return jb(e)}function lB(e){return jb(e)}function qb(e){return new nv(e)}function uB(e){return qb(e)}function cB(e){return qb(e)}function pB(e){return new av(e)}function dB(e){return new sv(e)}function M1(e){return new rv(e)}function P1(e){return new iv(e)}function O1(e){return new Jx(e)}function L1(e){return new Zx(e)}function hB(e){return new tv(e)}function mB(e){return new Sx(e)}function fB(e){return new Em(e)}function gB(e){return new Cx(e)}function yB(e){return new sp(e)}function bB(e){return new Nx(e)}function xB(e){return new _m(e)}function vB(e){return new _x(e)}function wB(e){return new Fm(e)}function kB(e){return new nr(e)}function IB(e){return new Cm(e)}function TB(e){return new lv(e)}function NB(e){return new ov(e)}var SB=M1,CB=P1,_B=O1,EB=L1;function FB(e){return new Hx(e)}function AB(e){return new jx(e)}function $B(e){return new qx(e)}function DB(e){return new Px(e)}var HI={};Oe(HI,{MAPE:()=>u4,MSE:()=>d4,binaryAccuracy:()=>ZW,binaryCrossentropy:()=>e4,categoricalAccuracy:()=>n4,categoricalCrossentropy:()=>a4,cosineProximity:()=>i4,mape:()=>c4,meanAbsoluteError:()=>o4,meanAbsolutePercentageError:()=>l4,meanSquaredError:()=>p4,mse:()=>h4,precision:()=>r4,recall:()=>s4,sparseCategoricalAccuracy:()=>t4});function ZW(e,t){return Zb(e,t)}function e4(e,t){return Z1(e,t)}function t4(e,t){return eI(e,t)}function n4(e,t){return ex(e,t)}function a4(e,t){return tx(e,t)}function r4(e,t){return Q1(e,t)}function s4(e,t){return QB(e,t)}function i4(e,t){return Jb(e,t)}function o4(e,t){return gm(e,t)}function l4(e,t){return ru(e,t)}function u4(e,t){return ru(e,t)}function c4(e,t){return ru(e,t)}function p4(e,t){return Gi(e,t)}function d4(e,t){return Gi(e,t)}function h4(e,t){return Gi(e,t)}var jI={};Oe(jI,{modelFromJSON:()=>$W});var qI={};Oe(qI,{l1:()=>f4,l1l2:()=>m4,l2:()=>g4});function m4(e){return new np(e)}function f4(e){return BW(e)}function g4(e){return WW(e)}var KI=class extends au{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Tr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Dm(e,t){return e<t}function XI(e,t){return e>t}var YI=class extends KI{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=Dm:this.mode==="max"?this.monitorFunc=XI:this.monitor.indexOf("acc")!==-1?this.monitorFunc=XI:this.monitorFunc=Dm,this.monitorFunc===Dm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Dm?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 y4(e){return new YI(e)}var b4={earlyStopping:y4},Ra;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Ra||(Ra={}));var JI;(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={}))})(JI||(JI={}));var uv={};function x4(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};uv[e]=n}function QI(e){return uv[e]}function v4(e){delete uv[e]}function k(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 Fn(t.inputNames[s.inputIndexStart],n,a,r);if(s.type==="tensors")return t.inputNames.slice(o,l).map(p=>Fn(p,n,a,r));let c=Fn(t.inputNames.slice(o)[0],n,a,r),u=c.dataSync();return s.type==="number"?u[0]:w.toNestedArray(c.shape,u)}let i=t.attrParams[e];return i&&i.value}function Fn(e,t,n,a){let[r,s]=Wn(e);if(a!=null){let o=a.getHashTableHandleByName(r);if(o!=null)return o}let i=n.currentContextIds.find(o=>!!t[Rm(r,o)]);return i!==void 0?t[Rm(r,i)][s]:void 0}function w4(e,t,n){return t[Rm(e,n.currentContextId)]}function Nr(e,t){let[n,a]=Wn(e);return[Rm(n,t&&t.currentContextId),a]}function Rm(e,t){return t?`${e}-${t}`:e}function Wn(e){let t=e.split(":");return t.length===1?[e,0]:[t[0],Number(t[t.length-1])]}function Mm(e,t,n){let a=k("pad",e,t,n);if(a==="explicit"){a=k("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 Sr(e){return e.kept?e:Zr(e)}var ZI={};Oe(ZI,{json:()=>k4});var k4=[{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}]}],eT={};Oe(eT,{json:()=>I4});var I4=[{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}]}],tT={};Oe(tT,{json:()=>T4});var T4=[{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"}]}],nT={};Oe(nT,{json:()=>N4});var N4=[{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"}]}],aT={};Oe(aT,{json:()=>S4});var S4=[{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"}]}],rT={};Oe(rT,{json:()=>C4});var C4=[{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}]}],sT={};Oe(sT,{json:()=>_4});var _4=[{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"}]}],iT={};Oe(iT,{json:()=>E4});var E4=[{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"}]}],oT={};Oe(oT,{json:()=>F4});var F4=[{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}]}],lT={};Oe(lT,{json:()=>A4});var A4=[{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"}]}],uT={};Oe(uT,{json:()=>$4});var $4=[{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}]}],cT={};Oe(cT,{json:()=>D4});var D4=[{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}]}],pT={};Oe(pT,{json:()=>R4});var R4=[{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}]}],dT={};Oe(dT,{json:()=>M4});var M4=[{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"}]}],hT={};Oe(hT,{json:()=>P4});var P4=[{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}]}],mT={};Oe(mT,{json:()=>O4});var O4=[{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}]}],fT={};Oe(fT,{json:()=>L4});var L4=[{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:[]}],yT=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[ZI,eT,tT,nT,aT,rT,sT,uT,lT,iT,cT,pT,dT,hT,mT,fT,oT],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]=Nr(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]=Nr(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]=Nr(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=QI(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=gT(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=gT(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]=Nr(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]=Nr(p);u.inputs.push(r[d]),r[d].children.push(u)})});let o=e.ret;e.signature.outputArg.forEach(c=>{let[u,p]=Nr(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 z4(e){let t=ee().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function bT(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):z4(e);return t?n:n.toLowerCase()}function cv(e,t,n,a=!1){let r=e[t];return r!=null?bT(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=Ra[e]),e){case Ra.DT_FLOAT:return"float32";case Ra.DT_INT32:case Ra.DT_INT64:case Ra.DT_INT8:case Ra.DT_UINT8:return"int32";case Ra.DT_BOOL:return"bool";case Ra.DT_DOUBLE:return"float32";case Ra.DT_STRING:return"string";default:return null}}function gT(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 xT(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?xT(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=>bT(s,a)):n}function xv(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>xT(r)):n}function vv(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var B4=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 Fn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Fn(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}},W4=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[J(k("a",e,t,n),k("b",e,t,n))];case"AddN":return[lk(k("tensors",e,t,n))];case"FloorMod":case"Mod":return[lb(k("a",e,t,n),k("b",e,t,n))];case"Mul":return[L(k("a",e,t,n),k("b",e,t,n))];case"RealDiv":case"Div":return[xe(k("a",e,t,n),k("b",e,t,n))];case"DivNoNan":return[Qy(k("a",e,t,n),k("b",e,t,n))];case"FloorDiv":return[gh(k("a",e,t,n),k("b",e,t,n))];case"Sub":return[me(k("a",e,t,n),k("b",e,t,n))];case"Minimum":return[Kl(k("a",e,t,n),k("b",e,t,n))];case"Maximum":return[Xa(k("a",e,t,n),k("b",e,t,n))];case"Pow":return[xr(k("a",e,t,n),k("b",e,t,n))];case"SquaredDifference":return[zh(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},V4=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Lt(k("x",e,t,n))];case"Acos":return[Py(k("x",e,t,n))];case"Acosh":return[Oy(k("x",e,t,n))];case"Asin":return[zy(k("x",e,t,n))];case"Asinh":return[By(k("x",e,t,n))];case"Atan":return[Wy(k("x",e,t,n))];case"Atan2":return[Vy(k("x",e,t,n),k("y",e,t,n))];case"Atanh":return[Uy(k("x",e,t,n))];case"Ceil":return[qy(k("x",e,t,n))];case"Complex":return[Yr(k("real",e,t,n),k("imag",e,t,n))];case"Cos":return[Rc(k("x",e,t,n))];case"Cosh":return[wh(k("x",e,t,n))];case"Elu":return[Gl(k("x",e,t,n))];case"Erf":return[Zy(k("x",e,t,n))];case"Exp":return[hn(k("x",e,t,n))];case"Expm1":return[eb(k("x",e,t,n))];case"Floor":return[Hl(k("x",e,t,n))];case"Log":return[Pn(k("x",e,t,n))];case"Log1p":return[Nh(k("x",e,t,n))];case"Imag":return[Ih(k("x",e,t,n))];case"Neg":return[Nt(k("x",e,t,n))];case"Reciprocal":return[pb(k("x",e,t,n))];case"Real":return[zc(k("x",e,t,n))];case"Relu":return[qe(k("x",e,t,n))];case"Round":return[db(k("x",e,t,n))];case"Selu":return[Rh(k("x",e,t,n))];case"Sigmoid":return[da(k("x",e,t,n))];case"Sin":return[Mh(k("x",e,t,n))];case"Sign":return[hb(k("x",e,t,n))];case"Sinh":return[Ph(k("x",e,t,n))];case"Softplus":return[jl(k("x",e,t,n))];case"Sqrt":return[an(k("x",e,t,n))];case"Square":return[lt(k("x",e,t,n))];case"Tanh":return[Ul(k("x",e,t,n))];case"Tan":return[gb(k("x",e,t,n))];case"ClipByValue":return[qt(k("x",e,t,n),k("clipValueMin",e,t,n),k("clipValueMax",e,t,n))];case"Relu6":return[$h(k("x",e,t,n))];case"Rsqrt":return[Dh(Fn(e.inputNames[0],t,n))];case"Prod":return[Fh(k("x",e,t,n),k("axes",e,t,n))];case"LeakyRelu":return[Mc(k("x",e,t,n),k("alpha",e,t,n))];case"Prelu":return[Lc(k("x",e,t,n),k("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function ba(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let a=0;a<e.length;a++){let r=e[a],s=t[a];w.assert(r<0||s<0||r===s,()=>n+` Shapes ${e} and ${t} must match`)}}}function vT(e){return!(typeof e=="number"||e.some(t=>t<0))}function lp(e,t,n){let a=wv(e,n),r=!vT(a);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${a}`);if(r&&t.forEach(s=>{a=wv(s.shape,a)}),!vT(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function wv(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let a=0;a<e.length;++a){let r=e[a],s=t[a];if(r>=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[a]=r>=0?r:s}return n}var U4=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=pe(0),jt(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
|
|
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),ba(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,jt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,a)=>this.write(n,t[a]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let a=0;a<this.size();a++)e.push(a)}if(e.length===0)return Jn([],[0].concat(this.elementShape));let n=this.readMany(e);return ba(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),$t(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return Jn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return ba(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Je(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,ut(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=U(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]=U(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)}},up=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}`);ba(t,r.shape,"TensorList shape mismatch: "),jt(r)}),this.idTensor=pe(0),this.maxNumElements=a,jt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new up([...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.`);ba(e,this.elementShape,"TensorList shape mismatch: ");let a=lp(this.elementShape,this.tensors,e);return D(()=>{let r=this.tensors.map(s=>U(s,a));return $t(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=lp(this.elementShape,this.tensors,e),a=this.tensors.pop();return ba(a.shape,e,"TensorList shape mismatch: "),U(a,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(ba(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");jt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);ba(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=lp(this.elementShape,this.tensors,t);return U(this.tensors[e],a)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);ba(this.elementShape,t.shape,"TensorList shape mismatch: "),jt(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);ba(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=lp(this.elementShape,this.tensors,n);return e.length===0?Jn([],[0].concat(a)):D(()=>{let r=e.map(s=>U(this.tensors[s],a));return $t(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);ba(this.elementShape,t,"TensorList shape mismatch: ");let n=lp(this.elementShape,this.tensors,t);return this.size()===0?Jn([],[0].concat(n)):D(()=>{let a=this.tensors.map(r=>U(r,n));return Je(a,0)})}};function G4(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);ba(r,t,"TensorList shape mismatch: ");let s=ut(e);return new up(s,t,a)}function H4(e,t,n){return new up([],e,t,n)}function j4(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 up([],n,e.dtype,a),i=ut(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function q4(e,t,n){let a=0,r=t.map(u=>(a+=u,a));if(a!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${a}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=wv(s,n),o=a===0?0:e.size/a,l=D(()=>{let u=[];e=U(e,[1,a,o]);for(let p=0;p<t.length;++p){let d=p===0?0:r[p-1],h=[0,d,0],m=[1,t[p],o];u[p]=U(We(e,h,m),i)}return e.dispose(),u}),c=new up([],n,e.dtype,t.length);for(let u=0;u<l.length;u++)c.setItem(u,l[u]);return c}var K4=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=k("thenBranch",e,t,n),r=k("elseBranch",e,t,n),s=k("cond",e,t,n),i=k("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=k("body",e,t,n),r=k("cond",e,t,n),s=k("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=k("pred",e,t,n);return[Sr(a)]}case"Switch":{let a=k("pred",e,t,n),r=k("data",e,t,n);return r.kept||(r=Sr(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>Fn(r,t,n)!==void 0);if(a){let r=Fn(a,t,n);return[Sr(r)]}return}case"Enter":{let a=k("frameName",e,t,n),r=k("tensor",e,t,n);return n.enterFrame(a),[Sr(r)]}case"Exit":{let a=k("tensor",e,t,n);return n.exitFrame(),[Sr(a)]}case"NextIteration":{let a=k("tensor",e,t,n);return n.nextIteration(),[Sr(a)]}case"TensorArrayV3":{let a=k("size",e,t,n),r=k("dtype",e,t,n),s=k("elementShape",e,t,n),i=k("dynamicSize",e,t,n),o=k("clearAfterRead",e,t,n),l=k("identicalElementShapes",e,t,n),c=k("name",e,t,n),u=new U4(c,r,a,s,l,i,o);return n.addTensorArray(u),[u.idTensor,pe(1)]}case"TensorArrayWriteV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=k("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=k("tensorArrayId",e,t,n),r=k("tensor",e,t,n),s=k("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[pe(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=k("indices",e,t,n),r=k("tensor",e,t,n),s=k("elementShape",e,t,n),i=k("numElements",e,t,n),o=j4(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=k("elementShape",e,t,n),r=k("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,n),o=H4(a,r,i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=k("tensorListId",e,t,n),r=k("indices",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}case"TensorListStack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=k("numElements",e,t,n);return[n.getTensorList(a.id).stack(r,s,i)]}case"TensorListFromTensor":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=G4(a,r,s);return n.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let a=k("tensorListId",e,t,n),r=n.getTensorList(a.id),s=k("dtype",e,t,n),i=k("elementShape",e,t,n);return[r.concat(s,i)]}case"TensorListPushBack":{let a=k("tensorListId",e,t,n),r=k("tensor",e,t,n),s=n.getTensorList(a.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n);return[n.getTensorList(a.id).popBack(r,s)]}case"TensorListSplit":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("lengths",e,t,n),i=q4(a,s,r);return n.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function wT(e,t,n){let[a,r]=k("fusedOps",e,t,n),s=a==="biasadd",i=r==="prelu",o=a==="fusedbatchnorm",l=k("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=k("strides",e,t,n),u=Mm(e,t,n),p=k("dataFormat",e,t,n).toUpperCase(),d=k("dilations",e,t,n),[h,m]=k("args",e,t,n),f=k("leakyreluAlpha",e,t,n);return{stride:c,pad:u,dataFormat:p,dilations:d,biasArg:h,preluArg:m,activationFunc:r,leakyreluAlpha:f}}var X4=(e,t,n)=>{switch(e.op){case"Conv1D":{let a=k("stride",e,t,n),r=k("pad",e,t,n),s=k("dataFormat",e,t,n).toUpperCase(),i=k("dilation",e,t,n);return[xh(k("x",e,t,n),k("filter",e,t,n),a,r,s,i)]}case"Conv2D":{let a=k("strides",e,t,n),r=Mm(e,t,n),s=k("dataFormat",e,t,n).toUpperCase(),i=k("dilations",e,t,n);return[Ft(k("x",e,t,n),k("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}=wT(e,t,n);return[is.conv2d({x:k("x",e,t,n),filter:k("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}=wT(e,t,n);return[is.depthwiseConv2d({x:k("x",e,t,n),filter:k("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=k("outputShape",e,t,n),r=k("strides",e,t,n),s=Mm(e,t,n);return[vh(k("x",e,t,n),k("filter",e,t,n),a,[r[1],r[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let a=k("strides",e,t,n),r=Mm(e,t,n),s=k("dilations",e,t,n),i=k("dataFormat",e,t,n).toUpperCase();return[ns(k("input",e,t,n),k("filter",e,t,n),[a[1],a[2]],r,i,[s[1],s[2]])]}case"Conv3D":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("dataFormat",e,t,n).toUpperCase(),i=k("dilations",e,t,n);return[Xy(k("x",e,t,n),k("filter",e,t,n),[a[1],a[2],a[3]],r,s,[i[1],i[2],i[3]])]}case"AvgPool":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("kernelSize",e,t,n);return[Zn(k("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPool":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("kernelSize",e,t,n);return[At(k("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPoolWithArgmax":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("kernelSize",e,t,n),i=k("includeBatchInIndex",e,t,n),{result:o,indexes:l}=Dk(k("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r,i);return[o,l]}case"AvgPool3D":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("kernelSize",e,t,n);return[jy(k("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"MaxPool3D":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("kernelSize",e,t,n);return[ib(k("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"Dilation2D":{let a=k("strides",e,t,n),r=k("pad",e,t,n),s=k("dilations",e,t,n),i=a[1],o=a[2],l=s[1],c=s[2];return[Jy(k("x",e,t,n),k("filter",e,t,n),[i,o],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Y4=(e,t,n)=>{switch(e.op){case"Fill":{let a=k("shape",e,t,n),r=k("dtype",e,t,n),s=k("value",e,t,n);return[Cn(a,s,r)]}case"LinSpace":{let a=k("start",e,t,n),r=k("stop",e,t,n),s=k("num",e,t,n);return[Sk(a,r,s)]}case"Multinomial":{let a=k("logits",e,t,n),r=k("numSamples",e,t,n),s=k("seed",e,t,n);return[Rk(a,r,s)]}case"OneHot":{let a=k("indices",e,t,n),r=k("depth",e,t,n),s=k("onValue",e,t,n),i=k("offValue",e,t,n);return[Bl(a,r,s,i)]}case"Ones":return[Ya(k("shape",e,t,n),k("dtype",e,t,n))];case"OnesLike":return[On(k("x",e,t,n))];case"RandomUniform":return[Xl(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("dtype",e,t,n))];case"Range":{let a=k("start",e,t,n),r=k("stop",e,t,n),s=k("step",e,t,n);return[Ah(a,r,s,k("dtype",e,t,n))]}case"TruncatedNormal":{let a=k("shape",e,t,n),r=k("mean",e,t,n),s=k("stdDev",e,t,n),i=k("seed",e,t,n);return[Bh(a,r,s,k("dtype",e,t,n),i)]}case"Zeros":return[xt(k("shape",e,t,n),k("dtype",e,t,n))];case"ZerosLike":return[Ge(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kv(e,t,n){let a=k("boxes",e,t,n),r=k("scores",e,t,n),s=k("maxOutputSize",e,t,n),i=k("iouThreshold",e,t,n),o=k("scoreThreshold",e,t,n),l=k("softNmsSigma",e,t,n);return{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var J4=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=kv(e,t,n),c=await Ja.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}=kv(e,t,n),l=k("padToMaxOutputSize",e,t,n),c=await Ja.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}=kv(e,t,n);return[await Ja.nonMaxSuppressionAsync(a,r,s,i,o)]}case"Where":{let a=ue(k("condition",e,t,n),"bool"),r=[await xb(a)];return a.dispose(),r}case"ListDiff":return Ok(k("x",e,t,n),k("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Q4=(e,t,n)=>{switch(e.op){case"TopKV2":{let a=k("x",e,t,n),r=k("k",e,t,n),s=k("sorted",e,t,n),i=yb(a,r,s);return[i.values,i.indices]}case"Unique":{let a=k("x",e,t,n),r=Wh(a);return[r.values,r.indices]}case"UniqueV2":{let a=k("x",e,t,n),r=k("axis",e,t,n),s=Wh(a,r);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Z4=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=k("default",e,t,n);return[Fn(e.name,t,n)||a];case"Placeholder":return[Fn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=k("x",e,t,n);return[Sr(c)]}case"IdentityN":return k("x",e,t,n).map(c=>Sr(c));case"Snapshot":let r=k("x",e,t,n);return[Sr(r)];case"Shape":return[Ze(k("x",e,t,n).shape,"int32")];case"ShapeN":return k("x",e,t,n).map(c=>Ze(c.shape));case"Size":return[pe(k("x",e,t,n).size,"int32")];case"Rank":return[pe(k("x",e,t,n).rank,"int32")];case"NoOp":return[pe(1)];case"Print":let s=k("x",e,t,n),i=k("data",e,t,n),o=k("message",e,t,n),l=k("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(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`)}},eV=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=pe(0),this.tensorMap=new Map,jt(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),D(()=>{let a=ut(t),r=n.length,s=a.length;w.assert(r===s,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`);for(let i=0;i<r;i++){let o=n[i],l=a[i];jt(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return D(()=>{let a=[];for(let r=0;r<n.length;r++){let s=n[r],i=this.findWithDefault(s,t);a.push(i)}return $t(a)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},tV=async(e,t,n,a)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=k("keyDType",e,t,n),s=k("valueDType",e,t,n),i=new eV(r,s);return a.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("values",e,t,n);return[await a.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("defaultValue",e,t,n);return[await a.getHashTableById(r.id).find(s,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},nV=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let a=k("images",e,t,n),r=k("size",e,t,n),s=k("alignCorners",e,t,n),i=k("halfPixelCenters",e,t,n);return[Ja.resizeBilinear(a,[r[0],r[1]],s,i)]}case"ResizeNearestNeighbor":{let a=k("images",e,t,n),r=k("size",e,t,n),s=k("alignCorners",e,t,n),i=k("halfPixelCenters",e,t,n);return[Ja.resizeNearestNeighbor(a,[r[0],r[1]],s,i)]}case"CropAndResize":{let a=k("image",e,t,n),r=k("boxes",e,t,n),s=k("boxInd",e,t,n),i=k("cropSize",e,t,n),o=k("method",e,t,n),l=k("extrapolationValue",e,t,n);return[Ja.cropAndResize(a,r,s,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},aV=(e,t,n)=>{switch(e.op){case"Equal":return[as(k("a",e,t,n),k("b",e,t,n))];case"NotEqual":return[Mi(k("a",e,t,n),k("b",e,t,n))];case"Greater":return[ha(k("a",e,t,n),k("b",e,t,n))];case"GreaterEqual":return[rs(k("a",e,t,n),k("b",e,t,n))];case"Less":return[Th(k("a",e,t,n),k("b",e,t,n))];case"LessEqual":return[Di(k("a",e,t,n),k("b",e,t,n))];case"LogicalAnd":return[ma(k("a",e,t,n),k("b",e,t,n))];case"LogicalNot":return[Pc(k("a",e,t,n))];case"LogicalOr":return[_h(k("a",e,t,n),k("b",e,t,n))];case"Select":case"SelectV2":return[Sn(k("condition",e,t,n),k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},rV=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[ze(k("a",e,t,n),k("b",e,t,n),k("transposeA",e,t,n),k("transposeB",e,t,n))];case"Transpose":return[Ve(k("x",e,t,n),k("perm",e,t,n))];case"_FusedMatMul":let[a,r]=k("fusedOps",e,t,n),s=a==="biasadd",i=r==="prelu",o=k("numArgs",e,t,n),l=k("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]=k("args",e,t,n);return[is.matMul({a:k("a",e,t,n),b:k("b",e,t,n),transposeA:k("transposeA",e,t,n),transposeB:k("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},sV=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[br(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"FusedBatchNormV3":return[br(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"LRN":return[nb(k("x",e,t,n),k("radius",e,t,n),k("bias",e,t,n),k("alpha",e,t,n),k("beta",e,t,n))];case"Softmax":return[Na(k("x",e,t,n))];case"LogSoftmax":return[Ch(k("x",e,t,n))];case"SparseToDense":return[vb(k("sparseIndices",e,t,n),k("outputShape",e,t,n),k("sparseValues",e,t,n),k("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},iV=(e,t,n)=>{switch(e.op){case"Max":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[ea(k("x",e,t,n),i,o)]}case"Mean":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[St(k("x",e,t,n),i,o)]}case"Min":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[ql(k("x",e,t,n),i,o)]}case"Sum":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[Se(k("x",e,t,n),i,o)]}case"All":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[yh(k("x",e,t,n),i,o)]}case"Any":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[Ec(k("x",e,t,n),i,o)]}case"ArgMax":{let i=k("axis",e,t,n);return[Fc(k("x",e,t,n),i)]}case"ArgMin":{let i=k("axis",e,t,n);return[Ly(k("x",e,t,n),i)]}case"Prod":{let i=k("axis",e,t,n),o=k("keepDims",e,t,n);return[Fh(k("x",e,t,n),i,o)]}case"Cumsum":{let i=k("axis",e,t,n),o=k("exclusive",e,t,n),l=k("reverse",e,t,n);return[kh(k("x",e,t,n),i,o,l)]}case"Bincount":let a=k("x",e,t,n),r=k("weights",e,t,n),s=k("size",e,t,n);return[fk(a,r,s)];case"DenseBincount":{let i=k("x",e,t,n),o=k("weights",e,t,n),l=k("size",e,t,n),c=k("binaryOutput",e,t,n);return[wk(i,o,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},oV=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let a=k("n",e,t,n),r=k("axis",e,t,n),s=k("tensors",e,t,n);return s=s.slice(0,a),[Je(s,r)]}case"Gather":{let a=k("x",e,t,n),r=k("indices",e,t,n);return[$i(a,ue(r,"int32"),0)]}case"GatherV2":{let a=k("axis",e,t,n),r=k("batchDims",e,t,n),s=k("x",e,t,n),i=k("indices",e,t,n);return[$i(s,ue(i,"int32"),a,r)]}case"Reverse":{let a=k("dims",e,t,n),r=[];for(let i=0;i<a.length;i++)a[i]&&r.push(i);let s=k("x",e,t,n);return[Ln(s,r)]}case"ReverseV2":{let a=k("axis",e,t,n),r=k("x",e,t,n);return[Ln(r,a)]}case"Slice":{let a=k("begin",e,t,n),r=k("size",e,t,n);return[We(k("x",e,t,n),a,r)]}case"StridedSlice":{let a=k("begin",e,t,n),r=k("end",e,t,n),s=k("strides",e,t,n),i=k("beginMask",e,t,n),o=k("endMask",e,t,n),l=k("ellipsisMask",e,t,n),c=k("newAxisMask",e,t,n),u=k("shrinkAxisMask",e,t,n),p=k("x",e,t,n);return[fb(p,a,r,s,i,o,l,c,u)]}case"Pack":return D(()=>{let a=k("axis",e,t,n),r=k("tensors",e,t,n),s=r[0].shape,i=ss(r[0]).shape,o=r.map(l=>{let c=w.arraysEqual(l.shape,s);if(!c&&!w.arraysEqual(ss(l).shape,i))throw new Error("the input tensors shape does not match");return c?l:U(l,s)});return[$t(o,a)]});case"Unpack":{let a=k("axis",e,t,n),r=k("tensor",e,t,n);return ut(r,a)}case"Tile":{let a=k("reps",e,t,n);return[qa(k("x",e,t,n),a)]}case"Split":case"SplitV":{let a=k("axis",e,t,n),r=k("numOrSizeSplits",e,t,n),s=k("x",e,t,n);return zn(s,r,a)}case"ScatterNd":{let a=k("indices",e,t,n),r=k("values",e,t,n),s=k("shape",e,t,n);return[Wk(a,r,s)]}case"GatherNd":{let a=k("x",e,t,n),r=k("indices",e,t,n);return[Vk(a,r)]}case"SparseToDense":{let a=k("sparseIndices",e,t,n),r=k("outputShape",e,t,n),s=k("sparseValues",e,t,n),i=k("defaultValue",e,t,n);return[vb(a,s,r,s.dtype===i.dtype?i:ue(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},lV=(e,t,n)=>{switch(e.op){case"FFT":return[Wc(k("x",e,t,n))];case"IFFT":return[Jl(k("x",e,t,n))];case"RFFT":return[Vc(k("x",e,t,n))];case"IRFFT":return[Lh(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},uV=(e,t,n)=>{switch(e.op){case"Cast":return[ue(k("x",e,t,n),k("dtype",e,t,n))];case"ExpandDims":{let a=k("axis",e,t,n);return[Mn(k("x",e,t,n),a)]}case"Squeeze":{let a=k("axis",e,t,n);return[ss(k("x",e,t,n),a)]}case"Reshape":return[U(k("x",e,t,n),k("shape",e,t,n))];case"MirrorPad":return[ob(k("x",e,t,n),k("padding",e,t,n),k("mode",e,t,n))];case"PadV2":case"Pad":return[ta(k("x",e,t,n),k("padding",e,t,n),k("constantValue",e,t,n))];case"SpaceToBatchND":{let a=k("blockShape",e,t,n),r=k("paddings",e,t,n);return[Oc(k("x",e,t,n),a,r)]}case"BatchToSpaceND":{let a=k("blockShape",e,t,n),r=k("crops",e,t,n);return[$c(k("x",e,t,n),a,r)]}case"DepthToSpace":{let a=k("blockSize",e,t,n),r=k("dataFormat",e,t,n).toUpperCase();return[Yy(k("x",e,t,n),a,r)]}case"BroadcastTo":return[Dc(k("x",e,t,n),k("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kT(e,t,n,a){let r=((s,i,o)=>{switch(s.category){case"arithmetic":return D(()=>W4(s,i,o));case"basic_math":return D(()=>V4(s,i,o));case"control":return K4(s,i,o);case"convolution":return D(()=>X4(s,i,o));case"creation":return D(()=>Y4(s,i,o));case"dynamic":return J4(s,i,o);case"evaluation":return D(()=>Q4(s,i,o));case"image":return D(()=>nV(s,i,o));case"graph":return D(()=>Z4(s,i,o));case"logical":return D(()=>aV(s,i,o));case"matrices":return D(()=>rV(s,i,o));case"normalization":return D(()=>sV(s,i,o));case"reduction":return D(()=>iV(s,i,o));case"slice_join":return D(()=>oV(s,i,o));case"spectral":return D(()=>lV(s,i,o));case"transformation":return D(()=>uV(s,i,o));case"hash_table":return tV(s,i,o,a);case"custom":let l=QI(s.op);if(l&&l.customExecutor)return l.customExecutor(new B4(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 w.isPromise(r)?r.then(s=>[].concat(s)):[].concat(r)}var IT=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 NT(e,t,n,a){let r=new Set,s=[],i=null,o=null,l=new Set,c=Object.keys(e).map(d=>Wn(d)[0]),u=[];a!=null&&(u=a.map(d=>Wn(d.name)[0]));let p=[...t];for(;p.length>0;){let d=p.pop();if((TT(d)||cV(d)||pV(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 dV(e,t,n){let{usedNodes:a,inputs:r}=n,s=[],i=Object.keys(r).map(u=>Wn(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 hV=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],mV=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],fV=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function TT(e){return hV.indexOf(e.op)>=0}function cV(e){return mV.indexOf(e.op)>=0}function pV(e){return fV.indexOf(e.op)>=0}var Iv=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 Iv(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=NT(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 dV(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[Wn(u)[0]]),r=t.map(u=>Wn(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 IT(this.weightMap,l,c,this.functionExecutorMap),p=Object.assign({},this.weightMap);Object.keys(e).forEach(m=>{let[f,g]=Wn(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=kT(f,p,u,this._resourceManager);if(w.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=>Fn(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=w4(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 IT(this.weightMap,a,r,this.functionExecutorMap),i=await this.executeWithControlFlow(e,s,t,n),o=t.map(p=>Fn(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[Wn(b)[0]]),i=n.map(b=>Wn(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}=NT(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[x,v]=Wn(b),N=[];N[v]=e[b],h[x]=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=>!TT(b)&&!Fn(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"&&k("isConstant",u.node,a,n)&&([p]=Nr(u.node.name,n)),a[u.node.name]==null){let d=kT(u.node,a,n,this._resourceManager);p||([p]=Nr(u.node.name,n));let h=n.currentContext;w.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]=Nr(i.name,n);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Fn(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(l=>!!Fn(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]=Wn(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);w.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&&w.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]=Wn(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]=Wn(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},gV=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]}},yV="?tfjs-format=file",bV="model.json",ST=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new gV}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=Ht.browserHTTPRequest(e,this.loadOptions);else{let t=Ht.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Ht.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let a=Ht.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Iv(yT.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=yT.Instance.transformGraph(e.modelInitializer);this.initializer=new Iv(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=Ht.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Ee)&&!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 xV(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}${bV}${yV}`);let n=new ST(e,t);return await n.load(),n}var CT="3.2.0",_T={};Oe(_T,{CSVDataset:()=>FT,Dataset:()=>ou,FileDataSource:()=>AT,TextLineDataset:()=>ET,URLDataSource:()=>$T,array:()=>vV,csv:()=>kV,func:()=>IV,generator:()=>TV,microphone:()=>SV,version_data:()=>DT,webcam:()=>NV,zip:()=>wV});var CV=Do(wd()),_V=Do(wd());function EV(e,t){return Pm(e,t)}function Pm(e,t,n=new Map,a=new Set){if(e==null)return null;if(a.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(lu(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=Pm(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 FV(e,t=MT){return RT(e,t)}function RT(e,t,n=new Set){let a=e[0];if(n.has(a))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(lu(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(c=>c[i]),l=RT(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 MT(e){return e===null?null:lu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function PT(e,t){let n=new Map;Pm(e,t,n);for(let a of Array.from(n.keys())){let r=n.get(a);if(w.isPromise(r)){let s=await r;n.set(a,s)}}return Pm(e,t,n)}function lu(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ee))}function $V(e){return e==null||AV(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ee||w.isTypedArray(e)}function AV(e){return e===null||typeof e!="object"&&typeof e!="function"}function RV(e){return EV(e,DV)}function DV(e){return e instanceof Ee?{value:e.clone(),recurse:!1}:lu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var OT=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}},Tv=class extends OT{constructor(){super(Tv.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}};Tv.INITIAL_CAPACITY=32;function LT(e){return new MV(e)}function Nv(e){return new PV(e)}function OV(e,t){return new zT(e,t)}function zV(e,t=ms.FAIL){return new LV(e,t)}var Yt=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new jV(this,e)}filter(e){return new GV(this,e)}map(e){return new HV(this,e)}mapAsync(e){return new BT(this,e)}serialMapAsync(e){return new BT(this,e).serial()}flatmap(e){return new qV(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 UV(this,e,t)}columnMajorBatch(e,t=!0,n=MT){return this.rowMajorBatch(e,t).map(a=>FV(a,n))}concatenate(e,t){return new zT(LT([this,e]),t)}take(e){return e<0||e==null?this:new VV(this,e)}skip(e){return e<0||e==null?this:new WV(this,e)}prefetch(e){return new WT(this,e)}shuffle(e,t){return new KV(this,e,t)}serial(){return new BV(this)}},MV=class extends Yt{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:RV(e),done:!1}}},PV=class extends Yt{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},BV=class extends Yt{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},WV=class extends Yt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;Ae(e.value)}return this.upstream.next()}},VV=class extends Yt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},UV=class extends Yt{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},GV=class extends Yt{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Ae(e.value)}}},HV=class extends Yt{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Ta.getTensorsInContainer(e.value),n=this.transform(e.value),a=Ta.getTensorsInContainer(n);for(let r of t)Ta.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},jV=class extends Yt{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},BT=class extends Yt{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Ta.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Ta.getTensorsInContainer(n);for(let r of t)Ta.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},Sv=class extends Yt{constructor(){super();this.outputQueue=new Tv,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}}},qV=class extends Sv{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=Ta.getTensorsInContainer(e.value),n=this.transform(e.value),a=Ta.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Ta.isTensorInList(r,a)||r.dispose();return!0}},zT=class extends Yt{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},ms;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(ms||(ms={}));var LV=class extends Yt{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 Yt?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await PT(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}},WT=class extends Yt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new OT(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()}},KV=class extends WT{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=_V.alea(n||w.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},ou=class{constructor(){this.size=null}batch(e,t=!0){let n=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let a;return this.size===Infinity||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),Vn(async()=>(await n.iterator()).columnMajorBatch(e,t,XV),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,Vn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,Vn(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 Vn(async()=>(await t.iterator()).map(n=>D(()=>e(n))),this.size)}mapAsync(e){let t=this;return Vn(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 Vn(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,Vn(async()=>{let a=Nv(async()=>({value:await t.iterator(),done:!1}));return OV(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,Vn(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=CV.alea(t||w.now().toString());return Vn(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,Vn(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()}};ou.MAX_BUFFER_SIZE=1e4;function Vn(e,t=null){return new class extends ou{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function vV(e){return Vn(async()=>LT(e),e.length)}function wV(e){if(!lu(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<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 Vn(async()=>{let n=await PT(e,a=>{if(a instanceof ou)return{value:a.iterator(),recurse:!1};if(lu(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return zV(n,ms.SHORTEST)},t)}function XV(e){if(e===null)return null;let t=e[0];return $V(t)?{value:YV(e),recurse:!1}:{value:null,recurse:!0}}function YV(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?$t(e):Jn(e)}var ET=class extends ou{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))}},Om='"',cp=Symbol("out"),VT=Symbol("field"),Lm=Symbol("quote"),Cv=Symbol("quoteafterquote"),UT=Symbol("quoteinquote"),FT=class extends ou{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 ET(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(w.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=cp;for(let i=0;i<r;i++)switch(s){case cp:switch(e.charAt(i)){case Om:a=i+1,s=Lm;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=cp;break;default:s=VT,a=i;break}break;case VT:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=cp,a=i+1;break;default:}break;case Lm:switch(e.charAt(i)){case Om:s=Cv;break;default:}break;case Cv:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=cp,a=i+1;break;case Om:s=Lm;break;default:s=UT;break}break;case UT:switch(e.charAt(i)){case Om:s=Lm;break;default:}break;default:}if(s===Cv?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}},GT=class extends Yt{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(ee().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new GT(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(w.sizeFromShape(t));return n.set(e,n.length-e.length),Jn(n,t)}},HT=class extends Yt{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Ze([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,a=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,s=(1-a)/2,i=r+n,o=a+s;this.cropBox=Sa([s,r,o,i],[1,4])}else this.cropBox=Sa([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(ee().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new HT(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&w.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Ei.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=Mn(ue(e,"float32"),0),n;n=Ja.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return U(n,a.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},jT=class{},qT=class extends Yt{split(e){return new JV(this,e)}},JV=class extends qT{constructor(e,t){super();this.upstream=e,this.impl=new QV(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},QV=class extends Sv{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}},eU=class extends Yt{decodeUTF8(){return new ZV(this)}},ZV=class extends qT{constructor(e){super();this.upstream=e,this.impl=new tU(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},tU=class extends Sv{constructor(e){super();if(this.upstream=e,ee().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=NE();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return ee().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},KT=class extends eU{constructor(e,t={}){super();this.file=e,this.options=t,w.assert(e instanceof Uint8Array||(ee().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((e,t)=>{let n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{let a=new FileReader;a.onload=s=>{let i=a.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},a.onabort=s=>t(new Error("Aborted")),a.onerror=s=>t(new Error(s.type));let r=this.file.slice(this.offset,n);a.readAsArrayBuffer(r)}this.offset=n}),done:!1}}};async function aU(e,t={}){let n,a;typeof e=="string"?n=e:(n=e.url,a=nU(e));let r=await w.fetch(n,a);if(r.ok){let s=new Uint8Array(await r.arrayBuffer());return new KT(s,t)}else throw new Error(r.statusText)}var nU=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 XT(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var AT=class extends jT{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(XT(this.input)&&ee().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new KT(this.input,this.options)}},$T=class extends jT{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return XT(this.url)?new AT(this.url,this.fileOptions).iterator():aU(this.url,this.fileOptions)}};function kV(e,t={}){return new FT(new $T(e),t)}function IV(e){let t=Nv(e);return Vn(async()=>t)}function TV(e){return Vn(async()=>{let t=await e();return Nv(()=>t.next())})}async function NV(e,t){return HT.create(e,t)}async function SV(e){return GT.create(e)}var DT="3.2.0";function ve(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var rU=Qa.whereImpl,_v=class extends Zu{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new kd(this,Ha())}nextDataId(){return _v.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,ee().get("IS_NODE")&&_.warn(`
|
|
============================
|
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let r=n.map(s=>w.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,a,r){this.data.set(e,{values:t,dtype:a,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let a=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(a,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(a=>w.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}makeOutput(e,t,n){let a=this.write(e,t,n);return Ha().makeTensorFromDataId(a,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){ve([e],"where");let t=this.readSync(e.dataId);return rU(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};_v.nextDataId=0;var YT={};Oe(YT,{addImpl:()=>QT,bincountImpl:()=>Ev,bincountReduceImpl:()=>ZT,ceilImpl:()=>eN,concatImpl:()=>Fv,expImpl:()=>tN,expm1Impl:()=>nN,floorImpl:()=>aN,gatherV2Impl:()=>rN,greaterImpl:()=>sN,lessImpl:()=>iN,linSpaceImpl:()=>oN,logImpl:()=>lN,maxImpl:()=>uN,maximumImpl:()=>cN,minimumImpl:()=>pN,multiplyImpl:()=>Av,negImpl:()=>dN,notEqualImpl:()=>hN,prodImpl:()=>mN,rangeImpl:()=>Dv,rsqrtImpl:()=>fN,simpleAbsImpl:()=>JT,sliceImpl:()=>zm,squaredDifferenceImpl:()=>gN,stridedSliceImpl:()=>yN,subImpl:()=>bN,tileImpl:()=>xN,topKImpl:()=>vN,transposeImpl:()=>$v,uniqueImpl:()=>wN});function JT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var sU=e=>{let{x:t}=e.inputs,n=e.backend;ve(t,"abs");let a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=JT(r),n.makeOutput(a,t.shape,"float32")},iU={kernelName:Po,backendName:"cpu",kernelFunc:sU};function Rt(e){return(t,n,a,r,s)=>{let i=_.assertAndGetBroadcastShape(t,n),o=i.length,l=w.computeStrides(i),c=w.sizeFromShape(i),u=w.getTypedArrayFromDType(s,c),p=t.length,d=n.length,h=w.computeStrides(t),m=w.computeStrides(n),f=_.getBroadcastDims(t,i),g=_.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(a[y%a.length],r[y%r.length]);else for(let y=0;y<u.length;++y){let b=w.indexToLoc(y,o,l),x=b.slice(-p);f.forEach(S=>x[S]=0);let v=w.locToIndex(x,p,h),N=b.slice(-d);g.forEach(S=>N[S]=0);let T=w.locToIndex(N,d,m);u[y]=e(a[v],r[T])}return[u,i]}}function Un(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 oU={kernelName:Ad,backendName:"cpu",kernelFunc:Un};function Bm(e,t,n="float32"){if(n==="complex64"){let r=Bm(e,t,"float32"),s=Bm(e,t,"float32");return Un({inputs:{real:r,imag:s},backend:e})}let a=w.makeZerosTypedArray(w.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function rr(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var lU={kernelName:Ks,backendName:"cpu",kernelFunc:rr};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 uU={kernelName:Jd,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 rr({inputs:{x:r},backend:n});let i=Bm(n,r.shape,r.dtype),o=fs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Un({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(!w.hasEncodingLoss(r.dtype,s)){let i=rr({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=n.data.get(r.dataId).values,o=Int32Array.from(i);return n.makeTensorInfo(r.shape,"int32",o)}if(s==="bool"){let i=n.data.get(r.dataId).values,o=w.toTypedArray([0],r.dtype),[l,c]=Rt((u,p)=>u!==p?1:0)(r.shape,[],i,o,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var cU={kernelName:Ms,backendName:"cpu",kernelFunc:fs};function Jt(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;ve([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,x=l.data.get(y.dataId).values,v=l.data.get(b.dataId).values,[N,T,S]=n(i.shape,o.shape,h,m,x,v),A=l.makeTensorInfo(S,"float32",N),$=l.makeTensorInfo(S,"float32",T),R=Un({inputs:{real:A,imag:$},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(A),l.disposeIntermediateTensorInfo($),R}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 Rv(e){return(t,n,a,r,s,i)=>{let o=_.assertAndGetBroadcastShape(t,n),l=w.sizeFromShape(o),c=o.length,u=w.computeStrides(o),p=w.getTypedArrayFromDType("float32",l),d=w.getTypedArrayFromDType("float32",l),h=_.getBroadcastDims(t,o),m=_.getBroadcastDims(n,o),f=_.mergeRealAndImagArrays(a,r),g=_.mergeRealAndImagArrays(s,i),y=t.length,b=w.computeStrides(t),x=n.length,v=w.computeStrides(n);if(h.length+m.length===0)for(let N=0;N<p.length;N++){let T=N%f.length,S=N%g.length,A=e(f[T*2],f[T*2+1],g[S*2],g[S*2+1]);p[N]=A.real,d[N]=A.imag}else for(let N=0;N<p.length;N++){let T=w.indexToLoc(N,c,u),S=T.slice(-y);h.forEach(V=>S[V]=0);let A=w.locToIndex(S,y,b),$=T.slice(-x);m.forEach(V=>$[V]=0);let R=w.locToIndex($,x,v),B=e(f[A*2],f[A*2+1],g[R*2],g[R*2+1]);p[N]=B.real,d[N]=B.imag}return[p,d,o]}}var QT=Rt((e,t)=>e+t),pU=Rv((e,t,n,a)=>({real:e+n,imag:t+a})),pp=Jt(Hr,QT,pU),dU={kernelName:Hr,backendName:"cpu",kernelFunc:pp};function Ev(e,t,n,a,r){let s=w.sizeFromShape(a),i=w.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 ZT(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 uu(e){return(t,n,a)=>{let r=w.getTypedArrayFromDType(n,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],a);return r}}function st(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(ve(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=w.sizeFromShape(i.shape),u=n||i.dtype,p=w.getArrayFromDType(u,c);for(let d=0;d<c;++d)p[d]=t(l[d],r);return o.makeTensorInfo(i.shape,u,p)}}function cu(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;if(ve(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 eN=uu(e=>Math.ceil(e)),hU=cu(Ps,eN),mU={kernelName:Ps,backendName:"cpu",kernelFunc:hU};function Fv(e,t,n,a){let r=w.getArrayFromDType(n,w.sizeFromShape(t));if(a&&n!=="string"){let s=0;e.forEach(i=>{let o=w.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=n==="string"?_.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let c=0;c<i.shape[0];++c){let u=c*t[1]+s;for(let p=0;p<i.shape[1];++p)r[u+p]=o[l++]}s+=i.shape[1]})}return r}var tN=uu(e=>Math.exp(e)),kN=cu(Us,tN),fU={kernelName:Us,backendName:"cpu",kernelFunc:kN},nN=uu(e=>Math.expm1(e)),gU=cu(Qo,nN),yU={kernelName:Qo,backendName:"cpu",kernelFunc:gU},aN=uu(e=>Math.floor(e)),bU=cu(Gs,aN),xU={kernelName:Gs,backendName:"cpu",kernelFunc:bU};function rN(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 sN=Rt((e,t)=>e>t?1:0),vU=Jt(nl,sN,null,"bool"),wU={kernelName:nl,backendName:"cpu",kernelFunc:vU},iN=Rt((e,t)=>e<t?1:0),kU=Jt(il,iN,null,"bool"),IU={kernelName:il,backendName:"cpu",kernelFunc:kU};function oN(e,t,n){let a=(t-e)/(n-1),r=w.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;s<r.length;s++)r[s]=r[s-1]+a;return r}var lN=uu(e=>Math.log(e)),TU=cu(Ys,lN),NU={kernelName:Ys,backendName:"cpu",kernelFunc:TU};function uN(e,t,n,a){let r=w.getTypedArrayFromDType(a,w.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 cN=Rt((e,t)=>Math.max(e,t)),SU=Jt(Qs,cN),CU={kernelName:Qs,backendName:"cpu",kernelFunc:SU},pN=Rt((e,t)=>Math.min(e,t)),_U=Jt(ni,pN),EU={kernelName:ni,backendName:"cpu",kernelFunc:_U},Av=Rt((e,t)=>e*t),FU=Rv((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),Mv=Jt(ai,Av,FU),AU={kernelName:ai,backendName:"cpu",kernelFunc:Mv};function dN(e,t,n){let a=w.createScalarValue(-1,n);return Av([],t,a,e,n)}function $U(e){let{inputs:t,backend:n}=e,{x:a}=t;ve(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=dN(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var DU={kernelName:pl,backendName:"cpu",kernelFunc:$U},hN=Rt((e,t)=>e!==t?1:0),RU=Jt(dl,hN,null,"bool"),MU={kernelName:dl,backendName:"cpu",kernelFunc:RU};function $v(e,t,n,a,r){let s=t.length,i=w.sizeFromShape(t),o=w.computeStrides(t),l=w.computeStrides(r),c=w.getTypedArrayFromDType(n,w.sizeFromShape(r));for(let u=0;u<i;++u){let p=w.indexToLoc(u,s,o),d=new Array(p.length);for(let m=0;m<d.length;m++)d[m]=p[a[m]];let h=w.locToIndex(d,s,l);c[h]=e[u]}return c}function xa(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{perm:s}=n;ve(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=$v(l,r.shape,r.dtype,s,o);return{dataId:a.write(c,o,r.dtype),shape:o,dtype:r.dtype}}var PU={kernelName:ki,backendName:"cpu",kernelFunc:xa};function mN(e,t,n,a){let[r,s]=_.computeOutAndReduceShapes(e,a),i=pa(t,"int32"),o=w.makeZerosTypedArray(w.sizeFromShape(r),i),l=w.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 OU(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ve(r,"prod");let o=r.shape.length,l=w.parseAxisParam(s,r.shape),c=_.getAxesPermutation(l,o),u=l,p=r,d=[];c!=null&&(p=xa({inputs:{x:r},backend:n,attrs:{perm:c}}),d.push(p),u=_.getInnerMostAxes(u.length,o));let h=n.data.get(p.dataId).values,{outVals:m,outShape:f,outDtype:g}=mN(p.shape,p.dtype,h,u),y=f;return i&&(y=_.expandShapeToKeepDim(f,l)),d.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.makeTensorInfo(y,g,m)}var LU={kernelName:bl,backendName:"cpu",kernelFunc:OU};function Dv(e,t,n,a){let r=e===t,s=e<t&&n<0,i=t<e&&n>1;if(r||s||i)return w.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=w.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 fN=uu(e=>1/Math.sqrt(e)),zU=cu(hi,fN),BU={kernelName:hi,backendName:"cpu",kernelFunc:zU};function zm(e,t,n,a,r){let s=dn.isSliceContinous(a,t,n),i=w.sizeFromShape(n),o=w.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"?_.fromUint8ToStringArray(e):e,c=Le(a,r,l),u=Le(n,r);for(let p=0;p<u.size;++p){let d=u.indexToLoc(p),h=d.map((m,f)=>m+t[f]);u.set(c.get(...h),...d)}return r==="string"?_.fromStringArrayToUint8(u.values):u.values}function Xi(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;ve(r,"slice");let[o,l]=dn.parseSliceParams(r,s,i);dn.assertParamsValid(r,o,l);let c=n.data.get(r.dataId).values,u=zm(c,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var WU={kernelName:Tl,backendName:"cpu",kernelFunc:Xi},gN=Rt((e,t)=>{let n=e-t;return n*n}),VU=Jt(xi,gN),UU={kernelName:xi,backendName:"cpu",kernelFunc:VU};function yN(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 bN=Rt((e,t)=>e-t),GU=Rv((e,t,n,a)=>({real:e-n,imag:t-a})),Pv=Jt(vi,bN,GU),HU={kernelName:vi,backendName:"cpu",kernelFunc:Pv};function xN(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 vN(e,t,n,a,r){let s=t[t.length-1],[i,o]=[e.length/s,s],l=w.getTypedArrayFromDType(n,i*a),c=w.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,x)=>x.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 wN(e,t,n,a){let r=w.parseAxisParam(t,n)[0],s=[1,n[0],1];for(let m=0;m<r;m++)s[0]*=n[m];s[1]=n[r];for(let m=r+1;m<n.length;m++)s[2]*=n[m];let i={},o=new Int32Array(n[r]),l=new Ot(s,a,e),c=[],u=s[0]===1&&s[2]===1;for(let m=0;m<n[r];m++){let f;if(u)f=e[m].toString();else{let g=[];for(let y=0;y<s[0];y++)for(let b=0;b<s[2];b++)g.push(l.get(y,m,b));f=g.join(",")}if(i[f]!==void 0)o[m]=i[f];else{let g=Object.keys(i).length;i[f]=g,o[m]=g,c.push(m)}}let p=s.slice();p[1]=Object.keys(i).length;let d=new Ot(p,a);c.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)d.set(l.get(g,m,y),g,f,y)});let h=n.slice();return h[r]=p[1],{outputValues:d.values,outputShape:h,indices:o}}var jU="3.2.0";fh("cpu",()=>new _v,1);var IN=st(Ko,e=>e>=0?e:Math.exp(e)-1),qU={kernelName:Ko,backendName:"cpu",kernelFunc:IN};function TN(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;ve([r],"leakyRelu");let i=w.sizeFromShape(r.shape),o=n.data.get(r.dataId).values,l=w.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 KU={kernelName:Xs,backendName:"cpu",kernelFunc:TN},XU=Rt((e,t)=>e<0?t*e:e);function NN(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;ve([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=XU(a.shape,r.shape,s,i,a.dtype);return n.makeTensorInfo(l,a.dtype,o)}var YU={kernelName:oi,backendName:"cpu",kernelFunc:NN},SN=st(li,e=>Math.max(0,e)),JU={kernelName:li,backendName:"cpu",kernelFunc:SN},CN=st(ci,e=>Math.min(Math.max(0,e),6)),QU={kernelName:ci,backendName:"cpu",kernelFunc:CN};function Ov(e,t,n,a,r){if(n==="linear")return rr({inputs:{x:t},backend:e});if(n==="relu")return SN({inputs:{x:t},backend:e});if(n==="elu")return IN({inputs:{x:t},backend:e});if(n==="relu6")return CN({inputs:{x:t},backend:e});if(n==="prelu")return NN({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return TN({inputs:{x:t},backend:e,attrs:{alpha:r}});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function kt(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,i),l=w.sizeFromShape(o);w.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${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 ZU={kernelName:vl,backendName:"cpu",kernelFunc:kt};function _N(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;ve([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=w.sizeFromShape(m),y=w.sizeFromShape(f),b=g===y||g===1||y===1;w.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 x=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([d,h]);w.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 v=i?[g,u,d]:[g,d,u],N=o?[y,h,p]:[y,p,h],T=kt({inputs:{x:r},backend:n,attrs:{shape:v}}),S=kt({inputs:{x:s},backend:n,attrs:{shape:N}}),A=i?T.shape[1]:T.shape[2],$=i?T.shape[2]:T.shape[1],R=o?S.shape[1]:S.shape[2],B=Math.max(g,y),V=n.data.get(T.dataId).values,W=n.data.get(S.dataId).values,G=w.computeStrides(T.shape),H=w.computeStrides(S.shape),[X,q,te]=i?[G[0],1,G[1]]:[G[0],G[1],1],[Q,se,ne]=o?[1,H[1],H[0]]:[H[1],1,H[0]],ie=$*R,Z=Le([B,$,R],T.dtype),de=Z.values,oe=n.blockSize;for(let ge=0;ge<B;ge++)for(let fe=0;fe<$;fe+=oe)for(let we=0;we<R;we+=oe)for(let Te=0;Te<A;Te+=oe){let _e=Math.min(fe+oe,$),Re=Math.min(we+oe,R),Fe=Math.min(Te+oe,A);for(let nt=fe;nt<_e;nt++)for(let at=we;at<Re;at++){let ot=0;for(let Xe=Te;Xe<Fe;Xe++){let ft=Math.min(ge,g-1)*X,Be=Math.min(ge,y-1)*ne,wn=V[ft+nt*q+Xe*te],It=W[Xe*Q+at*se+Be];ot+=wn*It}de[ge*ie+(nt*R+at)]+=ot}}return n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(S),n.makeTensorInfo(x,Z.dtype,Z.values)}var eG={kernelName:Rs,backendName:"cpu",kernelFunc:_N};function tG(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=_N({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:c},backend:n}),i&&(h=pp({inputs:{a:d,b:i},backend:n}),f.push(d),d=h),u&&(m=Ov(n,d,u,o,p),f.push(d),d=m);for(let g of f)n.disposeIntermediateTensorInfo(g);return d}var nG={kernelName:Ii,backendName:"cpu",kernelFunc:tG},aG=st(Oo,e=>Math.acos(e)),rG={kernelName:Oo,backendName:"cpu",kernelFunc:aG},sG=st(Lo,e=>Math.acosh(e)),iG={kernelName:Lo,backendName:"cpu",kernelFunc:sG};function oG(e){let{inputs:t,backend:n}=e,a=t;ve(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 lG={kernelName:As,backendName:"cpu",kernelFunc:oG};function uG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ve(r,"all");let o=w.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=xa({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("all",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=w.sizeFromShape(d),m=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,x=f[b];for(let v=0;v<h;++v){let N=f[b+v];x=x&&N}m[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=kt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var cG={kernelName:Sd,backendName:"cpu",kernelFunc:uG};function pG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ve(r,"any");let o=w.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=xa({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("any",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=w.sizeFromShape(d),m=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,x=f[b];for(let v=0;v<h;++v){let N=f[b+v];x=x||N}m[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=kt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var dG={kernelName:Cd,backendName:"cpu",kernelFunc:pG};function hG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ve(r,"argMax");let i=w.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=xa({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[u,p]=_.computeOutAndReduceShapes(l.shape,i),d=w.sizeFromShape(u),h=w.makeZerosTypedArray(d,"int32"),m=w.sizeFromShape(p),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,b=f[y],x=0;for(let v=0;v<m;++v){let N=f[y+v];N>b&&(b=N,x=v)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var mG={kernelName:$s,backendName:"cpu",kernelFunc:hG};function fG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ve(r,"argMin");let i=w.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=xa({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[u,p]=_.computeOutAndReduceShapes(l.shape,i),d=w.sizeFromShape(u),h=w.makeZerosTypedArray(d,"int32"),m=w.sizeFromShape(p),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,b=f[y],x=0;for(let v=0;v<m;++v){let N=f[y+v];N<b&&(b=N,x=v)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var gG={kernelName:nc,backendName:"cpu",kernelFunc:fG},yG=st(zo,e=>Math.asin(e)),bG={kernelName:zo,backendName:"cpu",kernelFunc:yG},xG=st(Bo,e=>Math.asinh(e)),vG={kernelName:Bo,backendName:"cpu",kernelFunc:xG},wG=st(Wo,e=>Math.atan(e)),kG={kernelName:Wo,backendName:"cpu",kernelFunc:wG},IG=Rt((e,t)=>Math.atan2(e,t)),TG=Jt(Uo,IG),NG={kernelName:Uo,backendName:"cpu",kernelFunc:TG},SG=st(Vo,e=>Math.atanh(e)),CG={kernelName:Vo,backendName:"cpu",kernelFunc:SG};function Lv(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],x=r.outShape[3];for(let v=0;v<r.batchSize;++v){let N=v*y,T=v*a[0];for(let S=0;S<r.inChannels;++S)for(let A=0;A<r.outHeight;++A){let $=A*i-d,R=Math.max(0,$),B=Math.min(r.inHeight,u+$),V=N+A*b;for(let W=0;W<r.outWidth;++W){let G=W*o-h,H=Math.max(0,G),X=Math.min(r.inWidth,p+G),q=m,te=0,Q=0;for(let ne=R;ne<B;ne+=l){let ie=T+ne*a[1];for(let Z=H;Z<X;Z+=c){let de=ie+Z*a[2],oe=e[de+S];s==="max"&&oe>q?q=oe:s==="avg"&&(te+=oe,Q++)}if(isNaN(q))break}let se=V+W*x+S;g[se]=s==="avg"?te/Q:q}}}return f}function EN(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 x=b*o-h,v=x;for(;v<0;)v+=c;let N=Math.min(a.inHeight,p+x);for(let T=0;T<a.outWidth;++T){let S=T*l-m,A=S;for(;A<0;)A+=u;let $=Math.min(a.inWidth,d+S),R=Number.NEGATIVE_INFINITY,B=-1;for(let V=v;V<N;V+=c){let W=V-x;for(let G=A;G<$;G+=u){let H=G-S,X=f.get(g,V,G,y);X>R&&(R=X,r?B=s?((g*a.inHeight+V)*a.inWidth+G)*a.inChannels+y:(V*a.inWidth+G)*a.inChannels+y:B=W*d+H)}}i.set(B,g,b,T,y)}}return i}function FN(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,x=Le(r.outShape,n),v=x.values,N=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],T=r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[3]*r.outShape[4],A=r.outShape[4];for(let $=0;$<r.batchSize;++$){let R=$*N,B=$*a[0];for(let V=0;V<r.inChannels;++V)for(let W=0;W<r.outDepth;++W){let G=W*i-f,H=G;for(;H<0;)H+=c;let X=Math.min(r.inDepth,d+G),q=R+W*T;for(let te=0;te<r.outHeight;++te){let Q=te*o-g,se=Q;for(;se<0;)se+=u;let ne=Math.min(r.inHeight,h+Q),ie=q+te*S;for(let Z=0;Z<r.outWidth;++Z){let de=Z*l-y,oe=de;for(;oe<0;)oe+=p;let ge=Math.min(r.inWidth,m+de),fe=ie+Z*A,we=b,Te=0,_e=0;for(let Fe=H;Fe<X;Fe+=c){let nt=B+Fe*a[1];for(let at=se;at<ne;at+=u){let ot=nt+at*a[2];for(let Xe=oe;Xe<ge;Xe+=p){let ft=ot+Xe*a[3],Be=e[ft+V];if(s==="max"&&Be>we?we=Be:s==="avg"&&(Te+=Be,_e++),isNaN(we))break}if(isNaN(we))break}if(isNaN(we))break}let Re=fe+V;v[Re]=s==="avg"?Te/_e:we}}}}return x}function _G(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,x=b;for(;x<0;)x+=i;let v=Math.min(t.inDepth,c+b);for(let N=0;N<t.outHeight;++N){let T=N*r-h,S=T;for(;S<0;)S+=o;let A=Math.min(t.inHeight,u+T);for(let $=0;$<t.outWidth;++$){let R=$*s-m,B=R;for(;B<0;)B+=l;let V=Math.min(t.inWidth,p+R),W=Number.NEGATIVE_INFINITY,G=-1;for(let H=x;H<v;H+=i){let X=H-b;for(let q=S;q<A;q+=o){let te=q-T;for(let Q=B;Q<V;Q+=l){let se=Q-R,ne=e.get(f,H,q,Q,g);ne>=W&&(W=ne,G=X*u*p+te*u+se)}}}n.set(G,f,y,N,$,g)}}}return n}function EG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ve(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;w.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))p=rr({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=Lv(d,r.shape,r.dtype,h,u,"avg");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var FG={kernelName:Ds,backendName:"cpu",kernelFunc:EG};function AG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a;ve(r,"avgPool3d");let u=_.computePool3DInfo(r.shape,s,i,1,o,l,c),p=n.data.get(r.dataId).values,d=FN(p,r.shape,r.dtype,w.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}var $G={kernelName:ac,backendName:"cpu",kernelFunc:AG};function DG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=a;ve([r,s],"avgPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,c),p=u.strideDepth,d=u.strideHeight,h=u.strideWidth,m=u.filterDepth,f=u.filterHeight,g=u.filterWidth,y=u.dilationDepth,b=u.dilationHeight,x=u.dilationWidth,v=u.effectiveFilterDepth,N=u.effectiveFilterHeight,T=u.effectiveFilterWidth,S=v-1-u.padInfo.front,A=T-1-u.padInfo.left,$=N-1-u.padInfo.top,R=Le(s.shape,"float32"),B=1/(m*f*g),V=n.bufferSync(r);for(let W=0;W<u.batchSize;++W)for(let G=0;G<u.inChannels;++G)for(let H=0;H<u.inDepth;++H)for(let X=0;X<u.inHeight;++X)for(let q=0;q<u.inWidth;++q){let te=H-S,Q=X-$,se=q-A,ne=0;for(let ie=0;ie<v;ie+=y){let Z=(te+ie)/p;if(!(Z<0||Z>=u.outDepth||Math.floor(Z)!==Z))for(let de=0;de<N;de+=b){let oe=(Q+de)/d;if(!(oe<0||oe>=u.outHeight||Math.floor(oe)!==oe))for(let ge=0;ge<T;ge+=x){let fe=(se+ge)/h;fe<0||fe>=u.outWidth||Math.floor(fe)!==fe||(ne+=V.get(W,Z,oe,fe,G))}}}R.set(ne*B,W,H,X,q,G)}return n.makeTensorInfo(R.shape,R.dtype,R.values)}var RG={kernelName:Ed,backendName:"cpu",kernelFunc:DG};function MG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;ve([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=_.computePool2DInfo(i.shape,o,l,1,c),p=u.strideHeight,d=u.strideWidth,h=u.filterHeight,m=u.filterWidth,f=u.dilationHeight,g=u.dilationWidth,y=u.effectiveFilterHeight,b=u.effectiveFilterWidth,x=b-1-u.padInfo.left,v=y-1-u.padInfo.top,N=Le(i.shape,"float32"),T=1/(h*m),S=n.data.get(r.dataId).values,A=Le(r.shape,"float32",S);for(let $=0;$<u.batchSize;++$)for(let R=0;R<u.inChannels;++R)for(let B=0;B<u.inHeight;++B)for(let V=0;V<u.inWidth;++V){let W=B-v,G=V-x,H=0;for(let X=0;X<y;X+=f){let q=(W+X)/p;if(!(q<0||q>=u.outHeight||Math.floor(q)!==q))for(let te=0;te<b;te+=g){let Q=(G+te)/d;Q<0||Q>=u.outWidth||Math.floor(Q)!==Q||(H+=A.get($,q,Q,R))}}N.set(H*T,$,B,V,R)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}var PG={kernelName:_d,backendName:"cpu",kernelFunc:MG};function OG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,scale:s,offset:i,mean:o,variance:l}=t;w.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ve([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,x=p.length,v=0,N=0,T=0,S=0;for(let A=0;A<u.length;++A)f[A]=m[v++]+(u[A]-p[N++])*h[T++]/Math.sqrt(d[S++]+c),v>=g&&(v=0),N>=x&&(N=0),T>=y&&(T=0),S>=b&&(S=0);return n.makeTensorInfo(r.shape,r.dtype,f)}var LG={kernelName:js,backendName:"cpu",kernelFunc:OG};function zG(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;ve([r],"batchToSpaceND");let o=s.reduce((y,b)=>y*b),l=_.getReshaped(r.shape,s,o),c=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(r.shape,s,o),p=_.getSliceBeginCoords(i,s.length),d=_.getSliceSize(u,i,s.length),h=kt({inputs:{x:r},backend:n,attrs:{shape:l}}),m=xa({inputs:{x:h},backend:n,attrs:{perm:c}}),f=kt({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 BG={kernelName:rc,backendName:"cpu",kernelFunc:zG};function WG(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=Ev(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var VG={kernelName:Fd,backendName:"cpu",kernelFunc:WG},UG=st(jr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),GG={kernelName:jr,backendName:"cpu",kernelFunc:UG},HG=e=>{let{x:t}=e.inputs,n=e.backend,a=new Float32Array(w.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")},jG={kernelName:sc,backendName:"cpu",kernelFunc:HG};function pu(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 qG={kernelName:Gd,backendName:"cpu",kernelFunc:pu};function du(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=_.computeOutShape(t.map(f=>f.shape),s);if(w.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(f=>w.sizeFromShape(f.shape)>0);if(o.length===1)return rr({inputs:{x:o[0]},backend:n});let l=o.map(f=>f.shape);if(_.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let f=o.map(v=>Ki({inputs:{input:v},backend:n})),g=o.map(v=>pu({inputs:{input:v},backend:n})),y=du({inputs:f,backend:n,attrs:{axis:s}}),b=du({inputs:g,backend:n,attrs:{axis:s}}),x=Un({inputs:{real:y,imag:b},backend:n});return f.forEach(v=>n.disposeIntermediateTensorInfo(v)),g.forEach(v=>n.disposeIntermediateTensorInfo(v)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),x}let c=o.map(f=>{let g=w.sizeFromShape(f.shape.slice(s));return kt({inputs:{x:f},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));i=_.computeOutShape(c.map(f=>f.shape),1);let p=c[0].shape[0]===1,d=Fv(u,i,t[0].dtype,p),h=_.computeOutShape(o.map(f=>f.shape),s),m=n.makeTensorInfo(h,t[0].dtype,d);return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var KG={kernelName:Go,backendName:"cpu",kernelFunc:du};function AN(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;ve([r,s],"conv2d");let p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!1,p),h=d.filterHeight,m=d.filterWidth,f=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,b=d.padInfo.top,x=d.dataFormat==="channelsLast",v=new Ot(d.outShape,r.dtype),N=w.computeStrides(r.shape),T=w.computeStrides(s.shape),S=N[0],A=x?N[1]:N[2],$=x?N[2]:1,R=x?1:N[1],B=v.strides[0],V=x?v.strides[1]:v.strides[2],W=x?v.strides[2]:1,G=x?1:v.strides[1],H=n.data.get(r.dataId).values,X=n.data.get(s.dataId).values,q=v.values;for(let te=0;te<d.batchSize;++te){let Q=te*S,se=te*B;for(let ne=0;ne<d.outHeight;++ne){let ie=se+ne*V,Z=ne*d.strideHeight-b;for(let de=0;de<h;++de){let oe=Z+de*f;if(oe<0||oe>=d.inHeight)continue;let ge=de*T[0],fe=Q+oe*A;for(let we=0;we<d.outWidth;++we){let Te=ie+we*W,_e=we*d.strideWidth-y;for(let Re=0;Re<m;++Re){let Fe=_e+Re*g;if(Fe<0||Fe>=d.inWidth)continue;let nt=ge+Re*T[1],at=fe+Fe*$,ot=nt;for(let Xe=0;Xe<d.inChannels;++Xe){let ft=H[at+Xe*R];for(let Be=0;Be<d.outChannels;++Be)q[Te+Be*G]+=ft*X[ot+Be];ot+=d.outChannels}}}}}}return n.makeTensorInfo(v.shape,v.dtype,q)}var XG={kernelName:Os,backendName:"cpu",kernelFunc:AN};function YG(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;ve([r,s],"conv2dBackpropFilter");let p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),{strideHeight:h,strideWidth:m,filterHeight:f,filterWidth:g}=d,y=d.dataFormat==="channelsLast",b=new Ot(d.filterShape,"float32"),x=d.padInfo.left,v=d.padInfo.top,N=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,S=new Ot(r.shape,r.dtype,N),A=new Ot(s.shape,s.dtype,T);for(let $=0;$<f;++$){let R=Math.max(0,Math.ceil((v-$)/h)),B=Math.min(d.outHeight,(d.inHeight+v-$)/h);for(let V=0;V<g;++V){let W=Math.max(0,Math.ceil((x-V)/m)),G=Math.min(d.outWidth,(d.inWidth+x-V)/m);for(let H=0;H<d.inChannels;++H)for(let X=0;X<d.outChannels;++X){let q=0;for(let te=0;te<d.batchSize;++te)for(let Q=R;Q<B;++Q){let se=$+Q*h-v;for(let ne=W;ne<G;++ne){let ie=V+ne*m-x;y?q+=S.get(te,se,ie,H)*A.get(te,Q,ne,X):q+=S.get(te,H,se,ie)*A.get(te,X,Q,ne)}}b.set(q,$,V,H,X)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var JG={kernelName:$d,backendName:"cpu",kernelFunc:YG};function QG(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:c,dimRoundingMode:u}=a;ve([r,s],"conv2dBackpropInput");let p=w.computeStrides(s.shape),d=w.computeStrides(r.shape),h=_.convertConv2DDataFormat(c),m=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,h),f=new Ot(m.inShape,"float32"),g=f.values,y=n.data.get(r.dataId).values,b=n.data.get(s.dataId).values,[x,v,N]=p,{batchSize:T,filterHeight:S,filterWidth:A,inChannels:$,inHeight:R,inWidth:B,outChannels:V,outHeight:W,outWidth:G,strideHeight:H,strideWidth:X}=m;h=m.dataFormat;let q=S-1-m.padInfo.top,te=A-1-m.padInfo.left,Q=h==="channelsLast",se=f.strides[0],ne=Q?f.strides[1]:f.strides[2],ie=Q?f.strides[2]:1,Z=Q?1:f.strides[1],de=d[0],oe=Q?d[1]:d[2],ge=Q?d[2]:1,fe=Q?1:d[1];for(let we=0;we<T;++we)for(let Te=0;Te<$;++Te)for(let _e=0;_e<R;++_e){let Re=_e-q,Fe=Math.max(0,Math.ceil(Re/H)),nt=Math.min(W,(S+Re)/H);for(let at=0;at<B;++at){let ot=at-te,Xe=Math.max(0,Math.ceil(ot/X)),ft=Math.min(G,(A+ot)/X),Be=0;for(let It=Fe;It<nt;++It){let Kn=It*H-Re;for(let en=Xe;en<ft;++en){let kn=en*X-ot,Xn=de*we+oe*It+ge*en,Rn=x*(S-1-Kn)+v*(A-1-kn)+N*Te;for(let cn=0;cn<V;++cn){let tn=y[Xn+fe*cn],Wa=b[Rn+cn];Be+=tn*Wa}}}let wn=se*we+ne*_e+ie*at+Z*Te;g[wn]=Be}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var ZG={kernelName:Ls,backendName:"cpu",kernelFunc:QG};function eH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;ve([r,s],"conv3d");let c=_.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:u,filterHeight:p,filterWidth:d,dilationDepth:h,dilationHeight:m,dilationWidth:f,padInfo:g}=c,y=g.front,b=g.left,x=g.top,v=new Ot(c.outShape,r.dtype),N=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,S=v.values,A=w.computeStrides(r.shape),$=w.computeStrides(s.shape);for(let R=0;R<c.batchSize;++R){let B=R*A[0],V=R*v.strides[0];for(let W=0;W<c.outDepth;++W){let G=V+W*v.strides[1],H=W*c.strideDepth-y;for(let X=0;X<u;++X){let q=H+X*h;if(q<0||q>=c.inDepth)continue;let te=X*$[0],Q=B+q*A[1];for(let se=0;se<c.outHeight;++se){let ne=G+se*v.strides[2],ie=se*c.strideHeight-x;for(let Z=0;Z<p;++Z){let de=ie+Z*m;if(de<0||de>=c.inHeight)continue;let oe=te+Z*$[1],ge=Q+de*A[2];for(let fe=0;fe<c.outWidth;++fe){let we=ne+fe*c.outChannels,Te=fe*c.strideWidth-b;for(let _e=0;_e<d;++_e){let Re=Te+_e*f;if(Re<0||Re>=c.inWidth)continue;let Fe=oe+_e*$[2],nt=ge+Re*c.inChannels,at=Fe;for(let ot=0;ot<c.inChannels;++ot){let Xe=N[nt+ot];for(let ft=0;ft<c.outChannels;++ft)S[we+ft]+=Xe*T[at+ft];at+=c.outChannels}}}}}}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}var tH={kernelName:ic,backendName:"cpu",kernelFunc:eH};function nH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;ve([r,s],"conv3dBackpropFilterV2");let c=w.computeStrides(r.shape),u=w.computeStrides(s.shape),p=_.computeConv3DInfo(r.shape,l,i,1,o),d=p.strideDepth,h=p.strideHeight,m=p.strideWidth,f=p.filterDepth,g=p.filterHeight,y=p.filterWidth,b=new Ot(p.filterShape,"float32"),x=b.values,[v,N,T,S]=b.strides,A=n.data.get(s.dataId).values,[$,R,B,V]=u,W=n.data.get(r.dataId).values,[G,H,X,q]=c,te=p.padInfo.front,Q=p.padInfo.left,se=p.padInfo.top;for(let ne=0;ne<f;++ne){let ie=Math.max(0,Math.ceil((te-ne)/d)),Z=Math.min(p.outDepth,(p.inDepth+te-ne)/d),de=ne*v;for(let oe=0;oe<g;++oe){let ge=Math.max(0,Math.ceil((se-oe)/h)),fe=Math.min(p.outHeight,(p.inHeight+se-oe)/h),we=oe*N+de;for(let Te=0;Te<y;++Te){let _e=Math.max(0,Math.ceil((Q-Te)/m)),Re=Math.min(p.outWidth,(p.inWidth+Q-Te)/m),Fe=Te*T+we;for(let nt=0;nt<p.inChannels;++nt){let at=nt*S+Fe;for(let ot=0;ot<p.outChannels;++ot){let Xe=0;for(let ft=0;ft<p.batchSize;++ft){let Be=ft*G,wn=ft*$;for(let It=ie;It<Z;++It){let Kn=(ne+It*d-te)*H+Be,en=It*R+wn;for(let kn=ge;kn<fe;++kn){let Xn=(oe+kn*h-se)*X+Kn,Rn=kn*B+en;for(let cn=_e;cn<Re;++cn){let tn=(Te+cn*m-Q)*q+Xn,Wa=cn*V+Rn;Xe+=W[tn+nt]*A[Wa+ot]}}}}x[at+ot]=Xe}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var aH={kernelName:Dd,backendName:"cpu",kernelFunc:nH};function rH(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;ve([r],"conv3dBackpropInputV2");let c=w.computeStrides(r.shape),u=w.computeStrides(s.shape),p=_.computeConv3DInfo(l,s.shape,o,1,i),d=new Ot(p.inShape,"float32"),h=d.values,[m,f,g,y]=d.strides,b=n.data.get(r.dataId).values,[x,v,N,T]=c,S=n.data.get(s.dataId).values,[A,$,R,B]=u,{batchSize:V,filterDepth:W,filterHeight:G,filterWidth:H,inChannels:X,inDepth:q,inHeight:te,inWidth:Q,outChannels:se,outDepth:ne,outHeight:ie,outWidth:Z,strideDepth:de,strideHeight:oe,strideWidth:ge}=p,fe=W-1-p.padInfo.front,we=G-1-p.padInfo.top,Te=H-1-p.padInfo.left;for(let _e=0;_e<V;++_e)for(let Re=0;Re<X;++Re)for(let Fe=0;Fe<q;++Fe){let nt=Fe-fe,at=Math.max(0,Math.ceil(nt/de)),ot=Math.min(ne,(W+nt)/de);for(let Xe=0;Xe<te;++Xe){let ft=Xe-we,Be=Math.max(0,Math.ceil(ft/oe)),wn=Math.min(ie,(G+ft)/oe);for(let It=0;It<Q;++It){let Kn=It-Te,en=Math.max(0,Math.ceil(Kn/ge)),kn=Math.min(Z,(H+Kn)/ge),Xn=0;for(let Rn=at;Rn<ot;++Rn){let cn=Rn*de-nt;for(let tn=Be;tn<wn;++tn){let Wa=tn*oe-ft;for(let oa=en;oa<kn;++oa){let la=oa*ge-Kn,Pr=x*_e+v*Rn+N*tn+T*oa,pr=A*(W-1-cn)+$*(G-1-Wa)+R*(H-1-la)+B*Re;for(let Or=0;Or<se;++Or){let wo=b[Pr+Or],Ia=S[pr+Or];Xn+=wo*Ia}}}}h[m*_e+f*Fe+g*Xe+y*It+Re]=Xn}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}var sH={kernelName:Rd,backendName:"cpu",kernelFunc:rH},iH=st(zs,e=>Math.cos(e)),oH={kernelName:zs,backendName:"cpu",kernelFunc:iH},lH=st(Ho,e=>Math.cosh(e)),uH={kernelName:Ho,backendName:"cpu",kernelFunc:lH};function cH(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,x=n.data.get(i.dataId).values,v=n.data.get(r.dataId).values,N=w.computeStrides(r.shape),T=w.computeStrides(y.shape);for(let S=0;S<m;S++){let A=S*4,$=b[A],R=b[A+1],B=b[A+2],V=b[A+3],W=x[S];if(W>=u)continue;let G=f>1?(B-$)*(p-1)/(f-1):0,H=g>1?(V-R)*(d-1)/(g-1):0;for(let X=0;X<f;X++){let q=f>1?$*(p-1)+X*G:.5*($+B)*(p-1);if(q<0||q>p-1){for(let te=0;te<g;te++)for(let Q=0;Q<h;Q++){let se=Q+te*T[2]+X*T[1]+S*T[0];y.values[se]=c}continue}if(l==="bilinear"){let te=Math.floor(q),Q=Math.ceil(q),se=q-te;for(let ne=0;ne<g;ne++){let ie=g>1?R*(d-1)+ne*H:.5*(R+V)*(d-1);if(ie<0||ie>d-1){for(let ge=0;ge<h;ge++){let fe=ge+ne*T[2]+X*T[1]+S*T[0];y.values[fe]=c}continue}let Z=Math.floor(ie),de=Math.ceil(ie),oe=ie-Z;for(let ge=0;ge<h;ge++){let fe=ge+Z*N[2]+te*N[1]+W*N[0],we=v[fe];fe=ge+de*N[2]+te*N[1]+W*N[0];let Te=v[fe];fe=ge+Z*N[2]+Q*N[1]+W*N[0];let _e=v[fe];fe=ge+de*N[2]+Q*N[1]+W*N[0];let Re=v[fe],Fe=we+(Te-we)*oe,nt=_e+(Re-_e)*oe;fe=ge+ne*T[2]+X*T[1]+S*T[0],y.values[fe]=Fe+(nt-Fe)*se}}}else for(let te=0;te<g;++te){let Q=g>1?R*(d-1)+te*H:.5*(R+V)*(d-1);if(Q<0||Q>d-1){for(let ie=0;ie<h;ie++){let Z=ie+te*T[2]+X*T[1]+S*T[0];y.values[Z]=c}continue}let se=Math.round(Q),ne=Math.round(q);for(let ie=0;ie<h;ie++){let Z=ie+se*N[2]+ne*N[1]+W*N[0],de=ie+te*T[2]+X*T[1]+S*T[0];y.values[de]=v[Z]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var pH={kernelName:jo,backendName:"cpu",kernelFunc:cH};function dH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;ve(r,"cumsum");let l=_.getAxesPermutation([s],r.shape.length),c=r;l!=null&&(c=xa({inputs:{x:r},backend:n,attrs:{perm:l}}));let u=_.getInnerMostAxes(1,r.shape.length)[0];if(u!==c.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${c.shape.length-1} but got axis=${u}`);let p=pa(c.dtype,"int32"),d=w.makeZerosTypedArray(w.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 x=f(y,b);if(b===0)d[x]=i?0:h[x];else{let v=f(y,b-1);d[x]=i?h[v]+d[v]:h[x]+d[v]}}let g=n.makeTensorInfo(c.shape,p,d);if(l!=null){let y=_.getUndoAxesPermutation(l),b=xa({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(c),b}return g}var hH={kernelName:Bs,backendName:"cpu",kernelFunc:dH};function mH(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=Ev(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=ZT(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 fH={kernelName:Md,backendName:"cpu",kernelFunc:mH};function gH(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;w.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`),w.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 x=Math.floor(b/s),v=b%s;for(let N=0;N<d;++N){let T=Math.floor(N/s),S=N%s,A=(v*s+S)*h;for(let $=0;$<h;++$){let R=$+A+u*(T+c*(x+l*y));f[g++]=m[R]}}}return n.makeTensorInfo([o,p,d,h],r.dtype,f)}var yH={kernelName:qo,backendName:"cpu",kernelFunc:gH};function $N(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=a;ve([r,s],"depthwiseConv2DNative");let u=w.computeStrides(r.shape),p=w.computeStrides(s.shape),d=l;d==null&&(d=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=_.computeConv2DInfo(r.shape,s.shape,i,d,o,c,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:y,padInfo:b}=h,x=b.left,v=b.top,N=h.outChannels/h.inChannels,T=new Ot(h.outShape,r.dtype),S=n.data.get(r.dataId).values,A=n.data.get(s.dataId).values,$=T.values;for(let R=0;R<h.batchSize;++R){let B=R*u[0],V=R*T.strides[0];for(let W=0;W<h.outHeight;++W){let G=V+W*T.strides[1],H=W*h.strideHeight-x;for(let X=0;X<m;++X){let q=H+X*g;if(q<0||q>=h.inHeight)continue;let te=X*p[0],Q=B+q*u[1];for(let se=0;se<h.outWidth;++se){let ne=G+se*T.strides[2],ie=se*h.strideWidth-v;for(let Z=0;Z<f;++Z){let de=ie+Z*y;if(de<0||de>=h.inWidth)continue;let oe=te+Z*p[1],ge=Q+de*h.inChannels,fe=ne,we=oe;for(let Te=0;Te<h.inChannels;++Te){let _e=S[ge+Te];for(let Re=0;Re<N;++Re)$[fe+Re]+=_e*A[we+Re];fe+=N,we+=N}}}}}}return n.makeTensorInfo(T.shape,T.dtype,T.values)}var bH={kernelName:Ws,backendName:"cpu",kernelFunc:$N};function xH(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;ve([r,s],"depthwiseConv2dNativeBackpropFilter");let p=_.computeConv2DInfo(r.shape,u,i,o,l,c,!0),{strideHeight:d,strideWidth:h,filterHeight:m,filterWidth:f}=p,g=new Ot(p.filterShape,"float32"),y=p.padInfo.left,b=p.padInfo.top,x=p.outChannels/p.inChannels,v=n.data.get(r.dataId).values,N=new Ot(r.shape,r.dtype,v),T=n.data.get(s.dataId).values,S=new Ot(s.shape,s.dtype,T);for(let A=0;A<m;++A){let $=Math.max(0,Math.ceil((b-A)/d)),R=Math.min(p.outHeight,(p.inHeight+b-A)/d);for(let B=0;B<f;++B){let V=Math.max(0,Math.ceil((y-B)/h)),W=Math.min(p.outWidth,(p.inWidth+y-B)/h);for(let G=0;G<p.outChannels;++G){let H=Math.trunc(G/x),X=G%x,q=0;for(let te=0;te<p.batchSize;++te)for(let Q=$;Q<R;++Q){let se=A+Q*d-b;for(let ne=V;ne<W;++ne){let ie=B+ne*h-y;q+=N.get(te,se,ie,H)*S.get(te,Q,ne,G)}}g.set(q,A,B,H,X)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var vH={kernelName:Pd,backendName:"cpu",kernelFunc:xH};function wH(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;ve([r,s],"depthwiseConv2DNativeBackpropInput");let p=w.computeStrides(r.shape),d=w.computeStrides(s.shape),h=_.computeConv2DInfo(u,s.shape,i,o,l,c,!0),m=new Ot(h.inShape,"float32"),f=m.values,[g,y,b]=m.strides,x=n.data.get(r.dataId).values,[v,N,T]=p,S=n.data.get(s.dataId).values,[A,$,R]=d,{batchSize:B,filterHeight:V,filterWidth:W,inChannels:G,inHeight:H,inWidth:X,outChannels:q,outHeight:te,outWidth:Q,strideHeight:se,strideWidth:ne}=h,ie=V-1-h.padInfo.top,Z=W-1-h.padInfo.left,de=q/G;for(let oe=0;oe<B;++oe)for(let ge=0;ge<G;++ge)for(let fe=0;fe<H;++fe){let we=fe-ie,Te=Math.max(0,Math.ceil(we/se)),_e=Math.min(te,(V+we)/se);for(let Re=0;Re<X;++Re){let Fe=Re-Z,nt=Math.max(0,Math.ceil(Fe/ne)),at=Math.min(Q,(W+Fe)/ne),ot=0;for(let Xe=Te;Xe<_e;++Xe){let ft=Xe*se-we;for(let Be=nt;Be<at;++Be){let wn=Be*ne-Fe,It=v*oe+N*Xe+T*Be,Kn=A*(V-1-ft)+$*(W-1-wn)+R*ge;for(let en=0;en<de;++en){let kn=ge*de+en,Xn=x[It+kn],Rn=S[Kn+en];ot+=Xn*Rn}}}f[g*oe+y*fe+b*Re+ge]=ot}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var kH={kernelName:Od,backendName:"cpu",kernelFunc:wH};function IH(e){let{inputs:t,backend:n}=e,{x:a}=t,r=w.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 TH={kernelName:Ld,backendName:"cpu",kernelFunc:IH},NH={kernelName:oc,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:x,strideHeight:v,strideWidth:N,filterHeight:T,filterWidth:S,dilationHeight:A,dilationWidth:$,outShape:R}=_.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),B=w.sizeFromShape(R),V=R.length,W=w.getArrayFromDType(a.dtype,B);for(let G=0;G<h;++G)for(let H=0;H<y;++H){let X=H*v-x.top;for(let q=0;q<b;++q){let te=q*N-x.left;for(let Q=0;Q<g;++Q){let se=Number.MIN_SAFE_INTEGER;for(let ie=0;ie<T;++ie){let Z=X+ie*A;if(Z>=0&&Z<m)for(let de=0;de<S;++de){let oe=te+de*$;if(oe>=0&&oe<f){let ge=w.locToIndex([G,Z,oe,Q],u,w.computeStrides(a.shape)),fe=w.locToIndex([ie,de,Q],d,w.computeStrides(r.shape)),we=c[ge]+p[fe];we>se&&(se=we)}}}let ne=w.locToIndex([G,H,q,Q],V,w.computeStrides(R));W[ne]=se}}}return{dataId:l.write(w.toTypedArray(W,a.dtype),R,a.dtype),shape:R,dtype:a.dtype}}},SH={kernelName:Bd,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=w.toNestedArray(a.shape,c.data.get(a.dataId).values),p=w.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:v,filterHeight:N,filterWidth:T,dilationHeight:S,dilationWidth:A,outShape:$}=_.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===$.length,()=>`Error in ${Bd}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let R=w.toNestedArray($,c.data.get(s.dataId).values),B=w.makeZerosNestedTypedArray(r.shape,r.dtype);for(let V=0;V<d;++V)for(let W=0;W<g;++W){let G=W*x-b.top;for(let H=0;H<y;++H){let X=H*v-b.left;for(let q=0;q<f;++q){let te=Number.MIN_SAFE_INTEGER,Q=0,se=0;for(let ne=0;ne<N;++ne){let ie=G+ne*S;if(ie>=0&&ie<h)for(let Z=0;Z<T;++Z){let de=X+Z*A;if(de>=0&&de<m){let oe=u[V][ie][de][q]+p[ne][Z][q];oe>te&&(te=oe,Q=ne,se=Z)}}}B[Q][se][q]+=R[V][W][H][q]}}}return{dataId:c.write(w.toTypedArray(B,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},CH={kernelName:zd,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=w.toNestedArray(a.shape,c.data.get(a.dataId).values),p=w.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:v,filterHeight:N,filterWidth:T,dilationHeight:S,dilationWidth:A,outShape:$}=_.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===$.length,()=>`Error in ${zd}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let R=w.toNestedArray($,c.data.get(s.dataId).values),B=w.makeZerosNestedTypedArray(a.shape,a.dtype);for(let V=0;V<d;++V)for(let W=0;W<g;++W){let G=W*x-b.top;for(let H=0;H<y;++H){let X=H*v-b.left;for(let q=0;q<f;++q){let te=Number.MIN_SAFE_INTEGER,Q=G<0?0:G,se=X<0?0:X;for(let ne=0;ne<N;++ne){let ie=G+ne*S;if(ie>=0&&ie<h)for(let Z=0;Z<T;++Z){let de=X+Z*A;if(de>=0&&de<m){let oe=u[V][ie][de][q]+p[ne][Z][q];oe>te&&(te=oe,Q=ie,se=de)}}}B[V][Q][se][q]+=R[V][W][H][q]}}}return{dataId:c.write(w.toTypedArray(B,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function _H(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;ve([a,r],"eluGrad");let s=new Float32Array(w.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 EH={kernelName:Wd,backendName:"cpu",kernelFunc:_H},FH=Rt((e,t)=>e===t?1:0),DN=Jt(Yo,FH,null,"bool"),AH={kernelName:Yo,backendName:"cpu",kernelFunc:DN},$H=_.ERF_P,DH=_.ERF_A1,RH=_.ERF_A2,MH=_.ERF_A3,PH=_.ERF_A4,OH=_.ERF_A5,LH=st(Xo,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+$H*n);return t*(1-((((OH*a+PH)*a+MH)*a+RH)*a+DH)*a*Math.exp(-n*n))}),zH={kernelName:Xo,backendName:"cpu",kernelFunc:LH};function Wm(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&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),kt({inputs:{x:r},backend:n,attrs:{shape:o}})}var BH={kernelName:Jo,backendName:"cpu",kernelFunc:Wm},WH=Rt((e,t)=>e/t),zv=Jt(Vs,WH),Bv={kernelName:Vs,backendName:"cpu",kernelFunc:zv};function RN(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=w.sizeFromShape(c),p=w.getTypedArrayFromDType("float32",u),d=w.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]}}),x=Un({inputs:{real:y,imag:b},backend:n}),{real:v,imag:N}=VH(x,t,n),T=_.mergeRealAndImagArrays(v,N);for(let S=0;S<s;S++){let A=_.getComplexWithIndex(T,S);p[g*s+S]=A.real,d[g*s+S]=A.imag}n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(x)}let h=n.makeTensorInfo(c,"float32",p),m=n.makeTensorInfo(c,"float32",d),f=Un({inputs:{real:h,imag:m},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}function VH(e,t,n){let a=w.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(UH(a)){let o=Wv(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",w.createScalarValue(a,"float32")),d=rr({inputs:{x:p},backend:n}),h=Bv.kernelFunc({inputs:{a:c,b:p},backend:n}),m=Bv.kernelFunc({inputs:{a:u,b:d},backend:n}),f=n.data.get(h.dataId).values,g=n.data.get(m.dataId).values;return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=_.mergeRealAndImagArrays(s,i),l=GH(o,a,t);return _.splitRealAndImagArrays(l)}}function UH(e){return(e&e-1)==0}function Wv(e,t,n,a,r){if(n===1)return{real:e,imag:t};let s=_.mergeRealAndImagArrays(e,t),i=n/2,o=_.complexWithEvenIndex(s),l=o.real,c=o.imag,u=[l.length],p=r.makeTensorInfo(u,"float32",l),d=r.makeTensorInfo(u,"float32",c),h=Un({inputs:{real:p,imag:d},backend:r}),m=_.complexWithOddIndex(s),f=m.real,g=m.imag,y=[f.length],b=r.makeTensorInfo(y,"float32",f),x=r.makeTensorInfo(y,"float32",g),v=Un({inputs:{real:b,imag:x},backend:r}),N=Wv(l,c,i,a,r),T=N.real,S=N.imag,A=[T.length],$=r.makeTensorInfo(A,"float32",T),R=r.makeTensorInfo(A,"float32",S),B=Un({inputs:{real:$,imag:R},backend:r}),V=Wv(f,g,i,a,r),W=V.real,G=V.imag,H=[W.length],X=r.makeTensorInfo(H,"float32",W),q=r.makeTensorInfo(H,"float32",G),te=Un({inputs:{real:X,imag:q},backend:r}),Q=_.exponents(n,a),se=[Q.real.length],ne=r.makeTensorInfo(se,"float32",Q.real),ie=r.makeTensorInfo(se,"float32",Q.imag),Z=Un({inputs:{real:ne,imag:ie},backend:r}),de=Mv({inputs:{a:Z,b:te},backend:r}),oe=pp({inputs:{a:B,b:de},backend:r}),ge=Pv({inputs:{a:B,b:de},backend:r}),fe=Ki({inputs:{input:oe},backend:r}),we=Ki({inputs:{input:ge},backend:r}),Te=pu({inputs:{input:oe},backend:r}),_e=pu({inputs:{input:ge},backend:r}),Re=du({inputs:[fe,we],backend:r,attrs:{axis:0}}),Fe=du({inputs:[Te,_e],backend:r,attrs:{axis:0}}),nt=r.data.get(Re.dataId).values,at=r.data.get(Fe.dataId).values;return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(R),r.disposeIntermediateTensorInfo(B),r.disposeIntermediateTensorInfo(X),r.disposeIntermediateTensorInfo(q),r.disposeIntermediateTensorInfo(te),r.disposeIntermediateTensorInfo(ne),r.disposeIntermediateTensorInfo(ie),r.disposeIntermediateTensorInfo(Z),r.disposeIntermediateTensorInfo(de),r.disposeIntermediateTensorInfo(oe),r.disposeIntermediateTensorInfo(ge),r.disposeIntermediateTensorInfo(fe),r.disposeIntermediateTensorInfo(Te),r.disposeIntermediateTensorInfo(we),r.disposeIntermediateTensorInfo(_e),r.disposeIntermediateTensorInfo(Re),r.disposeIntermediateTensorInfo(Fe),{real:nt,imag:at}}function GH(e,t,n){let a=new Float32Array(t*2);for(let r=0;r<t;r++){let s=0,i=0;for(let o=0;o<t;o++){let l=_.exponent(r*o,t,n),c=_.getComplexWithIndex(e,o);s+=c.real*l.real-c.imag*l.imag,i+=c.real*l.imag+c.imag*l.real}n&&(s/=t,i/=t),_.assignToTypedArray(a,s,i,r)}return a}function HH(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=kt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=RN(o,!1,n),c=kt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var jH={kernelName:Vd,backendName:"cpu",kernelFunc:HH};function Vv(e){let{backend:t,attrs:n}=e,{shape:a,value:r,dtype:s}=n,i=s||w.inferDtype(r),o=w.getArrayFromDType(i,w.sizeFromShape(a));return qH(o,r,i),t.makeTensorInfo(a,i,o)}var KH={kernelName:lc,backendName:"cpu",kernelFunc:Vv};function qH(e,t,n){e.fill(t)}var XH={kernelName:Zo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,r=n,s=w.getTypedArrayFromDType(a.dtype,w.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],x=Math.round(l-b),v=d+m+g+y,N=u[v];if(x>=0&&x<l){let T=x*c,S=d+m+T+y;N=u[S]}s[v]=N}}}}return{dataId:r.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},YH=Rt((e,t)=>Math.floor(e/t)),JH=Jt(Hs,YH,null,"int32"),QH={kernelName:Hs,backendName:"cpu",kernelFunc:JH};function ZH(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=AN({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=pp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Ov(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var ej={kernelName:Ti,backendName:"cpu",kernelFunc:ZH};function tj(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=$N({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d}});if(i){let g=f;f=pp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Ov(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var nj={kernelName:Ni,backendName:"cpu",kernelFunc:tj};function aj(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=w.sizeFromShape(a.shape),i=r.shape,o=i[i.length-1],[l,c,u,p]=_.prepareAndValidate(a,r);if(c===0)return n.makeTensorInfo(l,a.dtype,[]);let d=Le([c,u],a.dtype),h=n.data.get(r.dataId).values,m=n.data.get(a.dataId).values;for(let f=0;f<c;f++){let g=[],y=0;for(let b=0;b<o;b++){let x=h[f*o+b];y+=x*p[b],g.push(x)}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 rj={kernelName:tl,backendName:"cpu",kernelFunc:aj};function sj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;ve([r,s],"gatherV2");let l=o;o==null&&(l=0);let c=w.sizeFromShape(s.shape),u=w.parseAxisParam(i,r.shape)[0],p=_.segment_util.collectGatherOpShapeInfo(r,s,u,l),d=kt({inputs:{x:r},backend:n,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),h=kt({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=rN(g,f,m);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.makeTensorInfo(p.outputShape,y.dtype,y.values)}var ij={kernelName:el,backendName:"cpu",kernelFunc:sj},oj=Rt((e,t)=>e>=t?1:0),lj=Jt(qs,oj,null,"bool"),uj={kernelName:qs,backendName:"cpu",kernelFunc:lj};function cj(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=kt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=RN(o,!0,n),c=kt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var pj={kernelName:Ud,backendName:"cpu",kernelFunc:cj},dj=st(al,e=>Number.isFinite(e)?1:0,"bool"),hj={kernelName:al,backendName:"cpu",kernelFunc:dj},mj=st(rl,e=>Math.abs(e)===Infinity?1:0,"bool"),fj={kernelName:rl,backendName:"cpu",kernelFunc:mj},gj=st(sl,e=>Number.isNaN(e)?1:0,"bool"),yj={kernelName:sl,backendName:"cpu",kernelFunc:gj},bj=Rt((e,t)=>e<=t?1:0),xj=Jt(ol,bj,null,"bool"),vj={kernelName:ol,backendName:"cpu",kernelFunc:xj};function wj(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=oN(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var kj={kernelName:Hd,backendName:"cpu",kernelFunc:wj},Ij=st(ll,e=>Math.log1p(e)),Tj={kernelName:ll,backendName:"cpu",kernelFunc:Ij},Nj=Rt((e,t)=>e&&t),Sj=Jt(ul,Nj,null,"bool"),Cj={kernelName:ul,backendName:"cpu",kernelFunc:Sj},_j=st(uc,e=>e?0:1,"bool"),Ej={kernelName:uc,backendName:"cpu",kernelFunc:_j},Fj=Rt((e,t)=>e||t),Aj=Jt(cc,Fj,null,"bool"),$j={kernelName:cc,backendName:"cpu",kernelFunc:Aj};function Dj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;ve(r,"LRN");let c=r.shape[3],u=c-1,p=n.data.get(r.dataId).values,d=w.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),x=0;for(;y<=b;y++){let v=p[y];x+=v*v}return x}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 Rj={kernelName:pc,backendName:"cpu",kernelFunc:Dj};function Mj(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;ve(i,"LRNGrad");let p=w.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 x=b%d,v=b-x+Math.max(0,x-o),N=b-x+Math.min(d,x+o+1),T=0;for(let S=v;S<N;S++)T+=Math.pow(m[S],2);T=c*T+l;for(let S=v;S<N;S++){let A=-2*c*u*m[S]*f[b]/T;b===S&&(A+=Math.pow(T,-u)),A*=h[b],g[S]+=A}}return n.makeTensorInfo(i.shape,r.dtype,g)}var Pj={kernelName:jd,backendName:"cpu",kernelFunc:Mj};function MN(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=w.parseAxisParam(s,l),p=u,d=_.getAxesPermutation(p,c),h=o.data.get(r.dataId).values;if(d!=null){let v=new Array(c);for(let N=0;N<v.length;N++)v[N]=l[d[N]];h=$v(h,l,r.dtype,d,v),p=_.getInnerMostAxes(p.length,c),l=v}ve(r,"max"),_.assertAxesAreInnerMostDims("max",p,c);let[m,f]=_.computeOutAndReduceShapes(l,p),g=w.sizeFromShape(f),y=uN(h,g,m,r.dtype),b=o.write(y,m,r.dtype),x=m;return i&&(x=_.expandShapeToKeepDim(m,u)),{dataId:b,shape:x,dtype:r.dtype}}var Oj={kernelName:Js,backendName:"cpu",kernelFunc:MN};function Lj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ve(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;w.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))p=rr({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=Lv(d,r.shape,r.dtype,h,u,"max");p=n.makeTensorInfo(u.outShape,r.dtype,m.values)}return p}var zj={kernelName:Zs,backendName:"cpu",kernelFunc:Lj};function Bj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a;ve(r,"maxPool3d");let u=_.computePool3DInfo(r.shape,s,i,1,o,l,c),p=n.data.get(r.dataId).values,d=FN(p,r.shape,r.dtype,w.computeStrides(r.shape),u,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}var Wj={kernelName:dc,backendName:"cpu",kernelFunc:Bj};function Vj(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=a;ve([r,s],"maxPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,c),p=n.bufferSync(s),d=_G(p,u),h=u.strideDepth,m=u.strideHeight,f=u.strideWidth,g=u.dilationDepth,y=u.dilationHeight,b=u.dilationWidth,x=u.effectiveFilterDepth,v=u.effectiveFilterHeight,N=u.effectiveFilterWidth,T=x-1-u.padInfo.front,S=N-1-u.padInfo.left,A=v-1-u.padInfo.top,$=Le(s.shape,"float32"),R=n.bufferSync(r);for(let B=0;B<u.batchSize;++B)for(let V=0;V<u.inChannels;++V)for(let W=0;W<u.inDepth;++W)for(let G=0;G<u.inHeight;++G)for(let H=0;H<u.inWidth;++H){let X=W-T,q=G-A,te=H-S,Q=0;for(let se=0;se<x;se+=g){let ne=(X+se)/h;if(!(ne<0||ne>=u.outDepth||Math.floor(ne)!==ne))for(let ie=0;ie<v;ie+=y){let Z=(q+ie)/m;if(!(Z<0||Z>=u.outHeight||Math.floor(Z)!==Z))for(let de=0;de<N;de+=b){let oe=(te+de)/f;if(oe<0||oe>=u.outWidth||Math.floor(oe)!==oe)continue;let ge=x*v*N-1-d.get(B,ne,Z,oe,V),fe=se*v*N+ie*N+de,we=ge===fe?1:0;we!==0&&(Q+=R.get(B,ne,Z,oe,V)*we)}}}$.set(Q,B,W,G,H,V)}return n.makeTensorInfo($.shape,$.dtype,$.values)}var Uj={kernelName:Kd,backendName:"cpu",kernelFunc:Vj};function Gj(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;ve([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=_.computePool2DInfo(o.shape,l,c,1,u,p),h=n.data.get(o.dataId).values,m=Le(d.outShape,o.dtype,EN(h,o.shape,o.dtype,d).values),f=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,b=d.dilationWidth,x=d.effectiveFilterHeight,v=d.effectiveFilterWidth,N=v-1-d.padInfo.left,T=x-1-d.padInfo.top,S=Le(o.shape,"float32"),A=n.data.get(r.dataId).values,$=Le(r.shape,"float32",A);for(let R=0;R<d.batchSize;++R)for(let B=0;B<d.inChannels;++B)for(let V=0;V<d.inHeight;++V)for(let W=0;W<d.inWidth;++W){let G=V-T,H=W-N,X=0;for(let q=0;q<x;q+=y){let te=(G+q)/f;if(!(te<0||te>=d.outHeight||Math.floor(te)!==te))for(let Q=0;Q<v;Q+=b){let se=(H+Q)/g;if(se<0||se>=d.outWidth||Math.floor(se)!==se)continue;let ne=x*v-1-m.get(R,te,se,B),ie=q*v+Q,Z=ne===ie?1:0;Z!==0&&(X+=$.get(R,te,se,B)*Z)}}S.set(X,R,V,W,B)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}var Hj={kernelName:qd,backendName:"cpu",kernelFunc:Gj};function jj(e,t,n,a,r){let s=w.computeStrides(t),i=Lv(e,t,n,s,r,"max"),o=EN(e,t,n,r,!0,a);return[i.values,o.values]}var qj={kernelName:Xd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;ve(a,"MaxPoolWithArgmax");let c=l.data.get(a.dataId).values,u=_.computePool2DInfo(a.shape,r,s,[1,1],i),[p,d]=jj(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 Vm(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ve(r,"sum");let o;r.dtype==="bool"?o=fs({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=rr({inputs:{x:r},backend:n});let l=o.shape.length,c=w.parseAxisParam(s,o.shape),u=_.getAxesPermutation(c,l),p=c,d=o;u!=null&&(d=xa({inputs:{x:o},backend:n,attrs:{perm:u}}),p=_.getInnerMostAxes(p.length,l)),_.assertAxesAreInnerMostDims("sum",p,d.shape.length);let[h,m]=_.computeOutAndReduceShapes(d.shape,p),f=_.upcastType(d.dtype,"int32"),g=Bm(n,h,f),y=w.sizeFromShape(m),b=n.data.get(g.dataId).values,x=n.data.get(d.dataId).values;for(let v=0;v<b.length;++v){let N=v*y,T=0;for(let S=0;S<y;++S)T+=x[N+S];b[v]=T}if(i){let v=_.expandShapeToKeepDim(g.shape,c),N=g;g=kt({inputs:{x:g},backend:n,attrs:{shape:v}}),n.disposeIntermediateTensorInfo(N)}return n.disposeIntermediateTensorInfo(o),u!=null&&n.disposeIntermediateTensorInfo(d),g}var Kj={kernelName:yi,backendName:"cpu",kernelFunc:Vm};function Xj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=w.parseAxisParam(s,r.shape),l=_.computeOutAndReduceShapes(r.shape,o)[1],c=w.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=zv({inputs:{a:d,b:p},backend:n});u.push(h);let m=Vm({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var Yj={kernelName:ei,backendName:"cpu",kernelFunc:Xj};function Jj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ve(r,"min");let o=w.parseAxisParam(s,r.shape),l=o,c=_.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=xa({inputs:{x:r},backend:n,attrs:{perm:c}}),l=_.getInnerMostAxes(l.length,r.shape.length)),_.assertAxesAreInnerMostDims("min",l,u.shape.length);let[p,d]=_.computeOutAndReduceShapes(u.shape,l),h=w.sizeFromShape(d),m=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),f=n.data.get(u.dataId).values;for(let y=0;y<m.length;++y){let b=y*h,x=f[b];for(let v=0;v<h;++v){let N=f[b+v];N<x&&(x=N)}m[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(p,u.dtype,m);if(i){let y=_.expandShapeToKeepDim(p,o),b=kt({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),b}return g}var Qj={kernelName:ti,backendName:"cpu",kernelFunc:Jj};function Zj(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,mode:i}=a;ve(r,"mirrorPad");let o=s.map((b,x)=>b[0]+r.shape[x]+b[1]),l=s.map(b=>b[0]),c=s.map((b,x)=>b[0]+r.shape[x]),u=i==="reflect"?0:1,p=n.data.get(r.dataId).values,d=r.shape.length,h=w.computeStrides(r.shape),m=w.sizeFromShape(o),f=o.length,g=w.computeStrides(o),y=w.getTypedArrayFromDType(r.dtype,m);for(let b=0;b<m;b++){let x=w.indexToLoc(b,f,g);for(let N=0;N<f;N++)x[N]<l[N]?x[N]=l[N]*2-x[N]-u:x[N]>=c[N]&&(x[N]=(c[N]-1)*2-x[N]+u);x=x.map((N,T)=>N-l[T]);let v=w.locToIndex(x,d,h);y[b]=p[v]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}var e6={kernelName:hc,backendName:"cpu",kernelFunc:Zj},t6=Rt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),n6=Jt(cl,t6),a6={kernelName:cl,backendName:"cpu",kernelFunc:n6},r6=Do(wd());function PN(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=w.parseAxisParam([o],r.shape),c=MN({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=_.expandShapeToKeepDim(c.shape,l),p=kt({inputs:{x:c},backend:n,attrs:{shape:u}}),d=Pv({inputs:{a:r,b:p},backend:n}),h=kN({inputs:{x:d},backend:n}),m=Vm({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),f=kt({inputs:{x:m},backend:n,attrs:{shape:u}}),g=zv({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 s6={kernelName:bi,backendName:"cpu",kernelFunc:PN};function i6(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;ve(r,"multinomial");let l=o?r:PN({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=w.makeZerosTypedArray(w.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 x=1;x<g.length;++x)g[x]=g[x-1]+p[f+x];let y=r6.alea(i.toString()),b=m*s;for(let x=0;x<s;++x){let v=y();h[b+x]=g.length;for(let N=0;N<g.length;N++)if(v<g[N]){h[b+x]=N;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(d,"int32",h)}var o6={kernelName:Yd,backendName:"cpu",kernelFunc:i6},l6=Qa.nonMaxSuppressionV3Impl;function u6(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;ve(r,"NonMaxSuppression");let c=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,{selectedIndices:p}=l6(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var c6={kernelName:hl,backendName:"cpu",kernelFunc:u6},p6=Qa.nonMaxSuppressionV4Impl;function d6(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:c}=a;ve(r,"NonMaxSuppressionPadded");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,{selectedIndices:d,validOutputs:h}=p6(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var h6={kernelName:ml,backendName:"cpu",kernelFunc:d6},m6=Qa.nonMaxSuppressionV5Impl;function f6(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:c}=a;ve(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}=m6(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var g6={kernelName:fl,backendName:"cpu",kernelFunc:f6};function y6(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a;ve(r,"oneHot");let l=w.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 b6={kernelName:ri,backendName:"cpu",kernelFunc:y6};function Um(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=Um({inputs:{x:r},backend:n}),i=pu({inputs:{input:a},backend:n}),o=Um({inputs:{x:i},backend:n}),l=Un({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Vv({backend:n,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var x6={kernelName:Dl,backendName:"cpu",kernelFunc:Um};function ON(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=ON({inputs:{x:r},backend:n}),i=pu({inputs:{input:a},backend:n}),o=Um({inputs:{x:i},backend:n}),l=Un({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Vv({backend:n,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var v6={kernelName:gl,backendName:"cpu",kernelFunc:ON};function LN(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return Wm({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=Wm({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=du({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var w6={kernelName:yl,backendName:"cpu",kernelFunc:LN};function k6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;ve(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=w.sizeFromShape(r.shape),p=r.shape.length,d=w.computeStrides(r.shape),h=w.sizeFromShape(o),m=o.length,f=w.computeStrides(o),g=w.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let y=0;y<u;y++){let b=w.indexToLoc(y,p,d).map((v,N)=>v+l[N]),x=w.locToIndex(b,m,f);g[x]=c[y]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var zN={kernelName:si,backendName:"cpu",kernelFunc:k6},I6=Rt((e,t)=>Math.pow(e,t)),T6=Jt(ii,I6),N6={kernelName:ii,backendName:"cpu",kernelFunc:T6};function S6(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=Dv(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var C6={kernelName:mc,backendName:"cpu",kernelFunc:S6},_6=st(xl,e=>1/e),E6={kernelName:xl,backendName:"cpu",kernelFunc:_6};function F6(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ve(r,"resizeBilinear");let l=w.computeStrides(r.shape),[c,u]=o,[p,d,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(w.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],x=0,v=y[0]/b[0],N=y[1]/b[1];for(let T=0;T<p;T++)for(let S=0;S<c;S++){let A;i?A=v*(S+.5)-.5:A=v*S;let $=Math.max(0,Math.floor(A)),R=A-$,B=Math.min(d-1,Math.ceil(A)),V=T*l[0]+$*l[1],W=T*l[0]+B*l[1];for(let G=0;G<u;G++){let H;i?H=N*(G+.5)-.5:H=N*G;let X=Math.max(0,Math.floor(H)),q=H-X,te=Math.min(h-1,Math.ceil(H)),Q=V+X*l[2],se=W+X*l[2],ne=V+te*l[2],ie=W+te*l[2];for(let Z=0;Z<m;Z++){let de=f[Q+Z],oe=f[se+Z],ge=f[ne+Z],fe=f[ie+Z],we=de+(ge-de)*q,Te=oe+(fe-oe)*q,_e=we+(Te-we)*R;g[x++]=_e}}}return n.makeTensorInfo([p,c,u,m],"float32",g)}var A6={kernelName:ui,backendName:"cpu",kernelFunc:F6};function $6(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ve([s,r],"resizeBilinearGrad");let o=w.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],x=n.data.get(s.dataId).values,v=0;for(let N=0;N<l;N++){let T=N*o[0];for(let S=0;S<d;S++){let A=S*y,$=Math.floor(A),R=Math.min(Math.ceil(A),c-1),B=T+$*o[1],V=T+R*o[1],W=A-$,G=1-W;for(let H=0;H<h;H++){let X=H*b,q=Math.floor(X),te=Math.min(Math.ceil(X),u-1),Q=X-q,se=1-Q,ne=B+q*o[2],ie=B+te*o[2],Z=V+q*o[2],de=V+te*o[2],oe=G*se,ge=G*Q,fe=W*se,we=W*Q;for(let Te=0;Te<p;Te++){let _e=x[v++];m[ne+Te]+=_e*oe,m[ie+Te]+=_e*ge,m[Z+Te]+=_e*fe,m[de+Te]+=_e*we}}}}return n.makeTensorInfo([l,u,c,p],"float32",m)}var D6={kernelName:Zd,backendName:"cpu",kernelFunc:$6};function R6(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ve(r,"resizeNearestNeighbor");let l=w.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],x=y[0]/b[0],v=y[1]/b[1],N=0;for(let T=0;T<p;T++){let S=T*l[0];for(let A=0;A<c;A++){let $=i?x*(A+.5):x*A,R=Math.min(d-1,s?Math.round($):Math.floor($));i&&(R=Math.max(0,R));let B=S+R*l[1];for(let V=0;V<u;V++){let W=i?v*(V+.5):v*V,G=Math.min(h-1,s?Math.round(W):Math.floor(W));i&&(G=Math.max(0,G));let H=B+G*l[2];for(let X=0;X<m;X++){let q=f[H+X];g[N++]=q}}}}return n.makeTensorInfo([p,c,u,m],r.dtype,g)}var M6={kernelName:fc,backendName:"cpu",kernelFunc:R6};function P6(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ve([s,r],"resizeNearestNeighborGrad");let o=w.computeStrides(r.shape),l=w.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],x=y[0]/b[0],v=y[1]/b[1],N=1/x,T=1/v,S=Math.ceil(N)*2+2,A=Math.ceil(T)*2+2;for(let $=0;$<c;$++){let R=$*o[0];for(let B=0;B<u;B++){let V=R+B*o[1],W=Math.floor(B*N),G=Math.floor(W-S/2);for(let H=0;H<p;H++){let X=V+H*o[2],q=Math.floor(H*T),te=Math.floor(q-A/2);for(let Q=0;Q<d;Q++){let se=0;for(let ne=0;ne<S;ne++){let ie=ne+G;if(ie<0||ie>=h)continue;let Z=R+ie*l[1],de=ie*x,oe=Math.min(u-1,i?Math.round(de):Math.floor(de));if(B===oe)for(let ge=0;ge<A;ge++){let fe=ge+te;if(fe<0||fe>=m)continue;let we=Z+fe*l[2],Te=fe*v,_e=Math.min(p-1,i?Math.round(Te):Math.floor(Te));H===_e&&(se+=g[we+Q])}}f[X+Q]=se}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var O6={kernelName:Qd,backendName:"cpu",kernelFunc:P6};function L6(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;ve(r,"reverse");let i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return rr({inputs:{x:r},backend:n});let l=new Ot(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;u<l.size;u++){let p=l.indexToLoc(u),d=p.slice();o.forEach(h=>d[h]=r.shape[h]-1-d[h]),l.set(c.get(...d),...p)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var z6={kernelName:pi,backendName:"cpu",kernelFunc:L6},B6={kernelName:Rl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[c,u,p,d]=a.shape,[h,m]=_.getImageCenter(i,u,p),f=255,g=Math.sin(r),y=Math.cos(r),b=o.data.get(a.dataId).values;for(let x=0;x<c;x++){let v=x*p*u*d;for(let N=0;N<u;N++){let T=N*(p*d);for(let S=0;S<p;S++){let A=S*d;for(let $=0;$<d;$++){let R=[c,N,S,$],B=R[2],V=R[1],W=(B-h)*y-(V-m)*g,G=(B-h)*g+(V-m)*y;W=Math.round(W+h),G=Math.round(G+m);let H=s;if(typeof s!="number"&&($===3?H=f:H=s[$]),W>=0&&W<p&&G>=0&&G<u){let q=G*(p*d),te=W*d,Q=v+q+te+$;H=b[Q]}let X=v+T+A+$;l[X]=H}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},W6=st(di,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}),V6={kernelName:di,backendName:"cpu",kernelFunc:W6};function BN(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 U6(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:c,strides:u,outputSize:p}=_.calculateShapes(s,r,i),d=!0,h=n.bufferSync(r),m=n.bufferSync(s),f=BN(h,m,i,p,c,l,o,u,0,d);return n.makeTensorInfo(i,f.dtype,f.values)}var G6={kernelName:wl,backendName:"cpu",kernelFunc:U6};function H6(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t;ve([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=pa(r.dtype,s.dtype),p=w.makeZerosTypedArray(w.sizeFromShape(r.shape),u),d=0,h=i===0||i>1||r.shape.length===1?1:w.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 j6={kernelName:kl,backendName:"cpu",kernelFunc:H6},q6=_.SELU_SCALEALPHA,K6=_.SELU_SCALE,X6=st(Il,e=>e>=0?K6*e:q6*(Math.exp(e)-1)),Y6={kernelName:Il,backendName:"cpu",kernelFunc:X6},J6=st(fi,e=>1/(1+Math.exp(-e))),Q6={kernelName:fi,backendName:"cpu",kernelFunc:J6},Z6=st(Sl,e=>e<0?-1:e>0?1:0),e5={kernelName:Sl,backendName:"cpu",kernelFunc:Z6},t5=st(mi,e=>Math.sin(e)),n5={kernelName:mi,backendName:"cpu",kernelFunc:t5},a5=st(Nl,e=>Math.sinh(e)),r5={kernelName:Nl,backendName:"cpu",kernelFunc:a5},s5=11920928955078125e-23,WN=Math.log(s5)+2,i5=st(Cl,e=>{let t=e>-WN,n=e<WN,a=Math.exp(e),r;return n?r=a:t?r=e:r=Math.log(1+a),r}),o5={kernelName:Cl,backendName:"cpu",kernelFunc:i5};function l5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;ve([r],"spaceToBatchND");let o=w.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=zN.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),u=_.getReshaped(c.shape,s,o,!1),p=_.getPermuted(u.length,s.length,!1),d=_.getReshapedPermuted(c.shape,s,o,!1),h=kt({inputs:{x:c},backend:n,attrs:{shape:u}}),m=xa({inputs:{x:h},backend:n,attrs:{perm:p}}),f=kt({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}var u5={kernelName:gc,backendName:"cpu",kernelFunc:l5};function c5(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:c,sliceSize:u,strides:p,outputSize:d}=_.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f=n.bufferSync(s),g=n.data.get(i.dataId).values[0],y=BN(m,f,o,d,u,c,l,p,g,h);return n.makeTensorInfo(o,y.dtype,y.values)}var p5={kernelName:eh,backendName:"cpu",kernelFunc:c5};function d5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=_.prepareSplitSize(r,s,o),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(p=>{let d=[...u];d[o]=p;let h=Xi({inputs:{x:r},backend:n,attrs:{begin:c,size:d}});return c[o]+=p,h})}var h5={kernelName:_l,backendName:"cpu",kernelFunc:d5},m5=st(gi,e=>Math.sqrt(e)),f5={kernelName:gi,backendName:"cpu",kernelFunc:m5},g5={kernelName:yc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;ve(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}}},y5=st(Kr,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),b5={kernelName:Kr,backendName:"cpu",kernelFunc:y5};function x5(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;ve(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),x=kt({inputs:{x:r},backend:n,attrs:{shape:y}}),v;if(h){let T=Xi({inputs:{x},backend:n,attrs:{begin:m,size:g}});v=kt({inputs:{x:T},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(T)}else if(b.some(T=>T===0))v=n.makeTensorInfo(b,r.dtype,[]);else{let T=n.bufferSync(x),S=yN(b,T,f,m);v=n.makeTensorInfo(S.shape,S.dtype,S.values)}let N=kt({inputs:{x:v},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),N}var v5={kernelName:El,backendName:"cpu",kernelFunc:x5},w5=st(Fl,e=>Math.tan(e)),k5={kernelName:Fl,backendName:"cpu",kernelFunc:w5},I5=st(wi,e=>Math.tanh(e)),T5={kernelName:wi,backendName:"cpu",kernelFunc:I5};function N5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;ve(r,"tile");let i=xN(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var S5={kernelName:qr,backendName:"cpu",kernelFunc:N5};function C5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;ve(r,"topk");let o=n.data.get(r.dataId).values,[l,c]=vN(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 _5={kernelName:Al,backendName:"cpu",kernelFunc:C5};function E5(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;ve(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:c}=wN(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var F5={kernelName:th,backendName:"cpu",kernelFunc:E5};function A5(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]=kt({inputs:{x:m},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(m)}return d}var $5={kernelName:$l,backendName:"cpu",kernelFunc:A5};function D5(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a;ve(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=Wm({inputs:{input:d},backend:n,attrs:{dim:m+1}});d=f,u.push(f)}for(let m=0;m<i;++m){let f=w.createScalarValue(m,"int32"),g=n.makeTensorInfo([],"int32",f),y=DN({inputs:{a:g,b:d},backend:n}),b=fs({inputs:{x:y},backend:n,attrs:{dtype:"float32"}}),x=Mv({inputs:{a:b,b:r},backend:n}),v=Vm({inputs:{x},backend:n,attrs:{axis:0,keepDims:!1}});c.push(v),u.push(g),u.push(y),u.push(b),u.push(x),u.push(v)}let h=LN({inputs:c,backend:n,attrs:{axis:0}});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var R5={kernelName:bc,backendName:"cpu",kernelFunc:D5},M5=[nG,iU,rG,iG,dU,lG,cG,dG,mG,gG,bG,vG,kG,NG,CG,FG,$G,RG,PG,eG,LG,BG,VG,cU,mU,GG,oU,jG,KG,JG,ZG,XG,aH,sH,tH,oH,uH,pH,hH,fH,yH,bH,vH,kH,TH,NH,CH,SH,Bv,qU,EH,AH,zH,fU,BH,yU,jH,KH,XH,xU,QH,ej,nj,rj,ij,wU,uj,lU,pj,qG,hj,fj,yj,KU,IU,vj,kj,NU,Tj,Cj,Ej,$j,Rj,Pj,CU,zj,Wj,Uj,Hj,qj,Oj,Yj,Qj,EU,e6,a6,o6,AU,DU,c6,h6,g6,MU,b6,v6,w6,zN,N6,YU,LU,C6,uU,E6,JU,QU,ZU,A6,D6,M6,O6,z6,B6,V6,BU,G6,j6,Y6,Q6,e5,n5,r5,WU,s6,o5,u5,p5,h5,f5,g5,UU,b5,v5,HU,Kj,k5,T5,S5,_5,PU,F5,$5,R5,x6];for(let e of M5)vc(e);var Yi={},Uv={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function P5(e,t){Yi[e]=t}function sr(e){if(!(e in Yi)){let n=O5(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],sr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),Yi[e])}function L5(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 O5(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=L5(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Yi[e]},!1),e===1?t.getContext("webgl",Uv)||t.getContext("experimental-webgl",Uv):t.getContext("webgl2",Uv)}var dp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(dp||(dp={}));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 hp(e,t){return[t,e]}function z5(e,t){return e*t}function mp(e){let t=w.sizeFromShape(e),n=Math.ceil(t/4);return w.sizeToSquarishShape(n)}function hu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function B5(e,t){let[n,a]=hu(e,t);return n*a*4}function Gv(e,t){let n=e,a,r,s,i,o,l,c,u,p,d;return ee().getNumber("WEBGL_VERSION")===2?(a=n.R32F,r=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=n.RED,c=4,u=1,p=n.HALF_FLOAT,d=n.FLOAT):(a=e.RGBA,r=e.RGBA,s=e.RGBA,i=n.RGBA,o=e.RGBA,c=4,u=4,p=t!=null?t.HALF_FLOAT_OES:null,d=e.FLOAT),l=e.RGBA,{internalFormatFloat:a,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:p,textureTypeFloat:d}}function Ie(e,t){let n=t();return ee().getBool("DEBUG")&&W5(e),n}function W5(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+V5(e,t))}var U5=596e-10,G5=65504;function H5(e){return!!(ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||U5<Math.abs(e)&&Math.abs(e)<G5)}function V5(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 Gm(e,t){return Cr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function j5(e,t){let n=Cr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ie(e,()=>e.shaderSource(n,t)),Ie(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 K5(e,t){let n=Cr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ie(e,()=>e.shaderSource(n,t)),Ie(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw q5(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var X5=/ERROR: [0-9]+:([0-9]+):/g;function q5(e,t){let n=X5.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)=>w.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 ${w.rightPad(c[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
|
|
`))}function Y5(e){return Cr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function J5(e,t){if(Ie(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 Hv(e,t){if(Ie(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Q5(e,t){let n=Cr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ie(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Z5(e,t){let n=Cr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ie(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ie(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function eq(e){return Cr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function tq(e,t){let n=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a=`[${e}x${t}]`;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function nq(e){return Cr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function VN(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),Ie(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),Ie(e,()=>e.enableVertexAttribArray(o)),!0)}function rq(e,t,n){aq(e,n),Ie(e,()=>e.activeTexture(e.TEXTURE0+n)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function sq(e,t,n){return Cr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function iq(e,t,n){return e.getUniformLocation(t,n)}function oq(e,t,n,a){Ie(e,()=>rq(e,t,a)),Ie(e,()=>e.uniform1i(n,a))}function jv(e,t,n){Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ie(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function UN(e,t){Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ie(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Hm(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+lq(e,t))}function lq(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 Cr(e,t,n){let a=Ie(e,()=>t());if(a==null)throw new Error(n);return a}function aq(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 mu(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function fu(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 qv(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[mu(e),...fu(e)]),t}function uq(e,t=!1){let n=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,s)=>s>=e.length-2?w.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let a=w.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=mu(e),s=2,i=2;return e.length&&([s,i]=fu(e)),a=r*(s/2)*(i/2),w.sizeToSquarishShape(a).map(o=>o*2)}return w.sizeToSquarishShape(a)}function jm(e){return e%2==0}function qm(e,t){if(e=e.slice(-2),t=t.slice(-2),w.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let n=e.slice(-1)[0],a=t.slice(-1)[0];if(n===a||jm(n)&&jm(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&jm(e[0])&&jm(t[0])}var Kv,Xv;function cq(e){if(Kv==null){let t=sr(e);Kv=t.getParameter(t.MAX_TEXTURE_SIZE)}return Kv}function pq(e){if(Xv==null){let t=sr(e);Xv=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Xv)}function dq(e){if(e===0)return 0;let t,n=sr(e);return va(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:va(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function va(e,t){return e.getExtension(t)!=null}function GN(e){try{if(sr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function hq(e){if(e===0)return!1;let t=sr(e);if(e===1){if(!va(t,"OES_texture_float"))return!1}else if(!va(t,"EXT_color_buffer_float"))return!1;return Yv(t)}function fq(e){if(e===0)return!1;let t=sr(e);if(e===1){if(!va(t,"OES_texture_float")||!va(t,"WEBGL_color_buffer_float"))return!1}else{if(va(t,"EXT_color_buffer_float"))return Yv(t);let n="EXT_color_buffer_half_float";if(va(t,n)){let a=t.getExtension(n);return mq(t,a)}return!1}return Yv(t)}function Yv(e){let t=Gv(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 mq(e,t){let n=Gv(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 gq(e){return e!==2?!1:sr(e).fenceSync!=null}function fp(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var Ce=ee();Ce.registerFlag("HAS_WEBGL",()=>Ce.getNumber("WEBGL_VERSION")>0);Ce.registerFlag("WEBGL_VERSION",()=>GN(2)?2:GN(1)?1:0);Ce.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ce.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ce.get("WEBGL_VERSION")===2);Ce.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ce.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ce.registerFlag("WEBGL_PACK",()=>Ce.getBool("HAS_WEBGL"));Ce.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_CLIP",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);Ce.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_PACK_REDUCE",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_CONV_IM2COL",()=>Ce.getBool("WEBGL_PACK"));Ce.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>cq(Ce.getNumber("WEBGL_VERSION")));Ce.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>pq(Ce.getNumber("WEBGL_VERSION")));Ce.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Ce.getNumber("WEBGL_VERSION");return e===0?0:dq(e)});Ce.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ce.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!uh.isMobile());Ce.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>hq(Ce.getNumber("WEBGL_VERSION")));Ce.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ce.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ce.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ce.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>fq(Ce.getNumber("WEBGL_VERSION")));Ce.registerFlag("WEBGL_FENCE_API_ENABLED",()=>gq(Ce.getNumber("WEBGL_VERSION")));Ce.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ce.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ce.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}.`)});Ce.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});function fn(){let e,t,n,a,r,s,i,o,l,c;return ee().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",a="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=`
|
|
bool isnan_custom(float val) {
|
|
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,l="",c=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",n="varying",a="varying",r="texture2D",s="gl_FragColor",i="",o=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,l=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,c=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:c}}function Ji(e,t,n="index"){let a=w.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 Jv(e){let t=w.computeStrides(e).map(n=>n.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}var HN=`
|
|
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;
|
|
}
|
|
`,yq=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=dp.DENSE;let t=mp(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;
|
|
}
|
|
`}},bq=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=dp.DENSE;let t=mp(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;
|
|
}
|
|
`}},xq=class{constructor(e){this.variableNames=["A"],this.outTexUsage=aa.DOWNLOAD;let t=fn();this.outputShape=e,this.userCode=`
|
|
${HN}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},vq=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=aa.DOWNLOAD;let t=fn();this.outputShape=e,this.userCode=`
|
|
${HN}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},wq=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=`
|
|
${Jv(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.);
|
|
}
|
|
`}},kq=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=`
|
|
${Jv(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 Iq(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 j5(e,n)}function Tq(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 Q5(e,t)}function Nq(e){let t=new Uint16Array([0,1,2,2,1,3]);return Z5(e,t)}function gp(e,t,n,a,r,s){tq(t,n);let i=eq(e),o=e.TEXTURE_2D;return Ie(e,()=>e.bindTexture(o,i)),Ie(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ie(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ie(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ie(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ie(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null)),i}function jN(e){return e.internalFormatFloat}function Sq(e,t,n,a){let[r,s]=hp(t,n);return gp(e,r,s,jN(a),a.textureFormatFloat,e.FLOAT)}function qN(e){return e.internalFormatHalfFloat}function Cq(e,t,n,a){let[r,s]=hp(t,n);return gp(e,r,s,qN(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function KN(e){return e.downloadTextureFormat}function _q(e,t,n,a){let[r,s]=hp(t,n);return gp(e,r,s,KN(a),e.RGBA,e.UNSIGNED_BYTE)}function XN(e){return e.internalFormatPackedFloat}function Eq(e,t,n,a){let[r,s]=hu(t,n);return gp(e,r,s,XN(a),e.RGBA,e.FLOAT)}function YN(e){return e.internalFormatPackedHalfFloat}function Fq(e,t,n,a){let[r,s]=hu(t,n);return gp(e,r,s,YN(a),e.RGBA,a.textureTypeHalfFloat)}function Aq(e,t,n){let a=0,r=3*4,s=3*4+2*4;return Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),VN(e,t,"clipSpacePos",n,3,s,a)&&VN(e,t,"uv",n,2,s,r)}function $q(e,t,n,a,r,s){Ie(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),Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Dq(e,t,n){Ie(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Rq(e,t,n,a){let r=e.createBuffer();Ie(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return Ie(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),Ie(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ie(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function Mq(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 Pq(e,t,n,a){let[r,s]=hp(t,n),i=4,o=new Uint8Array(z5(t*n,i));return Ie(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function Oq(e,t,n,a,r,s,i,o){let l=e,c=new Float32Array(B5(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 Lq(e,t,n){let a=new Float32Array(t*n*4);return Ie(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var Bq=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=ee().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,P5(t,e)):this.gl=sr(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(ee().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Gm(this.gl,r),va(this.gl,s))this.textureHalfFloatExtension=Gm(this.gl,s);else if(ee().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),va(this.gl,a))this.colorBufferHalfFloatExtension=Gm(this.gl,a);else if(ee().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",va(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(va(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=Tq(this.gl),this.indexBuffer=Nq(this.gl),this.framebuffer=nq(this.gl),this.textureConfig=Gv(this.gl,this.textureHalfFloatExtension)}get debug(){return ee().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;Ie(e,()=>e.finish()),Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ie(e,()=>e.deleteFramebuffer(this.framebuffer)),Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ie(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ie(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),Sq(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),Cq(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),_q(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),Dq(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),$q(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),Fq(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),Eq(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(UN(this.gl,this.framebuffer),this.outputTexture=null),Ie(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>Pq(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return Oq(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return Mq(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=Rq(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),a}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(ee().getBool("WEBGL_FENCE_API_ENABLED")){let a=e,r=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let s=a.clientWaitSync(r,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},t=r}else ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>Lq(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=K5(t,e),a=Iq(t),r=Y5(t);return Ie(t,()=>t.attachShader(r,a)),Ie(t,()=>t.attachShader(r,n)),J5(t,r),this.debug&&Hv(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=Aq(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ie(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Hv(this.gl,this.program),Ie(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?sq(this.gl,e,t):iq(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ie(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(),oq(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=hu(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&&Hv(this.gl,this.program),Hm(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ie(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ie(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Gm(this.gl,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(a.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await w.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),a=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=zq(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&w.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),jv(this.gl,e,this.framebuffer),this.debug&&Hm(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(jv(this.gl,this.outputTexture,this.framebuffer),this.debug&&Hm(this.gl)):UN(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;jv(a,e,this.framebuffer),this.debug&&Hm(a),this.outputTexture=e,Ie(a,()=>a.viewport(0,0,t,n)),Ie(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),Ie(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 zq(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{getBroadcastDims:JN}=_;function Xq(e,t,n,a){let r=[];e.forEach(h=>{let m=w.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=>Wq(h,t,a)).join(`
|
|
`),o=t.texShape,l=fn(),c=Gq(l),u,p,d=qq(l);return t.isPacked?(u=Vq(t.logicalShape,o),p=jq(l)):(u=Uq(t.logicalShape,o),p=Hq(l)),a&&(d+=Kq),[d,c,p,s,u,i,n].join(`
|
|
`)}function gu(e){let t=e.shapeInfo.logicalShape;switch(t.length){case 0:return Yq(e);case 1:return Jq(e);case 2:return Qq(e);case 3:return Zq(e);case 4:return e8(e);case 5:return t8(e);case 6:return n8(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function QN(e){switch(e.shapeInfo.logicalShape.length){case 0:return a8(e);case 1:return r8(e);case 2:return s8(e);case 3:return i8(e);default:return o8(e)}}function Wq(e,t,n=!1){let a="";n?a+=QN(e):a+=gu(e);let r=e.shapeInfo.logicalShape,s=t.logicalShape;return r.length<=s.length&&(n?a+=l8(e,t):a+=u8(e,t)),a}function Vq(e,t){switch(e.length){case 0:return ZN();case 1:return c8(e,t);case 2:return h8(e,t);case 3:return p8(e,t);default:return d8(e,t)}}function Uq(e,t){switch(e.length){case 0:return ZN();case 1:return m8(e,t);case 2:return x8(e,t);case 3:return f8(e,t);case 4:return g8(e,t);case 5:return y8(e,t);case 6:return b8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function Gq(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function Hq(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function jq(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function qq(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);
|
|
}
|
|
|
|
${v8}
|
|
${w8}
|
|
${k8}
|
|
`}var v8=`
|
|
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);
|
|
}
|
|
`,w8=`
|
|
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);
|
|
}
|
|
`,k8=`
|
|
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);
|
|
}
|
|
`,Kq=`
|
|
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 ZN(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function c8(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 m8(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 p8(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 f8(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 d8(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 g8(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 y8(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 b8(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 h8(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.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 x8(e,t){return w.arraysEqual(e,t)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`:e[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:e[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = index / ${e[1]};
|
|
int c = index - r * ${e[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function Qi(e){return`offset${e}`}function a8(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 Yq(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;let[a,r]=e.shapeInfo.texShape;if(a===1&&r===1)return`
|
|
float ${n}() {
|
|
return sampleTexture(${t}, halfCR);
|
|
}
|
|
`;let[s,i]=e.shapeInfo.texShape,o=Qi(t);return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, ${o});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function r8(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 Jq(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${yu(e)}
|
|
}
|
|
`;let a=e.shapeInfo.texShape,r=a[0],s=a[1];if(s===1&&r===1)return`
|
|
float ${n}(int index) {
|
|
return sampleTexture(${t}, halfCR);
|
|
}
|
|
`;let i=Qi(t);return s===1?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${r}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:r===1?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${s}.0, 0.5);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${r}, ${s}, index + ${i});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function s8(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&&w.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 Qq(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&&w.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}=w.squeezeShape(t),o=s;if(o.length<t.length){let p=bu(e,o),d=["row","col"];return`
|
|
${gu(p)}
|
|
float ${a}(int row, int col) {
|
|
return ${a}(${xu(d,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
|
|
${yu(e)}
|
|
}
|
|
`;let l=r[0],c=r[1],u=Qi(n);return c===1?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${u}), vec3(${t[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:l===1?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${u}), vec3(${t[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${t[1]} + col + ${u};
|
|
vec2 uv = uvFromFlat(${l}, ${c}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function i8(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=bu(e,p),m=["b","row","col"];return`
|
|
${QN(h)}
|
|
vec4 ${a}(int b, int row, int col) {
|
|
return ${a}(${xu(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 Zq(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}=w.squeezeShape(t),l=i;if(l.length<t.length){let m=bu(e,l),f=["row","col","depth"];return`
|
|
${gu(m)}
|
|
float ${a}(int row, int col, int depth) {
|
|
return ${a}(${xu(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)));
|
|
${yu(e)}
|
|
}
|
|
`;let c=e.shapeInfo.texShape,u=c[0],p=c[1],d=e.shapeInfo.flatOffset;if(p===r&&d==null)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(p===s&&d==null)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let h=Qi(n);return`
|
|
float ${a}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r} + col * ${s} + depth + ${h};
|
|
vec2 uv = uvFromFlat(${u}, ${p}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function o8(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 e8(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}=w.squeezeShape(t);if(o.length<t.length){let m=bu(e,o),f=["row","col","depth","depth2"];return`
|
|
${gu(m)}
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
return ${a}(${xu(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)));
|
|
${yu(e)}
|
|
}
|
|
`;let c=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,p=u[0],d=u[1];if(d===i&&c==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${s}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(d===r&&c==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${t[1]*t[2]}, ${t[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let h=Qi(n);return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${s} +
|
|
depth * ${r} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${d}, index + ${h});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function t8(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}=w.squeezeShape(t);if(l.length<t.length){let f=bu(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${gu(f)}
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${a}(${xu(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;
|
|
${yu(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1];if(h===o&&u==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===r&&u==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=Qi(n);return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} + depth * ${s} +
|
|
depth2 * ${r} + depth3 + ${m};
|
|
vec2 uv = uvFromFlat(${d}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function n8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=w.squeezeShape(t);if(r.length<t.length){let g=bu(e,r),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${gu(g)}
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${a}(${xu(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)));
|
|
${yu(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],m=d[1];if(m===u&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${c}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(m===i&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=Qi(n);return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${u} + col * ${c} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
|
|
vec2 uv = uvFromFlat(${h}, ${m}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function yu(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function l8(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=JN(e.shapeInfo.logicalShape,t.logicalShape),l=dt(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=w.sizeFromShape(e.shapeInfo.logicalShape)===1,f=w.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 u8(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&&w.arraysEqual(i,s))return`
|
|
float ${r}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;let c=dt(l),u=JN(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 dt(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 bu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function xu(e,t){return t.map(n=>e[n]).join(", ")}function I8(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=Xq(s,o,r,t.packedInputs),c=e.createProgram(l),u=null,p=e.getUniformLocation(c,"NAN",!1);ee().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let d={};for(let h=0;h<t.variableNames.length;h++){let m=t.variableNames[h],f=!1;d[m]=e.getUniformLocation(c,m,f),d[`offset${m}`]=e.getUniformLocation(c,`offset${m}`,f)}return{program:t,source:l,webGLProgram:c,uniformLocations:d,inShapeInfos:i,outShapeInfo:o,infLoc:u,nanLoc:p}}function eS(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(!w.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(!w.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function T8(e,t,n,a,r){eS(t.inShapeInfos,n),eS([t.outShapeInfo],[a]);let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s,i[0],i[1]):e.setOutputMatrixTexture(s,i[0],i[1]),e.setProgram(t.webGLProgram),ee().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((o,l)=>{let c=t.program.variableNames[l],u=t.uniformLocations[c],p=t.uniformLocations[`offset${c}`];if(u!=null){if(o.isUniform){if(w.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 N8(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:S8,bincountImpl:tS,bincountReduceImpl:C8,ceilImpl:_8,concatImpl:E8,expImpl:F8,expm1Impl:A8,floorImpl:$8,gatherV2Impl:D8,greaterImpl:R8,lessImpl:M8,linSpaceImpl:P8,logImpl:O8,maxImpl:L8,maximumImpl:z8,minimumImpl:B8,multiplyImpl:W8,negImpl:V8,prodImpl:U8,rangeImpl:G8,rsqrtImpl:H8,simpleAbsImpl:nS,sliceImpl:j8,stridedSliceImpl:q8,subImpl:K8,tileImpl:X8,topKImpl:Y8,transposeImpl:Qv,uniqueImpl:J8}=YT;function aS(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function gn(e,t){return t===1?[e]:aS(e,t)}function Q8(e,t){if(e===1)return"rc";let n="";for(let a=0;a<e;a++)n+=t[a],a<e-1&&(n+=",");return n}var nK=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=dt(t),r=Z8(t,e,n),s=eK(t,e[e.length-1],e[e.length-2],n),i=tK(e,n);this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
|
|
if(${r}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${s}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function aK(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 Z8(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 eK(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 tK(e,t){let n=e.length,a=aK(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 rS=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=`
|
|
${rK(t)}
|
|
${Jv(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function rK(e){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Ji(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var sK=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=iS(t,n),r=oS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=sS(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=iS(n,a),s=oS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=sS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=ee().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function iK(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 sS(e,t,n,a,r){let s=oK(t,a),i;if(r){let[l,c]=hu(e[0],e[1]);i=l*c}else{let[l,c]=hp(e[0],e[1]);i=l*c}let o=iK(n,s);return i*o}function oK(e,t){switch(e){case rn.PACKED_2X2_FLOAT32:return XN(t);case rn.PACKED_2X2_FLOAT16:return YN(t);case rn.UNPACKED_FLOAT32:return jN(t);case rn.UNPACKED_FLOAT16:return qN(t);case rn.PACKED_4X1_UNSIGNED_BYTE:return KN(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function lK(e){return ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?rn.PACKED_2X2_FLOAT32:rn.UNPACKED_FLOAT32:e?rn.PACKED_2X2_FLOAT16:rn.UNPACKED_FLOAT16}function iS(e,t){if(e===aa.UPLOAD)return rn.PACKED_2X2_FLOAT32;if(e===aa.RENDER||e==null)return lK(t);if(e===aa.DOWNLOAD||e===aa.PIXELS)return rn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function oS(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);
|
|
}
|
|
`}},Ma="if (isnan(x)) return x;",uK="return x;",lS="return abs(x);",cK="return (x >= 0.0) ? x : (exp(x) - 1.0);",pK=Ma+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,dK=Ma+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Km="return x;",hK="return x;",mK=`
|
|
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;
|
|
`,fK=`
|
|
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;
|
|
`,gK=`
|
|
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;
|
|
`,vu=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);
|
|
}
|
|
`}},yK=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=gn("rc",t),a=dt(t),r=Q8(t,n),s=n.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${r});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}},bK=Qa.whereImpl,xK=1e-7,vK=1e-4,Zv={};function wK(e){return e in Zv||(Zv[e]={}),Zv[e]}var kK=128,IK=600;function TK(){return ee().global.screen==null?1024:ee().global.screen.height*ee().global.screen.width*window.devicePixelRatio*IK/1024/1024}var ew=class extends Zu{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!ee().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=sr(ee().getNumber("WEBGL_VERSION"));this.binaryCache=wK(ee().getNumber("WEBGL_VERSION")),this.gpgpu=new Bq(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 sK(this.gpgpu),this.numMBBeforeWarning=TK(),this.texData=new kd(this,Ha())}nextDataId(){return ew.nextDataId++}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((ee().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ee().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:aa.UPLOAD,refCount:1}),a}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,a,r){if(ee().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:a,values:t,usage:aa.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:a,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let p;o?p=new vu(i,Km):p=new gs(i,Km);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=w.now());let u;if(a==="complex64"){let p=this.readSync(r.real.dataId),d=this.readSync(r.imag.dataId);u=_.mergeRealAndImagArrays(p,d)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.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 vu(a,Km):h=new gs(a,Km);let m=this.runWebGLProgram(h,[{dataId:e,shape:a,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(n!=null)return this.convertAndCacheOnCPU(e);if(!ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ee().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(s!=="complex64"&&ee().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...mp(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=h[0],f=h[1];u=_.mergeRealAndImagArrays(m,f)}else if(l==null)u=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(a);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}c!=null&&this.disposeIntermediateTensorInfo(c);let p=this.convertAndCacheOnCPU(e,u),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Ha().removeDataId(e,this),this.pendingDeletes--),p}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(a=>w.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(!H5(n))throw ee().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:a}=this.texData.get(e),r=w.sizeFromShape(t);if(ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(e),d=this.texData.get(p.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(d.texture,...mp(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(p),h}let s=ee().getBool("WEBGL_PACK")&&a===!0,i=s?qv(t):t,o=s?new vq(i):new xq(i),l=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),c=this.texData.get(l.dataId),u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),u}timerAvailable(){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){let t=this.activeTimers,n=[],a=!1;this.programTimersStack==null?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=w.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=w.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,a&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(r);i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,c)=>({name:s[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:w.now(),endMs:null}}endTimer(e){return ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=w.now(),e)}async getQueryTime(e){if(ee().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:a,usage:r,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(a,n),this.textureManager.releaseTexture(t,a,r,s)));let c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return ee().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Ha().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=kK){let n=this.getCPUBackend();return!ee().getBool("IS_TEST")&&!this.warnedAboutCPUBackend&&n==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),n!=null&&e.every(a=>this.texData.get(a.dataId).texture==null&&w.sizeFromShape(a.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){_.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return bK(e.shape,t)}packedUnaryOp(e,t,n){let a=new vu(e.shape,t),r=this.compileAndRun(a,[e],n);return Ha().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let a=nS(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,a)}if(ee().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,lS,e.dtype);let t=new gs(e.shape,lS),n=this.compileAndRun(t,[e]);return Ha().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let r=n.map(s=>w.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:a}=this.makeTensorInfo(e,t,n);return Ha().makeTensorFromDataId(a,e,t,this)}unpackTensor(e){let t=new yK(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new nK(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[mu(e.shape),...fu(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},r=[mu(t),...fu(t)],s=new rS(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=qv(a),i;n?i=new bq(s):i=new yq(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===dp.DENSE){let f=mp(e.outputShape);i.texShape=f.map(g=>g*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),w.sizeFromShape(s.shape)===0)return i.values=w.getTypedArrayFromDType(s.dtype,0),s;let o=[],l=t.map(f=>{if(f.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(f.dataId);if(g.texture==null){if(!e.packedInputs&&w.sizeFromShape(f.shape)<=ee().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:f.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=f.shape)}else if(!!g.isPacked!=!!e.packedInputs)f=g.isPacked?this.unpackTensor(f):this.packTensor(f),o.push(f),g=this.texData.get(f.dataId);else if(g.isPacked&&!qm(g.shape,f.shape)){let y=f,b=f.shape;f.shape=g.shape,f=this.packedReshape(f,b),o.push(f),g=this.texData.get(f.dataId),y.shape=b}return this.uploadToGPU(f.dataId),{shape:f.shape,texData:g,isUniform:!1}});this.uploadToGPU(s.dataId);let c={shape:s.shape,texData:i,isUniform:!1},u=N8(e,l,c),p=this.getAndSaveBinary(u,()=>I8(this.gpgpu,e,l,c)),d=this.activeTimers!=null,h;d&&(h=this.startTimer()),T8(this.gpgpu,p,l,c,a),o.forEach(f=>this.disposeIntermediateTensorInfo(f)),d&&(h=this.endTimer(h),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)}));let m=ee().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let f=w.now();f-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=f)}if(!ee().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&r===!1){let f=this.unpackTensor(s);return this.disposeIntermediateTensorInfo(s),f}return s}compileAndRun(e,t,n,a,r=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,a,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(ee().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=D(()=>{if(!ee().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=ee().getBool("DEBUG");ee().set("DEBUG",!1);let t=this.abs(pe(1e-8)).dataSync()[0];if(ee().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?xK:vK}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=w.now());let u=t.texShape;if(u==null&&(u=uq(n,o),t.texShape=u),r!=null){let p=qv(n),d,h=u[1],m=u[0],f=r instanceof Uint8Array;o?([h,m]=hu(u[0],u[1]),d=new kq(p,[m,h],f)):d=new wq(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),x=this.texData.get(b.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(b.dataId),t.values=null,l&&(this.uploadWaitMs+=w.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=NK(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]*w.bytesPerElement(t)}};ew.nextDataId=0;function NK(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 SK="3.2.0";uh.isBrowser()&&fh("webgl",()=>new ew,2);var uS=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,wu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Xm=`
|
|
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;
|
|
`,yp=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length,s="";if(a)if(r===0||w.sizeFromShape(this.outputShape)===1)s=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(s=`
|
|
${dt(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 Gn(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 CK={kernelName:Ks,backendName:"webgl",kernelFunc:Gn};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=Gn({inputs:{x:a},backend:n}),l=Gn({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var _K={kernelName:Ad,backendName:"webgl",kernelFunc:ys},cS="return (a < 0.) ? b * a : a;",pS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function EK(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new yp(pS,r.shape,i.shape):new wu(cS,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],r.dtype);return n.disposeIntermediateTensorInfo(i),l}var FK={kernelName:Xs,backendName:"webgl",kernelFunc:EK},dS="return (a < 0.) ? b * a : a;",hS=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function AK(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new yp(hS,a.shape,r.shape):new wu(dS,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)}var $K={kernelName:oi,backendName:"webgl",kernelFunc:AK},mS="if (isnan(x)) return x;",DK=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,RK=`
|
|
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 Ke({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let p=o.texData.get(i.dataId),d=n(p.values,l);return o.makeTensorInfo(i.shape,l,d)}let c=ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new vu(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(x=>{let[v,N]=x,T={dataId:v.dataId,dtype:v.dtype,shape:l.shape},S={dataId:N.dataId,dtype:N.dtype,shape:c.shape},A=new wu(e,l.shape,c.shape);return u.runWebGLProgram(A,[T,S],pa(v.dtype,N.dtype))}),b=ys({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),b}let p=s||pa(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),x=u.texData.get(b.dataId);return x.values=g,b}let d=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new yp(t,l.shape,c.shape,n):h=new wu(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],p)}}function Ym(e,t=!1){if(e==="linear")return t?hK:uK;if(e==="relu")return t?fK:pK;if(e==="elu")return t?mK:cK;if(e==="relu6")return t?gK:dK;if(e==="prelu")return t?hS:dS;if(e==="leakyrelu")return t?pS:cS;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var fS=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",x="rc.x";e[0]<t[0]?b=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(x=`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 = ${x};
|
|
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);
|
|
}
|
|
`}},gS={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},yS=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`}},bS="return a * b;";function xS(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=_.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),c=new yS(gS.REAL,a.shape,r.shape),u=new yS(gS.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]=W8(a.shape,r.shape,o.values,l.values,s),p=n.makeTensorInfo(u,s),d=n.texData.get(p.dataId);return d.values=c,p}let i;return ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new yp(bS,a.shape,r.shape):i=new wu(bS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var MK={kernelName:ai,backendName:"webgl",kernelFunc:xS};function PK(e,t,n){let a=[mu(e.shape),...fu(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[mu(t),...fu(t)],i=new rS(s,a),o=!0,l=n.runWebGLProgram(i,[r],e.dtype,null,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function ye(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=w.sizeFromShape(r.shape),l=w.inferFromImplicitShape(s,o),c=w.sizeFromShape(l);w.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&&!qm(r.shape,l)&&!(u.texture!==null&&qm(u.shape,l))?PK(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var OK={kernelName:vl,backendName:"webgl",kernelFunc:ye},vS=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 * ${w.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);
|
|
}
|
|
`}},LK=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 zK(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function Zi(e,t,n,a){let r=zK(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 vS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},o):new vS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c}):u=new LK({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 WK=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=dt(this.rank),r=BK(t);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function BK(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 VK=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=dt(this.rank),r=aS("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 Jm(e,t,n){let a=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VK(e.shape,t):new WK(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function UK(e,t,n,a){let r=t,s=e.shape.length,i=w.parseAxisParam(r,e.shape),o=i,l=_.getAxesPermutation(o,s),c=l!=null,u=e;c&&(u=Jm(e,l,a),o=_.getInnerMostAxes(o.length,s)),_.assertAxesAreInnerMostDims("sum",o,s);let[p,d]=_.computeOutAndReduceShapes(u.shape,o),h=p;n&&(h=_.expandShapeToKeepDim(p,i));let m=w.sizeFromShape(d),f=w.sizeFromShape(e.shape)/m,g=ye({inputs:{x:u},attrs:{shape:[f,m]},backend:a}),y=lh(e.dtype),b=Zi(g,y,"sum",a),x=ye({inputs:{x:b},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(b),c&&a.disposeIntermediateTensorInfo(u),x}function tw(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return UK(r,s,i,n)}var GK={kernelName:yi,backendName:"webgl",kernelFunc:tw};function An(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=Qv(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=Jm(r,s,i);return c}var HK={kernelName:ki,backendName:"webgl",kernelFunc:An},wS=1e3;function Qm({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=w.sizeFromShape(f),b=w.sizeFromShape(g),x=y===b||y===1||b===1;w.assert(c>=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${g}).`);let v=(y>b?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,m]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`);let N=n?[y,p,h]:[y,h,p],T=a?[b,m,d]:[b,d,m],S=ye({inputs:{x:e},backend:r,attrs:{shape:N}}),A=ye({inputs:{x:t},backend:r,attrs:{shape:T}}),$=[S,A],R=Math.max(y,b),B=n?S.shape[1]:S.shape[2],V=s!=null,W=i!=null,G=l==="leakyrelu",H=l!=null?Ym(l,!0):null,X=V||W||G||H!=null,q;if((h===1||m===1)&&B>wS&&X===!1){let Q=S,se=A;n&&(Q=An({inputs:{x:S},backend:r,attrs:{perm:[0,2,1]}}),$.push(Q)),a&&(se=An({inputs:{x:A},backend:r,attrs:{perm:[0,2,1]}}),$.push(se));let ne=m!==1,ie=m===1,Z=Q;ne&&(Z=ye({inputs:{x:Q},backend:r,attrs:{shape:[R,B,1]}}),$.push(Z));let de=m===1?2:1,oe=se;ie&&(oe=ye({inputs:{x:se},backend:r,attrs:{shape:[R,1,B]}}),$.push(oe));let ge=xS({inputs:{a:Z,b:oe},backend:r});q=tw({inputs:{x:ge},backend:r,attrs:{axis:de,keepDims:!0}}),$.push(ge)}else{let Q=pa(e.dtype,t.dtype),se=new fS(N,T,[R,h,m],n,a,V,H,W,G),ne=[S,A];if(s!=null&&ne.push(s),W&&ne.push(i),G){let ie=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));ne.push(ie),$.push(ie)}q=r.runWebGLProgram(se,ne,Q)}let te=ye({inputs:{x:q},backend:r,attrs:{shape:v}});$.push(q);for(let Q of $)r.disposeIntermediateTensorInfo(Q);return te}function jK(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 Qm({a:r,b:s,transposeA:l,transposeB:c,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var qK={kernelName:Ii,backendName:"webgl",kernelFunc:jK},kS="return abs(x);";function KK(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=nS(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new vu(a.shape,kS):r=new gs(a.shape,kS),n.runWebGLProgram(r,[a],a.dtype)}var XK={kernelName:Po,backendName:"webgl",kernelFunc:KK},YK=Ma+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,JK=Ke({opSnippet:YK}),QK={kernelName:Oo,backendName:"webgl",kernelFunc:JK},ZK=Ma+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,eX=Ke({opSnippet:ZK}),tX={kernelName:Lo,backendName:"webgl",kernelFunc:eX},IS="return a + b;",nX=sn({opSnippet:IS,packedOpSnippet:IS,supportsComplex:!0,cpuKernelImpl:S8}),aX={kernelName:Hr,backendName:"webgl",kernelFunc:nX},rX=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);
|
|
}
|
|
`}},sX=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 Zm(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return Gn({inputs:{x:a[0]},backend:n});if(a.length>ee().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=Zm({inputs:a.slice(0,o),backend:n}),c=Zm({inputs:a.slice(o),backend:n});return Zm({inputs:[l,c],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>pa(o,l)),s=a.map(o=>o.shape),i=ee().getBool("WEBGL_PACK")?new sX(a[0].shape,s):new rX(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var iX={kernelName:As,backendName:"webgl",kernelFunc:Zm};function oX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=An({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("all",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=w.sizeFromShape(h),f=ye({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Zi(f,f.dtype,"all",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=ye({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ye({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var lX={kernelName:Sd,backendName:"webgl",kernelFunc:oX};function uX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=An({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("any",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=w.sizeFromShape(h),f=ye({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Zi(f,f.dtype,"any",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=ye({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ye({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var cX={kernelName:Cd,backendName:"webgl",kernelFunc:uX},pX=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));
|
|
}
|
|
`}},dX=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let 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=dt(o),c=gn("coords",o),u,p;if(s===1){p=o+1;let S=dt(p);u=`
|
|
${S} sourceLocR = ${S}(${c.join()}, 0);
|
|
++${c[o-1]};
|
|
${S} sourceLocG = ${S}(${c.join()}, 0);
|
|
++${c[o-2]};
|
|
${S} sourceLocA = ${S}(${c.join()}, 0);
|
|
--${c[o-1]};
|
|
${S} sourceLocB = ${S}(${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(S=>"int "+S),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"),x=n==="max"?"greaterThan":"lessThan",v=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;
|
|
${v}
|
|
vec4 candidate = ${N};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function TS(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=_.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new pX(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=TS(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}function NS(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=_.computeOptimalWindowSize(s),o=new dX(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=NS(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function SS(e,t,n,a){let r=[n];if(_.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!ee().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],[i,o]=_.computeOutAndReduceShapes(t.shape,r),l=w.sizeFromShape(o),c=ye({inputs:{x:t},backend:e,attrs:{shape:[-1,l]}});s.push(c);let u=TS(e,c,a);s.push(u);let p=ye({inputs:{x:u},backend:e,attrs:{shape:i}});return s.forEach(d=>e.disposeIntermediateTensorInfo(d)),p}return NS(e,t,a)}function hX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=An({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=SS(n,l,i[0],"max");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var mX={kernelName:$s,backendName:"webgl",kernelFunc:hX};function fX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=An({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=SS(n,l,i[0],"min");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var gX={kernelName:nc,backendName:"webgl",kernelFunc:fX},yX=Ma+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,bX=Ke({opSnippet:yX}),xX={kernelName:zo,backendName:"webgl",kernelFunc:bX},vX=Ma+"return log(x + sqrt(x * x + 1.0));",wX=Ke({opSnippet:vX}),kX={kernelName:Bo,backendName:"webgl",kernelFunc:wX},IX=Ma+`
|
|
return atan(x);
|
|
`,TX=Ke({opSnippet:IX}),NX={kernelName:Wo,backendName:"webgl",kernelFunc:TX},SX=DK+`
|
|
return atan(a, b);
|
|
`,CX=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+RK+`
|
|
return result;
|
|
`,_X=sn({opSnippet:SX,packedOpSnippet:CX}),EX={kernelName:Uo,backendName:"webgl",kernelFunc:_X},FX=Ma+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,AX=Ke({opSnippet:FX}),$X={kernelName:Vo,backendName:"webgl",kernelFunc:AX},bp=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 S=">=";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 ${S} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?r?f:g:`wR * ${p} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");let v=Math.floor(s/4)*4,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 < ${v}; 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 + ${v};
|
|
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(${x});
|
|
}
|
|
`}},nw=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",x="0.0";if(b||(x="-1.0 / 1e-20"),n){let $=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${y});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${d};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${p}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${$} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${m} +
|
|
wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let v="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,S=s%4,A=`
|
|
if (${b}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${v}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${y});
|
|
const float initializationValue = ${x};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${x});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${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)
|
|
);
|
|
|
|
${A}
|
|
}
|
|
|
|
int xC = xCCorner + ${T};
|
|
if (${S===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${S===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${S===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
|
|
);
|
|
|
|
${A}
|
|
}
|
|
}
|
|
setOutput(${N});
|
|
}
|
|
}
|
|
`}};function DX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;fp(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;w.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return Gn({inputs:{x:r},backend:n});let p=new bp(u,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var RX={kernelName:Ds,backendName:"webgl",kernelFunc:DX};function MX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,l,c),d=new nw(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var PX={kernelName:ac,backendName:"webgl",kernelFunc:MX},OX=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);
|
|
}
|
|
`}},LX=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 zX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new LX(d);return n.runWebGLProgram(h,[r],i.dtype)}var BX={kernelName:Ed,backendName:"webgl",kernelFunc:zX};function WX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;fp([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=_.computePool2DInfo(i.shape,o,l,1,c),p=new OX(u);return n.runWebGLProgram(p,[r],i.dtype)}var VX={kernelName:_d,backendName:"webgl",kernelFunc:WX};function UX(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return Qm({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var GX={kernelName:Rs,backendName:"webgl",kernelFunc:UX},HX=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${i};
|
|
float scale = ${o};
|
|
float inv = scale * inversesqrt(variance + float(${s}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},jX=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${i};
|
|
vec4 scale = ${o};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${s}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},qX=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;w.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let c=[a,r,s],u=null;i!=null&&(u=i.shape,c.push(i));let p=null;o!=null&&(p=o.shape,c.push(o));let d=ee().getBool("WEBGL_PACK_NORMALIZATION")?new jX(a.shape,r.shape,s.shape,u,p,l):new HX(a.shape,r.shape,s.shape,u,p,l);return t.runWebGLProgram(d,c,c[0].dtype)},KX={kernelName:js,backendName:"webgl",kernelFunc:qX},YX=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=dt(this.rank),n=`uniform int start[${this.rank}];`,a=XX(this.rank),r,s=e.map((i,o)=>`sourceLoc.${aw[o]} = start[${o}] + coords.${aw[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)}}},aw=["x","y","z","w","u","v"];function XX(e){if(e===1)return"sourceLoc";if(e<=6)return aw.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var JX=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=dt(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 QX(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=dn.computeFlatOffset(t,w.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 xp(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),w.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let p=n.texData.get(r.dataId),d=j8(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=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new JX(l):new YX(l),d=p.getCustomSetupFunc(o);return n.runWebGLProgram(p,[r],r.dtype,d)}return n.uploadToGPU(r.dataId),QX(r,o,l,n)}var ZX={kernelName:Tl,backendName:"webgl",kernelFunc:xp},eY=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;w.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,x)=>b*x),l=_.getReshaped(r.shape,s,o),c=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(r.shape,s,o),p=_.getSliceBeginCoords(i,s.length),d=_.getSliceSize(u,i,s.length),h=[],m=ye({inputs:{x:r},backend:n,attrs:{shape:l}}),f=An({inputs:{x:m},backend:n,attrs:{perm:c}}),g=ye({inputs:{x:f},backend:n,attrs:{shape:u}}),y=xp({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},tY={kernelName:rc,backendName:"webgl",kernelFunc:eY};function nY(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=tS(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var aY={kernelName:Fd,backendName:"webgl",kernelFunc:nY},rY="return float(a != b);",CS=sn({opSnippet:rY,dtype:"bool"}),sY={kernelName:dl,backendName:"webgl",kernelFunc:CS};function vp(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Gn({inputs:{x:r.complexTensorInfos.real},backend:n})}var iY={kernelName:Jd,backendName:"webgl",kernelFunc:vp},oY="return float(int(x));";function lY(e,t){let n=new gs(e.shape,oY),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function rw(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return Gn({inputs:{x:r},backend:n});let i=xt(r.shape),o=rw({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=vp({inputs:{input:r},backend:n}),o=rw({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(r.dtype,s)){let i=Gn({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return lY(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=CS({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 uY={kernelName:Ms,backendName:"webgl",kernelFunc:rw},_S="return ceil(x);",cY=Ke({opSnippet:_S,packedOpSnippet:_S,cpuKernelImpl:_8}),pY={kernelName:Ps,backendName:"webgl",kernelFunc:cY},dY=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)}}},hY=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 mY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;ee().getBool("WEBGL_PACK_CLIP")?o=new hY(r.shape):o=new dY(r.shape);let l=o.getCustomSetupFunc(s,i);return n.runWebGLProgram(o,[r],r.dtype,l)}var fY={kernelName:jr,backendName:"webgl",kernelFunc:mY},gY=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 ES(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function yY(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new gY(a.shape),i=[ES(a,r.complexTensorInfos.real),ES(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var bY={kernelName:sc,backendName:"webgl",kernelFunc:yY},xY=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];n.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let a=t.length,r=t[t.length-1];n.push(`else setOutput(getT${a}(yR, yC-${r}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},vY=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=dt(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}(${ef(i,l,f)}),
|
|
vec2(${ef(c,l,f)}));
|
|
}`}let d=o.length,h=o[o.length-1];p+=`
|
|
return getChannel(
|
|
getT${d}(${ef(i,l,h)}),
|
|
vec2(${ef(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 ef(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function tf(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Gn({inputs:{x:r.complexTensorInfos.imag},backend:n})}var wY={kernelName:Gd,backendName:"webgl",kernelFunc:tf};function ku(e,t,n){let a=e[0].dtype;if(a==="complex64"){let c=e.map(m=>vp({inputs:{input:m},backend:n})),u=e.map(m=>tf({inputs:{input:m},backend:n})),p=ku(c,t,n),d=ku(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}=FS(e,t,n),p=c.map(g=>({vals:n.readSync(g.dataId),shape:g.shape})),d=c[0].shape[0]===1,h=E8(p,u,a,d),m=_.computeOutShape(e.map(g=>g.shape),t),f=n.makeTensorInfo(m,a,h);return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}if(e.length>ee().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(e.length/2),u=ku(e.slice(0,c),t,n),p=ku(e.slice(c),t,n),d=ku([u,p],t,n);return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),d}if(ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let c=new vY(e.map(u=>u.shape),t);return n.runWebGLProgram(c,e,a)}let{tensors2D:r,outShape:s}=FS(e,t,n),i=new xY(r.map(c=>c.shape)),o=n.runWebGLProgram(i,r,a);r.forEach(c=>n.disposeIntermediateTensorInfo(c));let l=ye({inputs:{x:o},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(o),l}function FS(e,t,n){let a=_.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ye({inputs:{x:r},attrs:{shape:[-1,w.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function AS(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=_.computeOutShape(t.map(c=>c.shape),s);if(w.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(c=>w.sizeFromShape(c.shape)>0);if(o.length===1)return Gn({inputs:{x:o[0]},backend:n});let l=o.map(c=>c.shape);return _.assertParamsConsistent(l,s),ku(o,s,n)}var kY={kernelName:Go,backendName:"webgl",kernelFunc:AS},$S=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,x="",v="";n&&(a?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,v="result = activation(result);");let N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${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}
|
|
${v}
|
|
setOutput(result);
|
|
}
|
|
`}},IY=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);
|
|
}
|
|
`}},TY=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,x="";for(let v=0;v<=1;v++)for(let N=0;N<=1;N++)x+=`
|
|
blockIndex = rc.y + ${N};
|
|
pos = rc.x + ${v};
|
|
|
|
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[${v*2+N}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${v*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;
|
|
|
|
${x}
|
|
|
|
${f.output} = result;
|
|
}
|
|
`}};function DS({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>wS,x=l[2]%2!=0&&!!c.isPacked;if(b||!ee().getBool("WEBGL_LAZILY_UNPACK")||!ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!x){let v=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],N=ye({inputs:{x:e},backend:a,attrs:{shape:[1,v,n.inChannels]}}),T=ye({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),S=Qm({a:N,b:T,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ye({inputs:{x:S},backend:a,attrs:{shape:n.outShape}}),y.push(N),y.push(T),y.push(S)}else{let v=h?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),N={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},T=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,w.assert(qm(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);let S=ye({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(S);let A=Qm({a:N,b:S,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),$=a.texData.get(A.dataId);w.assert($.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=T,$.shape=n.outShape,g=Gn({inputs:{x:A},backend:a}),g.shape=n.outShape,y.push(A)}for(let v of y)a.disposeIntermediateTensorInfo(v);return g}function RS({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,x=!1,v=[],N=ye({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),T=ye({inputs:{x:t},backend:a,attrs:{shape:[1,f,w.sizeFromShape(t.shape)/f]}});v.push(N),v.push(T);let S=new TY(y,N.shape,n),A=a.runWebGLProgram(S,[N],"float32"),$=ye({inputs:{x:A},backend:a,attrs:{shape:[1,y[0],y[1]]}});v.push(A),v.push($);let R=r!=null,B=s!=null,V=o==="leakyrelu",W=o?Ym(o,!0):null,G=new fS($.shape,T.shape,[1,g,n.outChannels],b,x,R,W,B,V),H=[$,T];if(r&&H.push(r),B&&H.push(s),V){let Q=a.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));H.push(Q),v.push(Q)}let X=a.runWebGLProgram(G,H,"float32"),q=m?[1,d,p,n.outChannels]:[1,n.outChannels,d,p],te=ye({inputs:{x:X},backend:a,attrs:{shape:q}});v.push(X);for(let Q of v)a.disposeIntermediateTensorInfo(Q);return te}function NY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!1,p),h;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))h=DS({x:r,filter:s,convInfo:d,backend:n});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=RS({x:r,filter:s,convInfo:d,backend:n});else{let f=new $S(d);h=n.runWebGLProgram(f,[r,s],"float32")}let m=ye({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),m}var SY={kernelName:Os,backendName:"webgl",kernelFunc:NY},CY=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);
|
|
}
|
|
`}},_Y=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);
|
|
}
|
|
`}},EY=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);
|
|
}
|
|
`}},FY=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 AY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,filterShape:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),h=new CY(d);return n.runWebGLProgram(h,[r,s],"float32")}var $Y={kernelName:$d,backendName:"webgl",kernelFunc:AY};function DY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(c),d=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),h=new _Y(d);return n.runWebGLProgram(h,[r,s],"float32")}var RY={kernelName:Ls,backendName:"webgl",kernelFunc:DY};function MY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeConv3DInfo(r.shape,s.shape,i,l,o),u=new IY(c);return n.runWebGLProgram(u,[r,s],"float32")}var PY={kernelName:ic,backendName:"webgl",kernelFunc:MY};function OY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,c=_.computeConv3DInfo(r.shape,l,i,1,o),u=new EY(c);return n.runWebGLProgram(u,[r,s],"float32")}var LY={kernelName:Dd,backendName:"webgl",kernelFunc:OY};function zY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,c=_.computeConv3DInfo(l,s.shape,o,1,i),u=new FY(c);return n.runWebGLProgram(u,[r,s],"float32")}var BY={kernelName:Rd,backendName:"webgl",kernelFunc:zY},WY=mS+`
|
|
return cos(x);
|
|
`,VY=Ke({opSnippet:WY}),UY={kernelName:zs,backendName:"webgl",kernelFunc:VY},GY=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,HY=Ke({opSnippet:GY}),jY={kernelName:Ho,backendName:"webgl",kernelFunc:HY},qY=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,x,v]=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 = ${x};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
float in_x = ${v};
|
|
if( in_x < 0.0 || in_x > ${m} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${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);
|
|
}
|
|
}
|
|
`}},KY=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 qY(r.shape,s.shape,o,l,c);return n.runWebGLProgram(u,[r,s,i],"float32")},XY={kernelName:jo,backendName:"webgl",kernelFunc:KY},OS=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let a=e.length,r=t?"0.0":`getX(${MS(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() {
|
|
${dt(a)} coords = getOutputCoords();
|
|
int end = ${PS(a,"coords")};
|
|
float val = ${r};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${PS(a,"coords")} = idx;
|
|
val += getX(${MS(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 MS(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 PS(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 YY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length,c=_.getAxesPermutation([s],l),u=r;c!=null&&(u=An({inputs:{x:r},backend:n,attrs:{perm:c}}));let p=_.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${r.shape.length-1} but got axis=${s}`);let d=u.shape[p],h=Gn({inputs:{x:u},backend:n});for(let m=0;m<=Math.ceil(Math.log2(d))-1;m++){let f=new OS(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 OS(u.shape,i,o),f=h;h=n.runWebGLProgram(m,[h],h.dtype),n.disposeIntermediateTensorInfo(f)}if(c!=null){let m=_.getUndoAxesPermutation(c),f=An({inputs:{x:h},backend:n,attrs:{perm:m}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),f}return h}var JY={kernelName:Bs,backendName:"webgl",kernelFunc:YY};function QY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),c=n.readSync(s.dataId),u=tS(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=C8(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 ZY={kernelName:Md,backendName:"webgl",kernelFunc:QY},e7=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 t7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;w.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 e7(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var n7={kernelName:qo,backendName:"webgl",kernelFunc:t7},LS=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 v=0;v<h;v++)for(let N=0;N<m;N++)g+=`
|
|
vec4 xTexelR${v}C${N*2} = vec4(0.);
|
|
vec4 wR${v}C${N} = vec4(0.);
|
|
vec4 xR${v}C${N} = vec4(0.);`;for(let v=0;v<h;v++)for(let N=0;N<f;N++){let T=N*2;if(g+=`
|
|
xR = xRCorner + ${v*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${v}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${v}C${T}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${v}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${v}C${T} = vec4(previous.zw, xTexelR${v}C${T}.xy);
|
|
} else {
|
|
xR${v}C${T} = vec4(0, 0, xTexelR${v}C${T}.xy);
|
|
}
|
|
`:g+=`
|
|
if(xR >= 0 && xR < ${s} && xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${T} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${T} = xTexelR${v}C${T};
|
|
`,T+1<m)){let S=l%2==0?w.nearestLargerEven(d):d;d%2==0&&l%2==1||d%2!=0&&l%2!=1?(g+=`
|
|
xCOffset = xC + ${l%2} + ${S};
|
|
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,d>1&&(g+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${T} = vec4(0.);
|
|
}
|
|
`),g+=`
|
|
xR${v}C${T+1} = vec4(
|
|
xTexelR${v}C${T}.zw, xTexelR${v}C${T+2}.xy);
|
|
`):g+=`
|
|
xCOffset = xC + ${S};
|
|
|
|
if(xR >= 0 && xR < ${s} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${v}C${T+1} = xTexelR${v}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${v}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${T} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${i}) {
|
|
xTexelR${v}C${T+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${v}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${T} = vec4(
|
|
xTexelR${v}C${T}.zw, xTexelR${v}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${v}C${T+1} = vec4(xTexelR${v}C${T+2}.xy, final.xy);
|
|
`)):(g+=`
|
|
if(xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${T} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${u};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${T} = vec4(
|
|
xTexelR${v}C${T}.xy, xTexelR${v}C${T+2}.xy);
|
|
`,T+1<m&&(g+=`
|
|
xR${v}C${T+1} = vec4(
|
|
xTexelR${v}C${T}.zw, xTexelR${v}C${T+2}.zw);
|
|
`)),g+="}");T<m&&(g+=`
|
|
vec4 wTexelR${v}C${T} = getW(${v}, ${T}, d1, q);
|
|
wR${v}C${T} = vec4(wTexelR${v}C${T}.xz, wTexelR${v}C${T}.xz);
|
|
`,T+1<m&&(g+=`
|
|
vec4 wTexelR${v}C${T+1} = getW(${v}, ${T+1}, d1, q);
|
|
wR${v}C${T+1} =
|
|
vec4(wTexelR${v}C${T+1}.xz, wTexelR${v}C${T+1}.xz);`))}for(let v=0;v<h;v++)for(let N=0;N<m;N++)g+=`dotProd += xR${v}C${N} * wR${v}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 x=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;
|
|
${x}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}};function a7(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]),w.assert(_.eitherStridesOrDilationsAreOne(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=_.computeConv2DInfo(r.shape,s.shape,i,u,o,c,!0),d;return ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?d=new zS(p):d=new LS(p),n.runWebGLProgram(d,[r,s],"float32")}var r7={kernelName:Ws,backendName:"webgl",kernelFunc:a7},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.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);
|
|
}
|
|
`}},i7=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 o7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,filterShape:u}=a,p=_.computeConv2DInfo(r.shape,u,i,o,l,c,!0),d=new s7(p);return n.runWebGLProgram(d,[r,s],"float32")}var l7={kernelName:Pd,backendName:"webgl",kernelFunc:o7};function u7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,inputShape:u}=a,p=_.computeConv2DInfo(u,s.shape,i,o,l,c,!0),d=new i7(p);return n.runWebGLProgram(d,[r,s],"float32")}var c7={kernelName:Od,backendName:"webgl",kernelFunc:u7},p7=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 d7(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=w.sizeFromShape(a.shape),i=ye({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new p7(s),l=n.runWebGLProgram(o,[i],i.dtype),c=ye({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var h7={kernelName:Ld,backendName:"webgl",kernelFunc:d7},m7=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 f7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),u,p=new m7(c);u=n.runWebGLProgram(p,[r,s],"float32");let d=ye({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),d}var g7={kernelName:oc,backendName:"webgl",kernelFunc:f7},y7="return (x >= 0.0) ? x : (exp(x) - 1.0);",b7=`
|
|
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;
|
|
`,x7=Ke({opSnippet:y7,packedOpSnippet:b7}),v7={kernelName:Ko,backendName:"webgl",kernelFunc:x7},w7="return (b >= 1.0) ? a : a * (b + 1.0);",k7=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,I7=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new yp(k7,a.shape,r.shape):new wu(w7,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},T7={kernelName:Wd,backendName:"webgl",kernelFunc:I7},N7=`
|
|
return vec4(equal(a, b));
|
|
`,S7="return float(a == b);",C7=sn({opSnippet:S7,packedOpSnippet:N7,dtype:"bool"}),_7={kernelName:Yo,backendName:"webgl",kernelFunc:C7},E7=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${_.ERF_P};
|
|
float a1 = ${_.ERF_A1};
|
|
float a2 = ${_.ERF_A2};
|
|
float a3 = ${_.ERF_A3};
|
|
float a4 = ${_.ERF_A4};
|
|
float a5 = ${_.ERF_A5};
|
|
|
|
float sign = sign(x);
|
|
x = abs(x);
|
|
float t = 1.0 / (1.0 + p * x);
|
|
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
|
|
`,F7=Ke({opSnippet:E7}),A7={kernelName:Xo,backendName:"webgl",kernelFunc:F7},BS="return exp(x);",WS=Ke({opSnippet:BS,packedOpSnippet:BS,cpuKernelImpl:F8}),$7={kernelName:Us,backendName:"webgl",kernelFunc:WS};function sw(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&&(w.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),ye({inputs:{x:s},backend:a,attrs:{shape:o}})}var D7={kernelName:Jo,backendName:"webgl",kernelFunc:sw},VS="return exp(x) - 1.0;",R7=Ke({opSnippet:VS,packedOpSnippet:VS,cpuKernelImpl:A8}),M7={kernelName:Qo,backendName:"webgl",kernelFunc:R7},US=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 GS(e,t,n){let a=n.texData.get(e.dataId),r=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=ye({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,c=new US("real",l,t),u=new US("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=ye({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function P7(e){let{inputs:t,backend:n}=e,{input:a}=t;return GS(a,!1,n)}var O7={kernelName:Vd,backendName:"webgl",kernelFunc:P7},L7=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 iw(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||w.inferDtype(r),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new L7(a,r),o=i.getCustomSetupFunc(r);return t.runWebGLProgram(i,[],s,o)}}var z7={kernelName:lc,backendName:"webgl",kernelFunc:iw},B7=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);
|
|
}
|
|
`}},W7={kernelName:Zo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new B7(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},HS="return floor(x);",V7=Ke({opSnippet:HS,packedOpSnippet:HS,cpuKernelImpl:$8}),U7={kernelName:Gs,backendName:"webgl",kernelFunc:V7},G7=`
|
|
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;
|
|
}
|
|
`,H7=`
|
|
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);
|
|
`,j7=sn({opSnippet:G7,packedOpSnippet:H7,dtype:"int32"}),q7={kernelName:Hs,backendName:"webgl",kernelFunc:j7},K7=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));
|
|
}
|
|
`}},X7=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;
|
|
}
|
|
`}},J7={kernelName:nh,backendName:"webgl",kernelFunc:Y7},Iu;function Y7(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)&&(Iu==null&&(Iu=document.createElement("canvas").getContext("2d")),Iu.canvas.width=c,Iu.canvas.height=u,Iu.drawImage(r,0,0,c,u),r=Iu.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=ee().getBool("WEBGL_PACK")?new X7(d):new K7(d),f=n.runWebGLProgram(m,[h],"int32");return n.disposeData(h.dataId),f}function Q7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=a,f=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(r.shape,s.shape,l,p,c,d,!1,f),y,b=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=DS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=RS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let v=i!=null,N=o!=null,T=h==="leakyrelu",S=h?Ym(h,!1):null,A=new $S(g,v,S,N,T),$=[r,s];if(i&&$.push(i),o&&$.push(o),T){let R=n.makeTensorInfo([],"float32",w.createScalarValue(m,"float32"));$.push(R),b.push(R)}y=n.runWebGLProgram(A,$,"float32")}let x=ye({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var Z7={kernelName:Ti,backendName:"webgl",kernelFunc:Q7};function e9(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]),w.assert(_.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=_.computeConv2DInfo(r.shape,s.shape,l,f,c,p,!0),y=ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=d?Ym(d,y):null,x=[r,s],v=i!=null,N=o!=null,T=d==="leakyrelu";if(v&&x.push(i),N&&x.push(o),T){let $=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));x.push($),m.push($)}let S;y?S=new zS(g,v,b,N,T):S=new LS(g,v,b,N,T);let A=n.runWebGLProgram(S,x,"float32");return m.forEach($=>n.disposeIntermediateTensorInfo($)),A}var t9={kernelName:Ni,backendName:"webgl",kernelFunc:e9},n9=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=dt(t.length),r=dt(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 a9(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],[o,l,c,u]=_.prepareAndValidate(a,r),p=ye({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),d=ye({inputs:{x:a},backend:n,attrs:{shape:[w.sizeFromShape(a.shape)/c,c]}}),h=new n9(i,u,[l,c]),m=n.runWebGLProgram(h,[d,p],d.dtype),f=ye({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),f}var r9={kernelName:tl,backendName:"webgl",kernelFunc:a9},i9=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=dt(this.rank),a=s9(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function s9(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 o9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0],c=_.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=w.sizeFromShape(s.shape),p=[],d=ye({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),h=ye({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),x=n.bufferSync(d),v=D8(x,b,m);return p.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(c.outputShape,v.dtype,v.values)}let f=new i9(d.shape,m),g=n.runWebGLProgram(f,[d,h],d.dtype);p.push(g);let y=ye({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return p.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var l9={kernelName:el,backendName:"webgl",kernelFunc:o9},u9="return float(a > b);",c9=`
|
|
return vec4(greaterThan(a, b));
|
|
`,p9=sn({opSnippet:u9,packedOpSnippet:c9,cpuKernelImpl:R8,dtype:"bool"}),d9={kernelName:nl,backendName:"webgl",kernelFunc:p9},h9="return float(a >= b);",m9=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,f9=sn({opSnippet:h9,packedOpSnippet:m9,dtype:"bool"}),g9={kernelName:qs,backendName:"webgl",kernelFunc:f9};function y9(e){let{inputs:t,backend:n}=e,{input:a}=t;return GS(a,!0,n)}var b9={kernelName:Ud,backendName:"webgl",kernelFunc:y9},x9="return float(!isnan(x) && !isinf(x));",v9=Ke({opSnippet:x9,dtype:"bool"}),w9={kernelName:al,backendName:"webgl",kernelFunc:v9},k9="return float(isinf(x));",I9=Ke({opSnippet:k9,dtype:"bool"}),T9={kernelName:rl,backendName:"webgl",kernelFunc:I9},N9="return float(isnan(x));",S9=Ke({opSnippet:N9,dtype:"bool"}),C9={kernelName:sl,backendName:"webgl",kernelFunc:S9},_9="return float(a < b);",E9=`
|
|
return vec4(lessThan(a, b));
|
|
`,F9=sn({opSnippet:_9,packedOpSnippet:E9,cpuKernelImpl:M8,dtype:"bool"}),A9={kernelName:il,backendName:"webgl",kernelFunc:F9},$9="return float(a <= b);",D9=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,R9=sn({opSnippet:$9,packedOpSnippet:D9,dtype:"bool"}),M9={kernelName:ol,backendName:"webgl",kernelFunc:R9};function P9(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=P8(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var O9={kernelName:Hd,backendName:"webgl",kernelFunc:P9},L9=`if (x < 0.0) return NAN;
|
|
return log(x);`,z9=`
|
|
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;
|
|
`,B9=Ke({opSnippet:L9,packedOpSnippet:z9,cpuKernelImpl:O8}),W9={kernelName:Ys,backendName:"webgl",kernelFunc:B9},V9="return log(1.0 + x);",U9=Ke({opSnippet:V9}),G9={kernelName:ll,backendName:"webgl",kernelFunc:U9},H9="return float(a >= 1.0 && b >= 1.0);",j9=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,q9=sn({opSnippet:H9,packedOpSnippet:j9,dtype:"bool"}),K9={kernelName:ul,backendName:"webgl",kernelFunc:q9},X9="return float(!(x >= 1.0));",Y9=Ke({opSnippet:X9}),J9={kernelName:uc,backendName:"webgl",kernelFunc:Y9},Q9="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));
|
|
`,eJ=sn({opSnippet:Q9,packedOpSnippet:Z9,dtype:"bool"}),tJ={kernelName:cc,backendName:"webgl",kernelFunc:eJ},nJ=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);
|
|
}
|
|
`}},aJ=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);
|
|
}
|
|
`}},rJ=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,c=ee().getBool("WEBGL_PACK_NORMALIZATION")?new aJ(r.shape,s,i,o,l):new nJ(r.shape,s,i,o,l);return n.runWebGLProgram(c,[r],r.dtype)},sJ={kernelName:pc,backendName:"webgl",kernelFunc:rJ},iJ=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);
|
|
}
|
|
`}},oJ=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 iJ(r.shape,o,l,c,u);return n.runWebGLProgram(p,[r,s,i],r.dtype)},lJ={kernelName:jd,backendName:"webgl",kernelFunc:oJ};function uJ(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ye({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=Zi(i,e.dtype,"max",a),l=ye({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function jS(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=n.shouldExecuteOnCPU([r]),h=r;if(p){if(d){let b=n.texData.get(h.dataId).values,x=new Array(o);for(let T=0;T<x.length;T++)x[T]=r.shape[u[T]];let v=Qv(b,r.shape,r.dtype,u,x);h=n.makeTensorInfo(x,r.dtype);let N=n.texData.get(h.dataId);N.values=v}else h=Jm(r,u,n);c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("max",c,o);let[m,f]=_.computeOutAndReduceShapes(h.shape,c),g=m;i&&(g=_.expandShapeToKeepDim(m,l));let y;if(d){let b=n.texData.get(h.dataId).values,x=L8(b,w.sizeFromShape(f),g,r.dtype);y=n.makeTensorInfo(g,r.dtype);let v=n.texData.get(y.dataId);v.values=x}else y=uJ(h,f,g,n);return p&&n.disposeIntermediateTensorInfo(h),y}var cJ={kernelName:Js,backendName:"webgl",kernelFunc:jS},pJ=uS+`
|
|
return max(a, b);
|
|
`,dJ=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Xm+`
|
|
return result;
|
|
`,hJ=sn({opSnippet:pJ,packedOpSnippet:dJ,cpuKernelImpl:z8}),mJ={kernelName:Qs,backendName:"webgl",kernelFunc:hJ};function fJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;fp(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;w.assert(_.eitherStridesOrDilationsAreOne(i,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return Gn({inputs:{x:r},backend:n});let p=new bp(u,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var gJ={kernelName:Zs,backendName:"webgl",kernelFunc:fJ};function yJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,c,l),d=new nw(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var bJ={kernelName:dc,backendName:"webgl",kernelFunc:yJ},xJ=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);
|
|
}
|
|
`}},vJ=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 wJ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new nw(d,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new vJ(d),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var kJ={kernelName:Kd,backendName:"webgl",kernelFunc:wJ};function IJ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;fp([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=_.computePool2DInfo(o.shape,l,c,1,u,p),h=!0,m=new bp(d,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new xJ(d),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var TJ={kernelName:qd,backendName:"webgl",kernelFunc:IJ};function NJ(e,t,n,a){let r=new bp(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new bp(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var SJ={kernelName:Xd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;w.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let c=[1,1];w.assert(_.eitherStridesOrDilationsAreOne(s,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${c}'`);let u=_.computePool2DInfo(a.shape,r,s,c,i),[p,d]=NJ(a,o,u,l);return[p,d]}};function CJ(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ye({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=Zi(i,"float32","mean",a),l=ye({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var _J={kernelName:ei,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=w.parseAxisParam(s,a.shape),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=i.shouldExecuteOnCPU([a]),h=[],m=a;if(p){if(d){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let S=0;S<v.length;S++)v[S]=a.shape[u[S]];let N=Qv(x,a.shape,a.dtype,u,v);m=i.makeTensorInfo(v,a.dtype);let T=i.texData.get(m.dataId);T.values=N}else m=Jm(a,u,i);h.push(m),c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("sum",c,o);let[f,g]=_.computeOutAndReduceShapes(m.shape,c),y=f;r&&(y=_.expandShapeToKeepDim(f,l));let b=CJ(m,g,y,i);for(let x of h)i.disposeIntermediateTensorInfo(x);return b}};function EJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=An({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,r.shape.length)),_.assertAxesAreInnerMostDims("min",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=w.sizeFromShape(h),f=ye({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=Zi(f,f.dtype,"min",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=ye({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=ye({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var FJ={kernelName:ti,backendName:"webgl",kernelFunc:EJ},AJ=uS+`
|
|
return min(a, b);
|
|
`,$J=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Xm+`
|
|
return result;
|
|
`,DJ=sn({opSnippet:AJ,packedOpSnippet:$J,cpuKernelImpl:B8}),RJ={kernelName:ni,backendName:"webgl",kernelFunc:DJ},MJ=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=dt(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}));
|
|
}
|
|
`}},PJ=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=dt(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);
|
|
}
|
|
`}},OJ=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new PJ(a.shape,r,s):new MJ(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},LJ={kernelName:hc,backendName:"webgl",kernelFunc:OJ},zJ=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,BJ=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Xm+`
|
|
return result;
|
|
`,WJ=sn({opSnippet:zJ,packedOpSnippet:BJ}),VJ={kernelName:cl,backendName:"webgl",kernelFunc:WJ},UJ=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)}}},GJ=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,HJ=`
|
|
// 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;
|
|
`,qS=sn({opSnippet:GJ,packedOpSnippet:HJ,checkOutOfBounds:!0}),jJ={kernelName:Vs,backendName:"webgl",kernelFunc:qS},KS="return a - b;",XS=sn({opSnippet:KS,packedOpSnippet:KS,supportsComplex:!0,cpuKernelImpl:K8}),qJ={kernelName:vi,backendName:"webgl",kernelFunc:XS};function YS(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=w.parseAxisParam([s],r.shape),o=jS({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=_.expandShapeToKeepDim(o.shape,i),c=ye({inputs:{x:o},backend:n,attrs:{shape:l}}),u=XS({inputs:{a:r,b:c},backend:n}),p=WS({inputs:{x:u},backend:n}),d=tw({inputs:{x:p},backend:n,attrs:{axis:i,keepDims:!1}}),h=ye({inputs:{x:d},backend:n,attrs:{shape:l}}),m=qS({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 KJ={kernelName:bi,backendName:"webgl",kernelFunc:YS};function XJ(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:YS({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],p=new UJ(c,u,s),d=p.getCustomSetupFunc(i),h=n.runWebGLProgram(p,[l],"int32",d);return o||n.disposeIntermediateTensorInfo(l),h}var YJ={kernelName:Yd,backendName:"webgl",kernelFunc:XJ},JS="return -x;";function JJ(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=V8(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new vu(a.shape,JS):r=new gs(a.shape,JS),n.runWebGLProgram(r,[a],a.dtype)}var QJ={kernelName:pl,backendName:"webgl",kernelFunc:JJ},ZJ=Qa.nonMaxSuppressionV3Impl;function eQ(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}=ZJ(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var tQ={kernelName:hl,backendName:"webgl",kernelFunc:eQ},nQ=Qa.nonMaxSuppressionV4Impl;function aQ(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}=nQ(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var rQ={kernelName:ml,backendName:"webgl",kernelFunc:aQ},sQ=Qa.nonMaxSuppressionV5Impl;function iQ(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}=sQ(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var oQ={kernelName:fl,backendName:"webgl",kernelFunc:iQ},lQ=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)));
|
|
}
|
|
`}},uQ=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=w.sizeFromShape(r.shape),c=new lQ(l,s,i,o),u=ye({inputs:{x:r},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let d=[...r.shape,s],h=ye({inputs:{x:p},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(p),h},cQ={kernelName:ri,backendName:"webgl",kernelFunc:uQ};function nf(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=vp({inputs:{input:a},backend:n}),s=nf({inputs:{x:r},backend:n}),i=tf({inputs:{input:a},backend:n}),o=nf({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 iw({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var pQ={kernelName:Dl,backendName:"webgl",kernelFunc:nf};function QS(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=vp({inputs:{input:a},backend:n}),s=QS({inputs:{x:r},backend:n}),i=tf({inputs:{input:a},backend:n}),o=nf({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 iw({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var dQ={kernelName:gl,backendName:"webgl",kernelFunc:QS};function hQ(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(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=sw({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=AS({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var mQ={kernelName:yl,backendName:"webgl",kernelFunc:hQ},fQ=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=dt(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}));
|
|
}
|
|
}
|
|
`}},gQ=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=dt(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);
|
|
}
|
|
`}},ZS=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a,o=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new gQ(r.shape,s,i):new fQ(r.shape,s,i);return n.runWebGLProgram(o,[r],r.dtype)},yQ={kernelName:si,backendName:"webgl",kernelFunc:ZS},bQ=`
|
|
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);
|
|
`,xQ=`
|
|
// 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));
|
|
`+Xm+`
|
|
return result;
|
|
`,vQ=sn({opSnippet:bQ,packedOpSnippet:xQ}),wQ={kernelName:ii,backendName:"webgl",kernelFunc:vQ};function kQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],c=w.parseAxisParam(s,r.shape),u=c,p=_.getAxesPermutation(u,o),d=r;p!=null&&(d=An({inputs:{x:r},backend:n,attrs:{perm:p}}),u=_.getInnerMostAxes(u.length,o),l.push(d)),_.assertAxesAreInnerMostDims("prod",u,o);let h;if(n.shouldExecuteOnCPU([d])){let m=n.texData.get(d.dataId).values,{outVals:f,outShape:g,outDtype:y}=U8(d.shape,d.dtype,m,u);h=n.makeTensorInfo(g,y,f)}else{let[m,f]=_.computeOutAndReduceShapes(d.shape,u),g=w.sizeFromShape(f),y=ye({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),b=lh(r.dtype),x=Zi(y,b,"prod",n);h=ye({inputs:{x},backend:n,attrs:{shape:m}}),l.push(y),l.push(x)}if(i){l.push(h);let m=_.expandShapeToKeepDim(h.shape,c);h=ye({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var IQ={kernelName:bl,backendName:"webgl",kernelFunc:kQ},e2=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=G8(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},TQ={kernelName:mc,backendName:"webgl",kernelFunc:e2},NQ="return 1.0 / x;",SQ=Ke({opSnippet:NQ}),CQ={kernelName:xl,backendName:"webgl",kernelFunc:SQ},_Q=Ma+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,EQ=`
|
|
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;
|
|
`,FQ=Ke({opSnippet:_Q,packedOpSnippet:EQ}),AQ={kernelName:li,backendName:"webgl",kernelFunc:FQ},$Q=Ma+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,DQ=`
|
|
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;
|
|
`,RQ=Ke({opSnippet:$Q,packedOpSnippet:DQ}),MQ={kernelName:ci,backendName:"webgl",kernelFunc:RQ},PQ=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);
|
|
}
|
|
`}},OQ=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 LQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=ee().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new OQ(r.shape,l,c,s,i):new PQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],"float32")}var zQ={kernelName:ui,backendName:"webgl",kernelFunc:LQ},BQ=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 WQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new BQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var VQ={kernelName:Zd,backendName:"webgl",kernelFunc:WQ},UQ=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 GQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=new UQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],r.dtype)}var HQ={kernelName:fc,backendName:"webgl",kernelFunc:GQ},jQ=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 qQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new jQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var KQ={kernelName:Qd,backendName:"webgl",kernelFunc:qQ},XQ=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=dt(n);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},YQ=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=dt(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 JQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return Gn({inputs:{x:r},backend:n});let l=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new YQ(r.shape,o):new XQ(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var QQ={kernelName:pi,backendName:"webgl",kernelFunc:JQ},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]=_.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);
|
|
}
|
|
`}},eZ={kernelName:Rl,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)}},tZ=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,nZ=Ke({opSnippet:tZ}),aZ={kernelName:di,backendName:"webgl",kernelFunc:nZ},rZ="return inversesqrt(x);",sZ=Ke({opSnippet:rZ,cpuKernelImpl:H8}),iZ={kernelName:hi,backendName:"webgl",kernelFunc:sZ},t2=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=dt(r.length),l=dt(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 oZ(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:c,strides:u,outputSize:p}=_.calculateShapes(s,r,i),d=[p/c,c];if(p===0)return n.makeTensorInfo(i,r.dtype);let h=ye({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=ye({inputs:{x:s},backend:n,attrs:{shape:[l,c]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new t2(l,o,h.shape.length,m.shape.length,u,d),y=n.runWebGLProgram(g,[m,h,f],m.dtype),b=ye({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),b}var lZ={kernelName:wl,backendName:"webgl",kernelFunc:oZ},uZ=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=dt(n);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${a});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function cZ(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new uZ(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],pa(r.dtype,s.dtype))}var pZ={kernelName:kl,backendName:"webgl",kernelFunc:cZ},dZ=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${_.SELU_SCALEALPHA};
|
|
float scale = ${_.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,hZ=Ke({opSnippet:dZ}),mZ={kernelName:Il,backendName:"webgl",kernelFunc:hZ},fZ="return 1.0 / (1.0 + exp(-1.0 * x));",gZ=Ke({opSnippet:fZ}),yZ={kernelName:fi,backendName:"webgl",kernelFunc:gZ},bZ=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,xZ=Ke({opSnippet:bZ}),vZ={kernelName:Sl,backendName:"webgl",kernelFunc:xZ},wZ=mS+`
|
|
return sin(x);
|
|
`,kZ=Ke({opSnippet:wZ}),IZ={kernelName:mi,backendName:"webgl",kernelFunc:kZ},TZ=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,NZ=Ke({opSnippet:TZ}),SZ={kernelName:Nl,backendName:"webgl",kernelFunc:NZ},CZ=`
|
|
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;
|
|
`,_Z=Ke({opSnippet:CZ}),EZ={kernelName:Cl,backendName:"webgl",kernelFunc:_Z},FZ=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;w.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=ZS({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=_.getReshaped(u.shape,s,o,!1),d=_.getPermuted(p.length,s.length,!1),h=_.getReshapedPermuted(u.shape,s,o,!1),m=ye({inputs:{x:u},backend:n,attrs:{shape:p}}),f=An({inputs:{x:m},backend:n,attrs:{perm:d}}),g=ye({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},AZ={kernelName:gc,backendName:"webgl",kernelFunc:FZ};function $Z(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:c,strides:u,outputSize:p}=_.calculateShapes(s,r,o),d=!1,h=new t2(c,l,r.shape.length,s.shape.length,u,[p,1],d),m=n.runWebGLProgram(h,[s,r,i],s.dtype),f=ye({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),f}var DZ={kernelName:eh,backendName:"webgl",kernelFunc:$Z};function RZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=_.prepareSplitSize(r,s,o),c=r.shape.length,u=new Array(c).fill(0),p=r.shape.slice();return l.map(d=>{let h=[...p];h[o]=d;let m=xp({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[o]+=d,m})}var MZ={kernelName:_l,backendName:"webgl",kernelFunc:RZ},PZ="return sqrt(x);",OZ=Ke({opSnippet:PZ}),LZ={kernelName:gi,backendName:"webgl",kernelFunc:OZ},zZ="return x * x;",BZ=Ke({opSnippet:zZ}),WZ={kernelName:yc,backendName:"webgl",kernelFunc:BZ},n2="return (a - b) * (a - b);",VZ=sn({opSnippet:n2,packedOpSnippet:n2}),UZ={kernelName:xi,backendName:"webgl",kernelFunc:VZ};function GZ({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Ma+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new gs(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var HZ={kernelName:Kr,backendName:"webgl",kernelFunc:GZ},jZ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=dt(n.length),s=dt(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 qZ(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),x=ye({inputs:{x:r},backend:n,attrs:{shape:y}}),v;if(h){let T=xp({inputs:{x},backend:n,attrs:{begin:m,size:g}});v=ye({inputs:{x:T},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(T)}else if(b.some(T=>T===0))v=n.makeTensorInfo(b,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let T=n.texData.get(x.dataId).values,S=Le(x.shape,x.dtype,T),A=q8(b,S,f,m);v=n.makeTensorInfo(b,x.dtype,A.values)}else{let T=new jZ(m,f,b);v=n.runWebGLProgram(T,[x],x.dtype)}let N=ye({inputs:{x:v},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),N}var KZ={kernelName:El,backendName:"webgl",kernelFunc:qZ},XZ="return tan(x);",YZ=Ke({opSnippet:XZ}),JZ={kernelName:Fl,backendName:"webgl",kernelFunc:YZ},QZ=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,ZZ=Ke({opSnippet:QZ}),eee={kernelName:wi,backendName:"webgl",kernelFunc:ZZ},nee=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=dt(this.rank),r=tee(e);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function tee(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 a2(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=>w.decodeString(u)),l=Le(r.shape,r.dtype,o),c=X8(l,s);return n.makeTensorInfo(c.shape,c.dtype,c.values)}let i=new nee(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var aee={kernelName:qr,backendName:"webgl",kernelFunc:a2};function ree(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=n.readSync(r.dataId),[l,c]=Y8(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 see={kernelName:Al,backendName:"webgl",kernelFunc:ree};function iee(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;fp(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:c}=J8(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var oee={kernelName:th,backendName:"webgl",kernelFunc:iee};function lee(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=xp({inputs:{x:i},backend:n,attrs:{begin:d,size:h}}),y=ye({inputs:{x:g},backend:n,attrs:{shape:c}});m[f]=y,p.push(g)}return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var uee={kernelName:$l,backendName:"webgl",kernelFunc:lee},cee=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 pee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],c=0,u=_.getAxesPermutation([c],o),p=r;u!=null&&(p=An({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(p),c=_.getInnerMostAxes(1,o)[0]);let d=_.segment_util.computeOutShape(p.shape,c,i),h=w.sizeFromShape([p.shape[c]]),m=ye({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=lh(r.dtype),g=(v,N,T,S,A)=>{let $=v.shape[0],R=v.shape[1],B=_.segment_util.segOpComputeOptimalWindowSize(R,A),V={windowSize:B,inSize:R,batchSize:$,numSegments:A},W=new cee(V,N),G=n.compileAndRun(W,[v,T],S);if(l.push(G),G.shape[1]===A)return G;let H=e2({backend:n,attrs:{start:0,stop:A,step:1,dtype:"float32"}}),X=a2({inputs:{x:H},backend:n,attrs:{reps:[R/B]}});return l.push(H),l.push(X),g(G,N,X,S,A)},y=g(m,"unsortedSegmentSum",s,f,i),b=ye({inputs:{x:y},backend:n,attrs:{shape:d}}),x=b;if(u!=null){l.push(b);let v=_.getUndoAxesPermutation(u);x=An({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var dee={kernelName:bc,backendName:"webgl",kernelFunc:pee},hee=[sJ,lJ,qK,XK,QK,tX,aX,iX,lX,cX,mX,gX,xX,kX,EX,NX,$X,PX,RX,BX,VX,GX,KX,tY,aY,uY,pY,fY,bY,_K,kY,$Y,RY,SY,LY,BY,PY,UY,jY,XY,JY,ZY,n7,l7,c7,r7,h7,g7,v7,T7,_7,A7,$7,D7,M7,O7,z7,W7,U7,q7,J7,Z7,t9,r9,l9,d9,g9,CK,b9,wY,w9,T9,C9,FK,A9,M9,O9,G9,W9,K9,J9,tJ,cJ,bJ,gJ,kJ,TJ,SJ,mJ,_J,FJ,RJ,LJ,VJ,YJ,MK,QJ,tQ,rQ,oQ,sY,cQ,dQ,mQ,yQ,wQ,$K,IQ,TQ,iY,jJ,CQ,MQ,AQ,OK,zQ,VQ,HQ,KQ,QQ,eZ,aZ,iZ,lZ,pZ,mZ,yZ,vZ,IZ,SZ,ZX,KJ,EZ,AZ,DZ,MZ,LZ,WZ,UZ,HZ,KZ,qJ,GK,JZ,eee,aee,see,HK,oee,uee,dee,pQ];for(let e of hee)vc(e);var mee="3.2.0",fee={"tfjs-core":ik,"tfjs-backend-cpu":jU,"tfjs-backend-webgl":SK,"tfjs-data":DT,"tfjs-layers":Im,"tfjs-converter":CT,tfjs:mee},Hn;(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"})(Hn||(Hn={}));var wp;(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"})(wp||(wp={}));var r2;function gee(e){r2=e.wasm.cwrap(Ii,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function yee(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 A=n.dataIdMap.get(i.dataId);if(A.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${A.shape.length}.`);m=A.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=wp[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],x=r.shape[0],v=n.makeOutput([x,y,b],r.dtype),N=n.dataIdMap.get(v.dataId).id,T=new Uint8Array(new Int32Array(r.shape).buffer),S=new Uint8Array(new Int32Array(s.shape).buffer);return r2(d,T,r.shape.length,h,S,s.shape.length,l,c,g,m,f,p||0,N),v}var bee={kernelName:Ii,backendName:"wasm",setupFunc:gee,kernelFunc:yee};function $n(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 w.sizeFromShape(l.shape)===0||t(o,c),l}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var xee=$n(Po);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=_.assertAndGetBroadcastShape(c.shape,u.shape),f=o.makeOutput(m,h);if(w.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,x=()=>a(p,g,c.shape.length,d,y,u.shape.length,Hn[c.dtype],b);if(t&&c.dtype==="float32")return x(),f;let v=_.getBroadcastDims(c.shape,m),N=_.getBroadcastDims(u.shape,m),T=v.every((A,$)=>A===$),S=N.every((A,$)=>A===$);if(T&&S)return x(),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 vee=!0,wee=yn(Hr,vee),s2;function kee(e){s2=e.wasm.cwrap(As,null,["array","number","number","number"])}function Iee(e){let{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(w.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 s2(s,r.length,Hn[a.dtype],i),a}var Tee={kernelName:As,backendName:"wasm",setupFunc:kee,kernelFunc:Iee};function af(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 Nee={kernelName:Ks,backendName:"wasm",kernelFunc:af},i2;function See(e){i2=e.wasm.cwrap(ki,null,["number","array","number","number","number","array","number"])}function rf(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=_ee(t.x.shape,a.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=Cee(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=af({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 i2(u,h,l.shape.length,Hn[l.dtype],p,d,s.length),c}function Cee(e,t){let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];return n}function _ee(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 Eee={kernelName:ki,backendName:"wasm",kernelFunc:rf,setupFunc:See};function Tu(e,t,n){let a=e.shape,r=e.shape.length,s=w.parseAxisParam(t,a),i=s,o=_.getAxesPermutation(i,r),l=null,c=!1;if(o!=null){let u=new Array(r);for(let d=0;d<u.length;d++)u[d]=a[o[d]];i=_.getInnerMostAxes(i.length,r),l=rf({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 o2;function Fee(e){o2=e.wasm.cwrap($s,null,["number","number","number","number","number"])}function Aee(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}=Tu(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=w.sizeFromShape(h.shape),g=l.shape[u[0]];return o2(o,Hn[l.dtype],f,g,m),p&&t.disposeData(c.dataId),h}var $ee={kernelName:$s,backendName:"wasm",kernelFunc:Aee,setupFunc:Fee},l2;function Dee(e){l2=e.wasm.cwrap(Ds,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Ree(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=n,u=_.computePool2DInfo(r.shape,i,o,1,l,c),p=u.filterHeight,d=u.filterWidth,h=u.padInfo.top,m=u.padInfo.right,f=u.padInfo.bottom,g=u.padInfo.left,y=u.strideHeight,b=u.strideWidth,x=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 v=a.makeOutput(u.outShape,"float32"),N=a.dataIdMap.get(v.dataId).id;return l2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,x,N),v}var Mee={kernelName:Ds,backendName:"wasm",setupFunc:Dee,kernelFunc:Ree};function Pa(e){let{inputs:t,attrs:n}=e,{x:a}=t,{shape:r}=n,s=w.sizeFromShape(a.shape),i=w.inferFromImplicitShape(r,s);return w.assert(s===w.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var Pee={kernelName:vl,backendName:"wasm",kernelFunc:Pa},u2;function Oee(e){u2=e.wasm.cwrap(Rs,null,["number","array","number","number","array","number","number","number","number"])}function Lee(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=w.sizeFromShape(m),y=w.sizeFromShape(f),b=g===y||g===1||y===1;w.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 x=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([d,h]);w.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 v=i?[g,u,d]:[g,d,u],N=o?[y,h,p]:[y,p,h],T=Pa({inputs:{x:r},backend:n,attrs:{shape:v}}),S=Pa({inputs:{x:s},backend:n,attrs:{shape:N}}),A=n.dataIdMap.get(T.dataId).id,$=n.dataIdMap.get(S.dataId).id,R=i?T.shape[2]:T.shape[1],B=o?S.shape[1]:S.shape[2],V=Math.max(g,y),W=n.makeOutput([V,R,B],T.dtype),G=n.dataIdMap.get(W.dataId).id,H=new Uint8Array(new Int32Array(T.shape).buffer),X=new Uint8Array(new Int32Array(S.shape).buffer);return u2(A,H,T.shape.length,$,X,S.shape.length,i,o,G),n.disposeData(T.dataId),n.disposeData(S.dataId),W.shape=x,W}var zee={kernelName:Rs,backendName:"wasm",setupFunc:Oee,kernelFunc:Lee};function sf(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 Bee={kernelName:Ms,backendName:"wasm",kernelFunc:sf},Wee=$n(Ps),c2;function Vee(e){c2=e.wasm.cwrap(jr,null,["number","number","number","number"])}function Uee(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 c2(o,s,i,c),l}var Gee={kernelName:jr,backendName:"wasm",setupFunc:Vee,kernelFunc:Uee};function p2(e){let{inputs:t,backend:n}=e,a=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=_.computeOutShape(t.map(h=>h.shape),a),s=t.filter(h=>w.sizeFromShape(h.shape)>0);if(s.length===1)return af({inputs:{x:s[0]},backend:n});let i=n.makeOutput(r,t[0].dtype);if(w.sizeFromShape(r)===0)return i;let o=s.map(h=>h.shape);if(_.assertParamsConsistent(o,a),s[0].dtype==="string"){let h=s.map(x=>{let v=w.sizeFromShape(x.shape.slice(a));return Pa({inputs:{x},backend:n,attrs:{shape:[-1,v]}})}),m=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));r=_.computeOutShape(h.map(x=>x.shape),1);let f=h[0].shape[0]===1,g=Fv(m,r,t[0].dtype,f),y=_.computeOutShape(s.map(x=>x.shape),a);i.shape=y;let b=n.dataIdMap.get(i.dataId);return b.stringBytes=_.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),i}let l=w.sizeFromShape(s[0].shape.slice(0,a)),c=0,u=s.map(h=>{let m=w.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 Hee={kernelName:Go,backendName:"wasm",kernelFunc:p2},d2;function jee(e){d2=e.wasm.cwrap(Os,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function qee(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:p,dataFormat:d}=n,h=_.convertConv2DDataFormat(d),m=_.computeConv2DInfo(r.shape,s.shape,l,c,u,p,!1,h),f=m.filterHeight,g=m.filterWidth,y=m.padInfo.top,b=m.padInfo.right,x=m.padInfo.bottom,v=m.padInfo.left,N=m.dilationHeight,T=m.dilationWidth,S=m.strideHeight,A=m.strideWidth,$=m.inChannels,R=m.outChannels,B=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let V=a.makeOutput(m.outShape,"float32"),W=a.dataIdMap.get(V.dataId).id;return d2(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,y,b,x,v,B,N,T,S,A,$,R,W),V}var Kee={kernelName:Os,backendName:"wasm",setupFunc:jee,kernelFunc:qee},h2;function Xee(e){h2=e.wasm.cwrap(Ls,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 Yee(e){let{backend:t,inputs:n,attrs:a}=e,{dy:r,filter:s}=n,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,inputShape:u}=a,p=1,d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(u,s.shape,i,p,o,c,!1,d),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:y,inHeight:b,inWidth:x,outChannels:v,outHeight:N,outWidth:T,strideHeight:S,strideWidth:A}=h,$=f-1-h.padInfo.top,R=g-1-h.padInfo.left,B=h.dataFormat==="channelsLast",V=w.computeStrides(h.inShape),W=w.computeStrides(r.shape),[G,H,X]=w.computeStrides(s.shape),q=V[0],te=B?V[1]:V[2],Q=B?V[2]:1,se=B?1:V[1],ne=W[0],ie=B?W[1]:W[2],Z=B?W[2]:1,de=B?1:W[1],oe=t.makeOutput(h.inShape,"float32"),ge=t.dataIdMap.get(oe.dataId).id,fe=t.dataIdMap.get(r.dataId).id,we=t.dataIdMap.get(s.dataId).id;return h2(fe,we,m,f,g,b,x,y,N,T,v,S,A,$,R,G,H,X,q,te,Q,se,ne,ie,Z,de,ge),oe}var Jee={kernelName:Ls,backendName:"wasm",setupFunc:Xee,kernelFunc:Yee},Qee=$n(zs),ow;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(ow||(ow={}));var m2;function Zee(e){m2=e.wasm.cwrap(jo,null,["number","number","number","number","array","number","number","number","number","number"])}function ete(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=sf({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,x=t.makeOutput(h,"float32"),v=t.dataIdMap.get(x.dataId).id,N=new Uint8Array(new Int32Array(o.shape).buffer);return m2(g,y,b,u,N,p,d,ow[r],s,v),f!=null&&t.disposeData(f.dataId),x}var tte={kernelName:jo,backendName:"wasm",setupFunc:Zee,kernelFunc:ete},f2;function nte(e){f2=e.wasm.cwrap(Bs,null,["number","number","number","number","number","number"])}function ate(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;w.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=_.getAxesPermutation([s],l),u=r;c!==null&&(u=rf({inputs:{x:r},attrs:{perm:c},backend:n}));let p=_.getInnerMostAxes(1,l)[0];_.assertAxesAreInnerMostDims("cumsum",[p],l);let d=n.makeOutput(u.shape,u.dtype),h=u.shape[p],m=n.dataIdMap.get(u.dataId).id,f=n.dataIdMap.get(d.dataId).id;f2(m,i?1:0,o?1:0,h,f,Hn[r.dtype]);let g=d;if(c!==null){let y=_.getUndoAxesPermutation(c);g=rf({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(u.dataId),n.disposeData(d.dataId)}return g}var rte={kernelName:Bs,backendName:"wasm",setupFunc:nte,kernelFunc:ate},g2;function ste(e){g2=e.wasm.cwrap(qo,null,["number","number","number","array","number","array","array","number","number"])}function ite(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{blockSize:s,dataFormat:i}=a;w.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(w.computeStrides(r.shape)).buffer),b=new Uint8Array(new Int32Array(m).buffer),x=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer),v=t.dataIdMap.get(f.dataId).id;return g2(g,s,i==="NHWC"?1:0,y,r.shape.length-1,b,x,m.length,v),f}var ote={kernelName:qo,backendName:"wasm",setupFunc:ste,kernelFunc:ite},y2;function lte(e){y2=e.wasm.cwrap(Ws,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ute(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:p}=n,d=c==null?[1,1]:c,h=_.computeConv2DInfo(r.shape,s.shape,l,d,u,p,!0),m=h.filterHeight,f=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,b=h.padInfo.bottom,x=h.padInfo.left,v=h.dilationHeight,N=h.dilationWidth,T=h.strideHeight,S=h.strideWidth,A=h.inChannels,$=h.outChannels,R=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let B=a.makeOutput(h.outShape,"float32"),V=a.dataIdMap.get(B.dataId).id;return y2(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,y,b,x,R,v,N,T,S,A,$,V),B}var cte={kernelName:Ws,backendName:"wasm",setupFunc:lte,kernelFunc:ute},pte=!1,dte=yn(Yo,pte,"bool"),hte=$n(Us);function lw(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&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Pa({inputs:{x:r},backend:a,attrs:{shape:o}})}var mte={kernelName:Jo,backendName:"wasm",kernelFunc:lw};function fte(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 gte={kernelName:lc,backendName:"wasm",kernelFunc:fte},b2;function yte(e){b2=e.wasm.cwrap(Zo,null,["number","number","number","number","number","number"])}function bte(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 b2(s,o,l,c,u,i),r}var xte={kernelName:Zo,backendName:"wasm",kernelFunc:bte,setupFunc:yte},vte=$n(Gs),wte=!1,kte=yn(Hs,wte),x2;function Ite(e){x2=e.wasm.cwrap(js,null,["number","number","number","number","number","number","number"])}function Tte(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(w.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return x2(u,p,d,h,m,r,g),f}var Nte={kernelName:js,backendName:"wasm",setupFunc:Ite,kernelFunc:Tte},v2;function Ste(e){v2=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 Cte(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=n,f=_.computeConv2DInfo(r.shape,s.shape,l,u,c,d),g=wp[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,x=f.outChannels,v=0;if(i!=null){let Z=a.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${Z.shape}) does not match the number of output channels (${x})`);v=Z.id}let N=f.filterHeight,T=f.filterWidth,S=f.padInfo.top,A=f.padInfo.right,$=f.padInfo.bottom,R=f.padInfo.left,B=f.dilationHeight,V=f.dilationWidth,W=f.strideHeight,G=f.strideWidth,H=f.inChannels,X=f.padInfo.type==="SAME"?1:0,q=f.batchSize,te=f.inHeight,Q=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let se=a.makeOutput(f.outShape,"float32"),ne=a.dataIdMap.get(se.dataId).id,ie=o==null?0:a.dataIdMap.get(o.dataId).id;return v2(y,q,te,Q,b,N,T,v,S,A,$,R,X,B,V,W,G,H,x,g,ie,m||0,ne),se}var _te={kernelName:Ti,backendName:"wasm",setupFunc:Ste,kernelFunc:Cte},w2;function Ete(e){w2=e.wasm.cwrap(Ni,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 Fte(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=n,f=_.computeConv2DInfo(r.shape,s.shape,l,u,c,d,!0),g=wp[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,x=f.outChannels,v=0;if(i!=null){let Z=a.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${Z.shape}) does not match the number of output channels (${x})`);v=Z.id}let N=f.filterHeight,T=f.filterWidth,S=f.padInfo.top,A=f.padInfo.right,$=f.padInfo.bottom,R=f.padInfo.left,B=f.dilationHeight,V=f.dilationWidth,W=f.strideHeight,G=f.strideWidth,H=f.inChannels,X=f.padInfo.type==="SAME"?1:0,q=f.batchSize,te=f.inHeight,Q=f.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let se=a.makeOutput(f.outShape,"float32"),ne=a.dataIdMap.get(se.dataId).id,ie=o==null?0:a.dataIdMap.get(o.dataId).id;return w2(y,q,te,Q,b,N,T,v,S,A,$,R,X,B,V,W,G,H,x,g,ie,m||0,ne),se}var Ate={kernelName:Ni,backendName:"wasm",setupFunc:Ete,kernelFunc:Fte},k2;function $te(e){k2=e.wasm.cwrap(tl,null,["number","number","number","number","number","number","array","number"])}function Dte(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=_y.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 k2(d,Hn[a.dtype],h,i,p,o,m,f),c}var Rte={kernelName:tl,backendName:"wasm",setupFunc:$te,kernelFunc:Dte},I2;function Mte(e){I2=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Pte(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,indices:s}=n,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0],c=_.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=Pa({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),p=w.sizeFromShape(s.shape),d=Pa({inputs:{x:s},attrs:{shape:[c.batchSize,p/c.batchSize]},backend:t}),h=[c.batchSize,c.outerSize,p/c.batchSize,c.sliceSize],m=t.makeOutput(h,r.dtype);if(w.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,x=new Uint8Array(new Int32Array(w.computeStrides(u.shape)).buffer),v=new Uint8Array(new Int32Array(w.computeStrides(h)).buffer);return I2(g,Hn[r.dtype],x,f,y,c.batchSize,v,b),t.disposeData(u.dataId),t.disposeData(d.dataId),m.shape=c.outputShape,m}var Ote={kernelName:el,backendName:"wasm",setupFunc:Mte,kernelFunc:Pte},Lte=!1,zte=yn(nl,Lte,"bool"),Bte=!1,Wte=yn(qs,Bte,"bool"),T2;function Vte(e){T2=e.wasm.cwrap(Xs,null,["number","number","number"])}function Ute(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(w.sizeFromShape(t.shape)!==0){let i=a.dataIdMap.get(s.dataId).id;T2(r,n,i)}return s}var Gte={kernelName:Xs,backendName:"wasm",setupFunc:Vte,kernelFunc:Ute},Hte=!1,jte=yn(il,Hte,"bool"),qte=!1,Kte=yn(ol,qte,"bool"),Xte=$n(Ys),Yte=!1,Jte=yn(ul,Yte,"bool"),N2;function Qte(e){N2=e.wasm.cwrap(Js,null,["number, number, number"])}function Zte(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}=Tu(i,r,t);if(d){let b=t.dataIdMap.get(c.dataId).id;l=c,o=b}let h=l.shape.length;_.assertAxesAreInnerMostDims("max",u,h);let[m,f]=_.computeOutAndReduceShapes(l.shape,u),g=w.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;N2(o,g,b)}if(d&&t.disposeData(c.dataId),s){let b=_.expandShapeToKeepDim(y.shape,p);y.shape=b}return y}var ene={kernelName:Js,backendName:"wasm",setupFunc:Qte,kernelFunc:Zte},tne=!1,nne=yn(Qs,tne),S2;function ane(e){S2=e.wasm.cwrap(Zs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function rne(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:c}=n,u=_.computePool2DInfo(r.shape,i,o,1,l,c),p=u.filterHeight,d=u.filterWidth,h=u.padInfo.top,m=u.padInfo.right,f=u.padInfo.bottom,g=u.padInfo.left,y=u.dilationHeight,b=u.dilationWidth,x=u.strideHeight,v=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 S=a.makeOutput(u.outShape,"float32"),A=a.dataIdMap.get(S.dataId).id;return S2(s,r.shape[0],r.shape[1],r.shape[2],p,d,h,m,f,g,y,b,x,v,N,T,A),S}var sne={kernelName:Zs,backendName:"wasm",setupFunc:ane,kernelFunc:rne},C2;function ine(e){C2=e.wasm.cwrap(ei,null,["number, number, number"])}function one(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}=Tu(i,r,t),m=p;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(c=u,l=v,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("mean",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=w.sizeFromShape(g),b=c;c.dtype!=="float32"&&(b=sf({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(b.dataId).id);let x=t.makeOutput(f,"float32");if(w.sizeFromShape(c.shape)!==0){let v=t.dataIdMap.get(x.dataId).id;C2(l,y,v)}if(h&&t.disposeData(u.dataId),s){let v=_.expandShapeToKeepDim(x.shape,d);x.shape=v}return c.dtype!=="float32"&&t.disposeData(b.dataId),x}var lne={kernelName:ei,backendName:"wasm",setupFunc:ine,kernelFunc:one},_2;function une(e){_2=e.wasm.cwrap(ti,null,["number, number, number"])}function cne(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}=Tu(i,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(c=u,l=x)}let m=c.shape.length;_.assertAxesAreInnerMostDims("min",p,m);let[f,g]=_.computeOutAndReduceShapes(c.shape,p),y=w.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(w.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;_2(l,y,x)}if(h&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,d);b.shape=x}return b}var pne={kernelName:ti,backendName:"wasm",setupFunc:une,kernelFunc:cne},dne=!1,hne=yn(ni,dne),mne=!0,fne=yn(ai,mne),gne=$n(pl);function uw(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 E2;function yne(e){E2=e.wasm.cwrap(hl,"number",["number","number","number","number","number"])}function bne(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=E2(c,u,s,r,i),{pSelectedIndices:d,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=uw(t,p);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",d)}var xne={kernelName:hl,backendName:"wasm",setupFunc:yne,kernelFunc:bne},F2;function vne(e){F2=e.wasm.cwrap(ml,"number",["number","number","number","number","number","bool"])}function wne(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=F2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=uw(t,d);t.wasm._free(f);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([],"int32",g);return[y,b]}var kne={kernelName:ml,backendName:"wasm",setupFunc:vne,kernelFunc:wne},A2;function Ine(e){A2=e.wasm.cwrap(fl,"number",["number","number","number","number","number","number"])}function Tne(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=A2(u,p,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=uw(t,d);t.wasm._free(g);let y=t.makeOutput([m],"int32",h),b=t.makeOutput([m],"float32",f);return[y,b]}var Nne={kernelName:fl,backendName:"wasm",setupFunc:Ine,kernelFunc:Tne},Sne=!1,Cne=yn(dl,Sne,"bool"),$2;function _ne(e){$2=e.wasm.cwrap(ri,null,["number","number","number","number","number"])}function Ene(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 $2(u,s,i,o,c),l}var Fne={kernelName:ri,backendName:"wasm",setupFunc:_ne,kernelFunc:Ene};function Ane(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var $ne={kernelName:gl,backendName:"wasm",kernelFunc:Ane};function Dne(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return lw({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=lw({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=p2({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeData(u.dataId)),c}var Rne={kernelName:yl,backendName:"wasm",kernelFunc:Dne},D2;function Mne(e){D2=e.wasm.cwrap(si,null,["number","array","number","number","array","array","number","number"])}function Pne(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 D2(i,c,t.shape.length,Hn[t.dtype],d,h,r,l),o}var One={kernelName:si,backendName:"wasm",kernelFunc:Pne,setupFunc:Mne},Lne=!1,zne=yn(ii,Lne),R2;function Bne(e){R2=e.wasm.cwrap(oi,null,["number","number","number"])}function Wne(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 R2(s,i,l),o}var Vne={kernelName:oi,backendName:"wasm",setupFunc:Bne,kernelFunc:Wne},M2;function Une(e){M2=e.wasm.cwrap(bl,null,["number","number","number","number"])}function Gne(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}=Tu(i,r,t),m=p;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(c=u,l=x,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("prod",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=w.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(w.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;M2(l,y,Hn[b.dtype],x)}if(h&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,d);b.shape=x}return b}var Hne={kernelName:bl,backendName:"wasm",setupFunc:Une,kernelFunc:Gne},jne=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=Dv(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},qne={kernelName:mc,backendName:"wasm",kernelFunc:jne},Kne=!0,Xne=yn(Vs,Kne),Yne=$n(li),Jne=$n(ci),P2;function Qne(e){P2=e.wasm.cwrap(ui,null,["number","number","number","number","number","number","number","number","number","number"])}function Zne(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=sf({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let y=f.id,b=t.makeOutput(m,"float32");if(w.sizeFromShape(r.shape)===0)return b;let x=t.dataIdMap.get(b.dataId).id;return P2(y,u,p,d,h,l,c,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),b}var eae={kernelName:ui,backendName:"wasm",setupFunc:Qne,kernelFunc:Zne},O2;function tae(e){O2=e.wasm.cwrap(pi,null,["number","array","number","array","number","number"])}function nae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=w.parseAxisParam(s,r.shape);if(r.shape.length===0)return af({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);O2(l,u,i.length,p,r.shape.length,c);let d=Pa({inputs:{x:o},attrs:{shape:r.shape},backend:n});return n.disposeData(o.dataId),d}var aae={kernelName:pi,backendName:"wasm",kernelFunc:nae,setupFunc:tae},L2;function rae(e){L2=e.wasm.cwrap(Rl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function sae(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{radians:s,fillValue:i,center:o}=a,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[p,d,h,m]=r.shape,[f,g]=_.getImageCenter(o,d,h),y=i===0,b=255,x=typeof i=="number"?[i,i,i,y?0:b]:[...i,b],v=new Uint8Array(new Int32Array(x).buffer);return L2(c,p,d,h,m,s,f,g,v,x.length,u),l}var iae={kernelName:Rl,backendName:"wasm",kernelFunc:sae,setupFunc:rae},oae=$n(di),lae=$n(hi),z2;function uae(e){z2=e.wasm.cwrap(wl,null,["number","number","number","number","number","number","array","number","number"])}function cae(e){let{backend:t,inputs:n,attrs:a}=e,{indices:r,updates:s}=n,{shape:i}=a,o=t.makeOutput(i,s.dtype);if(w.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:c,sliceSize:u,strides:p,outputSize:d}=Ey.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,Hn[s.dtype],l,c,u,f,d,g),o}var pae={kernelName:wl,backendName:"wasm",setupFunc:uae,kernelFunc:cae},B2;function dae(e){B2=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function hae(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:w.sizeFromShape(r.shape.slice(1));return B2(i,o,l,h,u),c}var mae={kernelName:kl,backendName:"wasm",kernelFunc:hae,setupFunc:dae},W2;function fae(e){W2=e.wasm.cwrap(fi,null,["number","number"])}function gae(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 w.sizeFromShape(r.shape)===0||W2(a,s),r}var yae={kernelName:"Sigmoid",backendName:"wasm",setupFunc:fae,kernelFunc:gae},bae=$n(mi);function of(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=w.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+w.sizeFromShape(i)):r.typedArrayFromHeap(c).set(l.subarray(m,m+w.sizeFromShape(i))),c}if(t.dtype==="string"){let m=zm(l,s,i,t.shape,t.dtype);return p.stringBytes=m,c}let d=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)xae(l,u[0],d,s,i);else if(h===3)vae(l,u[0],u[1],d,s,i);else if(h===4)wae(l,u[0],u[1],u[2],d,s,i);else{let m=zm(l,s,i,t.shape,t.dtype);d.set(m)}return c}function xae(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 vae(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 wae(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 kae={kernelName:Tl,backendName:"wasm",kernelFunc:of},V2;function Iae(e){V2=e.wasm.cwrap(bi,null,["number","number","number","number"])}function Tae(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=w.sizeFromShape(n.shape)/o;return w.sizeFromShape(s.shape)===0||V2(r,i,o,l),s}var Nae={kernelName:bi,backendName:"wasm",setupFunc:Iae,kernelFunc:Tae};function Sae(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,r.shape)[0],l=_.prepareSplitSize(r,s,o),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(p=>{let d=[...u];d[o]=p;let h=of({inputs:{x:r},attrs:{begin:c,size:d},backend:a});return c[o]+=p,h})}var Cae={kernelName:_l,backendName:"wasm",kernelFunc:Sae},_ae=$n(gi),Eae=$n(yc),Fae=!0,Aae=yn(xi,Fae),U2;function $ae(e){U2=e.wasm.cwrap(Kr,null,["number","number","number"])}function Dae(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 U2(i,r,l),o}var Rae={kernelName:Kr,backendName:"wasm",setupFunc:$ae,kernelFunc:Dae},G2;function Mae(e){G2=e.wasm.cwrap(El,null,["number","array","number","array","array","array","array","array","number","number"])}function Pae(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{begin:s,end:i,strides:o}=a;o==null&&(o=new Array(s.length));let{beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:d}=a,h=_.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let m=r.shape.length-s.length,f=_.slice_util.maskToAxes(p),g=r.shape.slice();f.forEach(R=>{s[R]=0,i[R]=1,g.splice(R,0,1)});let y=Pa({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:b,end:x,strides:v}=_.slice_util.getNormalizedAxes(y.shape,h,m,s,i,o,l,c,u);s=b,i=x,o=v;let N=_.slice_util.maskToAxes(d);N.forEach(R=>{i[R]=s[R]+1,o[R]=1});let T=_.slice_util.computeOutShape(s,i,o),S=T.filter((R,B)=>N.indexOf(B)===-1);if(o.every(R=>R===1)){let R=of({inputs:{x:r},attrs:{begin:s,size:T},backend:t});t.disposeData(y.dataId);let B=Pa({inputs:{x:R},attrs:{shape:S},backend:t});return t.disposeData(R.dataId),B}let A=t.makeOutput(S,"float32");if(!S.some(R=>R===0)){let R=t.dataIdMap.get(y.dataId).id,B=new Uint8Array(new Int32Array(w.computeStrides(y.shape)).buffer),V=new Uint8Array(new Int32Array(s).buffer),W=new Uint8Array(new Int32Array(i).buffer),G=new Uint8Array(new Int32Array(o).buffer),H=new Uint8Array(new Int32Array(S).buffer),X=new Uint8Array(new Int32Array(w.computeStrides(S)).buffer),q=t.dataIdMap.get(A.dataId).id;G2(R,B,y.shape.length,V,W,G,H,X,S.length,q)}t.disposeData(y.dataId);let $=Pa({inputs:{x:A},attrs:{shape:S},backend:t});return t.disposeData(A.dataId),$}var Oae={kernelName:El,backendName:"wasm",setupFunc:Mae,kernelFunc:Pae},Lae=!0,zae=yn(vi,Lae),H2;function Bae(e){H2=e.wasm.cwrap(yi,null,["number, number, number"])}function Wae(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}=Tu(i,r,t),m=p;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(c=u,l=x,m=_.getInnerMostAxes(m.length,c.shape.length))}_.assertAxesAreInnerMostDims("sum",m,c.shape.length);let[f,g]=_.computeOutAndReduceShapes(c.shape,m),y=w.sizeFromShape(g),b=t.makeOutput(f,c.dtype);if(w.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;H2(l,y,x)}if(h&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,d);b.shape=x}return b}var Vae={kernelName:yi,backendName:"wasm",setupFunc:Bae,kernelFunc:Wae},Uae=$n(wi),j2;function Gae(e){j2=e.wasm.cwrap(qr,null,["number","array","number","array","number","number"])}function Hae(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 j2(s,l,r.shape.length,c,o.length,Hn[u.dtype],p),u}var jae={kernelName:qr,backendName:"wasm",setupFunc:Gae,kernelFunc:Hae},q2;function qae(e){q2=e.wasm.cwrap(Al,null,["number","array","number","number","number","bool","number","number"])}var Kae=({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 q2(i,o,a.shape.length,Hn[a.dtype],r,s,u,d),[c,p]},Xae={kernelName:Al,backendName:"wasm",setupFunc:qae,kernelFunc:Kae};function Yae(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]=of({inputs:{x:r},attrs:{begin:p,size:d},backend:n});return u.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var Jae={kernelName:$l,backendName:"wasm",kernelFunc:Yae};function Qae(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var Zae={kernelName:Dl,backendName:"wasm",kernelFunc:Qae},ere=[xee,wee,Tee,$ee,Mee,zee,Bee,Wee,Gee,Hee,Kee,Jee,Qee,tte,rte,ote,cte,dte,hte,mte,gte,xte,vte,kte,bee,Nte,_te,Ate,Rte,Ote,zte,Wte,Nee,Gte,jte,Kte,Xte,Jte,ene,nne,sne,lne,pne,hne,fne,gne,xne,kne,Nne,Cne,Fne,$ne,Rne,One,zne,Vne,Hne,qne,Xne,Yne,Jne,Pee,eae,aae,iae,lae,oae,pae,mae,yae,bae,kae,Nae,Cae,_ae,Eae,Aae,Rae,Oae,zae,Vae,Uae,jae,Xae,Eee,Jae,Zae];for(let e of ere)vc(e);var cw=ee();cw.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])));cw.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(cw.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 K2=Do(_E()),tre='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',nre=Do(EE()),X2=class extends Zu{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new kd(this,Ha())}write(e,t,n){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,n,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,a,r){let s=this.dataIdNextNumber++;if(a==="string"){let c=t;this.dataIdMap.set(e,{id:s,stringBytes:c,shape:n,dtype:a,memoryOffset:null,refCount:r});return}let i=w.sizeFromShape(n),o=i*w.bytesPerElement(a),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:n,dtype:a,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:a,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let s=this.wasm.HEAPU8.slice(t,t+w.sizeFromShape(a)*w.bytesPerElement(n));return are(s.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let a;if(n==null)a=this.write(null,e,t);else{let r=this.dataIdNextNumber++;a={id:r},this.dataIdMap.set(a,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let s=w.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=w.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 rre(e){return(t,n)=>(w.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 Y2(e,t,n){if(lf!=null)return lf;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),kp!=null&&kp[a]!=null?kp[a]:n+a}async function sre(){let[e,t]=await Promise.all([ee().getAsync("WASM_HAS_SIMD_SUPPORT"),ee().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let c=tre,u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return o.endsWith(".wasm")?Y2(e,t,Ip!=null?Ip:l):l+o},pw&&(r.instantiateWasm=rre(Y2(e,t,Ip!=null?Ip:"")));let s=!1;r.onAbort=()=>{s||Tp||(Tp=!0,a({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&lf==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+K2.default.toString()],{type:"text/javascript"}),i=(0,K2.default)(r)):i=(0,nre.default)(r),i.then(o=>{s=!0,Tp=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},n({wasm:o})})})}function are(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 ire=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],lf=null,Ip=null,kp={},Tp=!1,pw=!1;function ore(e,t=!1){if(My("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Tp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");lf=e,pw=t}function lre(e,t=!1){if(Tp)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")Ip=e;else{kp=e;let n=ire.filter(a=>kp[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.`)}pw=t}var ure="3.2.0",cre=2;fh("wasm",async()=>{let{wasm:e}=await sre();return new X2(e)},cre);var Rf={};Ju(Rf,{AnchorPosition:()=>lr,DrawBox:()=>yf,DrawBoxOptions:()=>Iw,DrawFaceLandmarks:()=>Nw,DrawFaceLandmarksOptions:()=>Tw,DrawTextField:()=>vs,DrawTextFieldOptions:()=>Np,drawContour:()=>_r,drawDetections:()=>xre,drawFaceExpressions:()=>vre,drawFaceLandmarks:()=>kre});function _r(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 uf={};Ju(uf,{computeReshapedDimensions:()=>mw,getCenterPoint:()=>no,isDimensions:()=>pf,isEven:()=>cf,isFloat:()=>hw,isTensor:()=>eo,isTensor1D:()=>pre,isTensor2D:()=>dw,isTensor3D:()=>Er,isTensor4D:()=>ra,isValidNumber:()=>Oa,isValidProbablitiy:()=>Nu,range:()=>ir,round:()=>to});var un=class{constructor(t,n){if(!Oa(t)||!Oa(n))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:n})}`);this._width=t,this._height=n}get width(){return this._width}get height(){return this._height}reverse(){return new un(1/this.width,1/this.height)}};function eo(e,t){return e instanceof Ee&&e.shape.length===t}function pre(e){return eo(e,1)}function dw(e){return eo(e,2)}function Er(e){return eo(e,3)}function ra(e){return eo(e,4)}function hw(e){return e%1!=0}function cf(e){return e%2==0}function to(e,t=2){let n=10**t;return Math.floor(e*n)/n}function pf(e){return e&&e.width&&e.height}function mw({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 ir(e,t,n){return Array(e).fill(0).map((a,r)=>t+r*n)}function Oa(e){return!!e&&e!==Infinity&&e!==-Infinity&&!Number.isNaN(e)||e===0}function Nu(e){return Oa(e)&&e>=0&&e<=1}var De=class{constructor(t,n){this._x=t,this._y=n}get x(){return this._x}get y(){return this._y}add(t){return new De(this.x+t.x,this.y+t.y)}sub(t){return new De(this.x-t.x,this.y-t.y)}mul(t){return new De(this.x*t.x,this.y*t.y)}div(t){return new De(this.x/t.x,this.y/t.y)}abs(){return new De(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new De(Math.floor(this.x),Math.floor(this.y))}};var it=class{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(Oa)}static assertIsValidBox(t,n,a=!1){if(!it.isRect(t))throw new Error(`${n} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!a&&(t.width<0||t.height<0))throw new Error(`${n} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,n=!0){let a=t||{},r=[a.left,a.top,a.right,a.bottom].every(Oa),s=[a.x,a.y,a.width,a.height].every(Oa);if(!s&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(a)}`);let[i,o,l,c]=s?[a.x,a.y,a.width,a.height]:[a.left,a.top,a.right-a.left,a.bottom-a.top];it.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 it({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 it({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 it({x:t,y:n,width:a,height:r})}rescale(t){let n=pf(t)?t.width:t,a=pf(t)?t.height:t;return new it({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 it({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 it({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 it({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 it({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 it{constructor(t,n,a,r,s=!1){super({left:t,top:n,right:a,bottom:r},s)}};var Fr=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 it(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 it(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new Fr(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var mt=class extends Fr{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 mt(a,r,s)}};function df(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 hf(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 mf(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(df(p,d,a))}r=r.filter((c,u)=>l[u]<=n)}return s}function wa(e,t){return D(()=>{let[n,a,r]=t,s=Cn([...e.shape.slice(0,3),1],n,"float32"),i=Cn([...e.shape.slice(0,3),1],a,"float32"),o=Cn([...e.shape.slice(0,3),1],r,"float32"),l=Je([s,i,o],3);return me(e,l)})}function ff(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,Cn(h,0,"float32")},l=o(s),c=r-l.shape[i],p=[t&&c?o(c):null,e,l].filter(d=>!!d).map(d=>ue(d,"float32"));return Je(p,i)})}function J2(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 Su(e){return 1/(1+Math.exp(-e))}function Q2(e){return Math.log(e/(1-e))}var ro=class extends it{constructor(t,n,a,r,s=!1){super({x:t,y:n,width:a,height:r},s)}};var dre=.5,hre=.43,mre=.45,jn=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 mt?t.box.floor():new it(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/mre),l=no(t),c=Math.floor(Math.max(0,l.x-dre*o)),u=Math.floor(Math.max(0,l.y-hre*o));return new ro(c,u,Math.min(o,this.imageWidth+c),Math.min(o,this.imageHeight+u))}alignMinBbox(t){let n=hf(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var fw=class extends jn{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],no([t[3],t[4]])]}};var so=class extends jn{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 Cu=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 _u=class extends it{static assertIsValidLabeledBox(t,n){if(it.assertIsValidBox(t,n),!Oa(t.label))throw new Error(`${n} - expected property label (${t.label}) to be a number`)}constructor(t,n){super(t);this._label=n}get label(){return this._label}};var or=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 or(t.label,n)}};var gw=class extends _u{static assertIsValidPredictedBox(t,n){if(_u.assertIsValidLabeledBox(t,n),!Nu(t.score)||!Nu(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 La(e){return e.detection instanceof mt}function bs(e,t){return{...e,...{detection:t}}}function yw(){let e=window.fetch;if(!e)throw new Error("fetch - missing fetch implementation for browser environment");return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function gf(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 bw(){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=gf();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 xw(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var vw=lE(eC()),Qt;function yre(){if(!Qt)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Qt}function ww(e){Qt=e}function kw(){return xw()?ww(yw()):(0,vw.isNodejs)()?ww(bw()):null}function bre(e){if(Qt||kw(),!Qt)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=Qt.Canvas,Image:n=Qt.Image}=e;Qt.Canvas=t,Qt.Image=n,Qt.createCanvasElement=e.createCanvasElement||(()=>new t),Qt.createImageElement=e.createImageElement||(()=>new n),Qt.ImageData=e.ImageData||Qt.ImageData,Qt.Video=e.Video||Qt.Video,Qt.fetch=e.fetch||Qt.fetch,Qt.readFile=e.readFile||Qt.readFile}var tt={getEnv:yre,setEnv:ww,initialize:kw,createBrowserEnv:yw,createFileSystem:gf,createNodejsEnv:bw,monkeyPatch:bre,isBrowser:xw,isNodejs:vw.isNodejs};kw();function xs(e){return!tt.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function bn(e){let{Canvas:t,CanvasRenderingContext2D:n}=tt.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 lr;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(lr||(lr={}));var Np=class{constructor(t={}){let{anchorPosition:n,backgroundColor:a,fontColor:r,fontSize:s,fontStyle:i,padding:o}=t;this.anchorPosition=n||lr.TOP_LEFT,this.backgroundColor=a||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=s||14,this.fontStyle=i||"Georgia",this.padding=o||4}},vs=class{constructor(t,n,a={}){this.text=typeof t=="string"?[t]:t instanceof vs?t.text:t,this.anchor=n,this.options=new Np(a)}measureWidth(t){let{padding:n}=this.options;return this.text.map(a=>t.measureText(a).width).reduce((a,r)=>a<r?r:a,0)+2*n}measureHeight(){let{fontSize:t,padding:n}=this.options;return this.text.length*t+2*n}getUpperLeft(t,n){let{anchorPosition:a}=this.options,r=a===lr.BOTTOM_RIGHT||a===lr.TOP_RIGHT,s=a===lr.BOTTOM_LEFT||a===lr.BOTTOM_RIGHT,i=this.measureWidth(t),o=this.measureHeight(),l=r?this.anchor.x-i:this.anchor.x,c=s?this.anchor.y-o:this.anchor.y;if(n){let{width:u,height:p}=n,d=Math.max(Math.min(l,u-i),0),h=Math.max(Math.min(c,p-o),0);return{x:d,y:h}}return{x:l,y:c}}draw(t){let n=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 Iw=class{constructor(t={}){let{boxColor:n,lineWidth:a,label:r,drawLabelOptions:s}=t;this.boxColor=n||"rgba(0, 0, 255, 1)",this.lineWidth=a||2,this.label=r;let i={anchorPosition:lr.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Np({...i,...s})}},yf=class{constructor(t,n={}){this.box=new it(t),this.options=new Iw(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 xre(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof mt?a.score:La(a)?a.detection.score:void 0,s=a instanceof mt?a.box:La(a)?a.detection.box:new it(a),i=r?`${to(r)}`:void 0;new yf(s,{label:i}).draw(e)})}function Eu(e){let{Image:t,Video:n}=tt.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function bf(e){return new Promise((t,n)=>{if(e instanceof tt.getEnv().Canvas||Eu(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 xf(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=tt.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}=tt.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 ks({width:e,height:t}){let{createCanvasElement:n}=tt.getEnv(),a=n();return a.width=e,a.height=t,a}function Fu(e,t){let{ImageData:n}=tt.getEnv();if(!(e instanceof n)&&!Eu(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:a,height:r}=t||ws(e),s=ks({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 vf(e,t){let n=t||tt.getEnv().createCanvasElement(),[a,r,s]=e.shape.slice(ra(e)?1:0),i=D(()=>e.as3D(a,r,s).toInt());return await Ei.toPixels(i,n),i.dispose(),n}function Sp(e){let{Image:t,Canvas:n,Video:a}=tt.getEnv();return e instanceof t||e instanceof n||e instanceof a}function wf(e,t,n=!1){let{Image:a,Canvas:r}=tt.getEnv();if(!(e instanceof a||e instanceof r))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return ks({width:1,height:1});let s=ws(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,c=ks({width:t,height:t}),u=e instanceof r?e:Fu(e),p=Math.abs(o-l)/2,d=n&&o<l?p:0,h=n&&l<o?p:0;return u.width>0&&u.height>0&&bn(c).drawImage(u,d,h,o,l),c}var ur=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(Er(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 tt.getEnv().Canvas?a:Fu(a);this._canvases[r]=s,this._inputDimensions[r]=[s.height,s.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return ir(this.batchSize,0,1).map((t,n)=>this.getReshapedInputDimensions(n))}getInput(t){return this.canvases[t]||this.imageTensors[t]}getInputDimensions(t){return this._inputDimensions[t]}getInputHeight(t){return this._inputDimensions[t][0]}getInputWidth(t){return this._inputDimensions[t][1]}getReshapedInputDimensions(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let n=this.getInputWidth(t),a=this.getInputHeight(t);return mw({width:n,height:a},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,D(()=>{let a=ir(this.batchSize,0,1).map(s=>{let i=this.getInput(s);if(i instanceof Ee){let o=ra(i)?i:i.expandDims();return o=ff(o,n),(o.shape[1]!==t||o.shape[2]!==t)&&(o=Ja.resizeBilinear(o,[t,t])),o.as3D(t,t,3)}if(i instanceof tt.getEnv().Canvas)return Ei.fromPixels(wf(i,t,n));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)});return $t(a.map(s=>ue(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function ht(e){if(e instanceof ur)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(!Sp(r)&&!Er(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=>Sp(r)&&bf(r))),new ur(a,Array.isArray(e))}async function io(e,t){let{Canvas:n}=tt.getEnv(),a=e;if(!(e instanceof n)){let i=await ht(e);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let o=i.getInput(0);a=o instanceof n?o:await vf(o)}let r=bn(a);return t.map(i=>i instanceof mt?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=ks({width:l,height:c});return l>0&&c>0&&bn(u).putImageData(r.getImageData(i,o,l,c),0,0),u})}async function oo(e,t){if(!Er(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 mt?o.forSize(a,n).box:o).map(o=>o.clipAtImageBorders(a,n)).map(({x:o,y:l,width:c,height:u})=>Yl(e.as3D(n,a,r),[l,o,0],[u,c,r]))})}async function Is(e,t){let{fetch:n}=tt.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 tC(e){let t=await Is(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 xf(n)}async function kf(e){return(await Is(e)).json()}async function nC(e){return new Float32Array(await(await Is(e)).arrayBuffer())}function If(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 Tf(e,t){let{manifestUri:n,modelBaseUri:a}=If(e,t),r=await kf(n);return Ht.loadWeights(r,a)}function aC(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 Zt=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=Jn(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 Tf(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}=tt.getEnv(),{manifestUri:a,modelBaseUri:r}=If(t,this.getDefaultModelName()),s=c=>Promise.all(c.map(u=>n(u).then(p=>p.buffer))),i=Ht.weightsLoaderFactory(s),o=JSON.parse((await n(a)).toString()),l=await i(o,r);this.loadFromWeightMap(l)}loadFromWeightMap(t){let{paramMappings:n,params:a}=this.extractParamsFromWeightMap(t);this._paramMappings=n,this._params=a}extractWeights(t){let{paramMappings:n,params:a}=this.extractParams(t);this._paramMappings=n,this._params=a}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let n=t.split("/").reduce((s,i)=>{if(!s.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${t}`);return{obj:s.nextObj,objProp:i,nextObj:s.nextObj[i]}},{nextObj:this.params}),{obj:a,objProp:r}=n;if(!a||!r||!(a[r]instanceof Ee))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:a,objProp:r}}};function Dn(e,t,n){return D(()=>{let a=Pi(e,t.depthwise_filter,t.pointwise_filter,n,"same");return a=J(a,t.bias),a})}function Nf(e,t,n=!1){return D(()=>{let a=qe(n?J(Ft(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Dn(e,t.conv0,[2,2])),r=Dn(a,t.conv1,[1,1]),s=qe(J(a,r)),i=Dn(s,t.conv2,[1,1]);return qe(J(a,J(r,i)))})}function Cp(e,t,n=!1,a=!0){return D(()=>{let r=qe(n?J(Ft(e,t.conv0.filters,a?[2,2]:[1,1],"same"),t.conv0.bias):Dn(e,t.conv0,a?[2,2]:[1,1])),s=Dn(r,t.conv1,[1,1]),i=qe(J(r,s)),o=Dn(i,t.conv2,[1,1]),l=qe(J(r,J(s,o))),c=Dn(l,t.conv3,[1,1]);return qe(J(r,J(s,J(o,c))))})}function lo(e,t,n="same",a=!1){return D(()=>{let r=J(Ft(e,t.filters,[1,1],n),t.bias);return a?qe(r):r})}function xn(e,t){Object.keys(e).forEach(n=>{t.some(a=>a.originalPath===n)||e[n].dispose()})}function Au(e,t){return(n,a,r,s)=>{let i=Ca(e(n*a*r*r),[r,r,n,a]),o=Ze(e(a));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function Sf(e,t){return(n,a,r)=>{let s=Sa(e(n*a),[n,a]),i=Ze(e(a));return t.push({paramPath:`${r}/weights`},{paramPath:`${r}/bias`}),{weights:s,bias:i}}}var Cf=class{constructor(t,n,a){this.depthwise_filter=t;this.pointwise_filter=n;this.bias=a}};function $u(e,t){return(n,a,r)=>{let s=Ca(e(3*3*n),[3,3,n,1]),i=Ca(e(n*a),[1,1,n,a]),o=Ze(e(a));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new Cf(s,i,o)}}function Du(e){return t=>{let n=e(`${t}/depthwise_filter`,4),a=e(`${t}/pointwise_filter`,4),r=e(`${t}/bias`,1);return new Cf(n,a,r)}}function qn(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 _f(e,t){let n=Au(e,t),a=$u(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 rC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractDenseBlock4Params:r}=_f(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 Ef(e){return t=>{let n=e(`${t}/filters`,4),a=e(`${t}/bias`,1);return{filters:n,bias:a}}}function Ff(e,t){let n=qn(e,t),a=Ef(n),r=Du(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 sC(e){let t=[],{extractDenseBlock4Params:n}=Ff(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 _p=class extends Zt{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return D(()=>{let a=ue(t.toBatchTensor(112,!0),"float32"),s=wa(a,[122.782,117.001,104.298]).div(pe(255)),i=Cp(s,n.dense0,!0);return i=Cp(i,n.dense1),i=Cp(i,n.dense2),i=Cp(i,n.dense3),i=Zn(i,[7,7],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await ht(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return sC(t)}extractParams(t){return rC(t)}};function Ep(e,t){return D(()=>J(ze(e,t.weights),t.bias))}function iC(e,t,n){let a=[],{extractWeights:r,getRemainingWeights:s}=vn(e),o=Sf(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 oC(e){let t=[],n=qn(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 Af(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 Fp=class extends Zt{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 ur?this.faceFeatureExtractor.forwardInput(t):t;return Ep(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 iC(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=Af(t);return this.faceFeatureExtractor.loadFromWeightMap(n),oC(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 $f=["neutral","happy","sad","angry","fearful","disgusted","surprised"],Ar=class{constructor(t){if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);$f.forEach((n,a)=>{this[n]=t[a]})}asSortedArray(){return $f.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var Ap=class extends Fp{constructor(t=new _p){super("FaceExpressionNet",t)}forwardInput(t){return D(()=>Na(this.runNet(t)))}async forward(t){return this.forwardInput(await ht(t))}async predictExpressions(t){let n=await ht(t),a=await this.forwardInput(n),r=await Promise.all(ut(a).map(async i=>{let o=await i.data();return i.dispose(),o}));a.dispose();let s=r.map(i=>new Ar(i));return n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function Df(e){return e.expressions instanceof Ar}function $p(e,t){return{...e,...{expressions:t}}}function vre(e,t,n=.1,a){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof Ar?s:Df(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=La(s)?s.detection.box.bottomLeft:a||new De(0,0);new vs(l.map(p=>`${p.expression} (${to(p.probability)})`),c).draw(e)})}function Ts(e){return La(e)&&e.landmarks instanceof jn&&e.unshiftedLandmarks instanceof jn&&e.alignedRect instanceof mt}function wre(e){let t=(o,l,c,u)=>Math.atan2(u-l,c-o)%Math.PI,n=o=>o*180/Math.PI,a={roll:void 0,pitch:void 0,yaw:void 0};if(!e||!e._positions||e._positions.length!==68)return a;let r=e._positions;a.roll=-t(r[36]._x,r[36]._y,r[45]._x,r[45]._y),a.pitch=t(0,Math.abs(r[0]._x-r[30]._x)/r[30]._x,Math.PI,Math.abs(r[16]._x-r[30]._x)/r[30]._x);let s=r.reduce((o,l)=>o<l._y?o:l._y,Infinity),i=r.reduce((o,l)=>o>l._y?o:l._y,-Infinity);return a.yaw=Math.PI*(e._imgDims._height/(i-s)/1.4-1),a}function uo(e,t){let{box:n}=e.detection,a=t.shiftBy(n.x,n.y),r=a.align(),{imageDims:s}=e.detection,i=new mt(e.detection.score,r.rescale(s.reverse()),s),o=wre(t);return{...e,...{landmarks:a,unshiftedLandmarks:t,alignedRect:i,angle:o}}}var Tw=class{constructor(t={}){let{drawLines:n=!0,drawPoints:a=!0,lineWidth:r,lineColor:s,pointSize:i,pointColor:o}=t;this.drawLines=n,this.drawPoints=a,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=s||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}},Nw=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new Tw(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,_r(n,this.faceLandmarks.getJawOutline()),_r(n,this.faceLandmarks.getLeftEyeBrow()),_r(n,this.faceLandmarks.getRightEyeBrow()),_r(n,this.faceLandmarks.getNose()),_r(n,this.faceLandmarks.getLeftEye(),!0),_r(n,this.faceLandmarks.getRightEye(),!0),_r(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 kre(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof jn?a:Ts(a)?a.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new Nw(r).draw(e)})}var lC="1.0.0";function Ire(e,t){let n=Au(e,t),a=$u(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 uC(e,t){let n=[],{extractWeights:a,getRemainingWeights:r}=vn(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=Ire(a,n),c=s(3,32,3,"entry_flow/conv_in"),u=o(32,64,"entry_flow/reduction_block_0"),p=o(64,128,"entry_flow/reduction_block_1"),d={conv_in:c,reduction_block_0:u,reduction_block_1:p},h={};ir(t,0,1).forEach(y=>{h[`main_block_${y}`]=l(128,`middle_flow/main_block_${y}`)});let m=o(128,256,"exit_flow/reduction_block"),f=i(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{entry_flow:d,middle_flow:h,exit_flow:g}}}function Tre(e,t){let n=qn(e,t),a=Ef(n),r=Du(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 cC(e,t){let n=[],{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}=Tre(e,n),o=a("entry_flow/conv_in"),l=s("entry_flow/reduction_block_0"),c=s("entry_flow/reduction_block_1"),u={conv_in:o,reduction_block_0:l,reduction_block_1:c},p={};ir(t,0,1).forEach(f=>{p[`main_block_${f}`]=i(`middle_flow/main_block_${f}`)});let d=s("exit_flow/reduction_block"),h=r("exit_flow/separable_conv"),m={reduction_block:d,separable_conv:h};return xn(e,n),{params:{entry_flow:u,middle_flow:p,exit_flow:m},paramMappings:n}}function pC(e,t,n){return J(Ft(e,t.filters,n,"same"),t.bias)}function Sw(e,t,n=!0){let a=n?qe(e):e;return a=Dn(a,t.separable_conv0,[1,1]),a=Dn(qe(a),t.separable_conv1,[1,1]),a=At(a,[3,3],[2,2],"same"),a=J(a,pC(e,t.expansion_conv,[2,2])),a}function Nre(e,t){let n=Dn(qe(e),t.separable_conv0,[1,1]);return n=Dn(qe(n),t.separable_conv1,[1,1]),n=Dn(qe(n),t.separable_conv2,[1,1]),n=J(n,e),n}var Cw=class extends Zt{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=ue(t.toBatchTensor(112,!0),"float32"),s=wa(a,[122.782,117.001,104.298]).div(pe(256)),i=qe(pC(s,n.entry_flow.conv_in,[2,2]));return i=Sw(i,n.entry_flow.reduction_block_0,!1),i=Sw(i,n.entry_flow.reduction_block_1),ir(this._numMainBlocks,0,1).forEach(o=>{i=Nre(i,n.middle_flow[`main_block_${o}`])}),i=Sw(i,n.exit_flow.reduction_block),i=qe(Dn(i,n.exit_flow.separable_conv,[1,1])),i})}async forward(t){return this.forwardInput(await ht(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return cC(t,this._numMainBlocks)}extractParams(t){return uC(t,this._numMainBlocks)}};function dC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),r=Sf(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 hC(e){let t=[],n=qn(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 cr;(function(e){e.FEMALE="female",e.MALE="male"})(cr||(cr={}));var Dp=class extends Zt{constructor(t=new Cw(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 ur?this.faceFeatureExtractor.forwardInput(t):t,r=Zn(a,[7,7],[2,2],"valid").as2D(a.shape[0],-1),s=Ep(r,n.fc.age).as1D(),i=Ep(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:Na(a)}})}async forward(t){return this.forwardInput(await ht(t))}async predictAgeAndGender(t){let n=await ht(t),a=await this.forwardInput(n),r=ut(a.age),s=ut(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?cr.MALE:cr.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 dC(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=Af(t);return this.faceFeatureExtractor.loadFromWeightMap(n),hC(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 Rp=class extends Fp{postProcess(t,n,a){let r=a.map(({width:i,height:o})=>{let l=n/Math.max(o,i);return{width:i*l,height:o*l}}),s=r.length;return D(()=>{let i=(p,d)=>$t([Cn([68],p,"float32"),Cn([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(Cn([s,136],n,"float32")).sub($t(Array.from(Array(s),(p,d)=>i(l(d),c(d))))).div($t(Array.from(Array(s),(p,d)=>i(r[d].width,r[d].height))))})}forwardInput(t){return D(()=>{let n=this.runNet(t);return this.postProcess(n,t.inputSize,t.inputDimensions.map(([a,r])=>({height:a,width:r})))})}async forward(t){return this.forwardInput(await ht(t))}async detectLandmarks(t){let n=await ht(t),a=D(()=>ut(this.forwardInput(n))),r=await Promise.all(a.map(async(s,i)=>{let o=Array.from(await s.data()),l=o.filter((u,p)=>cf(p)),c=o.filter((u,p)=>!cf(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 co=class extends Rp{constructor(t=new _p){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function mC(e){let t=[],{extractDenseBlock3Params:n}=Ff(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return xn(e,t),{params:a,paramMappings:t}}function fC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractDenseBlock3Params:r}=_f(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 _w=class extends Zt{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return D(()=>{let a=ue(t.toBatchTensor(112,!0),"float32"),s=wa(a,[122.782,117.001,104.298]).div(pe(255)),i=Nf(s,n.dense0,!0);return i=Nf(i,n.dense1),i=Nf(i,n.dense2),i=Zn(i,[14,14],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await ht(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return mC(t)}extractParams(t){return fC(t)}};var Mp=class extends Rp{constructor(t=new _w){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var Ew=class extends co{};function gC(e,t){return J(L(e,t.weights),t.biases)}function Fw(e,t,n,a,r="same"){let{filters:s,bias:i}=t.conv,o=Ft(e,s,n,r);return o=J(o,i),o=gC(o,t.scale),a?qe(o):o}function yC(e,t){return Fw(e,t,[1,1],!0)}function Aw(e,t){return Fw(e,t,[1,1],!1)}function Mf(e,t){return Fw(e,t,[2,2],!0,"valid")}function Sre(e,t){function n(o,l,c){let u=e(o),p=u.length/(l*c*c);if(hw(p))throw new Error(`depth has to be an integer: ${p}, weights.length: ${u.length}, numFilters: ${l}, filterSize: ${c}`);return D(()=>Ve(Ca(u,[l,p,c,c]),[2,3,1,0]))}function a(o,l,c,u){let p=n(o,l,c),d=Ze(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/bias`}),{filters:p,bias:d}}function r(o,l){let c=Ze(e(o)),u=Ze(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 bC(e){let{extractWeights:t,getRemainingWeights:n}=vn(e),a=[],{extractConvLayerParams:r,extractResidualLayerParams:s}=Sre(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"),x=s(589824,256,3,"conv256_2"),v=s(589824,256,3,"conv256_down_out"),N=D(()=>Ve(Sa(t(256*128),[128,256]),[1,0]));if(a.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{conv32_down:i,conv32_1:o,conv32_2:l,conv32_3:c,conv64_down:u,conv64_1:p,conv64_2:d,conv64_3:h,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:y,conv256_1:b,conv256_2:x,conv256_down_out:v,fc:N},paramMappings:a}}function Cre(e,t){let n=qn(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 xC(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Cre(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:x}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!dw(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);let v={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:x};return xn(e,t),{params:v,paramMappings:t}}function za(e,t){let n=yC(e,t.conv1);return n=Aw(n,t.conv2),n=J(n,e),n=qe(n),n}function Pp(e,t){let n=Mf(e,t.conv1);n=Aw(n,t.conv2);let a=Zn(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=Je([n,l],1);let c=[...n.shape];c[2]=1;let u=xt(c);n=Je([n,u],2)}return a=s?Je([a,r],3):a,n=J(a,n),n=qe(n),n}var po=class extends Zt{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return D(()=>{let a=ue(t.toBatchTensor(150,!0),"float32"),s=wa(a,[122.782,117.001,104.298]).div(pe(256)),i=Mf(s,n.conv32_down);i=At(i,3,2,"valid"),i=za(i,n.conv32_1),i=za(i,n.conv32_2),i=za(i,n.conv32_3),i=Pp(i,n.conv64_down),i=za(i,n.conv64_1),i=za(i,n.conv64_2),i=za(i,n.conv64_3),i=Pp(i,n.conv128_down),i=za(i,n.conv128_1),i=za(i,n.conv128_2),i=Pp(i,n.conv256_down),i=za(i,n.conv256_1),i=za(i,n.conv256_2),i=Pp(i,n.conv256_down_out);let o=i.mean([1,2]);return ze(o,n.fc)})}async forward(t){return this.forwardInput(await ht(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 ht(t),a=D(()=>ut(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 xC(t)}extractParams(t){return bC(t)}};function vC(e){let t=new po;return t.extractWeights(e),t}function Op(e,t){return{...e,...{descriptor:t}}}function wC(e){return typeof e.age=="number"}function Lp(e,t){return{...e,...{age:t}}}function kC(e){return(e.gender===cr.MALE||e.gender===cr.FEMALE)&&Nu(e.genderProbability)}function zp(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function _re(e,t){function n(l,c){let u=Ca(e(3*3*l),[3,3,l,1]),p=Ze(e(l)),d=Ze(e(l)),h=Ze(e(l)),m=Ze(e(l));return t.push({paramPath:`${c}/filters`},{paramPath:`${c}/batch_norm_scale`},{paramPath:`${c}/batch_norm_offset`},{paramPath:`${c}/batch_norm_mean`},{paramPath:`${c}/batch_norm_variance`}),{filters:u,batch_norm_scale:p,batch_norm_offset:d,batch_norm_mean:h,batch_norm_variance:m}}function a(l,c,u,p,d){let h=Ca(e(l*c*u*u),[u,u,l,c]),m=Ze(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"),x=s(512,512,"mobilenetv1/conv_11"),v=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:x,conv_12:v,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"),x=a(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),v=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"),S=a(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),A=a(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),$=a(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),R=a(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),B=a(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:l,conv_1:c,conv_2:u,conv_3:p,conv_4:d,conv_5:h,conv_6:m,conv_7:f,box_predictor_0:{box_encoding_predictor:g,class_predictor:y},box_predictor_1:{box_encoding_predictor:b,class_predictor:x},box_predictor_2:{box_encoding_predictor:v,class_predictor:N},box_predictor_3:{box_encoding_predictor:T,class_predictor:S},box_predictor_4:{box_encoding_predictor:A,class_predictor:$},box_predictor_5:{box_encoding_predictor:R,class_predictor:B}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function IC(e){let t=[],{extractWeights:n,getRemainingWeights:a}=vn(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:s}=_re(n,t),i=r(),o=s(),c={extra_dim:dh(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 Ere(e,t){let n=qn(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 TC(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=Ere(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Er(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 ka(e,t,n){return D(()=>{let a=Ft(e,t.filters,n,"same");return a=J(a,t.batch_norm_offset),qt(a,0,6)})}var Fre=.0010000000474974513;function Are(e,t,n){return D(()=>{let a=ns(e,t.filters,n,"same");return a=br(a,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Fre),qt(a,0,6)})}function $re(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function NC(e,t){return D(()=>{let n,a=ka(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=$re(o);a=Are(a,s.depthwise_conv,l),a=ka(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 Dre(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 SC(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=Dre(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 Rre(e){let t=ut(Ve(e,[1,0])),n=[me(t[2],t[0]),me(t[3],t[1])],a=[J(t[0],xe(n[0],pe(2))),J(t[1],xe(n[1],pe(2)))];return{sizes:n,centers:a}}function Mre(e,t){let{sizes:n,centers:a}=Rre(e),r=ut(Ve(t,[1,0])),s=xe(L(hn(xe(r[2],pe(5))),n[0]),pe(2)),i=J(L(xe(r[0],pe(10)),n[0]),a[0]),o=xe(L(hn(xe(r[3],pe(5))),n[1]),pe(2)),l=J(L(xe(r[1],pe(10)),n[1]),a[1]);return Ve($t([me(i,s),me(l,o),J(i,s),J(l,o)]),[1,0])}function CC(e,t,n){return D(()=>{let a=e.shape[0],r=Mre(U(qa(n.extra_dim,[a,1,1]),[-1,4]),U(e,[-1,4]));r=U(r,[a,r.shape[0]/a,4]);let s=da(We(t,[0,0,1],[-1,-1,-1])),i=We(s,[0,0,0],[-1,-1,1]);i=U(i,[a,i.shape[1]]);let o=ut(r),l=ut(i);return{boxes:o,scores:l}})}function ho(e,t){return D(()=>{let n=e.shape[0],a=U(lo(e,t.box_encoding_predictor),[n,-1,1,4]),r=U(lo(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:a,classPrediction:r}})}function _C(e,t,n){return D(()=>{let a=ka(e,n.conv_0,[1,1]),r=ka(a,n.conv_1,[2,2]),s=ka(r,n.conv_2,[1,1]),i=ka(s,n.conv_3,[2,2]),o=ka(i,n.conv_4,[1,1]),l=ka(o,n.conv_5,[2,2]),c=ka(l,n.conv_6,[1,1]),u=ka(c,n.conv_7,[2,2]),p=ho(t,n.box_predictor_0),d=ho(e,n.box_predictor_1),h=ho(r,n.box_predictor_2),m=ho(i,n.box_predictor_3),f=ho(l,n.box_predictor_4),g=ho(u,n.box_predictor_5),y=Je([p.boxPredictionEncoding,d.boxPredictionEncoding,h.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),b=Je([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 Zt{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return D(()=>{let a=ue(t.toBatchTensor(512,!1),"float32"),r=me(L(a,pe(.007843137718737125)),pe(1)),s=NC(r,n.mobilenetv1),{boxPredictions:i,classPredictions:o}=_C(s.out,s.conv11,n.prediction_layer);return CC(i,o,n.output_layer)})}async forward(t){return this.forwardInput(await ht(t))}async locateFaces(t,n={}){let{maxResults:a,minConfidence:r}=new sa(n),s=await ht(t),{boxes:i,scores:o}=this.forwardInput(s),l=i[0],c=o[0];for(let x=1;x<i.length;x++)i[x].dispose(),o[x].dispose();let u=Array.from(await c.data()),d=SC(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(x=>{let[v,N]=[Math.max(0,y[x][0]),Math.min(1,y[x][2])].map(A=>A*g),[T,S]=[Math.max(0,y[x][1]),Math.min(1,y[x][3])].map(A=>A*f);return new mt(u[x],new ro(T,v,S-T,N-v),{height:s.getInputHeight(0),width:s.getInputWidth(0)})});return l.dispose(),c.dispose(),b}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return TC(t)}extractParams(t){return IC(t)}};function $w(e){let t=new Ns;return t.extractWeights(e),t}function EC(e){return $w(e)}var Dw=class extends Ns{};var FC=.4,AC=[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)],$C=[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)],DC=[117.001,114.697,97.404],RC="tiny_yolov2_model",MC="tiny_yolov2_separable_conv_model";var Pf=e=>typeof e=="number";function Of(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(!Pf(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=>Pf(t.x)&&Pf(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(Pf)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Ru(e){return D(()=>{let t=L(e,pe(.10000000149011612));return J(qe(me(e,t)),t)})}function $r(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=me(n,t.bn.sub),n=L(n,t.bn.truediv),n=J(n,t.conv.bias),Ru(n)})}function Dr(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=J(n,t.bias),Ru(n)})}function Pre(e,t){let n=Au(e,t);function a(i,o){let l=Ze(e(i)),c=Ze(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=$u(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}}function PC(e,t,n,a){let{extractWeights:r,getRemainingWeights:s}=vn(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=Pre(r,i),u;if(t.withSeparableConvs){let[p,d,h,m,f,g,y,b,x]=a,v=t.isFirstLayerConv2d?o(p,d,3,"conv0"):c(p,d,"conv0"),N=c(d,h,"conv1"),T=c(h,m,"conv2"),S=c(m,f,"conv3"),A=c(f,g,"conv4"),$=c(g,y,"conv5"),R=b?c(y,b,"conv6"):void 0,B=x?c(b,x,"conv7"):void 0,V=o(x||b||y,5*n,1,"conv8");u={conv0:v,conv1:N,conv2:T,conv3:S,conv4:A,conv5:$,conv6:R,conv7:B,conv8:V}}else{let[p,d,h,m,f,g,y,b,x]=a,v=l(p,d,"conv0"),N=l(d,h,"conv1"),T=l(h,m,"conv2"),S=l(m,f,"conv3"),A=l(f,g,"conv4"),$=l(g,y,"conv5"),R=l(y,b,"conv6"),B=l(b,x,"conv7"),V=o(x,5*n,1,"conv8");u={conv0:v,conv1:N,conv2:T,conv3:S,conv4:A,conv5:$,conv6:R,conv7:B,conv8:V}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:u,paramMappings:i}}function Ore(e,t){let n=qn(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=Du(n);return{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function OC(e,t){let n=[],{extractConvParams:a,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}=Ore(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 Ba=class{constructor({inputSize:t,scoreThreshold:n}={}){this._name="TinyYolov2Options";if(this._inputSize=t||416,this._scoreThreshold=n||.5,typeof this._inputSize!="number"||this._inputSize%32!=0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}};var Rw=class extends Zt{constructor(t){super("TinyYolov2");Of(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=$r(t,n.conv0);return a=At(a,[2,2],[2,2],"same"),a=$r(a,n.conv1),a=At(a,[2,2],[2,2],"same"),a=$r(a,n.conv2),a=At(a,[2,2],[2,2],"same"),a=$r(a,n.conv3),a=At(a,[2,2],[2,2],"same"),a=$r(a,n.conv4),a=At(a,[2,2],[2,2],"same"),a=$r(a,n.conv5),a=At(a,[2,2],[1,1],"same"),a=$r(a,n.conv6),a=$r(a,n.conv7),lo(a,n.conv8,"valid",!1)}runMobilenet(t,n){let a=this.config.isFirstLayerConv2d?Ru(lo(t,n.conv0,"valid",!1)):Dr(t,n.conv0);return a=At(a,[2,2],[2,2],"same"),a=Dr(a,n.conv1),a=At(a,[2,2],[2,2],"same"),a=Dr(a,n.conv2),a=At(a,[2,2],[2,2],"same"),a=Dr(a,n.conv3),a=At(a,[2,2],[2,2],"same"),a=Dr(a,n.conv4),a=At(a,[2,2],[2,2],"same"),a=Dr(a,n.conv5),a=At(a,[2,2],[1,1],"same"),a=n.conv6?Dr(a,n.conv6):a,a=n.conv7?Dr(a,n.conv7):a,lo(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=ue(t.toBatchTensor(n,!1),"float32");return r=this.config.meanRgb?wa(r,this.config.meanRgb):r,r=r.div(pe(256)),this.config.withSeparableConvs?this.runMobilenet(r,a):this.runTinyYolov2(r,a)})}async forward(t,n){return this.forwardInput(await ht(t),n)}async detect(t,n={}){let{inputSize:a,scoreThreshold:r}=new Ba(n),s=await ht(t),i=await this.forwardInput(s,a),o=D(()=>ut(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 mf(u.map(g=>g.rescale(a)),p,this.config.iouThreshold,!0).map(g=>new Fr(p[g],d[g],h[g],u[g],l))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return OC(t,this.config)}extractParams(t){let n=this.config.filterSizes||Rw.DEFAULT_FILTER_SIZES,a=n?n.length:void 0;if(a!==7&&a!==8&&a!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${a} filterSizes in config`);return PC(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]),x=y.slice([0,0,0,4],[c,c,u,1]),v=this.withClassScores?Na(y.slice([0,0,0,5],[c,c,u,this.config.classes.length]),3):pe(0);return[b,x,v]}),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 x=0;x<u;x++){let v=Su(f[y][b][x][0]);if(!a||v>a){let N=(b+Su(g[y][b][x][0]))/c*o,T=(y+Su(g[y][b][x][1]))/c*l,S=Math.exp(g[y][b][x][2])*this.config.anchors[x].x/c*o,A=Math.exp(g[y][b][x][3])*this.config.anchors[x].y/c*l,$=N-S/2,R=T-A/2,B={row:y,col:b,anchor:x},{classScore:V,label:W}=this.withClassScores?await this.extractPredictedClass(h,B):{classScore:1,label:0};m.push({box:new ao($,R,$+S,R+A),score:v,classScore:v*V,label:W,...B})}}return p.dispose(),d.dispose(),h.dispose(),m}async extractPredictedClass(t,n){let{row:a,col:r,anchor:s}=n,i=await t.array();return Array(this.config.classes.length).fill(0).map((o,l)=>i[a][r][s][l]).map((o,l)=>({classScore:o,label:l})).reduce((o,l)=>o.classScore>l.classScore?o:l)}},Mu=Rw;Mu.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var mo=class extends Mu{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:FC,classes:["face"],...t?{anchors:$C,meanRgb:DC}:{anchors:AC,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 mt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?MC:RC}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function LC(e,t=!0){let n=new mo(t);return n.extractWeights(e),n}var Bp=class extends Ba{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 fo(e,t,n,a,r=({alignedRect:s})=>s){let s=e.map(l=>Ts(l)?r(l):l.detection),i=a||(t instanceof Ee?await oo(t,s):await io(t,s)),o=await n(i);return i.forEach(l=>l instanceof Ee&&l.dispose()),o}async function Pu(e,t,n,a,r){return fo([e],t,async s=>n(s[0]),a,r)}var zC=.4,BC=[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)],WC=[117.001,114.697,97.404];var go=class extends Mu{constructor(){let t={withSeparableConvs:!0,iouThreshold:zC,classes:["face"],anchors:BC,meanRgb:WC,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 mt(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var Qe={ssdMobilenetv1:new Ns,tinyFaceDetector:new go,tinyYolov2:new mo,faceLandmark68Net:new co,faceLandmark68TinyNet:new Mp,faceRecognitionNet:new po,faceExpressionNet:new Ap,ageGenderNet:new Dp},Mw=(e,t)=>Qe.ssdMobilenetv1.locateFaces(e,t),VC=(e,t)=>Qe.tinyFaceDetector.locateFaces(e,t),UC=(e,t)=>Qe.tinyYolov2.locateFaces(e,t),Pw=e=>Qe.faceLandmark68Net.detectLandmarks(e),GC=e=>Qe.faceLandmark68TinyNet.detectLandmarks(e),HC=e=>Qe.faceRecognitionNet.computeFaceDescriptor(e),jC=e=>Qe.faceExpressionNet.predictExpressions(e),qC=e=>Qe.ageGenderNet.predictAgeAndGender(e),Ow=e=>Qe.ssdMobilenetv1.load(e),KC=e=>Qe.tinyFaceDetector.load(e),XC=e=>Qe.tinyYolov2.load(e),YC=e=>Qe.faceLandmark68Net.load(e),JC=e=>Qe.faceLandmark68TinyNet.load(e),QC=e=>Qe.faceRecognitionNet.load(e),ZC=e=>Qe.faceExpressionNet.load(e),e_=e=>Qe.ageGenderNet.load(e),t_=Ow,n_=Mw,a_=Pw;var Lw=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},zu=class extends Lw{async run(){let t=await this.parentTask,n=await fo(t,this.input,async a=>Promise.all(a.map(r=>Qe.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return t.map((a,r)=>$p(a,n[r]))}withAgeAndGender(){return new Ou(this,this.input)}},Bu=class extends Lw{async run(){let t=await this.parentTask;if(!t)return;let n=await Pu(t,this.input,a=>Qe.faceExpressionNet.predictExpressions(a),this.extractedFaces);return $p(t,n)}withAgeAndGender(){return new Lu(this,this.input)}},xo=class extends zu{withAgeAndGender(){return new yo(this,this.input)}withFaceDescriptors(){return new Rr(this,this.input)}},vo=class extends Bu{withAgeAndGender(){return new bo(this,this.input)}withFaceDescriptor(){return new Mr(this,this.input)}};var zw=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.extractedFaces=a}},Ou=class extends zw{async run(){let t=await this.parentTask,n=await fo(t,this.input,async a=>Promise.all(a.map(r=>Qe.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return t.map((a,r)=>{let{age:s,gender:i,genderProbability:o}=n[r];return Lp(zp(a,i,o),s)})}withFaceExpressions(){return new zu(this,this.input)}},Lu=class extends zw{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:a,genderProbability:r}=await Pu(t,this.input,s=>Qe.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return Lp(zp(t,a,r),n)}withFaceExpressions(){return new Bu(this,this.input)}},yo=class extends Ou{withFaceExpressions(){return new xo(this,this.input)}withFaceDescriptors(){return new Rr(this,this.input)}},bo=class extends Lu{withFaceExpressions(){return new vo(this,this.input)}withFaceDescriptor(){return new Mr(this,this.input)}};var Wp=class extends ia{constructor(t,n){super();this.parentTask=t;this.input=n}},Rr=class extends Wp{async run(){let t=await this.parentTask;return(await fo(t,this.input,a=>Promise.all(a.map(r=>Qe.faceRecognitionNet.computeFaceDescriptor(r))),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}))).map((a,r)=>Op(t[r],a))}withFaceExpressions(){return new xo(this,this.input)}withAgeAndGender(){return new yo(this,this.input)}},Mr=class extends Wp{async run(){let t=await this.parentTask;if(!t)return;let n=await Pu(t,this.input,a=>Qe.faceRecognitionNet.computeFaceDescriptor(a),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}));return Op(t,n)}withFaceExpressions(){return new vo(this,this.input)}withAgeAndGender(){return new bo(this,this.input)}};var Vp=class extends ia{constructor(t,n,a){super();this.parentTask=t;this.input=n;this.useTinyLandmarkNet=a}get landmarkNet(){return this.useTinyLandmarkNet?Qe.faceLandmark68TinyNet:Qe.faceLandmark68Net}},Up=class extends Vp{async run(){let t=await this.parentTask,n=t.map(s=>s.detection),a=this.input instanceof Ee?await oo(this.input,n):await io(this.input,n),r=await Promise.all(a.map(s=>this.landmarkNet.detectLandmarks(s)));return a.forEach(s=>s instanceof Ee&&s.dispose()),t.map((s,i)=>uo(s,r[i]))}withFaceExpressions(){return new xo(this,this.input)}withAgeAndGender(){return new yo(this,this.input)}withFaceDescriptors(){return new Rr(this,this.input)}},Gp=class extends Vp{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,a=this.input instanceof Ee?await oo(this.input,[n]):await io(this.input,[n]),r=await this.landmarkNet.detectLandmarks(a[0]);return a.forEach(s=>s instanceof Ee&&s.dispose()),uo(t,r)}withFaceExpressions(){return new vo(this,this.input)}withAgeAndGender(){return new bo(this,this.input)}withFaceDescriptor(){return new Mr(this,this.input)}};var Hp=class extends ia{constructor(t,n=new sa){super();this.input=t;this.options=n}},Wu=class extends Hp{async run(){let{input:t,options:n}=this,a;if(n instanceof Bp)a=Qe.tinyFaceDetector.locateFaces(t,n);else if(n instanceof sa)a=Qe.ssdMobilenetv1.locateFaces(t,n);else if(n instanceof Ba)a=Qe.tinyYolov2.locateFaces(t,n);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return a}runAndExtendWithFaceDetections(){return new Promise(async t=>{let n=await this.run();t(n.map(a=>bs({},a)))})}withFaceLandmarks(t=!1){return new Up(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new zu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Ou(this.runAndExtendWithFaceDetections(),this.input)}},jp=class extends Hp{async run(){let t=await new Wu(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 Gp(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new Bu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Lu(this.runAndExtendWithFaceDetection(),this.input)}};function r_(e,t=new sa){return new jp(e,t)}function qp(e,t=new sa){return new Wu(e,t)}async function Bw(e,t){return qp(e,new sa(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function s_(e,t={}){return qp(e,new Ba(t)).withFaceLandmarks().withFaceDescriptors()}var i_=Bw;function Lf(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 Kp=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 or)return i;if(i instanceof Float32Array)return new or(s(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new or(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=>Lf(a,t)).reduce((a,r)=>a+r,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:a})=>new Cu(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 Cu("unknown",n.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(a=>or.fromJSON(a));return new Kp(n,t.distanceThreshold)}};function o_(e){let t=new go;return t.extractWeights(e),t}function Ww(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=>Ww(r,{width:n,height:a}));if(Ts(e)){let r=e.detection.forSize(n,a),s=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return uo(bs(e,r),s)}return La(e)?bs(e,e.detection.forSize(n,a)):e instanceof jn||e instanceof mt?e.forSize(n,a):e}var zre=typeof process!="undefined",Bre=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",l_={faceapi:lC,node:zre,browser:Bre};return Lre;})();
|
|
/**
|
|
* @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
|