4824 lines
1.2 MiB
4824 lines
1.2 MiB
/*
|
|
Face-API
|
|
homepage: <https://github.com/vladmandic/face-api>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var faceapi=(()=>{var J0=Object.defineProperty;var QA=e=>J0(e,"__esModule",{value:!0});var Qr=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Rp=(e,t)=>{QA(e);for(var n in t)J0(e,n,{get:t[n],enumerable:!0})};var sue={};Rp(sue,{AgeGenderNet:()=>qm,BoundingBox:()=>Lu,Box:()=>ut,ComposableTask:()=>Ar,ComputeAllFaceDescriptorsTask:()=>Aa,ComputeFaceDescriptorsTaskBase:()=>tg,ComputeSingleFaceDescriptorTask:()=>Da,DetectAllFaceLandmarksTask:()=>rg,DetectAllFacesTask:()=>ip,DetectFaceLandmarksTaskBase:()=>ng,DetectFacesTaskBase:()=>ag,DetectSingleFaceLandmarksTask:()=>sg,DetectSingleFaceTask:()=>og,Dimensions:()=>An,FACE_EXPRESSION_LABELS:()=>S0,FaceDetection:()=>vt,FaceDetectionNet:()=>VE,FaceExpressionNet:()=>Hm,FaceExpressions:()=>Ea,FaceLandmark68Net:()=>qu,FaceLandmark68TinyNet:()=>Km,FaceLandmarkNet:()=>AE,FaceLandmarks:()=>gr,FaceLandmarks5:()=>mE,FaceLandmarks68:()=>zu,FaceMatch:()=>Yd,FaceMatcher:()=>cg,FaceRecognitionNet:()=>Ku,Gender:()=>Ws,LabeledBox:()=>Zd,LabeledFaceDescriptors:()=>Ls,NetInput:()=>Bs,NeuralNetwork:()=>pn,ObjectDetection:()=>Na,Point:()=>Pe,PredictedBox:()=>gE,Rect:()=>Bu,SsdMobilenetv1:()=>Ai,SsdMobilenetv1Options:()=>Er,TinyFaceDetector:()=>Qu,TinyFaceDetectorOptions:()=>eg,TinyYolov2:()=>Zu,TinyYolov2Options:()=>ys,allFaces:()=>eue,allFacesSsdMobilenetv1:()=>rA,allFacesTinyYolov2:()=>Qce,awaitMediaLoaded:()=>y0,bufferToImage:()=>v0,computeFaceDescriptor:()=>Bce,createCanvas:()=>Ti,createCanvasFromMedia:()=>ep,createFaceDetectionNet:()=>Fce,createFaceRecognitionNet:()=>wce,createSsdMobilenetv1:()=>WE,createTinyFaceDetector:()=>tue,createTinyYolov2:()=>Pce,detectAllFaces:()=>ig,detectFaceLandmarks:()=>tA,detectFaceLandmarksTiny:()=>Lce,detectLandmarks:()=>Zce,detectSingleFace:()=>Jce,draw:()=>_0,env:()=>Je,euclideanDistance:()=>L0,extendWithAge:()=>Zm,extendWithFaceDescriptor:()=>Ym,extendWithFaceDetection:()=>Ii,extendWithFaceExpressions:()=>jm,extendWithFaceLandmarks:()=>ju,extendWithGender:()=>Jm,extractFaceTensors:()=>Vu,extractFaces:()=>Wu,fetchImage:()=>cce,fetchJson:()=>k0,fetchNetWeights:()=>uce,fetchOrThrow:()=>zs,fetchVideo:()=>lce,getContext2dOrThrow:()=>Un,getMediaDimensions:()=>Ci,imageTensorToCanvas:()=>x0,imageToSquare:()=>w0,inverseSigmoid:()=>tce,iou:()=>i0,isMediaElement:()=>Om,isMediaLoaded:()=>Qd,isWithAge:()=>kce,isWithFaceDetection:()=>gs,isWithFaceExpressions:()=>C0,isWithFaceLandmarks:()=>_i,isWithGender:()=>Ice,loadAgeGenderModel:()=>Kce,loadFaceDetectionModel:()=>Xce,loadFaceExpressionModel:()=>qce,loadFaceLandmarkModel:()=>Gce,loadFaceLandmarkTinyModel:()=>Hce,loadFaceRecognitionModel:()=>jce,loadSsdMobilenetv1Model:()=>nA,loadTinyFaceDetectorModel:()=>Vce,loadTinyYolov2Model:()=>Uce,loadWeightMap:()=>I0,locateFaces:()=>Yce,matchDimensions:()=>dce,minBbox:()=>c0,nets:()=>Qe,nonMaxSuppression:()=>u0,normalize:()=>Kr,padToSquare:()=>l0,predictAgeAndGender:()=>Wce,recognizeFaceExpressions:()=>zce,resizeResults:()=>sA,resolveInput:()=>Si,shuffleArray:()=>ece,sigmoid:()=>Xd,ssdMobilenetv1:()=>eA,tf:()=>n0,tinyFaceDetector:()=>Oce,tinyYolov2:()=>Mce,toNetInput:()=>mt,utils:()=>o0,validateConfig:()=>R0,version:()=>rue});var n0={};Rp(n0,{Abs:()=>Ki,Acos:()=>Xi,Acosh:()=>Yi,AdadeltaOptimizer:()=>gf,AdagradOptimizer:()=>bf,AdamOptimizer:()=>yf,AdamaxOptimizer:()=>vf,Add:()=>Qs,AddN:()=>Ba,All:()=>Zi,Any:()=>Ji,ArgMax:()=>za,ArgMin:()=>xl,Asin:()=>Qi,Asinh:()=>ec,Atan:()=>tc,Atan2:()=>rc,Atanh:()=>nc,AvgPool:()=>Wa,AvgPool3D:()=>wl,AvgPool3DGrad:()=>Vp,AvgPoolGrad:()=>Wp,BackendWasm:()=>pE,BatchMatMul:()=>Va,BatchToSpaceND:()=>sc,Bincount:()=>Up,BroadcastArgs:()=>Gp,BroadcastTo:()=>b1,Callback:()=>iC,CallbackList:()=>QI,Cast:()=>Ua,Ceil:()=>Ga,ClipByValue:()=>ea,Complex:()=>Hp,ComplexAbs:()=>kl,Concat:()=>ac,Conv2D:()=>Ha,Conv2DBackpropFilter:()=>jp,Conv2DBackpropInput:()=>ja,Conv3D:()=>Il,Conv3DBackpropFilterV2:()=>qp,Conv3DBackpropInputV2:()=>Kp,Cos:()=>qa,Cosh:()=>Ka,CropAndResize:()=>oc,Cumsum:()=>Xa,CustomCallback:()=>tS,DataStorage:()=>Op,DenseBincount:()=>Xp,DepthToSpace:()=>ic,DepthwiseConv2dNative:()=>Ya,DepthwiseConv2dNativeBackpropFilter:()=>Yp,DepthwiseConv2dNativeBackpropInput:()=>Zp,Diag:()=>Jp,Dilation2D:()=>Sl,Dilation2DBackpropFilter:()=>eh,Dilation2DBackpropInput:()=>Qp,ENV:()=>qi,EarlyStopping:()=>uC,Einsum:()=>th,Elu:()=>Ja,EluGrad:()=>nh,Environment:()=>m1,Equal:()=>uc,Erf:()=>cc,Exp:()=>Qa,ExpandDims:()=>lc,Expm1:()=>dc,FFT:()=>rh,Fill:()=>Cl,FlipLeftRight:()=>pc,Floor:()=>eo,FloorDiv:()=>to,FromPixels:()=>Sh,FusedBatchNorm:()=>no,FusedConv2D:()=>Mo,FusedDepthwiseConv2D:()=>Lo,GPGPUContext:()=>iN,GatherNd:()=>fc,GatherV2:()=>hc,GraphModel:()=>WC,Greater:()=>mc,GreaterEqual:()=>ro,History:()=>eS,IFFT:()=>sh,Identity:()=>so,Imag:()=>ah,InputSpec:()=>Bt,IsFinite:()=>gc,IsInf:()=>bc,IsNan:()=>yc,KernelBackend:()=>bl,LRN:()=>_l,LRNGrad:()=>ih,LayerVariable:()=>KI,LayersModel:()=>Fs,LeakyRelu:()=>ao,Less:()=>vc,LessEqual:()=>xc,LinSpace:()=>oh,Log:()=>oo,Log1p:()=>wc,LogSoftmax:()=>y1,LogicalAnd:()=>kc,LogicalNot:()=>Tl,LogicalOr:()=>Nl,MathBackendWebGL:()=>xm,Max:()=>io,MaxPool:()=>uo,MaxPool3D:()=>El,MaxPool3DGrad:()=>uh,MaxPoolGrad:()=>ch,MaxPoolWithArgmax:()=>lh,Maximum:()=>co,Mean:()=>lo,Min:()=>po,Minimum:()=>ho,MirrorPad:()=>fo,Mod:()=>Ic,MomentumOptimizer:()=>xf,Multinomial:()=>dh,Multiply:()=>mo,Neg:()=>Sc,NonMaxSuppressionV3:()=>Tc,NonMaxSuppressionV4:()=>Nc,NonMaxSuppressionV5:()=>_c,NotEqual:()=>Cc,OP_SCOPE_SUFFIX:()=>$1,OneHot:()=>go,OnesLike:()=>Ec,Optimizer:()=>Es,Pack:()=>Ac,PadV2:()=>bo,Pool:()=>XD,Pow:()=>yo,Prelu:()=>vo,Prod:()=>Dc,RMSPropOptimizer:()=>wf,RNN:()=>ps,Range:()=>Al,Rank:()=>Gb,Real:()=>ph,RealDiv:()=>Za,Reciprocal:()=>Fc,Reduction:()=>Sn,Relu:()=>xo,Relu6:()=>ko,Reshape:()=>$c,ResizeBilinear:()=>wo,ResizeBilinearGrad:()=>fh,ResizeNearestNeighbor:()=>Dl,ResizeNearestNeighborGrad:()=>hh,Reverse:()=>Io,RotateWithOffset:()=>Kc,Round:()=>So,Rsqrt:()=>Co,SGDOptimizer:()=>id,ScatterNd:()=>Rc,Select:()=>Pc,Selu:()=>Oc,Sequential:()=>yu,Sigmoid:()=>No,Sign:()=>Bc,Sin:()=>To,Sinh:()=>Lc,Slice:()=>Mc,Softmax:()=>Ao,Softplus:()=>zc,SpaceToBatchND:()=>Wc,SparseFillEmptyRows:()=>mh,SparseReshape:()=>gh,SparseSegmentMean:()=>bh,SparseSegmentSum:()=>yh,SparseToDense:()=>vh,SplitV:()=>Vc,Sqrt:()=>_o,Square:()=>Fl,SquaredDifference:()=>Do,Step:()=>na,StridedSlice:()=>Uc,StringNGrams:()=>xh,StringSplit:()=>wh,StringToHashBucketFast:()=>kh,Sub:()=>Fo,Sum:()=>Eo,SymbolicTensor:()=>Vr,Tan:()=>$o,Tanh:()=>Ro,Tensor:()=>Ee,TensorBuffer:()=>Ut,Tile:()=>ta,TopK:()=>Gc,Transform:()=>Hc,Transpose:()=>Po,Unique:()=>Ih,Unpack:()=>jc,UnsortedSegmentSum:()=>$l,Variable:()=>sa,ZerosLike:()=>qc,_FusedMatMul:()=>Oo,abs:()=>Lt,acos:()=>yy,acosh:()=>vy,add:()=>Y,addN:()=>bk,all:()=>Bh,any:()=>jl,argMax:()=>jo,argMin:()=>xy,asin:()=>wy,asinh:()=>ky,atan:()=>Iy,atan2:()=>Sy,atanh:()=>Cy,avgPool:()=>ir,avgPool3d:()=>_y,backend:()=>gk,backend_util:()=>_,basicLSTMCell:()=>PR,batchNorm:()=>Ts,batchNorm2d:()=>wk,batchNorm3d:()=>kk,batchNorm4d:()=>Ik,batchToSpaceND:()=>Kl,bincount:()=>Ey,booleanMaskAsync:()=>WO,broadcastArgs:()=>Sk,broadcastTo:()=>ru,browser:()=>Go,buffer:()=>ze,callbacks:()=>tG,cast:()=>ce,ceil:()=>Ay,clipByValue:()=>Qt,clone:()=>Ss,complex:()=>aa,concat:()=>Ze,concat1d:()=>Ck,concat2d:()=>Tk,concat3d:()=>Nk,concat4d:()=>_k,constraints:()=>NI,conv1d:()=>Wh,conv2d:()=>Rt,conv2dTranspose:()=>Vh,conv3d:()=>Fy,conv3dTranspose:()=>Ak,copyRegisteredKernels:()=>JD,cos:()=>Xl,cosh:()=>Uh,cosineWindow:()=>sv,cumsum:()=>Gh,customGrad:()=>ss,data:()=>VC,denseBincount:()=>Dk,deprecationWarn:()=>by,depthToSpace:()=>$y,depthwiseConv2d:()=>la,deregisterOp:()=>rG,device_util:()=>Ul,diag:()=>dP,dilation2d:()=>Ry,disableDeprecationWarnings:()=>q$,dispose:()=>De,disposeVariables:()=>K$,div:()=>ge,divNoNan:()=>Py,dot:()=>Fk,dropout:()=>Qk,einsum:()=>$k,elu:()=>su,enableDebugMode:()=>j$,enableProdMode:()=>H$,enclosingPowerOfTwo:()=>eI,engine:()=>Cs,env:()=>J,equal:()=>Kn,erf:()=>Oy,exp:()=>gn,expandDims:()=>bn,expm1:()=>My,eye:()=>Ly,fft:()=>sd,fill:()=>In,findBackend:()=>tR,findBackendFactory:()=>nR,floor:()=>au,floorDiv:()=>Lh,forceHalfFloat:()=>bN,fused:()=>ha,gather:()=>Xo,gatherND:()=>Jk,gather_util:()=>ly,getBackend:()=>Q$,getGradient:()=>zb,getKernel:()=>Ch,getKernelsForBackend:()=>Th,getThreadsCount:()=>Wie,gpgpu_util:()=>G2,grad:()=>WP,grads:()=>VP,greater:()=>Mn,greaterEqual:()=>da,ifft:()=>lu,imag:()=>Hh,image:()=>Qn,inTopKAsync:()=>JO,initializers:()=>RI,input:()=>SS,io:()=>Zt,irfft:()=>af,isFinite:()=>Rk,isInf:()=>Pk,isNaN:()=>By,keep:()=>Jt,kernel_impls:()=>is,layers:()=>HI,leakyRelu:()=>Yl,less:()=>jh,lessEqual:()=>pa,linalg:()=>pI,linspace:()=>Ok,loadGraphModel:()=>oH,loadLayersModel:()=>dV,localResponseNormalization:()=>zy,log:()=>Xn,log1p:()=>Zl,logSigmoid:()=>Lk,logSoftmax:()=>Kh,logSumExp:()=>Uy,logicalAnd:()=>Ir,logicalNot:()=>Jl,logicalOr:()=>Xh,logicalXor:()=>Vk,losses:()=>RL,matMul:()=>Ae,math:()=>Z1,max:()=>kr,maxPool:()=>Pt,maxPool3d:()=>Gy,maxPoolWithArgmax:()=>Uk,maximum:()=>as,mean:()=>Et,memory:()=>Oh,meshgrid:()=>l3,metrics:()=>sC,min:()=>Ql,minimum:()=>ou,mirrorPad:()=>Hy,mod:()=>jy,model:()=>uV,models:()=>aC,moments:()=>Yh,movingAverage:()=>GO,mul:()=>V,multiRNNCell:()=>y3,multinomial:()=>Gk,neg:()=>It,nextFrame:()=>hI,norm:()=>lf,notEqual:()=>Jo,oneHot:()=>eu,ones:()=>Yn,onesLike:()=>Zn,op:()=>W,outerProduct:()=>I3,pad:()=>ur,pad1d:()=>T3,pad2d:()=>_3,pad3d:()=>A3,pad4d:()=>F3,pool:()=>Hk,pow:()=>Ns,prelu:()=>td,print:()=>H1,prod:()=>Zh,profile:()=>X$,rand:()=>W3,randomGamma:()=>H3,randomNormal:()=>jk,randomUniform:()=>iu,range:()=>cu,ready:()=>J$,real:()=>nd,reciprocal:()=>Xy,registerBackend:()=>Mh,registerCallbackConstructor:()=>pV,registerGradient:()=>v1,registerKernel:()=>Pl,registerOp:()=>nG,regularizers:()=>oC,relu:()=>je,relu6:()=>Jh,removeBackend:()=>eR,reshape:()=>U,reverse:()=>Jn,reverse1d:()=>eO,reverse2d:()=>nO,reverse3d:()=>sO,reverse4d:()=>oO,rfft:()=>ad,round:()=>Qh,rsqrt:()=>ef,scalar:()=>Se,scatterND:()=>Zk,scatter_util:()=>dy,selu:()=>tf,separableConv2d:()=>Qo,sequential:()=>lV,serialization:()=>ie,setBackend:()=>Z$,setPlatform:()=>rR,setThreadsCount:()=>zie,setWasmPath:()=>Lie,setWasmPaths:()=>Bie,setWebGLContext:()=>f2,setdiff1dAsync:()=>qk,sigmoid:()=>cr,sign:()=>Yy,signal:()=>$L,sin:()=>nf,sinh:()=>rf,slice:()=>We,slice1d:()=>sf,slice2d:()=>Zy,slice3d:()=>uu,slice4d:()=>rd,slice_util:()=>kn,softmax:()=>Pr,softplus:()=>Yo,spaceToBatchND:()=>ed,sparse:()=>od,sparseToDense:()=>rv,spectral:()=>FL,split:()=>Ln,sqrt:()=>cn,square:()=>ct,squaredDifference:()=>of,squeeze:()=>os,stack:()=>Ot,step:()=>du,stridedSlice:()=>Jy,string:()=>mf,sub:()=>fe,sum:()=>ve,sumOutType:()=>Dh,tan:()=>Qy,tanh:()=>Ko,tensor:()=>qn,tensor1d:()=>Ge,tensor2d:()=>Or,tensor3d:()=>Rh,tensor4d:()=>Mr,tensor5d:()=>FO,tensor6d:()=>$O,tensor_util:()=>$r,test_util:()=>hk,tidy:()=>M,tile:()=>On,time:()=>Y$,topk:()=>ev,train:()=>ti,transpose:()=>Re,truncatedNormal:()=>cf,unique:()=>uf,unregisterGradient:()=>ZD,unregisterKernel:()=>YD,unsortedSegmentSum:()=>tv,unstack:()=>dt,upcastType:()=>wr,util:()=>w,valueAndGrad:()=>UP,valueAndGrads:()=>GP,variable:()=>Kk,variableGrads:()=>Mk,version:()=>Jie,version_converter:()=>iH,version_core:()=>G$,version_layers:()=>Bv,version_wasm:()=>Vie,version_webgl:()=>v9,webgl:()=>x9,webgl_util:()=>h2,where:()=>mn,whereAsync:()=>nv,zeros:()=>St,zerosLike:()=>Ue});var eD=Object.create,Pp=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,nD=Object.getOwnPropertyNames,rD=Object.getPrototypeOf,sD=Object.prototype.hasOwnProperty,Q0=e=>Pp(e,"__esModule",{value:!0}),Gi=(e=>typeof Qr!="undefined"?Qr:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof Qr!="undefined"?Qr:t)[n]}):e)(function(e){if(typeof Qr!="undefined")return Qr.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),kt=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},$e=(e,t)=>{Q0(e);for(var n in t)Pp(e,n,{get:t[n],enumerable:!0})},aD=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of nD(t))!sD.call(e,r)&&r!=="default"&&Pp(e,r,{get:()=>t[r],enumerable:!(n=tD(t,r))||n.enumerable});return e},Oa=e=>aD(Q0(Pp(e!=null?eD(rD(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),oD=kt({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=r;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(P){}function r(P,T,L){this.low=P|0,this.high=T|0,this.unsigned=!!L}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0});function s(P){return(P&&P.__isLong__)===!0}r.isLong=s;var a={},o={};function i(P,T){var L,G,j;return T?(P>>>=0,(j=0<=P&&P<256)&&(G=o[P],G)?G:(L=l(P,(P|0)<0?-1:0,!0),j&&(o[P]=L),L)):(P|=0,(j=-128<=P&&P<128)&&(G=a[P],G)?G:(L=l(P,P<0?-1:0,!1),j&&(a[P]=L),L))}r.fromInt=i;function c(P,T){if(isNaN(P))return T?x:v;if(T){if(P<0)return x;if(P>=g)return R}else{if(P<=-b)return O;if(P+1>=b)return F}return P<0?c(-P,T).neg():l(P%m|0,P/m|0,T)}r.fromNumber=c;function l(P,T,L){return new r(P,T,L)}r.fromBits=l;var u=Math.pow;function d(P,T,L){if(P.length===0)throw Error("empty string");if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return v;if(typeof T=="number"?(L=T,T=!1):T=!!T,L=L||10,L<2||36<L)throw RangeError("radix");var G;if((G=P.indexOf("-"))>0)throw Error("interior hyphen");if(G===0)return d(P.substring(1),T,L).neg();for(var j=c(u(L,8)),q=v,K=0;K<P.length;K+=8){var ee=Math.min(8,P.length-K),te=parseInt(P.substring(K,K+ee),L);if(ee<8){var ne=c(u(L,ee));q=q.mul(ne).add(c(te))}else q=q.mul(j),q=q.add(c(te))}return q.unsigned=T,q}r.fromString=d;function p(P,T){return typeof P=="number"?c(P,T):typeof P=="string"?d(P,T):l(P.low,P.high,typeof T=="boolean"?T:P.unsigned)}r.fromValue=p;var h=1<<16,f=1<<24,m=h*h,g=m*m,b=g/2,y=i(f),v=i(0);r.ZERO=v;var x=i(0,!0);r.UZERO=x;var k=i(1);r.ONE=k;var C=i(1,!0);r.UONE=C;var N=i(-1);r.NEG_ONE=N;var F=l(4294967295|0,2147483647|0,!1);r.MAX_VALUE=F;var R=l(4294967295|0,4294967295|0,!0);r.MAX_UNSIGNED_VALUE=R;var O=l(0,2147483648|0,!1);r.MIN_VALUE=O;var D=r.prototype;D.toInt=function(){return this.unsigned?this.low>>>0:this.low},D.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},D.toString=function(T){if(T=T||10,T<2||36<T)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(O)){var L=c(T),G=this.div(L),j=G.mul(L).sub(this);return G.toString(T)+j.toInt().toString(T)}else return"-"+this.neg().toString(T);for(var q=c(u(T,6),this.unsigned),K=this,ee="";;){var te=K.div(q),ne=K.sub(te.mul(q)).toInt()>>>0,ae=ne.toString(T);if(K=te,K.isZero())return ae+ee;for(;ae.length<6;)ae="0"+ae;ee=""+ae+ee}},D.getHighBits=function(){return this.high},D.getHighBitsUnsigned=function(){return this.high>>>0},D.getLowBits=function(){return this.low},D.getLowBitsUnsigned=function(){return this.low>>>0},D.getNumBitsAbs=function(){if(this.isNegative())return this.eq(O)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,L=31;L>0&&(T&1<<L)==0;L--);return this.high!=0?L+33:L+1},D.isZero=function(){return this.high===0&&this.low===0},D.eqz=D.isZero,D.isNegative=function(){return!this.unsigned&&this.high<0},D.isPositive=function(){return this.unsigned||this.high>=0},D.isOdd=function(){return(this.low&1)==1},D.isEven=function(){return(this.low&1)==0},D.equals=function(T){return s(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},D.eq=D.equals,D.notEquals=function(T){return!this.eq(T)},D.neq=D.notEquals,D.ne=D.notEquals,D.lessThan=function(T){return this.comp(T)<0},D.lt=D.lessThan,D.lessThanOrEqual=function(T){return this.comp(T)<=0},D.lte=D.lessThanOrEqual,D.le=D.lessThanOrEqual,D.greaterThan=function(T){return this.comp(T)>0},D.gt=D.greaterThan,D.greaterThanOrEqual=function(T){return this.comp(T)>=0},D.gte=D.greaterThanOrEqual,D.ge=D.greaterThanOrEqual,D.compare=function(T){if(s(T)||(T=p(T)),this.eq(T))return 0;var L=this.isNegative(),G=T.isNegative();return L&&!G?-1:!L&&G?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},D.comp=D.compare,D.negate=function(){return!this.unsigned&&this.eq(O)?O:this.not().add(k)},D.neg=D.negate,D.add=function(T){s(T)||(T=p(T));var L=this.high>>>16,G=this.high&65535,j=this.low>>>16,q=this.low&65535,K=T.high>>>16,ee=T.high&65535,te=T.low>>>16,ne=T.low&65535,ae=0,se=0,re=0,ue=0;return ue+=q+ne,re+=ue>>>16,ue&=65535,re+=j+te,se+=re>>>16,re&=65535,se+=G+ee,ae+=se>>>16,se&=65535,ae+=L+K,ae&=65535,l(re<<16|ue,ae<<16|se,this.unsigned)},D.subtract=function(T){return s(T)||(T=p(T)),this.add(T.neg())},D.sub=D.subtract,D.multiply=function(T){if(this.isZero())return v;if(s(T)||(T=p(T)),n){var L=n.mul(this.low,this.high,T.low,T.high);return l(L,n.get_high(),this.unsigned)}if(T.isZero())return v;if(this.eq(O))return T.isOdd()?O:v;if(T.eq(O))return this.isOdd()?O:v;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(y)&&T.lt(y))return c(this.toNumber()*T.toNumber(),this.unsigned);var G=this.high>>>16,j=this.high&65535,q=this.low>>>16,K=this.low&65535,ee=T.high>>>16,te=T.high&65535,ne=T.low>>>16,ae=T.low&65535,se=0,re=0,ue=0,de=0;return de+=K*ae,ue+=de>>>16,de&=65535,ue+=q*ae,re+=ue>>>16,ue&=65535,ue+=K*ne,re+=ue>>>16,ue&=65535,re+=j*ae,se+=re>>>16,re&=65535,re+=q*ne,se+=re>>>16,re&=65535,re+=K*te,se+=re>>>16,re&=65535,se+=G*ae+j*ne+q*te+K*ee,se&=65535,l(ue<<16|de,se<<16|re,this.unsigned)},D.mul=D.multiply,D.divide=function(T){if(s(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var L=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return l(L,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?x:v;var G,j,q;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return x;if(T.gt(this.shru(1)))return C;q=x}else{if(this.eq(O)){if(T.eq(k)||T.eq(N))return O;if(T.eq(O))return k;var K=this.shr(1);return G=K.div(T).shl(1),G.eq(v)?T.isNegative()?k:N:(j=this.sub(T.mul(G)),q=G.add(j.div(T)),q)}else if(T.eq(O))return this.unsigned?x:v;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();q=v}for(j=this;j.gte(T);){G=Math.max(1,Math.floor(j.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(G)/Math.LN2),te=ee<=48?1:u(2,ee-48),ne=c(G),ae=ne.mul(T);ae.isNegative()||ae.gt(j);)G-=te,ne=c(G,this.unsigned),ae=ne.mul(T);ne.isZero()&&(ne=k),q=q.add(ne),j=j.sub(ae)}return q},D.div=D.divide,D.modulo=function(T){if(s(T)||(T=p(T)),n){var L=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return l(L,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},D.mod=D.modulo,D.rem=D.modulo,D.not=function(){return l(~this.low,~this.high,this.unsigned)},D.and=function(T){return s(T)||(T=p(T)),l(this.low&T.low,this.high&T.high,this.unsigned)},D.or=function(T){return s(T)||(T=p(T)),l(this.low|T.low,this.high|T.high,this.unsigned)},D.xor=function(T){return s(T)||(T=p(T)),l(this.low^T.low,this.high^T.high,this.unsigned)},D.shiftLeft=function(T){return s(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?l(this.low<<T,this.high<<T|this.low>>>32-T,this.unsigned):l(0,this.low<<T-32,this.unsigned)},D.shl=D.shiftLeft,D.shiftRight=function(T){return s(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?l(this.low>>>T|this.high<<32-T,this.high>>T,this.unsigned):l(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},D.shr=D.shiftRight,D.shiftRightUnsigned=function(T){if(s(T)&&(T=T.toInt()),T&=63,T===0)return this;var L=this.high;if(T<32){var G=this.low;return l(G>>>T|L<<32-T,L>>>T,this.unsigned)}else return T===32?l(L,0,this.unsigned):l(L>>>T-32,0,this.unsigned)},D.shru=D.shiftRightUnsigned,D.shr_u=D.shiftRightUnsigned,D.toSigned=function(){return this.unsigned?l(this.low,this.high,!1):this},D.toUnsigned=function(){return this.unsigned?this:l(this.low,this.high,!0)},D.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},D.toBytesLE=function(){var T=this.high,L=this.low;return[L&255,L>>>8&255,L>>>16&255,L>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},D.toBytesBE=function(){var T=this.high,L=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,L>>>24,L>>>16&255,L>>>8&255,L&255]},r.fromBytes=function(T,L,G){return G?r.fromBytesLE(T,L):r.fromBytesBE(T,L)},r.fromBytesLE=function(T,L){return new r(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,L)},r.fromBytesBE=function(T,L){return new r(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],L)}}}),iD=kt({"(disabled):node_modules/.pnpm/node-fetch@2.6.5/node_modules/node-fetch/browser.js"(){}}),cD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,r,s){function a(l){var u=this,d=c();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(l),u.s0<0&&(u.s0+=1),u.s1-=d(l),u.s1<0&&(u.s1+=1),u.s2-=d(l),u.s2<0&&(u.s2+=1),d=null}function o(l,u){return u.c=l.c,u.s0=l.s0,u.s1=l.s1,u.s2=l.s2,u}function i(l,u){var d=new a(l),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function c(){var l=4022871197,u=function(d){d=d.toString();for(var p=0;p<d.length;p++){l+=d.charCodeAt(p);var h=.02519603282416938*l;l=h>>>0,h-=l,h*=l,l=h>>>0,h-=l,l+=h*4294967296}return(l>>>0)*23283064365386963e-26};return u}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),uD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var p=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^p^p>>>8},c===(c|0)?l.x=c:u+=c;for(var d=0;d<u.length+64;d++)l.x^=u.charCodeAt(d)|0,l.next()}function o(c,l){return l.x=c.x,l.y=c.y,l.z=c.z,l.w=c.w,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),lD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.next=function(){var p=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(p^p<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,c===(c|0)?l.x=c:u+=c;for(var d=0;d<u.length+64;d++)l.x^=u.charCodeAt(d)|0,d==u.length&&(l.d=l.x<<10^l.x>>>4),l.next()}function o(c,l){return l.x=c.x,l.y=c.y,l.z=c.z,l.w=c.w,l.v=c.v,l.d=c.d,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),dD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,r,s){function a(c){var l=this;l.next=function(){var d=l.x,p=l.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,l.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h<p.length;++h)m[h&7]=m[h&7]<<15^p.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],d.x=m,d.i=0,h=256;h>0;--h)d.next()}u(l,c)}function o(c,l){return l.x=c.x.slice(),l.i=c.i,l}function i(c,l){c==null&&(c=+new Date);var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),pD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,r,s){function a(c){var l=this;l.next=function(){var d=l.w,p=l.X,h=l.i,f,m;return l.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,l.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,b,y=[],v=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,v=Math.max(v,p.length)),m=0,g=-32;g<v;++g)p&&(f^=p.charCodeAt((g+32)%p.length)),g===0&&(b=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(b=b+1640531527|0,h=y[g&127]^=f+b,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=b,d.X=y,d.i=m}u(l,c)}function o(c,l){return l.i=c.i,l.w=c.w,l.X=c.X.slice(),l}function i(c,l){c==null&&(c=+new Date);var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),hD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.next=function(){var p=l.b,h=l.c,f=l.d,m=l.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,l.b=p=p<<20^p>>>12^h,l.c=h=h-f|0,l.d=f<<16^h>>>16^m,l.a=m-p|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,c===Math.floor(c)?(l.a=c/4294967296|0,l.b=c|0):u+=c;for(var d=0;d<u.length+20;d++)l.b^=u.charCodeAt(d)|0,l.next()}function o(c,l){return l.a=c.a,l.b=c.b,l.c=c.c,l.d=c.d,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),e1=kt({"(disabled):crypto"(){}}),fD=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,r){var s=this,a=256,o=6,i=52,c="random",l=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(k,C,N){var F=[];C=C==!0?{entropy:!0}:C||{};var R=y(b(C.entropy?[k,x(n)]:k==null?v():k,3),F),O=new m(F),D=function(){for(var P=O.g(o),T=l,L=0;P<u;)P=(P+L)*a,T*=a,L=O.g(1);for(;P>=d;)P/=2,T/=2,L>>>=1;return(P+L)/T};return D.int32=function(){return O.g(4)|0},D.quick=function(){return O.g(4)/4294967296},D.double=D,y(x(O.S),n),(C.pass||N||function(P,T,L,G){return G&&(G.S&&g(G,O),P.state=function(){return g(O,{})}),L?(r[c]=P,T):P})(D,R,"global"in C?C.global:this==r,C.state)}r["seed"+c]=f;function m(k){var C,N=k.length,F=this,R=0,O=F.i=F.j=0,D=F.S=[];for(N||(k=[N++]);R<a;)D[R]=R++;for(R=0;R<a;R++)D[R]=D[O=p&O+k[R%N]+(C=D[R])],D[O]=C;(F.g=function(P){for(var T,L=0,G=F.i,j=F.j,q=F.S;P--;)T=q[G=p&G+1],L=L*a+q[p&(q[G]=q[j=p&j+T])+(q[j]=T)];return F.i=G,F.j=j,L})(a)}function g(k,C){return C.i=k.i,C.j=k.j,C.S=k.S.slice(),C}function b(k,C){var N=[],F=typeof k,R;if(C&&F=="object")for(R in k)try{N.push(b(k[R],C-1))}catch(O){}return N.length?N:F=="string"?k:k+"\0"}function y(k,C){for(var N=k+"",F,R=0;R<N.length;)C[p&R]=p&(F^=C[p&R]*19)+N.charCodeAt(R++);return x(C)}function v(){try{var k;return h&&(k=h.randomBytes)?k=k(a):(k=new Uint8Array(a),(s.crypto||s.msCrypto).getRandomValues(k)),x(k)}catch(F){var C=s.navigator,N=C&&C.plugins;return[+new Date,s,N,s.screen,x(n)]}}function x(k){return String.fromCharCode.apply(0,k)}if(y(r.random(),n),typeof t=="object"&&t.exports){t.exports=f;try{h=e1()}catch(k){}}else typeof define=="function"&&define.amd&&define(function(){return f})})([],Math)}}),t1=kt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/index.js"(e,t){var n=cD(),r=uD(),s=lD(),a=dD(),o=pD(),i=hD(),c=fD();c.alea=n,c.xor128=r,c.xorwow=s,c.xorshift7=a,c.xor4096=o,c.tychei=i,t.exports=c}}),mD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,r,s){function a(l){var u=this,d=c();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(l),u.s0<0&&(u.s0+=1),u.s1-=d(l),u.s1<0&&(u.s1+=1),u.s2-=d(l),u.s2<0&&(u.s2+=1),d=null}function o(l,u){return u.c=l.c,u.s0=l.s0,u.s1=l.s1,u.s2=l.s2,u}function i(l,u){var d=new a(l),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function c(){var l=4022871197,u=function(d){d=String(d);for(var p=0;p<d.length;p++){l+=d.charCodeAt(p);var h=.02519603282416938*l;l=h>>>0,h-=l,h*=l,l=h>>>0,h-=l,l+=h*4294967296}return(l>>>0)*23283064365386963e-26};return u}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),gD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var p=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^p^p>>>8},c===(c|0)?l.x=c:u+=c;for(var d=0;d<u.length+64;d++)l.x^=u.charCodeAt(d)|0,l.next()}function o(c,l){return l.x=c.x,l.y=c.y,l.z=c.z,l.w=c.w,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),bD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.next=function(){var p=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(p^p<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,c===(c|0)?l.x=c:u+=c;for(var d=0;d<u.length+64;d++)l.x^=u.charCodeAt(d)|0,d==u.length&&(l.d=l.x<<10^l.x>>>4),l.next()}function o(c,l){return l.x=c.x,l.y=c.y,l.z=c.z,l.w=c.w,l.v=c.v,l.d=c.d,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),yD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,r,s){function a(c){var l=this;l.next=function(){var d=l.x,p=l.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,l.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h<p.length;++h)m[h&7]=m[h&7]<<15^p.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],d.x=m,d.i=0,h=256;h>0;--h)d.next()}u(l,c)}function o(c,l){return l.x=c.x.slice(),l.i=c.i,l}function i(c,l){c==null&&(c=+new Date);var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),vD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,r,s){function a(c){var l=this;l.next=function(){var d=l.w,p=l.X,h=l.i,f,m;return l.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,l.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,b,y=[],v=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,v=Math.max(v,p.length)),m=0,g=-32;g<v;++g)p&&(f^=p.charCodeAt((g+32)%p.length)),g===0&&(b=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(b=b+1640531527|0,h=y[g&127]^=f+b,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=b,d.X=y,d.i=m}u(l,c)}function o(c,l){return l.i=c.i,l.w=c.w,l.X=c.X.slice(),l}function i(c,l){c==null&&(c=+new Date);var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),xD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,r,s){function a(c){var l=this,u="";l.next=function(){var p=l.b,h=l.c,f=l.d,m=l.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,l.b=p=p<<20^p>>>12^h,l.c=h=h-f|0,l.d=f<<16^h>>>16^m,l.a=m-p|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,c===Math.floor(c)?(l.a=c/4294967296|0,l.b=c|0):u+=c;for(var d=0;d<u.length+20;d++)l.b^=u.charCodeAt(d)|0,l.next()}function o(c,l){return l.a=c.a,l.b=c.b,l.c=c.c,l.d=c.d,l}function i(c,l){var u=new a(c),d=l&&l.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),wD=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,r,s){var a=256,o=6,i=52,c="random",l=s.pow(a,o),u=s.pow(2,i),d=u*2,p=a-1,h;function f(k,C,N){var F=[];C=C==!0?{entropy:!0}:C||{};var R=y(b(C.entropy?[k,x(r)]:k==null?v():k,3),F),O=new m(F),D=function(){for(var P=O.g(o),T=l,L=0;P<u;)P=(P+L)*a,T*=a,L=O.g(1);for(;P>=d;)P/=2,T/=2,L>>>=1;return(P+L)/T};return D.int32=function(){return O.g(4)|0},D.quick=function(){return O.g(4)/4294967296},D.double=D,y(x(O.S),r),(C.pass||N||function(P,T,L,G){return G&&(G.S&&g(G,O),P.state=function(){return g(O,{})}),L?(s[c]=P,T):P})(D,R,"global"in C?C.global:this==s,C.state)}function m(k){var C,N=k.length,F=this,R=0,O=F.i=F.j=0,D=F.S=[];for(N||(k=[N++]);R<a;)D[R]=R++;for(R=0;R<a;R++)D[R]=D[O=p&O+k[R%N]+(C=D[R])],D[O]=C;(F.g=function(P){for(var T,L=0,G=F.i,j=F.j,q=F.S;P--;)T=q[G=p&G+1],L=L*a+q[p&(q[G]=q[j=p&j+T])+(q[j]=T)];return F.i=G,F.j=j,L})(a)}function g(k,C){return C.i=k.i,C.j=k.j,C.S=k.S.slice(),C}function b(k,C){var N=[],F=typeof k,R;if(C&&F=="object")for(R in k)try{N.push(b(k[R],C-1))}catch(O){}return N.length?N:F=="string"?k:k+"\0"}function y(k,C){for(var N=k+"",F,R=0;R<N.length;)C[p&R]=p&(F^=C[p&R]*19)+N.charCodeAt(R++);return x(C)}function v(){try{var k;return h&&(k=h.randomBytes)?k=k(a):(k=new Uint8Array(a),(n.crypto||n.msCrypto).getRandomValues(k)),x(k)}catch(F){var C=n.navigator,N=C&&C.plugins;return[+new Date,n,N,n.screen,x(r)]}}function x(k){return String.fromCharCode.apply(0,k)}if(y(s.random(),r),typeof t=="object"&&t.exports){t.exports=f;try{h=e1()}catch(k){}}else typeof define=="function"&&define.amd?define(function(){return f}):s["seed"+c]=f})(typeof self!="undefined"?self:e,[],Math)}}),n1=kt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(e,t){var n=mD(),r=gD(),s=bD(),a=yD(),o=vD(),i=xD(),c=wD();c.alea=n,c.xor128=r,c.xorwow=s,c.xorshift7=a,c.xor4096=o,c.tychei=i,t.exports=c}}),r1=kt({"(disabled):node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js"(){}}),gl=kt({"(disabled):path"(){}}),kD=kt({"(disabled):worker_threads"(){}}),ID=kt({"(disabled):perf_hooks"(){}}),SD=kt({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.10.0_@tensorflow+tfjs-core@3.10.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var n=function(){var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(s){s=s||{};function a(){return re.buffer!=xt&&an(re.buffer),Nt}function o(){return re.buffer!=xt&&an(re.buffer),$n}function i(){return re.buffer!=xt&&an(re.buffer),yn}function c(){return re.buffer!=xt&&an(re.buffer),Hn}function l(){return re.buffer!=xt&&an(re.buffer),ar}var u=typeof s!="undefined"?s:{},d,p;u.ready=new Promise(function(S,E){d=S,p=E});var h={},f;for(f in u)u.hasOwnProperty(f)&&(h[f]=u[f]);var m=[],g="./this.program",b=function(S,E){throw E},y=!1,v=!1,x=!1,k=!1;y=typeof window=="object",v=typeof importScripts=="function",x=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",k=!y&&!x&&!v;var C=u.ENVIRONMENT_IS_PTHREAD||!1;C&&(xt=u.buffer);var N="";function F(S){return u.locateFile?u.locateFile(S,N):N+S}var R,O,D,P,T,L;if(x){v?N=gl().dirname(N)+"/":N=__dirname+"/",R=function(E,B){return T||(T=Gi("fs")),L||(L=gl()),E=L.normalize(E),T.readFileSync(E,B?null:"utf8")},D=function(E){var B=R(E,!0);return B.buffer||(B=new Uint8Array(B)),we(B.buffer),B},process.argv.length>1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(S){if(!(S instanceof ml))throw S}),process.on("unhandledRejection",vs),b=function(S){process.exit(S)},u.inspect=function(){return"[Emscripten Module object]"};var G;try{G=kD()}catch(S){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),S}global.Worker=G.Worker}else k?(typeof read!="undefined"&&(R=function(E){return read(E)}),D=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(B=read(E,"binary"),we(typeof B=="object"),B)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(b=function(S){quit(S)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(y||v)&&(v?N=self.location.href:typeof document!="undefined"&&document.currentScript&&(N=document.currentScript.src),typeof r!="undefined"&&r&&(N=r),N.indexOf("blob:")!==0?N=N.substr(0,N.lastIndexOf("/")+1):N="",x?(R=function(E,B){return T||(T=Gi("fs")),L||(L=gl()),E=L.normalize(E),T.readFileSync(E,B?null:"utf8")},D=function(E){var B=R(E,!0);return B.buffer||(B=new Uint8Array(B)),we(B.buffer),B}):(R=function(S){var E=new XMLHttpRequest;return E.open("GET",S,!1),E.send(null),E.responseText},v&&(D=function(S){var E=new XMLHttpRequest;return E.open("GET",S,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),O=function(S,E,B){var X=new XMLHttpRequest;X.open("GET",S,!0),X.responseType="arraybuffer",X.onload=function(){if(X.status==200||X.status==0&&X.response){E(X.response);return}B()},X.onerror=B,X.send(null)}),P=function(S){document.title=S});x&&typeof performance=="undefined"&&(global.performance=ID().performance);var j=u.print||console.log.bind(console),q=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(b=u.quit);function K(S){K.shown||(K.shown={}),K.shown[S]||(K.shown[S]=1,q(S))}var ee=Atomics.load,te=Atomics.store,ne=Atomics.compareExchange,ae;u.wasmBinary&&(ae=u.wasmBinary);var se=u.noExitRuntime||!0;typeof WebAssembly!="object"&&vs("no native wasm support detected");var re,ue,de=!1,me;function we(S,E){S||vs("Assertion failed: "+E)}function Ce(S){var E=u["_"+S];return we(E,"Cannot call unknown function "+S+", make sure it is exported"),E}function _e(S,E,B,X,he){var le={string:function(vn){var Ui=0;if(vn!=null&&vn!==0){var Z0=(vn.length<<2)+1;Ui=zi(Z0),et(vn,Ui,Z0)}return Ui},array:function(vn){var Ui=zi(vn.length);return it(vn,Ui),Ui}};function pe(vn){return E==="string"?Ke(vn):E==="boolean"?Boolean(vn):vn}var ke=Ce(S),rt=[],Kt=0;if(X)for(var Vt=0;Vt<X.length;Vt++){var Ys=le[B[Vt]];Ys?(Kt===0&&(Kt=fl()),rt[Vt]=Ys(X[Vt])):rt[Vt]=X[Vt]}var Vi=ke.apply(null,rt);return Vi=pe(Vi),Kt!==0&&Bi(Kt),Vi}function Me(S,E,B,X){B=B||[];var he=B.every(function(pe){return pe==="number"}),le=E!=="string";return le&&he&&!X?Ce(S):function(){return _e(S,E,B,arguments,X)}}function Be(S,E,B){for(var X=E+B,he="";!(E>=X);){var le=S[E++];if(!le)return he;if(!(le&128)){he+=String.fromCharCode(le);continue}var pe=S[E++]&63;if((le&224)==192){he+=String.fromCharCode((le&31)<<6|pe);continue}var ke=S[E++]&63;if((le&240)==224?le=(le&15)<<12|pe<<6|ke:le=(le&7)<<18|pe<<12|ke<<6|S[E++]&63,le<65536)he+=String.fromCharCode(le);else{var rt=le-65536;he+=String.fromCharCode(55296|rt>>10,56320|rt&1023)}}return he}function Ke(S,E){return S?Be(o(),S,E):""}function st(S,E,B,X){if(!(X>0))return 0;for(var he=B,le=B+X-1,pe=0;pe<S.length;++pe){var ke=S.charCodeAt(pe);if(ke>=55296&&ke<=57343){var rt=S.charCodeAt(++pe);ke=65536+((ke&1023)<<10)|rt&1023}if(ke<=127){if(B>=le)break;E[B++]=ke}else if(ke<=2047){if(B+1>=le)break;E[B++]=192|ke>>6,E[B++]=128|ke&63}else if(ke<=65535){if(B+2>=le)break;E[B++]=224|ke>>12,E[B++]=128|ke>>6&63,E[B++]=128|ke&63}else{if(B+3>=le)break;E[B++]=240|ke>>18,E[B++]=128|ke>>12&63,E[B++]=128|ke>>6&63,E[B++]=128|ke&63}}return E[B]=0,B-he}function et(S,E,B){return st(S,o(),E,B)}function tt(S){for(var E=0,B=0;B<S.length;++B){var X=S.charCodeAt(B);X>=55296&&X<=57343&&(X=65536+((X&1023)<<10)|S.charCodeAt(++B)&1023),X<=127?++E:X<=2047?E+=2:X<=65535?E+=3:E+=4}return E}function it(S,E){a().set(S,E)}function lt(S,E){return S%E>0&&(S+=E-S%E),S}var xt,Nt,$n,sn,Dr,yn,Hn,br,ar;function an(S){xt=S,u.HEAP8=Nt=new Int8Array(S),u.HEAP16=sn=new Int16Array(S),u.HEAP32=yn=new Int32Array(S),u.HEAPU8=$n=new Uint8Array(S),u.HEAPU16=Dr=new Uint16Array(S),u.HEAPU32=Hn=new Uint32Array(S),u.HEAPF32=br=new Float32Array(S),u.HEAPF64=ar=new Float64Array(S)}var Yr=u.INITIAL_MEMORY||16777216;if(C)re=u.wasmMemory,xt=u.buffer;else if(u.wasmMemory)re=u.wasmMemory;else if(re=new WebAssembly.Memory({initial:Yr/65536,maximum:2147483648/65536,shared:!0}),!(re.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"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");re&&(xt=re.buffer),Yr=xt.byteLength,an(xt);var hn,Zr=[],Jr=[],Gs=[],sl=[],Fr=[],cp=!1,ug=!1;C||Jr.push({func:function(){Tp()}});function up(){if(!C){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)lg(u.preRun.shift());Oi(Zr)}}function lp(){cp=!0,!C&&Oi(Jr)}function dp(){C||Oi(Gs)}function Rn(){C||(ug=!0)}function pp(){if(!C){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)dg(u.postRun.shift());Oi(Fr)}}function lg(S){Zr.unshift(S)}function dg(S){Fr.unshift(S)}var yr=0,al=null,Fa=null;function pg(S){we(!C,"addRunDependency cannot be used in a pthread worker"),yr++,u.monitorRunDependencies&&u.monitorRunDependencies(yr)}function hg(S){if(yr--,u.monitorRunDependencies&&u.monitorRunDependencies(yr),yr==0&&(al!==null&&(clearInterval(al),al=null),Fa)){var E=Fa;Fa=null,E()}}u.preloadedImages={},u.preloadedAudios={};function vs(S){u.onAbort&&u.onAbort(S),C&&console.error("Pthread aborting at "+new Error().stack),S+="",q(S),de=!0,me=1,S="abort("+S+"). Build with -s ASSERTIONS=1 for more info.";var E=new WebAssembly.RuntimeError(S);throw p(E),E}function $a(S,E){return String.prototype.startsWith?S.startsWith(E):S.indexOf(E)===0}var fg="data:application/octet-stream;base64,";function hp(S){return $a(S,fg)}var mg="file://";function fp(S){return $a(S,mg)}var Pn="tfjs-backend-wasm-threaded-simd.wasm";hp(Pn)||(Pn=F(Pn));function mp(S){try{if(S==Pn&&ae)return new Uint8Array(ae);if(D)return D(S);throw"both async and sync fetching of the wasm failed"}catch(E){vs(E)}}function gg(){if(!ae&&(y||v)){if(typeof fetch=="function"&&!fp(Pn))return fetch(Pn,{credentials:"same-origin"}).then(function(S){if(!S.ok)throw"failed to load wasm binary file at '"+Pn+"'";return S.arrayBuffer()}).catch(function(){return mp(Pn)});if(O)return new Promise(function(S,E){O(Pn,function(B){S(new Uint8Array(B))},E)})}return Promise.resolve().then(function(){return mp(Pn)})}function bg(){var S={a:ub};function E(pe,ke){var rt=pe.exports;if(u.asm=rt,hn=u.asm.I,ue=ke,!C){var Kt=Te.unusedWorkers.length;Te.unusedWorkers.forEach(function(Vt){Te.loadWasmModuleToWorker(Vt,function(){--Kt||hg("wasm-instantiate")})})}}C||pg("wasm-instantiate");function B(pe){E(pe.instance,pe.module)}function X(pe){return gg().then(function(ke){return WebAssembly.instantiate(ke,S)}).then(pe,function(ke){q("failed to asynchronously prepare wasm: "+ke),vs(ke)})}function he(){return!ae&&typeof WebAssembly.instantiateStreaming=="function"&&!hp(Pn)&&!fp(Pn)&&typeof fetch=="function"?fetch(Pn,{credentials:"same-origin"}).then(function(pe){var ke=WebAssembly.instantiateStreaming(pe,S);return ke.then(B,function(rt){return q("wasm streaming compile failed: "+rt),q("falling back to ArrayBuffer instantiation"),X(B)})}):X(B)}if(u.instantiateWasm)try{var le=u.instantiateWasm(S,E);return le}catch(pe){return q("Module.instantiateWasm callback failed with error: "+pe),!1}return he().catch(p),{}}var yg={10520:function(){throw"Canceled!"},10538:function(S,E){setTimeout(function(){H0(S,E)},0)}};function gp(){Te.initRuntime()}function Oi(S){for(;S.length>0;){var E=S.shift();if(typeof E=="function"){E(u);continue}var B=E.func;typeof B=="number"?E.arg===void 0?hn.get(B)():hn.get(B)(E.arg):B(E.arg===void 0?null:E.arg)}}var Hs={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function ol(S,E){if(S<=0||S>a().length||S&!0||E<0)return-28;if(E==0)return 0;E>=2147483647&&(E=1/0);var B=Atomics.load(i(),Wi>>2),X=0;if(B==S){var he=Atomics.compareExchange(i(),Wi>>2,B,0);if(he==B&&(--E,X=1,E<=0))return 1}var le=Atomics.notify(i(),S>>2,E);if(le>=0)return le+X;throw"Atomics.notify returned an unexpected value "+le}u._emscripten_futex_wake=ol;function vg(S){if(C)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in killThread!";i()[S+12>>2]=0;var E=Te.pthreads[S];E.worker.terminate(),Te.freeThreadData(E),Te.runningWorkers.splice(Te.runningWorkers.indexOf(E.worker),1),E.worker.pthread=void 0}function xg(S){if(C)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in cancelThread!";var E=Te.pthreads[S];E.worker.postMessage({cmd:"cancel"})}function bp(S){if(C)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in cleanupThread!";var E=Te.pthreads[S];if(E){i()[S+12>>2]=0;var B=E.worker;Te.returnWorkerToPool(B)}}var Te={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var S=8,E=0;E<S;++E)Te.allocateUnusedWorker()},initRuntime:function(){for(var S=Pa(228),E=0;E<228/4;++E)c()[S/4+E]=0;i()[S+12>>2]=S;var B=S+152;i()[B>>2]=B;for(var X=Pa(512),E=0;E<128;++E)c()[X/4+E]=0;Atomics.store(c(),S+100>>2,X),Atomics.store(c(),S+40>>2,S),Fb(S,!v,1),U0(S)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Te.threadExitHandlers.length>0;)Te.threadExitHandlers.pop()();C&&Xs()&&V0()},runExitHandlersAndDeinitThread:function(S,E){Atomics.store(c(),S+56>>2,1),Atomics.store(c(),S+60>>2,0),Te.runExitHandlers(),Atomics.store(c(),S+4>>2,E),Atomics.store(c(),S+0>>2,1),ol(S+0,2147483647),Fb(0,0,0)},threadExit:function(S){var E=Xs();E&&(Te.runExitHandlersAndDeinitThread(E,S),C&&postMessage({cmd:"exit"}))},threadCancel:function(){Te.runExitHandlersAndDeinitThread(Xs(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var S in Te.pthreads){var E=Te.pthreads[S];E&&E.worker&&Te.returnWorkerToPool(E.worker)}Te.pthreads={};for(var B=0;B<Te.unusedWorkers.length;++B){var X=Te.unusedWorkers[B];X.terminate()}Te.unusedWorkers=[];for(var B=0;B<Te.runningWorkers.length;++B){var X=Te.runningWorkers[B],E=X.pthread;Te.freeThreadData(E),X.terminate()}Te.runningWorkers=[]},freeThreadData:function(S){if(!!S){if(S.threadInfoStruct){var E=i()[S.threadInfoStruct+100>>2];i()[S.threadInfoStruct+100>>2]=0,hl(E),hl(S.threadInfoStruct)}S.threadInfoStruct=0,S.allocatedOwnStack&&S.stackBase&&hl(S.stackBase),S.stackBase=0,S.worker&&(S.worker.pthread=null)}},returnWorkerToPool:function(S){Te.runWithoutMainThreadQueuedCalls(function(){delete Te.pthreads[S.pthread.threadInfoStruct],Te.unusedWorkers.push(S),Te.runningWorkers.splice(Te.runningWorkers.indexOf(S),1),Te.freeThreadData(S.pthread),S.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(S){i()[Y0>>2]=0;try{S()}finally{i()[Y0>>2]=1}},receiveObjectTransfer:function(S){},loadWasmModuleToWorker:function(S,E){S.onmessage=function(B){var X=B.data,he=X.cmd;if(S.pthread&&(Te.currentProxiedOperationCallerThread=S.pthread.threadInfoStruct),X.targetThread&&X.targetThread!=Xs()){var le=Te.pthreads[X.targetThread];le?le.worker.postMessage(B.data,X.transferList):console.error('Internal error! Worker sent a message "'+he+'" to target pthread '+X.targetThread+", but that thread no longer exists!"),Te.currentProxiedOperationCallerThread=void 0;return}if(he==="processQueuedMainThreadWork")Fp();else if(he==="spawnThread")Sp(B.data);else if(he==="cleanupThread")bp(X.thread);else if(he==="killThread")vg(X.thread);else if(he==="cancelThread")xg(X.thread);else if(he==="loaded")S.loaded=!0,E&&E(S),S.runPthread&&(S.runPthread(),delete S.runPthread);else if(he==="print")j("Thread "+X.threadId+": "+X.text);else if(he==="printErr")q("Thread "+X.threadId+": "+X.text);else if(he==="alert")alert("Thread "+X.threadId+": "+X.text);else if(he==="exit"){var pe=S.pthread&&Atomics.load(c(),S.pthread.threadInfoStruct+64>>2);pe&&Te.returnWorkerToPool(S)}else if(he==="exitProcess")try{JA(X.returnCode)}catch(ke){if(ke instanceof ml)return;throw ke}else he==="cancelDone"?Te.returnWorkerToPool(S):he==="objectTransfer"?Te.receiveObjectTransfer(B.data):B.data.target==="setimmediate"?S.postMessage(B.data):q("worker sent an unknown command "+he);Te.currentProxiedOperationCallerThread=void 0},S.onerror=function(B){q("pthread sent an error! "+B.filename+":"+B.lineno+": "+B.message)},x&&(S.on("message",function(B){S.onmessage({data:B})}),S.on("error",function(B){S.onerror(B)}),S.on("exit",function(B){})),S.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:re,wasmModule:ue})},allocateUnusedWorker:function(){var S=F("tfjs-backend-wasm-threaded-simd.worker.js");Te.unusedWorkers.push(new Worker(S))},getNewWorker:function(){return Te.unusedWorkers.length==0&&(Te.allocateUnusedWorker(),Te.loadWasmModuleToWorker(Te.unusedWorkers[0])),Te.unusedWorkers.length>0?Te.unusedWorkers.pop():null},busySpinWait:function(S){for(var E=performance.now()+S;performance.now()<E;);}};function wg(S,E){K0(S,E),Bi(S)}u.establishStackSpace=wg;function kg(){return se}u.getNoExitRuntime=kg;function Ig(S,E){return hn.get(S)(E)}u.invokeEntryPoint=Ig;function Sg(S,E,B,X){vs("Assertion failed: "+Ke(S)+", at: "+[E?Ke(E):"unknown filename",B,X?Ke(X):"unknown function"])}function Cg(S,E){var B=_main(S,E)}var Ra;x?Ra=function(){var S=process.hrtime();return S[0]*1e3+S[1]/1e6}:C?Ra=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?Ra=dateNow:Ra=function(){return performance.now()};function Tg(S){return i()[z0()>>2]=S,S}function Ng(S,E){if(C)return js(1,1,S,E)}function _g(S,E){if(S==E)postMessage({cmd:"processQueuedMainThreadWork"});else if(C)postMessage({targetThread:S,cmd:"processThreadQueue"});else{var B=Te.pthreads[S],X=B&&B.worker;if(!X)return;X.postMessage({cmd:"processThreadQueue"})}return 1}function Eg(){vs()}function Ag(S,E,B){var X=Rg(E,B);return yg[S].apply(null,X)}function Dg(S,E){}function yp(S,E,B){if(S<=0||S>a().length||S&!0)return-28;if(y){if(Atomics.load(i(),S>>2)!=E)return-6;for(var he=performance.now(),le=he+B,pe=Atomics.exchange(i(),Wi>>2,S);;){if(he=performance.now(),he>le)return pe=Atomics.exchange(i(),Wi>>2,0),-73;if(pe=Atomics.exchange(i(),Wi>>2,0),pe==0)break;if(Fp(),Atomics.load(i(),S>>2)!=E)return-6;pe=Atomics.exchange(i(),Wi>>2,S)}return 0}else{var X=Atomics.wait(i(),S>>2,E,B);if(X==="timed-out")return-73;if(X==="not-equal")return-6;if(X==="ok")return 0;throw"Atomics.wait returned an unexpected value "+X}}function Fg(S,E,B){o().copyWithin(S,E,E+B)}function $g(){return x?Gi("os").cpus().length:navigator.hardwareConcurrency}function js(S,E){for(var B=arguments.length-2,X=fl(),he=B,le=zi(he*8),pe=le>>3,ke=0;ke<B;ke++){var rt=arguments[2+ke];l()[pe+ke]=rt}var Kt=q0(S,he,le,E);return Bi(X),Kt}var il=[],cl=[];function Rg(S,E){cl.length=0;var B;for(E>>=2;B=o()[S++];){var X=B<105;X&&E&1&&E++,cl.push(X?l()[E++>>1]:i()[E]),++E}return cl}function Pg(S,E,B){il.length=E;for(var X=B>>3,he=0;he<E;he++)il[he]=l()[X+he];var le=S<0,pe=le?yg[-S-1]:cb[S];return pe.apply(null,il)}function Og(){return o().length}function Mg(S){try{return re.grow(S-xt.byteLength+65535>>>16),an(re.buffer),1}catch(E){}}function Lg(S){var E=Og();if(S<=E)return!1;var B=2147483648;if(S>B)return!1;for(var X=1;X<=4;X*=2){var he=E*(1+.2/X);he=Math.min(he,S+100663296);var le=Math.min(B,lt(Math.max(S,he),65536)),pe=Mg(le);if(pe)return!0}return!1}var Le={inEventHandler:0,removeAllEventListeners:function(){for(var S=Le.eventHandlers.length-1;S>=0;--S)Le._removeHandler(S);Le.eventHandlers=[],Le.deferredCalls=[]},registerRemoveEventListeners:function(){Le.removeEventListenersRegistered||(sl.push(Le.removeAllEventListeners),Le.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(S,E,B){function X(pe,ke){if(pe.length!=ke.length)return!1;for(var rt in pe)if(pe[rt]!=ke[rt])return!1;return!0}for(var he in Le.deferredCalls){var le=Le.deferredCalls[he];if(le.targetFunction==S&&X(le.argsList,B))return}Le.deferredCalls.push({targetFunction:S,precedence:E,argsList:B}),Le.deferredCalls.sort(function(pe,ke){return pe.precedence<ke.precedence})},removeDeferredCalls:function(S){for(var E=0;E<Le.deferredCalls.length;++E)Le.deferredCalls[E].targetFunction==S&&(Le.deferredCalls.splice(E,1),--E)},canPerformEventHandlerRequests:function(){return Le.inEventHandler&&Le.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!Le.canPerformEventHandlerRequests())for(var S=0;S<Le.deferredCalls.length;++S){var E=Le.deferredCalls[S];Le.deferredCalls.splice(S,1),--S,E.targetFunction.apply(null,E.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(S,E){for(var B=0;B<Le.eventHandlers.length;++B)Le.eventHandlers[B].target==S&&(!E||E==Le.eventHandlers[B].eventTypeString)&&Le._removeHandler(B--)},_removeHandler:function(S){var E=Le.eventHandlers[S];E.target.removeEventListener(E.eventTypeString,E.eventListenerFunc,E.useCapture),Le.eventHandlers.splice(S,1)},registerOrRemoveHandler:function(S){var E=function(he){++Le.inEventHandler,Le.currentEventHandler=S,Le.runDeferredCalls(),S.handlerFunc(he),Le.runDeferredCalls(),--Le.inEventHandler};if(S.callbackfunc)S.eventListenerFunc=E,S.target.addEventListener(S.eventTypeString,E,S.useCapture),Le.eventHandlers.push(S),Le.registerRemoveEventListeners();else for(var B=0;B<Le.eventHandlers.length;++B)Le.eventHandlers[B].target==S.target&&Le.eventHandlers[B].eventTypeString==S.eventTypeString&&Le._removeHandler(B--)},queueEventHandlerOnThread_iiii:function(S,E,B,X,he){var le=fl(),pe=zi(12);i()[pe>>2]=B,i()[pe+4>>2]=X,i()[pe+8>>2]=he,Db(0,S,637534208,E,X,pe),Bi(le)},getTargetThreadForEventCallback:function(S){switch(S){case 1:return 0;case 2:return Te.currentProxiedOperationCallerThread;default:return S}},getNodeNameForTarget:function(S){return S?S==window?"#window":S==screen?"#screen":S&&S.nodeName?S.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Bg(S){var E=tt(S)+1,B=Pa(E);return et(S,B,E),B}function zg(S,E,B,X){var he=fl(),le=zi(12),pe=0;E&&(pe=Bg(E)),i()[le>>2]=pe,i()[le+4>>2]=B,i()[le+8>>2]=X,Db(0,S,657457152,0,pe,le),Bi(he)}function Wg(S,E,B,X){E=E?Ke(E):"",zg(S,E,B,X)}function Vg(S){return S>2?Ke(S):S}var Ug=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Gg(S){S=Vg(S);var E=Ug[S]||(typeof document!="undefined"?document.querySelector(S):void 0);return E}function ul(S){return Gg(S)}function vp(S,E,B){var X=ul(S);if(!X)return-4;if(X.canvasSharedPtr&&(i()[X.canvasSharedPtr>>2]=E,i()[X.canvasSharedPtr+4>>2]=B),X.offscreenCanvas||!X.controlTransferredOffscreen){X.offscreenCanvas&&(X=X.offscreenCanvas);var he=!1;if(X.GLctxObject&&X.GLctxObject.GLctx){var le=X.GLctxObject.GLctx.getParameter(2978);he=le[0]===0&&le[1]===0&&le[2]===X.width&&le[3]===X.height}X.width=E,X.height=B,he&&X.GLctxObject.GLctx.viewport(0,0,E,B)}else if(X.canvasSharedPtr){var pe=i()[X.canvasSharedPtr+8>>2];return Wg(pe,S,E,B),1}else return-4;return 0}function xp(S,E,B){return C?js(2,1,S,E,B):vp(S,E,B)}function Hg(S,E,B){var X=ul(S);return X?vp(S,E,B):xp(S,E,B)}function jg(S){}function qg(S,E){}function Kg(S){var E=S.getExtension("ANGLE_instanced_arrays");if(E)return S.vertexAttribDivisor=function(B,X){E.vertexAttribDivisorANGLE(B,X)},S.drawArraysInstanced=function(B,X,he,le){E.drawArraysInstancedANGLE(B,X,he,le)},S.drawElementsInstanced=function(B,X,he,le,pe){E.drawElementsInstancedANGLE(B,X,he,le,pe)},1}function Xg(S){var E=S.getExtension("OES_vertex_array_object");if(E)return S.createVertexArray=function(){return E.createVertexArrayOES()},S.deleteVertexArray=function(B){E.deleteVertexArrayOES(B)},S.bindVertexArray=function(B){E.bindVertexArrayOES(B)},S.isVertexArray=function(B){return E.isVertexArrayOES(B)},1}function Yg(S){var E=S.getExtension("WEBGL_draw_buffers");if(E)return S.drawBuffers=function(B,X){E.drawBuffersWEBGL(B,X)},1}function Zg(S){return!!(S.multiDrawWebgl=S.getExtension("WEBGL_multi_draw"))}var nt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(E){nt.lastError||(nt.lastError=E)},getNewId:function(S){for(var E=nt.counter++,B=S.length;B<E;B++)S[B]=null;return E},getSource:function(S,E,B,X){for(var he="",le=0;le<E;++le){var pe=X?i()[X+le*4>>2]:-1;he+=Ke(i()[B+le*4>>2],pe<0?void 0:pe)}return he},createContext:function(S,E){var B=S.getContext("webgl",E);if(!B)return 0;var X=nt.registerContext(B,E);return X},registerContext:function(S,E){var B=Pa(8);i()[B+4>>2]=Xs();var X={handle:B,attributes:E,version:E.majorVersion,GLctx:S};return S.canvas&&(S.canvas.GLctxObject=X),nt.contexts[B]=X,(typeof E.enableExtensionsByDefault=="undefined"||E.enableExtensionsByDefault)&&nt.initExtensions(X),B},makeContextCurrent:function(S){return nt.currentContext=nt.contexts[S],u.ctx=qs=nt.currentContext&&nt.currentContext.GLctx,!(S&&!qs)},getContext:function(S){return nt.contexts[S]},deleteContext:function(S){nt.currentContext===nt.contexts[S]&&(nt.currentContext=null),typeof Le=="object"&&Le.removeAllHandlersOnTarget(nt.contexts[S].GLctx.canvas),nt.contexts[S]&&nt.contexts[S].GLctx.canvas&&(nt.contexts[S].GLctx.canvas.GLctxObject=void 0),hl(nt.contexts[S].handle),nt.contexts[S]=null},initExtensions:function(S){if(S||(S=nt.currentContext),!S.initExtensionsDone){S.initExtensionsDone=!0;var E=S.GLctx;Kg(E),Xg(E),Yg(E),E.disjointTimerQueryExt=E.getExtension("EXT_disjoint_timer_query"),Zg(E);var B=E.getSupportedExtensions()||[];B.forEach(function(X){X.indexOf("lose_context")<0&&X.indexOf("debug")<0&&E.getExtension(X)})}},populateUniformTable:function(S){for(var E=nt.programs[S],B=nt.programInfos[S]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},X=B.uniforms,he=qs.getProgramParameter(E,35718),le=0;le<he;++le){var pe=qs.getActiveUniform(E,le),ke=pe.name;B.maxUniformLength=Math.max(B.maxUniformLength,ke.length+1),ke.slice(-1)=="]"&&(ke=ke.slice(0,ke.lastIndexOf("[")));var rt=qs.getUniformLocation(E,ke);if(rt){var Kt=nt.getNewId(nt.uniforms);X[ke]=[pe.size,Kt],nt.uniforms[Kt]=rt;for(var Vt=1;Vt<pe.size;++Vt){var Ys=ke+"["+Vt+"]";rt=qs.getUniformLocation(E,Ys),Kt=nt.getNewId(nt.uniforms),nt.uniforms[Kt]=rt}}}}},Jg=["default","low-power","high-performance"];function Qg(S,E){var B=E>>2,X=i()[B+(24>>2)],he={alpha:!!i()[B+(0>>2)],depth:!!i()[B+(4>>2)],stencil:!!i()[B+(8>>2)],antialias:!!i()[B+(12>>2)],premultipliedAlpha:!!i()[B+(16>>2)],preserveDrawingBuffer:!!i()[B+(20>>2)],powerPreference:Jg[X],failIfMajorPerformanceCaveat:!!i()[B+(28>>2)],majorVersion:i()[B+(32>>2)],minorVersion:i()[B+(36>>2)],enableExtensionsByDefault:i()[B+(40>>2)],explicitSwapControl:i()[B+(44>>2)],proxyContextToMainThread:i()[B+(48>>2)],renderViaOffscreenBackBuffer:i()[B+(52>>2)]},le=ul(S);if(!le||he.explicitSwapControl)return 0;var pe=nt.createContext(le,he);return pe}function eb(S,E){return Qg(S,E)}var Mi={mappings:{},buffers:[null,[],[]],printChar:function(S,E){var B=Mi.buffers[S];E===0||E===10?((S===1?j:q)(Be(B,0)),B.length=0):B.push(E)},varargs:void 0,get:function(){Mi.varargs+=4;var S=i()[Mi.varargs-4>>2];return S},getStr:function(S){var E=Ke(S);return E},get64:function(S,E){return S}};function wp(S){return C?js(3,1,S):0}function kp(S,E,B,X,he){if(C)return js(4,1,S,E,B,X,he)}function Ip(S,E,B,X){if(C)return js(5,1,S,E,B,X);for(var he=0,le=0;le<B;le++){for(var pe=i()[E+le*8>>2],ke=i()[E+(le*8+4)>>2],rt=0;rt<ke;rt++)Mi.printChar(S,o()[pe+rt]);he+=ke}return i()[X>>2]=he,0}function tb(S){var E=Te.threadExitHandlers.pop();S&&E()}function nb(S,E){Te.threadExitHandlers.push(function(){hn.get(S)(E)})}function Sp(S){if(C)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var E=Te.getNewWorker();if(E.pthread!==void 0)throw"Internal error!";if(!S.pthread_ptr)throw"Internal error, no pthread ptr!";Te.runningWorkers.push(E);for(var B=Pa(128*4),X=0;X<128;++X)i()[B+X*4>>2]=0;var he=S.stackBase+S.stackSize,le=Te.pthreads[S.pthread_ptr]={worker:E,stackBase:S.stackBase,stackSize:S.stackSize,allocatedOwnStack:S.allocatedOwnStack,threadInfoStruct:S.pthread_ptr},pe=le.threadInfoStruct>>2;Atomics.store(c(),pe+(64>>2),S.detached),Atomics.store(c(),pe+(100>>2),B),Atomics.store(c(),pe+(40>>2),le.threadInfoStruct),Atomics.store(c(),pe+(80>>2),S.stackSize),Atomics.store(c(),pe+(76>>2),he),Atomics.store(c(),pe+(104>>2),S.stackSize),Atomics.store(c(),pe+(104+8>>2),he),Atomics.store(c(),pe+(104+12>>2),S.detached);var ke=W0(),rt=ke+40;Atomics.store(c(),pe+(172>>2),rt),E.pthread=le;var Kt={cmd:"run",start_routine:S.startRoutine,arg:S.arg,threadInfoStruct:S.pthread_ptr,stackBase:S.stackBase,stackSize:S.stackSize};E.runPthread=function(){Kt.time=performance.now(),E.postMessage(Kt,S.transferList)},E.loaded&&(E.runPthread(),delete E.runPthread)}function rb(S,E,B,X){if(typeof SharedArrayBuffer=="undefined")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!S)return q("pthread_create called with a null thread pointer!"),28;var he=[],le=0;if(C&&(he.length===0||le))return j0(687865856,S,E,B,X);if(le)return le;var pe=0,ke=0,rt=0;E&&E!=-1?(pe=i()[E>>2],pe+=81920,ke=i()[E+8>>2],rt=i()[E+12>>2]!==0):pe=2097152;var Kt=ke==0;Kt?ke=X0(16,pe):(ke-=pe,we(ke>0));for(var Vt=Pa(228),Ys=0;Ys<228>>2;++Ys)c()[(Vt>>2)+Ys]=0;i()[S>>2]=Vt,i()[Vt+12>>2]=Vt;var Vi=Vt+152;i()[Vi>>2]=Vi;var vn={stackBase:ke,stackSize:pe,allocatedOwnStack:Kt,detached:rt,startRoutine:B,pthread_ptr:Vt,arg:X,transferList:he};return C?(vn.cmd="spawnThread",postMessage(vn,he)):Sp(vn),0}function sb(){if(!!C){var S=Xs();if(!!S){var E=Atomics.load(c(),S+56>>2);if(!E){var B=Atomics.load(c(),S+0>>2);if(B==2)throw"Canceled!"}}}}function ab(){x||v||K("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function ob(S,E,B){if(!S)return q("pthread_join attempted on a null thread pointer!"),Hs.ESRCH;if(C&&Xs()==S)return q("PThread "+S+" is attempting to join to itself!"),Hs.EDEADLK;if(!C&&G0()==S)return q("Main thread "+S+" is attempting to join to itself!"),Hs.EDEADLK;var X=i()[S+12>>2];if(X!==S)return q("pthread_join attempted on thread "+S+", which does not point to a valid thread, or does not exist anymore!"),Hs.ESRCH;var he=Atomics.load(c(),S+64>>2);if(he)return q("Attempted to join thread "+S+", which was already detached!"),Hs.EINVAL;for(B&&ab();;){var le=Atomics.load(c(),S+0>>2);if(le==1){var pe=Atomics.load(c(),S+4>>2);return E&&(i()[E>>2]=pe),Atomics.store(c(),S+64>>2,1),C?postMessage({cmd:"cleanupThread",thread:S}):bp(S),0}if(!B)return Hs.EBUSY;sb(),C||Fp(),yp(S+0,le,C?100:1)}}function ib(S,E){return ob(S,E,!0)}function Cp(S){if(C)return js(6,1,S);switch(S){case 30:return 16384;case 85:var E=2147483648;return E/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 Tg(28),-1}C||Te.initMainThreadBlock();var qs,cb=[null,Ng,xp,wp,kp,Ip,Cp],ub={e:Sg,r:Cg,x:_g,b:Eg,y:Ag,j:Dg,d:yp,c:ol,f:Ra,p:Fg,A:$g,u:Pg,q:Lg,v:Hg,i:jg,s:qg,w:eb,l:wp,n:kp,g:Ip,o:gp,a:re||u.wasmMemory,z:tb,k:nb,h:rb,m:ib,t:Cp},B0=bg(),Tp=u.___wasm_call_ctors=function(){return(Tp=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},lb=u._init=function(){return(lb=u._init=u.asm.C).apply(null,arguments)},db=u._init_with_threads_count=function(){return(db=u._init_with_threads_count=u.asm.D).apply(null,arguments)},pb=u._get_threads_count=function(){return(pb=u._get_threads_count=u.asm.E).apply(null,arguments)},hb=u._register_tensor=function(){return(hb=u._register_tensor=u.asm.F).apply(null,arguments)},fb=u._dispose_data=function(){return(fb=u._dispose_data=u.asm.G).apply(null,arguments)},mb=u._dispose=function(){return(mb=u._dispose=u.asm.H).apply(null,arguments)},gb=u._Abs=function(){return(gb=u._Abs=u.asm.J).apply(null,arguments)},bb=u._Add=function(){return(bb=u._Add=u.asm.K).apply(null,arguments)},yb=u._AddN=function(){return(yb=u._AddN=u.asm.L).apply(null,arguments)},vb=u._All=function(){return(vb=u._All=u.asm.M).apply(null,arguments)},xb=u._Any=function(){return(xb=u._Any=u.asm.N).apply(null,arguments)},wb=u._ArgMax=function(){return(wb=u._ArgMax=u.asm.O).apply(null,arguments)},kb=u._AvgPool=function(){return(kb=u._AvgPool=u.asm.P).apply(null,arguments)},Ib=u._BatchMatMul=function(){return(Ib=u._BatchMatMul=u.asm.Q).apply(null,arguments)},Sb=u._Ceil=function(){return(Sb=u._Ceil=u.asm.R).apply(null,arguments)},Cb=u._ClipByValue=function(){return(Cb=u._ClipByValue=u.asm.S).apply(null,arguments)},Tb=u._Conv2D=function(){return(Tb=u._Conv2D=u.asm.T).apply(null,arguments)},Nb=u._Conv2DBackpropInput=function(){return(Nb=u._Conv2DBackpropInput=u.asm.U).apply(null,arguments)},_b=u._Cos=function(){return(_b=u._Cos=u.asm.V).apply(null,arguments)},Eb=u._Cosh=function(){return(Eb=u._Cosh=u.asm.W).apply(null,arguments)},Np=u._CropAndResize=function(){return(Np=u._CropAndResize=u.asm.X).apply(null,arguments)},_p=u._Cumsum=function(){return(_p=u._Cumsum=u.asm.Y).apply(null,arguments)},Ep=u._DepthToSpace=function(){return(Ep=u._DepthToSpace=u.asm.Z).apply(null,arguments)},ll=u._DepthwiseConv2dNative=function(){return(ll=u._DepthwiseConv2dNative=u.asm._).apply(null,arguments)},Li=u._Elu=function(){return(Li=u._Elu=u.asm.$).apply(null,arguments)},Ab=u._Equal=function(){return(Ab=u._Equal=u.asm.aa).apply(null,arguments)},dl=u._Exp=function(){return(dl=u._Exp=u.asm.ba).apply(null,arguments)},Z=u._FlipLeftRight=function(){return(Z=u._FlipLeftRight=u.asm.ca).apply(null,arguments)},oe=u._Floor=function(){return(oe=u._Floor=u.asm.da).apply(null,arguments)},ye=u._FloorDiv=function(){return(ye=u._FloorDiv=u.asm.ea).apply(null,arguments)},Ye=u._FusedBatchNorm=function(){return(Ye=u._FusedBatchNorm=u.asm.fa).apply(null,arguments)},Dt=u._FusedConv2D=function(){return(Dt=u._FusedConv2D=u.asm.ga).apply(null,arguments)},wt=u._FusedDepthwiseConv2D=function(){return(wt=u._FusedDepthwiseConv2D=u.asm.ha).apply(null,arguments)},Ve=u._Gather=function(){return(Ve=u._Gather=u.asm.ia).apply(null,arguments)},He=u._GatherNd=function(){return(He=u._GatherNd=u.asm.ja).apply(null,arguments)},on=u._Greater=function(){return(on=u._Greater=u.asm.ka).apply(null,arguments)},xs=u._GreaterEqual=function(){return(xs=u._GreaterEqual=u.asm.la).apply(null,arguments)},ws=u._LeakyRelu=function(){return(ws=u._LeakyRelu=u.asm.ma).apply(null,arguments)},Ap=u._Less=function(){return(Ap=u._Less=u.asm.na).apply(null,arguments)},pl=u._LessEqual=function(){return(pl=u._LessEqual=u.asm.oa).apply(null,arguments)},jn=u._Log=function(){return(jn=u._Log=u.asm.pa).apply(null,arguments)},Ks=u._LogicalAnd=function(){return(Ks=u._LogicalAnd=u.asm.qa).apply(null,arguments)},Dp=u._Max=function(){return(Dp=u._Max=u.asm.ra).apply(null,arguments)},oA=u._MaxPool=function(){return(oA=u._MaxPool=u.asm.sa).apply(null,arguments)},iA=u._Maximum=function(){return(iA=u._Maximum=u.asm.ta).apply(null,arguments)},cA=u._Mean=function(){return(cA=u._Mean=u.asm.ua).apply(null,arguments)},uA=u._Min=function(){return(uA=u._Min=u.asm.va).apply(null,arguments)},lA=u._Minimum=function(){return(lA=u._Minimum=u.asm.wa).apply(null,arguments)},dA=u._MirrorPad=function(){return(dA=u._MirrorPad=u.asm.xa).apply(null,arguments)},pA=u._Multiply=function(){return(pA=u._Multiply=u.asm.ya).apply(null,arguments)},hA=u._Neg=function(){return(hA=u._Neg=u.asm.za).apply(null,arguments)},fA=u._NonMaxSuppressionV3=function(){return(fA=u._NonMaxSuppressionV3=u.asm.Aa).apply(null,arguments)},mA=u._NonMaxSuppressionV4=function(){return(mA=u._NonMaxSuppressionV4=u.asm.Ba).apply(null,arguments)},gA=u._NonMaxSuppressionV5=function(){return(gA=u._NonMaxSuppressionV5=u.asm.Ca).apply(null,arguments)},bA=u._NotEqual=function(){return(bA=u._NotEqual=u.asm.Da).apply(null,arguments)},yA=u._OneHot=function(){return(yA=u._OneHot=u.asm.Ea).apply(null,arguments)},vA=u._PadV2=function(){return(vA=u._PadV2=u.asm.Fa).apply(null,arguments)},xA=u._Pow=function(){return(xA=u._Pow=u.asm.Ga).apply(null,arguments)},wA=u._Prelu=function(){return(wA=u._Prelu=u.asm.Ha).apply(null,arguments)},kA=u._Prod=function(){return(kA=u._Prod=u.asm.Ia).apply(null,arguments)},IA=u._RealDiv=function(){return(IA=u._RealDiv=u.asm.Ja).apply(null,arguments)},SA=u._Relu=function(){return(SA=u._Relu=u.asm.Ka).apply(null,arguments)},CA=u._Relu6=function(){return(CA=u._Relu6=u.asm.La).apply(null,arguments)},TA=u._ResizeBilinear=function(){return(TA=u._ResizeBilinear=u.asm.Ma).apply(null,arguments)},NA=u._Reverse=function(){return(NA=u._Reverse=u.asm.Na).apply(null,arguments)},_A=u._RotateWithOffset=function(){return(_A=u._RotateWithOffset=u.asm.Oa).apply(null,arguments)},EA=u._Round=function(){return(EA=u._Round=u.asm.Pa).apply(null,arguments)},AA=u._Rsqrt=function(){return(AA=u._Rsqrt=u.asm.Qa).apply(null,arguments)},DA=u._ScatterNd=function(){return(DA=u._ScatterNd=u.asm.Ra).apply(null,arguments)},FA=u._SelectV2=function(){return(FA=u._SelectV2=u.asm.Sa).apply(null,arguments)},$A=u._Sigmoid=function(){return($A=u._Sigmoid=u.asm.Ta).apply(null,arguments)},RA=u._Sin=function(){return(RA=u._Sin=u.asm.Ua).apply(null,arguments)},PA=u._Softmax=function(){return(PA=u._Softmax=u.asm.Va).apply(null,arguments)},OA=u._Sqrt=function(){return(OA=u._Sqrt=u.asm.Wa).apply(null,arguments)},MA=u._Square=function(){return(MA=u._Square=u.asm.Xa).apply(null,arguments)},LA=u._SquaredDifference=function(){return(LA=u._SquaredDifference=u.asm.Ya).apply(null,arguments)},BA=u._Step=function(){return(BA=u._Step=u.asm.Za).apply(null,arguments)},zA=u._StridedSlice=function(){return(zA=u._StridedSlice=u.asm._a).apply(null,arguments)},WA=u._Sub=function(){return(WA=u._Sub=u.asm.$a).apply(null,arguments)},VA=u._Sum=function(){return(VA=u._Sum=u.asm.ab).apply(null,arguments)},UA=u._Tan=function(){return(UA=u._Tan=u.asm.bb).apply(null,arguments)},GA=u._Tanh=function(){return(GA=u._Tanh=u.asm.cb).apply(null,arguments)},HA=u._Tile=function(){return(HA=u._Tile=u.asm.db).apply(null,arguments)},jA=u._TopK=function(){return(jA=u._TopK=u.asm.eb).apply(null,arguments)},qA=u._Transform=function(){return(qA=u._Transform=u.asm.fb).apply(null,arguments)},KA=u._Transpose=function(){return(KA=u._Transpose=u.asm.gb).apply(null,arguments)},XA=u.__FusedMatMul=function(){return(XA=u.__FusedMatMul=u.asm.hb).apply(null,arguments)},Pa=u._malloc=function(){return(Pa=u._malloc=u.asm.ib).apply(null,arguments)},hl=u._free=function(){return(hl=u._free=u.asm.jb).apply(null,arguments)},z0=u.___errno_location=function(){return(z0=u.___errno_location=u.asm.kb).apply(null,arguments)},W0=u._emscripten_get_global_libc=function(){return(W0=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},Xs=u._pthread_self=function(){return(Xs=u._pthread_self=u.asm.mb).apply(null,arguments)},V0=u.___pthread_tsd_run_dtors=function(){return(V0=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},Fp=u._emscripten_main_thread_process_queued_calls=function(){return(Fp=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},YA=u._emscripten_current_thread_process_queued_calls=function(){return(YA=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},U0=u._emscripten_register_main_browser_thread_id=function(){return(U0=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},G0=u._emscripten_main_browser_thread_id=function(){return(G0=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},H0=u.__emscripten_do_dispatch_to_thread=function(){return(H0=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},j0=u._emscripten_sync_run_in_main_thread_4=function(){return(j0=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},q0=u._emscripten_run_in_main_runtime_thread_js=function(){return(q0=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},Db=u.__emscripten_call_on_thread=function(){return(Db=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},ZA=u._emscripten_tls_init=function(){return(ZA=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},Fb=u.__emscripten_thread_init=function(){return(Fb=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},fl=u.stackSave=function(){return(fl=u.stackSave=u.asm.yb).apply(null,arguments)},Bi=u.stackRestore=function(){return(Bi=u.stackRestore=u.asm.zb).apply(null,arguments)},zi=u.stackAlloc=function(){return(zi=u.stackAlloc=u.asm.Ab).apply(null,arguments)},K0=u._emscripten_stack_set_limits=function(){return(K0=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},X0=u._memalign=function(){return(X0=u._memalign=u.asm.Cb).apply(null,arguments)},Y0=u.__emscripten_allow_main_runtime_queued_calls=10512,Wi=u.__emscripten_main_thread_futex=12148;u.cwrap=Me,u.PThread=Te,u.PThread=Te,u.wasmMemory=re,u.ExitStatus=ml;var $p;function ml(S){this.name="ExitStatus",this.message="Program terminated with exit("+S+")",this.status=S}Fa=function S(){$p||$b(),$p||(Fa=S)};function $b(S){if(S=S||m,yr>0)return;if(C){d(u),lp(),postMessage({cmd:"loaded"});return}if(up(),yr>0)return;function E(){$p||($p=!0,u.calledRun=!0,!de&&(lp(),dp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),pp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),E()},1)):E()}u.run=$b;function JA(S,E){if(!(E&&se&&S===0)){if(!E&&C)throw postMessage({cmd:"exitProcess",returnCode:S}),new ml(S);se||(Te.terminateAllThreads(),me=S,Rn(),u.onExit&&u.onExit(S),de=!0),b(S,new ml(S))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return C&&(se=!1,Te.initWorker()),$b(),s.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),CD=kt({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.10.0_@tensorflow+tfjs-core@3.10.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(s){s=s||{};var a=typeof s!="undefined"?s:{},o,i;a.ready=new Promise(function(Z,oe){o=Z,i=oe});var c={},l;for(l in a)a.hasOwnProperty(l)&&(c[l]=a[l]);var u=[],d="./this.program",p=function(Z,oe){throw oe},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var b="";function y(Z){return a.locateFile?a.locateFile(Z,b):b+Z}var v,x,k,C,N,F;m?(f?b=gl().dirname(b)+"/":b=__dirname+"/",v=function(oe,ye){return N||(N=Gi("fs")),F||(F=gl()),oe=F.normalize(oe),N.readFileSync(oe,ye?null:"utf8")},k=function(oe){var ye=v(oe,!0);return ye.buffer||(ye=new Uint8Array(ye)),j(ye.buffer),ye},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(Z){if(!(Z instanceof Ab))throw Z}),process.on("unhandledRejection",Fr),p=function(Z){process.exit(Z)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(v=function(oe){return read(oe)}),k=function(oe){var ye;return typeof readbuffer=="function"?new Uint8Array(readbuffer(oe)):(ye=read(oe,"binary"),j(typeof ye=="object"),ye)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(Z){quit(Z)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?b=self.location.href:typeof document!="undefined"&&document.currentScript&&(b=document.currentScript.src),r&&(b=r),b.indexOf("blob:")!==0?b=b.substr(0,b.lastIndexOf("/")+1):b="",v=function(Z){var oe=new XMLHttpRequest;return oe.open("GET",Z,!1),oe.send(null),oe.responseText},f&&(k=function(Z){var oe=new XMLHttpRequest;return oe.open("GET",Z,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),x=function(Z,oe,ye){var Ye=new XMLHttpRequest;Ye.open("GET",Z,!0),Ye.responseType="arraybuffer",Ye.onload=function(){if(Ye.status==200||Ye.status==0&&Ye.response){oe(Ye.response);return}ye()},Ye.onerror=ye,Ye.send(null)},C=function(Z){document.title=Z});var R=a.print||console.log.bind(console),O=a.printErr||console.warn.bind(console);for(l in c)c.hasOwnProperty(l)&&(a[l]=c[l]);c=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var D;a.wasmBinary&&(D=a.wasmBinary);var P=a.noExitRuntime||!0;typeof WebAssembly!="object"&&Fr("no native wasm support detected");var T,L=!1,G;function j(Z,oe){Z||Fr("Assertion failed: "+oe)}function q(Z){var oe=a["_"+Z];return j(oe,"Cannot call unknown function "+Z+", make sure it is exported"),oe}function K(Z,oe,ye,Ye,Dt){var wt={string:function(jn){var Ks=0;if(jn!=null&&jn!==0){var Dp=(jn.length<<2)+1;Ks=ll(Dp),re(jn,Ks,Dp)}return Ks},array:function(jn){var Ks=ll(jn.length);return ue(jn,Ks),Ks}};function Ve(jn){return oe==="string"?ae(jn):oe==="boolean"?Boolean(jn):jn}var He=q(Z),on=[],xs=0;if(Ye)for(var ws=0;ws<Ye.length;ws++){var Ap=wt[ye[ws]];Ap?(xs===0&&(xs=_p()),on[ws]=Ap(Ye[ws])):on[ws]=Ye[ws]}var pl=He.apply(null,on);return pl=Ve(pl),xs!==0&&Ep(xs),pl}function ee(Z,oe,ye,Ye){ye=ye||[];var Dt=ye.every(function(Ve){return Ve==="number"}),wt=oe!=="string";return wt&&Dt&&!Ye?q(Z):function(){return K(Z,oe,ye,arguments,Ye)}}var te=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ne(Z,oe,ye){for(var Ye=oe+ye,Dt=oe;Z[Dt]&&!(Dt>=Ye);)++Dt;if(Dt-oe>16&&Z.subarray&&te)return te.decode(Z.subarray(oe,Dt));for(var wt="";oe<Dt;){var Ve=Z[oe++];if(!(Ve&128)){wt+=String.fromCharCode(Ve);continue}var He=Z[oe++]&63;if((Ve&224)==192){wt+=String.fromCharCode((Ve&31)<<6|He);continue}var on=Z[oe++]&63;if((Ve&240)==224?Ve=(Ve&15)<<12|He<<6|on:Ve=(Ve&7)<<18|He<<12|on<<6|Z[oe++]&63,Ve<65536)wt+=String.fromCharCode(Ve);else{var xs=Ve-65536;wt+=String.fromCharCode(55296|xs>>10,56320|xs&1023)}}return wt}function ae(Z,oe){return Z?ne(Ce,Z,oe):""}function se(Z,oe,ye,Ye){if(!(Ye>0))return 0;for(var Dt=ye,wt=ye+Ye-1,Ve=0;Ve<Z.length;++Ve){var He=Z.charCodeAt(Ve);if(He>=55296&&He<=57343){var on=Z.charCodeAt(++Ve);He=65536+((He&1023)<<10)|on&1023}if(He<=127){if(ye>=wt)break;oe[ye++]=He}else if(He<=2047){if(ye+1>=wt)break;oe[ye++]=192|He>>6,oe[ye++]=128|He&63}else if(He<=65535){if(ye+2>=wt)break;oe[ye++]=224|He>>12,oe[ye++]=128|He>>6&63,oe[ye++]=128|He&63}else{if(ye+3>=wt)break;oe[ye++]=240|He>>18,oe[ye++]=128|He>>12&63,oe[ye++]=128|He>>6&63,oe[ye++]=128|He&63}}return oe[ye]=0,ye-Dt}function re(Z,oe,ye){return se(Z,Ce,oe,ye)}function ue(Z,oe){we.set(Z,oe)}function de(Z,oe){return Z%oe>0&&(Z+=oe-Z%oe),Z}var me,we,Ce,_e,Me,Be,Ke,st,et;function tt(Z){me=Z,a.HEAP8=we=new Int8Array(Z),a.HEAP16=_e=new Int16Array(Z),a.HEAP32=Be=new Int32Array(Z),a.HEAPU8=Ce=new Uint8Array(Z),a.HEAPU16=Me=new Uint16Array(Z),a.HEAPU32=Ke=new Uint32Array(Z),a.HEAPF32=st=new Float32Array(Z),a.HEAPF64=et=new Float64Array(Z)}var it=a.INITIAL_MEMORY||16777216,lt,xt=[],Nt=[],$n=[],sn=[],Dr=!1;Nt.push({func:function(){gp()}});function yn(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)an(a.preRun.shift());yr(xt)}function Hn(){Dr=!0,yr(Nt)}function br(){yr($n)}function ar(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)Yr(a.postRun.shift());yr(sn)}function an(Z){xt.unshift(Z)}function Yr(Z){sn.unshift(Z)}var hn=0,Zr=null,Jr=null;function Gs(Z){hn++,a.monitorRunDependencies&&a.monitorRunDependencies(hn)}function sl(Z){if(hn--,a.monitorRunDependencies&&a.monitorRunDependencies(hn),hn==0&&(Zr!==null&&(clearInterval(Zr),Zr=null),Jr)){var oe=Jr;Jr=null,oe()}}a.preloadedImages={},a.preloadedAudios={};function Fr(Z){a.onAbort&&a.onAbort(Z),Z+="",O(Z),L=!0,G=1,Z="abort("+Z+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(Z);throw i(oe),oe}function cp(Z,oe){return String.prototype.startsWith?Z.startsWith(oe):Z.indexOf(oe)===0}var ug="data:application/octet-stream;base64,";function up(Z){return cp(Z,ug)}var lp="file://";function dp(Z){return cp(Z,lp)}var Rn="tfjs-backend-wasm.wasm";up(Rn)||(Rn=y(Rn));function pp(Z){try{if(Z==Rn&&D)return new Uint8Array(D);if(k)return k(Z);throw"both async and sync fetching of the wasm failed"}catch(oe){Fr(oe)}}function lg(){if(!D&&(h||f)){if(typeof fetch=="function"&&!dp(Rn))return fetch(Rn,{credentials:"same-origin"}).then(function(Z){if(!Z.ok)throw"failed to load wasm binary file at '"+Rn+"'";return Z.arrayBuffer()}).catch(function(){return pp(Rn)});if(x)return new Promise(function(Z,oe){x(Rn,function(ye){Z(new Uint8Array(ye))},oe)})}return Promise.resolve().then(function(){return pp(Rn)})}function dg(){var Z={a:bg};function oe(Ve,He){var on=Ve.exports;a.asm=on,T=a.asm.j,tt(T.buffer),lt=a.asm.r,sl("wasm-instantiate")}Gs("wasm-instantiate");function ye(Ve){oe(Ve.instance)}function Ye(Ve){return lg().then(function(He){return WebAssembly.instantiate(He,Z)}).then(Ve,function(He){O("failed to asynchronously prepare wasm: "+He),Fr(He)})}function Dt(){return!D&&typeof WebAssembly.instantiateStreaming=="function"&&!up(Rn)&&!dp(Rn)&&typeof fetch=="function"?fetch(Rn,{credentials:"same-origin"}).then(function(Ve){var He=WebAssembly.instantiateStreaming(Ve,Z);return He.then(ye,function(on){return O("wasm streaming compile failed: "+on),O("falling back to ArrayBuffer instantiation"),Ye(ye)})}):Ye(ye)}if(a.instantiateWasm)try{var wt=a.instantiateWasm(Z,oe);return wt}catch(Ve){return O("Module.instantiateWasm callback failed with error: "+Ve),!1}return Dt().catch(i),{}}function yr(Z){for(;Z.length>0;){var oe=Z.shift();if(typeof oe=="function"){oe(a);continue}var ye=oe.func;typeof ye=="number"?oe.arg===void 0?lt.get(ye)():lt.get(ye)(oe.arg):ye(oe.arg===void 0?null:oe.arg)}}function al(){Fr()}function Fa(Z,oe,ye){Ce.copyWithin(Z,oe,oe+ye)}function pg(){return Ce.length}function hg(Z){try{return T.grow(Z-me.byteLength+65535>>>16),tt(T.buffer),1}catch(oe){}}function vs(Z){var oe=pg(),ye=2147483648;if(Z>ye)return!1;for(var Ye=1;Ye<=4;Ye*=2){var Dt=oe*(1+.2/Ye);Dt=Math.min(Dt,Z+100663296);var wt=Math.min(ye,de(Math.max(Z,Dt),65536)),Ve=hg(wt);if(Ve)return!0}return!1}var $a={mappings:{},buffers:[null,[],[]],printChar:function(Z,oe){var ye=$a.buffers[Z];oe===0||oe===10?((Z===1?R:O)(ne(ye,0)),ye.length=0):ye.push(oe)},varargs:void 0,get:function(){$a.varargs+=4;var Z=Be[$a.varargs-4>>2];return Z},getStr:function(Z){var oe=ae(Z);return oe},get64:function(Z,oe){return Z}};function fg(Z){return 0}function hp(Z,oe,ye,Ye,Dt){}function mg(Z,oe,ye,Ye){for(var Dt=0,wt=0;wt<ye;wt++){for(var Ve=Be[oe+wt*8>>2],He=Be[oe+(wt*8+4)>>2],on=0;on<He;on++)$a.printChar(Z,Ce[Ve+on]);Dt+=He}return Be[Ye>>2]=Dt,0}function fp(){return 6}function Pn(){return 28}function mp(Z){return Be[Np()>>2]=Z,Z}function gg(Z){switch(Z){case 30:return 16384;case 85:var oe=2147483648;return oe/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return mp(28),-1}var bg={a:al,d:Fa,e:vs,f:fg,c:hp,b:mg,h:fp,g:Pn,i:gg},yg=dg(),gp=a.___wasm_call_ctors=function(){return(gp=a.___wasm_call_ctors=a.asm.k).apply(null,arguments)},Oi=a._init=function(){return(Oi=a._init=a.asm.l).apply(null,arguments)},Hs=a._init_with_threads_count=function(){return(Hs=a._init_with_threads_count=a.asm.m).apply(null,arguments)},ol=a._get_threads_count=function(){return(ol=a._get_threads_count=a.asm.n).apply(null,arguments)},vg=a._register_tensor=function(){return(vg=a._register_tensor=a.asm.o).apply(null,arguments)},xg=a._dispose_data=function(){return(xg=a._dispose_data=a.asm.p).apply(null,arguments)},bp=a._dispose=function(){return(bp=a._dispose=a.asm.q).apply(null,arguments)},Te=a._Abs=function(){return(Te=a._Abs=a.asm.s).apply(null,arguments)},wg=a._Add=function(){return(wg=a._Add=a.asm.t).apply(null,arguments)},kg=a._AddN=function(){return(kg=a._AddN=a.asm.u).apply(null,arguments)},Ig=a._All=function(){return(Ig=a._All=a.asm.v).apply(null,arguments)},Sg=a._Any=function(){return(Sg=a._Any=a.asm.w).apply(null,arguments)},Cg=a._ArgMax=function(){return(Cg=a._ArgMax=a.asm.x).apply(null,arguments)},Ra=a._AvgPool=function(){return(Ra=a._AvgPool=a.asm.y).apply(null,arguments)},Tg=a._BatchMatMul=function(){return(Tg=a._BatchMatMul=a.asm.z).apply(null,arguments)},Ng=a._Ceil=function(){return(Ng=a._Ceil=a.asm.A).apply(null,arguments)},_g=a._ClipByValue=function(){return(_g=a._ClipByValue=a.asm.B).apply(null,arguments)},Eg=a._Conv2D=function(){return(Eg=a._Conv2D=a.asm.C).apply(null,arguments)},Ag=a._Conv2DBackpropInput=function(){return(Ag=a._Conv2DBackpropInput=a.asm.D).apply(null,arguments)},Dg=a._Cos=function(){return(Dg=a._Cos=a.asm.E).apply(null,arguments)},yp=a._Cosh=function(){return(yp=a._Cosh=a.asm.F).apply(null,arguments)},Fg=a._CropAndResize=function(){return(Fg=a._CropAndResize=a.asm.G).apply(null,arguments)},$g=a._Cumsum=function(){return($g=a._Cumsum=a.asm.H).apply(null,arguments)},js=a._DepthToSpace=function(){return(js=a._DepthToSpace=a.asm.I).apply(null,arguments)},il=a._DepthwiseConv2dNative=function(){return(il=a._DepthwiseConv2dNative=a.asm.J).apply(null,arguments)},cl=a._Elu=function(){return(cl=a._Elu=a.asm.K).apply(null,arguments)},Rg=a._Equal=function(){return(Rg=a._Equal=a.asm.L).apply(null,arguments)},Pg=a._Exp=function(){return(Pg=a._Exp=a.asm.M).apply(null,arguments)},Og=a._FlipLeftRight=function(){return(Og=a._FlipLeftRight=a.asm.N).apply(null,arguments)},Mg=a._Floor=function(){return(Mg=a._Floor=a.asm.O).apply(null,arguments)},Lg=a._FloorDiv=function(){return(Lg=a._FloorDiv=a.asm.P).apply(null,arguments)},Le=a._FusedBatchNorm=function(){return(Le=a._FusedBatchNorm=a.asm.Q).apply(null,arguments)},Bg=a._FusedConv2D=function(){return(Bg=a._FusedConv2D=a.asm.R).apply(null,arguments)},zg=a._FusedDepthwiseConv2D=function(){return(zg=a._FusedDepthwiseConv2D=a.asm.S).apply(null,arguments)},Wg=a._Gather=function(){return(Wg=a._Gather=a.asm.T).apply(null,arguments)},Vg=a._GatherNd=function(){return(Vg=a._GatherNd=a.asm.U).apply(null,arguments)},Ug=a._Greater=function(){return(Ug=a._Greater=a.asm.V).apply(null,arguments)},Gg=a._GreaterEqual=function(){return(Gg=a._GreaterEqual=a.asm.W).apply(null,arguments)},ul=a._LeakyRelu=function(){return(ul=a._LeakyRelu=a.asm.X).apply(null,arguments)},vp=a._Less=function(){return(vp=a._Less=a.asm.Y).apply(null,arguments)},xp=a._LessEqual=function(){return(xp=a._LessEqual=a.asm.Z).apply(null,arguments)},Hg=a._Log=function(){return(Hg=a._Log=a.asm._).apply(null,arguments)},jg=a._LogicalAnd=function(){return(jg=a._LogicalAnd=a.asm.$).apply(null,arguments)},qg=a._Max=function(){return(qg=a._Max=a.asm.aa).apply(null,arguments)},Kg=a._MaxPool=function(){return(Kg=a._MaxPool=a.asm.ba).apply(null,arguments)},Xg=a._Maximum=function(){return(Xg=a._Maximum=a.asm.ca).apply(null,arguments)},Yg=a._Mean=function(){return(Yg=a._Mean=a.asm.da).apply(null,arguments)},Zg=a._Min=function(){return(Zg=a._Min=a.asm.ea).apply(null,arguments)},nt=a._Minimum=function(){return(nt=a._Minimum=a.asm.fa).apply(null,arguments)},Jg=a._MirrorPad=function(){return(Jg=a._MirrorPad=a.asm.ga).apply(null,arguments)},Qg=a._Multiply=function(){return(Qg=a._Multiply=a.asm.ha).apply(null,arguments)},eb=a._Neg=function(){return(eb=a._Neg=a.asm.ia).apply(null,arguments)},Mi=a._NonMaxSuppressionV3=function(){return(Mi=a._NonMaxSuppressionV3=a.asm.ja).apply(null,arguments)},wp=a._NonMaxSuppressionV4=function(){return(wp=a._NonMaxSuppressionV4=a.asm.ka).apply(null,arguments)},kp=a._NonMaxSuppressionV5=function(){return(kp=a._NonMaxSuppressionV5=a.asm.la).apply(null,arguments)},Ip=a._NotEqual=function(){return(Ip=a._NotEqual=a.asm.ma).apply(null,arguments)},tb=a._OneHot=function(){return(tb=a._OneHot=a.asm.na).apply(null,arguments)},nb=a._PadV2=function(){return(nb=a._PadV2=a.asm.oa).apply(null,arguments)},Sp=a._Pow=function(){return(Sp=a._Pow=a.asm.pa).apply(null,arguments)},rb=a._Prelu=function(){return(rb=a._Prelu=a.asm.qa).apply(null,arguments)},sb=a._Prod=function(){return(sb=a._Prod=a.asm.ra).apply(null,arguments)},ab=a._RealDiv=function(){return(ab=a._RealDiv=a.asm.sa).apply(null,arguments)},ob=a._Relu=function(){return(ob=a._Relu=a.asm.ta).apply(null,arguments)},ib=a._Relu6=function(){return(ib=a._Relu6=a.asm.ua).apply(null,arguments)},Cp=a._ResizeBilinear=function(){return(Cp=a._ResizeBilinear=a.asm.va).apply(null,arguments)},qs=a._Reverse=function(){return(qs=a._Reverse=a.asm.wa).apply(null,arguments)},cb=a._RotateWithOffset=function(){return(cb=a._RotateWithOffset=a.asm.xa).apply(null,arguments)},ub=a._Round=function(){return(ub=a._Round=a.asm.ya).apply(null,arguments)},B0=a._Rsqrt=function(){return(B0=a._Rsqrt=a.asm.za).apply(null,arguments)},Tp=a._ScatterNd=function(){return(Tp=a._ScatterNd=a.asm.Aa).apply(null,arguments)},lb=a._SelectV2=function(){return(lb=a._SelectV2=a.asm.Ba).apply(null,arguments)},db=a._Sigmoid=function(){return(db=a._Sigmoid=a.asm.Ca).apply(null,arguments)},pb=a._Sin=function(){return(pb=a._Sin=a.asm.Da).apply(null,arguments)},hb=a._Softmax=function(){return(hb=a._Softmax=a.asm.Ea).apply(null,arguments)},fb=a._Sqrt=function(){return(fb=a._Sqrt=a.asm.Fa).apply(null,arguments)},mb=a._Square=function(){return(mb=a._Square=a.asm.Ga).apply(null,arguments)},gb=a._SquaredDifference=function(){return(gb=a._SquaredDifference=a.asm.Ha).apply(null,arguments)},bb=a._Step=function(){return(bb=a._Step=a.asm.Ia).apply(null,arguments)},yb=a._StridedSlice=function(){return(yb=a._StridedSlice=a.asm.Ja).apply(null,arguments)},vb=a._Sub=function(){return(vb=a._Sub=a.asm.Ka).apply(null,arguments)},xb=a._Sum=function(){return(xb=a._Sum=a.asm.La).apply(null,arguments)},wb=a._Tan=function(){return(wb=a._Tan=a.asm.Ma).apply(null,arguments)},kb=a._Tanh=function(){return(kb=a._Tanh=a.asm.Na).apply(null,arguments)},Ib=a._Tile=function(){return(Ib=a._Tile=a.asm.Oa).apply(null,arguments)},Sb=a._TopK=function(){return(Sb=a._TopK=a.asm.Pa).apply(null,arguments)},Cb=a._Transform=function(){return(Cb=a._Transform=a.asm.Qa).apply(null,arguments)},Tb=a._Transpose=function(){return(Tb=a._Transpose=a.asm.Ra).apply(null,arguments)},Nb=a.__FusedMatMul=function(){return(Nb=a.__FusedMatMul=a.asm.Sa).apply(null,arguments)},_b=a._malloc=function(){return(_b=a._malloc=a.asm.Ta).apply(null,arguments)},Eb=a._free=function(){return(Eb=a._free=a.asm.Ua).apply(null,arguments)},Np=a.___errno_location=function(){return(Np=a.___errno_location=a.asm.Va).apply(null,arguments)},_p=a.stackSave=function(){return(_p=a.stackSave=a.asm.Wa).apply(null,arguments)},Ep=a.stackRestore=function(){return(Ep=a.stackRestore=a.asm.Xa).apply(null,arguments)},ll=a.stackAlloc=function(){return(ll=a.stackAlloc=a.asm.Ya).apply(null,arguments)};a.cwrap=ee;var Li;function Ab(Z){this.name="ExitStatus",this.message="Program terminated with exit("+Z+")",this.status=Z}Jr=function Z(){Li||dl(),Li||(Jr=Z)};function dl(Z){if(Z=Z||u,hn>0||(yn(),hn>0))return;function oe(){Li||(Li=!0,a.calledRun=!0,!L&&(Hn(),br(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),ar()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),oe()},1)):oe()}if(a.run=dl,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return dl(),s.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),TD=1e-7,ND=1e-4,Op=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}},bl=class{refCount(e){return vr("refCount")}incRef(e){return vr("incRef")}timerAvailable(){return!0}time(e){return vr("time")}read(e){return vr("read")}readSync(e){return vr("readSync")}numDataIds(){return vr("numDataIds")}disposeData(e,t){return vr("disposeData")}write(e,t,n){return vr("write")}move(e,t,n,r,s){return vr("move")}memory(){return vr("memory")}floatPrecision(){return vr("floatPrecision")}epsilon(){return this.floatPrecision()===32?TD:ND}dispose(){return vr("dispose")}};function vr(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 s1(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Mp(e,t,n)}function _D(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,Mp(e,n,r),Mp(t,n,r)}function yl(e,t,n){return Math.max(e,Math.min(t,n))}function ED(e){return e%2==0?e:e+1}function Mp(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function AD(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function DD(e,t){let n=Math.random();return t*n+(1-n)*e}function FD(e,t){let n=0;for(let r=0;r<e.length;r++){let s=Number(e[r])-Number(t[r]);n+=s*s}return n}function $(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function xn(e,t,n=""){$(ks(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Ma(e){$(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function La(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||fn(e)&&!n)for(let r=0;r<e.length;++r)La(e[r],t,n);else t.push(e);return t}function $t(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 $D(e){return e.length===0}function ks(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 Xt(e){return e%1==0}function RD(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function PD(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function OD(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return s1(t),t}function vl(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function MD(e,t=r=>0,n){return new Promise((r,s)=>{let a=0,o=()=>{if(e()){r();return}a++;let i=t(a);if(n!=null&&a>=n){s();return}setTimeout(o,i)};o()})}function LD(e,t){let n=1,r=-1;for(let a=0;a<e.length;++a)if(e[a]>=0)n*=e[a];else if(e[a]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${a}`);r=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(r===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let s=e.slice();return s[r]=t/n,s}function xr(e,t){let n=t.length;return e=e==null?t.map((r,s)=>s):[].concat(e),$(e.every(r=>r>=-n&&r<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),$(e.every(r=>Xt(r)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(r=>r<0?n+r:r)}function a1(e,t){let n=[],r=[],s=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||s?null:xr(t,e).sort(),o=0;for(let i=0;i<e.length;++i){if(a!=null){if(a[o]===i&&e[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${e[i]}' is not 1`);(a[o]==null||a[o]>i)&&e[i]===1&&(n.push(e[i]),r.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function o1(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 i1(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 c1(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function u1(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function BD(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function fn(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function Rb(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 l1(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Zs(e){return typeof e=="string"||e instanceof String}function d1(e){return typeof e=="boolean"}function p1(e){return typeof e=="number"}function Lp(e){return Array.isArray(e)?Lp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":p1(e)?"float32":Zs(e)?"string":d1(e)?"bool":"float32"}function Js(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Bp(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Hi(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function h1(e,t,n,r=!1){let s=new Array;if(t.length===1){let a=t[0]*(r?2:1);for(let o=0;o<a;o++)s[o]=n[e+o]}else{let a=t[0],o=t.slice(1),i=o.reduce((c,l)=>c*l)*(r?2:1);for(let c=0;c<a;c++)s[c]=h1(e+c*i,o,n,r)}return s}function ji(e,t,n=!1){if(e.length===0)return t[0];let r=e.reduce((s,a)=>s*a)*(n?2:1);if(r===0)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return h1(0,e,t,n)}function Pb(e,t){let n=zp(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function zp(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 zD(e,t){let n=e.reduce((r,s)=>r*s,1);if(t==null||t==="float32")return ji(e,new Float32Array(n));if(t==="int32")return ji(e,new Int32Array(n));if(t==="bool")return ji(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ob(e){e.forEach(t=>{$(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function WD(e,t,n){if(t===0)return 0;if(t===1)return e[0];let r=e[e.length-1];for(let s=0;s<e.length-1;++s)r+=n[s]*e[s];return r}function VD(e,t,n){if(t===0)return[];if(t===1)return[e];let r=new Array(t);for(let s=0;s<r.length-1;++s)r[s]=Math.floor(e/n[s]),e-=r[s]*n[s];return r[r.length-1]=e,r}function Mb(e){return e&&e.then&&typeof e.then=="function"}function es(...e){J().getBool("IS_TEST")||J().getBool("PROD")||console.warn(...e)}function UD(...e){J().getBool("IS_TEST")||J().getBool("PROD")||console.log(...e)}var f1="tfjsflags",m1=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=GD,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&es(`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 r=this.urlFlags[e];es(`Setting feature override from URL ${e}: ${r}.`),this.set(e,r)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(Mb(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);f1 in e&&e[f1].split(",").forEach(n=>{let[r,s]=n.split(":");this.urlFlags[r]=jD(r,s)})}};function GD(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>(HD(t,r[0],r[1]),r.join("="))),t}function HD(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function jD(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 J(){return qi}var qi=null;function qD(e){qi=e}var Lb;function g1(){if(Lb==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");Lb=e}return Lb}function KD(){let e=g1();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Bb(e,t){let n=KD();if(n.has(e))return n.get(e);{let r=t();return n.set(e,r),n.get(e)}}var Ki="Abs",Xi="Acos",Yi="Acosh",Qs="Add",Ba="AddN",Zi="All",Ji="Any",za="ArgMax",xl="ArgMin",Qi="Asin",ec="Asinh",tc="Atan",nc="Atanh",rc="Atan2",Wa="AvgPool",Wp="AvgPoolGrad",wl="AvgPool3D",Vp="AvgPool3DGrad",Va="BatchMatMul",sc="BatchToSpaceND",Up="Bincount",b1="BroadcastTo",Gp="BroadcastArgs",Ua="Cast",Ga="Ceil",ea="ClipByValue",Hp="Complex",kl="ComplexAbs",ac="Concat",Ha="Conv2D",jp="Conv2DBackpropFilter",ja="Conv2DBackpropInput",Il="Conv3D",qp="Conv3DBackpropFilterV2",Kp="Conv3DBackpropInputV2",qa="Cos",Ka="Cosh",Xa="Cumsum",oc="CropAndResize",Xp="DenseBincount",ic="DepthToSpace",Ya="DepthwiseConv2dNative",Yp="DepthwiseConv2dNativeBackpropFilter",Zp="DepthwiseConv2dNativeBackpropInput",Jp="Diag",Sl="Dilation2D",Qp="Dilation2DBackpropInput",eh="Dilation2DBackpropFilter",Za="RealDiv",th="Einsum",Ja="Elu",nh="EluGrad",cc="Erf",uc="Equal",Qa="Exp",lc="ExpandDims",dc="Expm1",rh="FFT",Cl="Fill",pc="FlipLeftRight",eo="Floor",to="FloorDiv",no="FusedBatchNorm",hc="GatherV2",fc="GatherNd",mc="Greater",ro="GreaterEqual",so="Identity",sh="IFFT",ah="Imag",gc="IsFinite",bc="IsInf",yc="IsNan",ao="LeakyRelu",vc="Less",xc="LessEqual",oh="LinSpace",oo="Log",wc="Log1p",kc="LogicalAnd",Tl="LogicalNot",Nl="LogicalOr",y1="LogSoftmax",_l="LRN",ih="LRNGrad",io="Max",co="Maximum",uo="MaxPool",ch="MaxPoolGrad",El="MaxPool3D",uh="MaxPool3DGrad",lh="MaxPoolWithArgmax",lo="Mean",po="Min",ho="Minimum",fo="MirrorPad",Ic="Mod",dh="Multinomial",mo="Multiply",Sc="Neg",Cc="NotEqual",Tc="NonMaxSuppressionV3",Nc="NonMaxSuppressionV4",_c="NonMaxSuppressionV5",Ec="OnesLike",go="OneHot",Ac="Pack",bo="PadV2",XD="Pool",yo="Pow",vo="Prelu",Dc="Prod",Al="Range",ph="Real",Fc="Reciprocal",xo="Relu",$c="Reshape",Dl="ResizeNearestNeighbor",hh="ResizeNearestNeighborGrad",wo="ResizeBilinear",fh="ResizeBilinearGrad",ko="Relu6",Io="Reverse",So="Round",Co="Rsqrt",Rc="ScatterNd",Pc="Select",Oc="Selu",Mc="Slice",To="Sin",Lc="Sinh",Bc="Sign",No="Sigmoid",zc="Softplus",_o="Sqrt",Eo="Sum",Wc="SpaceToBatchND",Vc="SplitV",Ao="Softmax",mh="SparseFillEmptyRows",gh="SparseReshape",bh="SparseSegmentMean",yh="SparseSegmentSum",vh="SparseToDense",Do="SquaredDifference",Fl="Square",Uc="StridedSlice",xh="StringNGrams",wh="StringSplit",kh="StringToHashBucketFast",Fo="Sub",$o="Tan",Ro="Tanh",ta="Tile",Gc="TopK",Hc="Transform",Po="Transpose",Ih="Unique",jc="Unpack",$l="UnsortedSegmentSum",qc="ZerosLike",na="Step",Sh="FromPixels",Kc="RotateWithOffset",Oo="_FusedMatMul",Mo="FusedConv2D",Lo="FusedDepthwiseConv2D",Xc=Bb("kernelRegistry",()=>new Map),Rl=Bb("gradRegistry",()=>new Map);function Ch(e,t){let n=Wb(e,t);return Xc.get(n)}function zb(e){return Rl.get(e)}function Th(e){let t=Xc.entries(),n=[];for(;;){let{done:r,value:s}=t.next();if(r)break;let[a,o]=s,[i]=a.split("_");i===e&&n.push(o)}return n}function Pl(e){let{kernelName:t,backendName:n}=e,r=Wb(t,n);Xc.has(r)&&es(`The kernel '${t}' for backend '${n}' is already registered`),Xc.set(r,e)}function v1(e){let{kernelName:t}=e;Rl.has(t)&&J().getBool("DEBUG")&&es(`Overriding the gradient for '${t}'`),Rl.set(t,e)}function YD(e,t){let n=Wb(e,t);if(!Xc.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Xc.delete(n)}function ZD(e){if(!Rl.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Rl.delete(e)}function JD(e,t){Th(e).forEach(r=>{let s=Object.assign({},r,{backendName:t});Pl(s)})}function Wb(e,t){return`${t}_${e}`}var w={};$e(w,{arraysEqual:()=>ks,assert:()=>$,assertNonNegativeIntegerDimensions:()=>Ob,assertNonNull:()=>Ma,assertShapesMatch:()=>xn,bytesFromStringArray:()=>l1,bytesPerElement:()=>Rb,checkConversionForErrors:()=>c1,clamp:()=>yl,computeStrides:()=>Hi,createScalarValue:()=>sF,createShuffledIndices:()=>OD,decodeString:()=>Eh,distSquared:()=>FD,encodeString:()=>Ll,fetch:()=>oF,fingerPrint64:()=>rF,flatten:()=>La,getArrayFromDType:()=>i1,getTypedArrayFromDType:()=>o1,hasEncodingLoss:()=>BD,hexToLong:()=>Ol,indexToLoc:()=>VD,inferDtype:()=>Lp,inferFromImplicitShape:()=>LD,isBoolean:()=>d1,isFunction:()=>Js,isInt:()=>Xt,isNumber:()=>p1,isPromise:()=>Mb,isScalarShape:()=>$D,isString:()=>Zs,isTypedArray:()=>fn,isValidDtype:()=>u1,locToIndex:()=>WD,makeOnesTypedArray:()=>Pb,makeZerosNestedTypedArray:()=>zD,makeZerosTypedArray:()=>zp,nearestDivisor:()=>Bp,nearestLargerEven:()=>ED,now:()=>Ml,parseAxisParam:()=>xr,randUniform:()=>DD,repeatedTry:()=>MD,rightPad:()=>vl,shuffle:()=>s1,shuffleCombo:()=>_D,sizeFromShape:()=>$t,sizeToSquarishShape:()=>PD,squeezeShape:()=>a1,sum:()=>AD,swap:()=>Mp,tanh:()=>RD,toNestedArray:()=>ji,toTypedArray:()=>_h});var x1=Oa(oD()),Bo=x1.default||x1;function Ol(e){return Bo.fromString(e,!0,16)}var w1=Ol("c3a5c85c97cb3127"),zo=Ol("b492b66fbe98f273"),wn=Ol("9ae16a3b2f90404f");function Vb(e){return e.xor(e.shru(47))}function k1(e,t,n){let r=e.slice(t,t+n);return Bo.fromBytes(Array.from(r),!0,!0)}function ft(e,t){return k1(e,t,8)}function I1(e,t){return k1(e,t,4)}function Yt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function ra(e,t,n=Ol("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function QD(e,t,n,r,s,a){s=s.add(e),a=Yt(a.add(s).add(r),21);let o=s;return s=s.add(t),s=s.add(n),a=a.add(Yt(s,44)),[s.add(r),a.add(o)]}function Nh(e,t,n,r){return QD(ft(e,t),ft(e,t+8),ft(e,t+16),ft(e,t+24),n,r)}function eF(e,t=e.length){if(t>=8){let n=wn.add(t*2),r=ft(e,0).add(wn),s=ft(e,t-8),a=Yt(s,37).mul(n).add(r),o=Yt(r,25).add(s).mul(n);return ra(a,o,n)}if(t>=4){let n=wn.add(t*2),r=I1(e,0);return ra(r.shl(3).add(t),I1(e,t-4),n)}if(t>0){let n=e[0],r=e[t>>1],s=e[t-1],a=n+(r<<8),o=t+(s<<2);return Vb(wn.mul(a).xor(w1.mul(o))).mul(wn)}return wn}function tF(e,t=e.length){let n=wn.add(t*2),r=ft(e,0).mul(zo),s=ft(e,8),a=ft(e,t-8).mul(n),o=ft(e,t-16).mul(wn);return ra(Yt(r.add(s),43).add(Yt(a,30)).add(o),r.add(Yt(s.add(wn),18)).add(a),n)}function nF(e,t=e.length){let n=wn.add(t*2),r=ft(e,0).mul(wn),s=ft(e,8),a=ft(e,t-8).mul(n),o=ft(e,t-16).mul(wn),i=Yt(r.add(s),43).add(Yt(a,30)).add(o),c=ra(i,r.add(Yt(s.add(wn),18)).add(a),n),l=ft(e,16).mul(n),u=ft(e,24),d=i.add(ft(e,t-32)).mul(n),p=c.add(ft(e,t-24)).mul(n);return ra(Yt(l.add(u),43).add(Yt(d,30)).add(p),l.add(Yt(u.add(r),18)).add(d),n)}function rF(e,t=e.length){let n=Bo.fromNumber(81,!0);if(t<=32)return t<=16?eF(e,t):tF(e,t);if(t<=64)return nF(e,t);let r=n,s=n.mul(zo).add(113),a=Vb(s.mul(wn).add(113)).mul(wn),o=[Bo.UZERO,Bo.UZERO],i=[Bo.UZERO,Bo.UZERO];r=r.mul(wn).add(ft(e,0));let c=0,l=(t-1>>6)*64,u=l+(t-1&63)-63;do r=Yt(r.add(s).add(o[0]).add(ft(e,c+8)),37).mul(zo),s=Yt(s.add(o[1]).add(ft(e,c+48)),42).mul(zo),r=r.xor(i[1]),s=s.add(o[0]).add(ft(e,c+40)),a=Yt(a.add(i[0]),33).mul(zo),o=Nh(e,c,o[1].mul(zo),r.add(i[0])),i=Nh(e,c+32,a.add(i[1]),s.add(ft(e,c+16))),[a,r]=[r,a],c+=64;while(c!==l);let d=zo.add(a.and(255).shl(1));return c=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=Yt(r.add(s).add(o[0]).add(ft(e,c+8)),37).mul(d),s=Yt(s.add(o[1]).add(ft(e,c+48)),42).mul(d),r=r.xor(i[1].mul(9)),s=s.add(o[0].mul(9).add(ft(e,c+40))),a=Yt(a.add(i[0]),33).mul(d),o=Nh(e,c,o[1].mul(d),r.add(i[0])),i=Nh(e,c+32,a.add(i[1]),s.add(ft(e,c+16))),[a,r]=[r,a],ra(ra(o[0],i[0],d).add(Vb(s).mul(w1)).add(a),ra(o[1],i[1],d).add(r),d)}function sF(e,t){return t==="string"?Ll(e):_h([e],t)}function aF(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function _h(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=La(e)),J().getBool("DEBUG")&&c1(e,t),aF(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let r=0;r<n.length;++r)Math.round(e[r])!==0&&(n[r]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Ml(){return J().platform.now()}function oF(e,t){return J().platform.fetch(e,t)}function Ll(e,t="utf-8"){return t=t||"utf-8",J().platform.encode(e,t)}function Eh(e,t="utf-8"){return t=t||"utf-8",J().platform.decode(e,t)}var iF=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new uF)}profileKernel(e,t,n){let r,s=()=>{r=n()},a,o=Ml();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(let c of r)c.dataSync();a=Promise.resolve({kernelMs:Ml()-o})}if(J().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let c=0;c<r.length;c++){let l=r[c];l.data().then(u=>{cF(u,l.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then(c=>c.kernelMs),extraInfo:a.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),r,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],s,i[2])})})}};function cF(e,t,n){if(t!=="float32")return!1;for(let r=0;r<e.length;r++){let s=e[r];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}var uF=class{logKernelProfile(e,t,n,r,s,a){let o=typeof r=="number"?vl(`${r}ms`,9):r.error,i=vl(e,25),c=t.rank,l=t.size,u=vl(t.shape.toString(),14),d="";for(let p in s){let h=s[p];if(h!=null){let f=h.shape||t.shape,m=f.length;d+=`${p}: ${m}D ${m>0?f:""} `}}console.log(`%c${i} %c${o} %c${c}D ${u} %c${l} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function lF(e,t,n){let r={},s={};for(let c=0;c<t.length;c++)r[t[c].id]=!0;for(let c=0;c<e.length;c++){let l=e[c],u=l.inputs;for(let d in u){let p=u[d],h=!1;for(let f=0;f<t.length;f++)if(r[p.id]){l.outputs.forEach(m=>r[m.id]=!0),h=!0,s[l.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let c=e.length-1;c>=0;c--){let l=e[c],u=l.inputs;for(let d=0;d<l.outputs.length;d++)if(a[l.outputs[d].id]){for(let p in u)a[u[p].id]=!0,o[l.id]=!0;break}}let i=[];for(let c=0;c<e.length;c++){let l=e[c];if(s[l.id]&&o[l.id]){let u={};for(let p in l.inputs){let h=l.inputs[p];r[h.id]&&(u[p]=h)}let d=Object.assign({},l);d.inputs=u,d.outputs=l.outputs,i.push(d)}}return i}function dF(e,t,n,r){for(let s=t.length-1;s>=0;s--){let a=t[s],o=[];if(a.outputs.forEach(c=>{let l=e[c.id];l!=null?o.push(l):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let c in a.inputs){if(!(c in i))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(i)}.`);let l=n(()=>i[c]());if(l.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${l.dtype}'`);let u=a.inputs[c];if(!ks(l.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${c}' has shape '${l.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=l;else{let d=e[u.id];e[u.id]=r(d,l),d.dispose()}}}}var S1=20,Bl=3,Ub=7;function pF(e,t,n,r){let s=Hi(t),a=hF(e,t,n,s),o=t.length,i=Ah(e,t,n,s,a),c=["Tensor"];return r&&(c.push(` dtype: ${n}`),c.push(` rank: ${o}`),c.push(` shape: [${t}]`),c.push(" values:")),c.push(i.map(l=>" "+l).join(`
|
|
`)),c.join(`
|
|
`)}function hF(e,t,n,r){let s=$t(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Wl(e):e;if(i>1)for(let l=0;l<s/a;l++){let u=l*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],zl(c[u+d],0,n).length)}return o}function zl(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(Ub))} + ${parseFloat(e[1].toFixed(Ub))}j`:Zs(e)?r=`'${e}'`:n==="bool"?r=C1(e):r=parseFloat(e.toFixed(Ub)).toString(),vl(r,t)}function C1(e){return e===0?"false":"true"}function Ah(e,t,n,r,s,a=!0){let o=n==="complex64"?2:1,i=t[0],c=t.length;if(c===0){if(n==="complex64"){let m=Wl(e);return[zl(m[0],0,n)]}return n==="bool"?[C1(e[0])]:[e[0].toString()]}if(c===1){if(i>S1){let g=Bl*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-Bl)*o,i*o));return n==="complex64"&&(b=Wl(b),y=Wl(y)),["["+b.map((v,x)=>zl(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>zl(v,s[i-Bl+x],n)).join(", ")+"]"]}let m=n==="complex64"?Wl(e):Array.from(e);return["["+m.map((g,b)=>zl(g,s[b],n)).join(", ")+"]"]}let l=t.slice(1),u=r.slice(1),d=r[0]*o,p=[];if(i>S1){for(let m=0;m<Bl;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,!1))}p.push("...");for(let m=i-Bl;m<i;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,m===i-1))}let h=c===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=`,
|
|
`;for(let m=2;m<c;m++)f+=`
|
|
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Wl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ut=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=$t(e),n!=null){let r=n.length;$(r===this.size,()=>`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||i1(t,this.size),this.strides=Hi(e)}set(e,...t){t.length===0&&(t=[0]),$(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let r of e){if(r<0||r>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return ts().makeTensor(this.values,this.shape,this.dtype)}},ts=null,Yc=null,fF=null;function mF(e){ts=e}function gF(e){Yc=e}function bF(e){fF=e}var Ee=class{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=$t(e),this.strides=Hi(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Yc.buffer(this.shape,this.dtype,e)}bufferSync(){return Yc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return ji(this.shape,e,this.dtype==="complex64")}arraySync(){return ji(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=ts().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Eh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=ts().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Eh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await ts().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(ts().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Yc.print(this,e)}clone(){return this.throwIfDisposed(),Yc.clone(this)}toString(e=!1){let t=this.dataSync();return pF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Yc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ts().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Q(){return Bb("Tensor",()=>Ee)}Q();var sa=class extends Ee{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ks(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ts().disposeTensor(this),this.dataId=e.dataId,ts().incRef(this,null)}dispose(){ts().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sa,Symbol.hasInstance,{value:e=>e instanceof Ee&&e.assign!=null&&e.assign instanceof Function});var $r={};$e($r,{assertTypesMatch:()=>T1,getTensorsInContainer:()=>Xb,isTensorInList:()=>vF,makeTypesMatch:()=>_t});var Gb;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Gb||(Gb={}));var Hb;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Hb||(Hb={}));var jb;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(jb||(jb={}));var qb;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(qb||(qb={}));var Kb;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Kb||(Kb={}));var yF={float32:qb,int32:Hb,bool:jb,complex64:Kb};function wr(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 Dh(e){return wr(e,"int32")}function _t(e,t){if(e.dtype===t.dtype)return[e,t];let n=wr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function T1(e,t){$(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function vF(e,t){return t.some(n=>n.id===e.id)}function Xb(e){let t=[],n=new Set;return N1(e,t,n),t}function N1(e,t,n){if(e==null)return;if(e instanceof Ee){t.push(e);return}if(!xF(e))return;let r=e;for(let s in r){let a=r[s];n.has(a)||(n.add(a),N1(a,t,n))}}function xF(e){return Array.isArray(e)||typeof e=="object"}function Yb(e){return e.kernelName!=null}var _1=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()}},Vl=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new _1}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?(es(`${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 iF(this.backendInstance),!0}setupRegisteredKernels(){Th(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Th(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof bl)&&typeof n.then=="function"){let r=++this.pendingBackendInitId,s=n.then(a=>r<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,es(`Initialization of backend ${e} failed`),es(a.stack||a.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return es(`Initialization of backend ${e} failed`),es(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),r=n.backend,s=this.readSync(t),a=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let r;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,n){e();try{let r=n();return t(),r}catch(r){throw t(),r}}nextTensorId(){return Vl.nextTensorId++}nextVariableId(){return Vl.nextVariableId++}clone(e){let t=z.runKernel(so,{x:e}),n={x:e},r=a=>({x:()=>{let o="float32",i={x:a},c={dtype:o};return z.runKernel(Ua,i,c)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[t],r,s,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!(Ch(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let r=this.backend.numDataIds(),s=0;n.forEach(i=>{s+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-s-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,c=Yb(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Yb(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Ch(h,this.backendName);$(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let b=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let y=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,b,y);let v=y.map(x=>{if(x.rank!=null)return x;let{dataId:k,shape:C,dtype:N}=x;return this.makeTensorFromDataId(k,C,N)});if(r){let x=this.getTensorsForGradient(h,f,v);n=this.saveTensorsForBackwardMode(x)}return v}}else{let{forwardFunc:h}=e,f=m=>{!r||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,m,g),g}}let{inputs:l,attrs:u}=e,d=Yb(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(c,l,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),r&&this.addTapeNode(c,l,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(h=>l[h]!=null?l[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let r=zb(e);if(r!=null){let s=r.inputsToSave||[],a=r.outputsToSave||[],o;r.saveAllInputs?($(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(c=>t[c])):o=s.map(c=>t[c]);let i=n.filter((c,l)=>a[l]);return o.concat(i)}return[]}makeTensor(e,t,n,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;n==="string"&&Zs(e[0])&&(s=e.map(i=>Ll(i)));let a=r.write(s,t,n),o=new Ee(t,n,a,this.nextTensorId());if(this.trackTensor(o,r),n==="string"){let i=this.state.tensorInfo.get(a),c=l1(s);this.state.numBytes+=c-i.bytes,i.bytes=c}return o}makeTensorFromDataId(e,t,n,r){n=n||"float32";let s=new Ee(t,n,e,this.nextTensorId());return this.trackTensor(s,r),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));let s=new sa(e,t,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*Rb(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 sa||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*Rb(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,s,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},i=zb(e);i!=null&&(r=i.gradFunc),r!=null&&(o.gradient=c=>(c=c.map((l,u)=>{if(l==null){let d=n[u],p=zp(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return l}),r(c.length>1?c:c[0],s,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Xb(e),n=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let a=this.state.activeScope.track[s];!a.kept&&!n.has(a.id)&&a.dispose()}let r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(s=>{!s.kept&&s.scopeId===r.id&&this.track(s)})}gradients(e,t,n,r=!1){if($(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));$(s instanceof Ee,()=>"The result y returned by f() must be a tensor.");let a=lF(this.state.activeTape,t,s);if(!r&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[s.id]=n==null?wF(s.shape):n,dF(o,a,c=>this.tidy(c),kF);let i=t.map(c=>o[c.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(c=>{for(let l of c.saved)l.dispose()}),this.state.activeTape=null),{value:s,grads:i}})}customGrad(e){return $(Js(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{$(t.every(o=>o instanceof Ee),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,r={};t.forEach((o,i)=>{r[i]=o});let s=(o,i)=>(n=e(...t,i),$(n.value instanceof Ee,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),$(Js(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let c=n.gradFunc(o,i),l=Array.isArray(c)?c:[c];$(l.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),$(l.every(d=>d 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 l.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:s,backwardsFunc:a,inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Ml(),n=await this.backend.time(e);return n.wallMs=Ml()-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 _1;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}};Vl.nextTensorId=0;Vl.nextVariableId=0;function wF(e){let t=Pb($t(e),"float32");return z.makeTensor(t,e,"float32")}function E1(){let e=g1();if(e._tfengine==null){let t=new m1(e);e._tfengine=new Vl(t)}return qD(e._tfengine.ENV),mF(()=>e._tfengine),e._tfengine}var z=E1();function kF(e,t){let n={a:e,b:t};return z.runKernel(Qs,n)}var Ul={};$e(Ul,{isBrowser:()=>A1,isMobile:()=>CF,mockIsMobile:()=>SF});function IF(){return typeof navigator!="undefined"&&navigator!=null}var Zb;function SF(e){Zb=e}function CF(e){if(Zb!==void 0)return Zb;if(e||IF()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function A1(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Rr=J();Rr.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Rr.registerFlag("IS_BROWSER",()=>A1());Rr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Rr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Rr.registerFlag("PROD",()=>!1);Rr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Rr.getBool("DEBUG"));Rr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Rr.registerFlag("IS_TEST",()=>!1);Rr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Rr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function ns(e,t){let n=e;if(fn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let r=[];for(;Array.isArray(n)||fn(n)&&t!=="string";)r.push(n.length),n=n[0];return Array.isArray(e)&&J().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&D1(e,r,[]),r}function D1(e,t,n){if(n=n||[],!Array.isArray(e)&&!fn(e)){$(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}$(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),$(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let r=t.slice(1);for(let s=0;s<e.length;++s)D1(e[s],r,n.concat(s))}function F1(e,t,n,r){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function A(e,t,n,r="numeric"){if(e instanceof Ee)return F1(r,e.dtype,t,n),e;let s=Lp(e);if(s!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),F1(r,s,t,n),e==null||!fn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let c=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${c}'`)}let a=ns(e,s);!fn(e)&&!Array.isArray(e)&&(e=[e]);let i=s!=="string"?_h(e,s):La(e,[],!0);return z.makeTensor(i,a,s)}function Gl(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>A(a,`${t}[${o}]`,n,r))}var $1="__op";function W(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+$1;let s=(...a)=>{z.startScope(n);try{let o=r(...a);return Mb(o)&&console.error("Cannot return a Promise inside of tidy."),z.endScope(o),o}catch(o){throw z.endScope(null),o}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}function TF(e,t){let n=A(e,"real","complex"),r=A(t,"imag","complex");xn(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);let s={real:n,imag:r};return z.runKernel(Hp,s)}var aa=W({complex_:TF});function oa(e,t,n,r){if(r==null&&(r=Lp(e)),r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!fn(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){Ob(t);let s=$t(t),a=$t(n);$(s===a,()=>`Based on the provided shape, [${t}], the tensor should have ${s} values but has ${a}`);for(let o=0;o<n.length;++o){let i=n[o],c=o===n.length-1?i!==$t(t.slice(o)):!0;$(n[o]===t[o]||!c,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!fn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=r!=="string"?_h(e,r):La(e,[],!0),z.makeTensor(e,t,r)}function qn(e,t,n){let r=ns(e,n);return oa(e,t,r,n)}var Jb={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Fh=4;async function NF(e,t){let n=[],r=[],s=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o<s.length;++o){let i=s[o],c=Array.isArray(e)?e[o].tensor:e[i];if(c.dtype!=="float32"&&c.dtype!=="int32"&&c.dtype!=="bool"&&c.dtype!=="string"&&c.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${c.dtype}`);let l={name:i,shape:c.shape,dtype:c.dtype};if(c.dtype==="string"){let u=new Promise(async d=>{let p=await c.bytes(),h=p.reduce((g,b)=>g+b.length,0)+Fh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g<p.length;g++){let b=p[g],y=new Uint8Array(new Uint32Array([b.length]).buffer);f.set(y,m),m+=Fh,f.set(b,m),m+=b.length}d(f)});r.push(u)}else r.push(c.data());t!=null&&(l.group=t),n.push(l)}let a=await Promise.all(r);return{data:_F(a),specs:n}}function R1(e,t){let n={},r,s=0;for(let a of t){let o=a.name,i=a.dtype,c=a.shape,l=$t(c),u;if("quantization"in a){let d=a.quantization;if(d.dtype==="uint8"||d.dtype==="uint16"){if(!("min"in d&&"scale"in d))throw new Error(`Weight ${a.name} with quantization ${d.dtype} doesn't have corresponding metadata min and scale.`)}else if(d.dtype==="float16"){if(i!=="float32")throw new Error(`Weight ${a.name} is quantized with ${d.dtype} which only supports weights of type float32 not ${i}.`)}else throw new Error(`Weight ${a.name} has unknown quantization dtype ${d.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let p=Jb[d.dtype],h=e.slice(s,s+l*p),f=d.dtype==="uint8"?new Uint8Array(h):new Uint16Array(h);if(i==="float32")if(d.dtype==="uint8"||d.dtype==="uint16"){u=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=g*d.scale+d.min}}else if(d.dtype==="float16")r===void 0&&(r=RF()),u=r(f);else throw new Error(`Unsupported quantization type ${d.dtype} for weight type float32.`);else if(i==="int32"){if(d.dtype!=="uint8"&&d.dtype!=="uint16")throw new Error(`Unsupported quantization type ${d.dtype} for weight type int32.`);u=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=Math.round(g*d.scale+d.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);s+=l*p}else if(i==="string"){let d=$t(a.shape);u=[];for(let p=0;p<d;p++){let h=new Uint32Array(e.slice(s,s+Fh))[0];s+=Fh;let f=new Uint8Array(e.slice(s,s+h));u.push(f),s+=h}}else{let d=Jb[i],p=e.slice(s,s+l*d);if(i==="float32")u=new Float32Array(p);else if(i==="int32")u=new Int32Array(p);else if(i==="bool")u=new Uint8Array(p);else if(i==="complex64"){u=new Float32Array(p);let h=new Float32Array(u.length/2),f=new Float32Array(u.length/2);for(let b=0;b<h.length;b++)h[b]=u[b*2],f[b]=u[b*2+1];let m=qn(h,c,"float32"),g=qn(f,c,"float32");n[o]=aa(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);s+=l*d}i!=="complex64"&&(n[o]=qn(u,c,i))}return n}function _F(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(a=>{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let r=new Uint8Array(t),s=0;return n.forEach(a=>{r.set(new Uint8Array(a.buffer),s),s+=a.byteLength}),r.buffer}var Qb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function P1(e){return Qb?Buffer.byteLength(e):new Blob([e]).size}function EF(e){if(Qb)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let r=0,s=t.length;r<s;r++)n+=String.fromCharCode(t[r]);return btoa(n)}function AF(e){if(Qb){let r=Buffer.from(e,"base64");return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;++r)n.set([t.charCodeAt(r)],r);return n.buffer}function ey(e){if(e.length===1)return e[0];let t=0;e.forEach(s=>{t+=s.byteLength});let n=new Uint8Array(t),r=0;return e.forEach(s=>{n.set(new Uint8Array(s),r),r+=s.byteLength}),n.buffer}function O1(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 M1(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function ty(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[r,s]=await t(e.weightsManifest);n.weightSpecs=r,n.weightData=s}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function Hl(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:P1(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:P1(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function DF(){let e=n=>{let r=n<<13,s=0;for(;(r&8388608)==0;)s-=8388608,r<<=1;return r&=~8388608,s+=947912704,r|s},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function 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 $F(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function RF(){let e=DF(),t=FF(),n=$F();return r=>{let s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let o=0;o<r.length;o++){let i=r[o],c=e[n[i>>10]+(i&1023)]+t[i>>10];a[o]=c}return new Float32Array(s)}}var Ft=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ft.instance==null&&(Ft.instance=new Ft),Ft.instance}static registerSaveRouter(e){Ft.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ft.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ft.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ft.getHandlers(e,"load",t)}static getHandlers(e,t,n){let r=[];return(t==="load"?Ft.getInstance().loadRouters:Ft.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&r.push(o)}),r}},PF=e=>Ft.registerSaveRouter(e),OF=e=>Ft.registerLoadRouter(e),MF=e=>Ft.getSaveHandlers(e),LF=(e,t)=>Ft.getLoadHandlers(e,t),ny="tensorflowjs",ry=1,Wo="models_store",ia="model_info_store";function L1(){if(!J().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 sy(e){let t=e.result;t.createObjectStore(Wo,{keyPath:"modelPath"}),t.createObjectStore(ia,{keyPath:"modelPath"})}var Vo=class{constructor(e){if(this.indexedDB=L1(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,r)=>{let s=this.indexedDB.open(ny,ry);s.onupgradeneeded=()=>sy(s),s.onsuccess=()=>{let a=s.result;if(t==null){let o=a.transaction(Wo,"readonly"),c=o.objectStore(Wo).get(this.modelPath);c.onsuccess=()=>{if(c.result==null)return a.close(),r(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(c.result.modelArtifacts)},c.onerror=l=>(a.close(),r(c.error)),o.oncomplete=()=>a.close()}else{let o=Hl(t),i=a.transaction(ia,"readwrite"),c=i.objectStore(ia),l=c.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;l.onsuccess=()=>{u=a.transaction(Wo,"readwrite");let p=u.objectStore(Wo).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{c=i.objectStore(ia);let f=c.delete(this.modelPath);f.onsuccess=()=>(a.close(),r(p.error)),f.onerror=m=>(a.close(),r(p.error))}},l.onerror=d=>(a.close(),r(l.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},s.onerror=a=>r(s.error)})}};Vo.URL_SCHEME="indexeddb://";var B1=e=>J().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Vo.URL_SCHEME)?BF(e.slice(Vo.URL_SCHEME.length)):null;Ft.registerSaveRouter(B1);Ft.registerLoadRouter(B1);function BF(e){return new Vo(e)}function zF(e){return e.startsWith(Vo.URL_SCHEME)?e.slice(Vo.URL_SCHEME.length):e}var WF=class{constructor(){this.indexedDB=L1()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(ny,ry);n.onupgradeneeded=()=>sy(n),n.onsuccess=()=>{let r=n.result,s=r.transaction(ia,"readonly"),o=s.objectStore(ia).getAll();o.onsuccess=()=>{let i={};for(let c of o.result)i[c.modelPath]=c.modelArtifactsInfo;e(i)},o.onerror=i=>(r.close(),t(o.error)),s.oncomplete=()=>r.close()},n.onerror=r=>t(n.error)})}async removeModel(e){return e=zF(e),new Promise((t,n)=>{let r=this.indexedDB.open(ny,ry);r.onupgradeneeded=()=>sy(r),r.onsuccess=()=>{let s=r.result,a=s.transaction(ia,"readwrite"),o=a.objectStore(ia),i=o.get(e),c;i.onsuccess=()=>{if(i.result==null)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let l=o.delete(e),u=()=>{c=s.transaction(Wo,"readwrite");let p=c.objectStore(Wo).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};l.onsuccess=u,l.onerror=d=>(u(),s.close(),n(i.error))}},i.onerror=l=>(s.close(),n(i.error)),a.oncomplete=()=>{c==null?s.close():c.oncomplete=()=>s.close()}},r.onerror=s=>n(r.error)})}},Is="/",Zc="tensorflowjs_models",z1="info",VF="model_topology",UF="weight_specs",GF="weight_data",HF="model_metadata";function W1(e){return{info:[Zc,e,z1].join(Is),topology:[Zc,e,VF].join(Is),weightSpecs:[Zc,e,UF].join(Is),weightData:[Zc,e,GF].join(Is),modelMetadata:[Zc,e,HF].join(Is)}}function V1(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function jF(e){let t=e.split(Is);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Is)}function qF(e){return e.startsWith(Uo.URL_SCHEME)?e.slice(Uo.URL_SCHEME.length):e}var Uo=class{constructor(e){if(!J().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=W1(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=Hl(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,EF(e.weightData));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:r}}catch(s){throw V1(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(r==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;let s=this.LS.getItem(this.keys.modelMetadata);if(s!=null){let o=JSON.parse(s);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=AF(a),t}};Uo.URL_SCHEME="localstorage://";var U1=e=>J().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Uo.URL_SCHEME)?KF(e.slice(Uo.URL_SCHEME.length)):null;Ft.registerSaveRouter(U1);Ft.registerLoadRouter(U1);function KF(e){return new Uo(e)}var XF=class{constructor(){$(J().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),$(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Zc+Is,n=Is+z1;for(let r=0;r<this.LS.length;++r){let s=this.LS.key(r);if(s.startsWith(t)&&s.endsWith(n)){let a=jF(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=qF(e);let t=W1(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 V1(t),n}},Jc="://",or=class{constructor(){this.managers={}}static getInstance(){return or.instance==null&&(or.instance=new or),or.instance}static registerManager(e,t){$(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Jc)&&(e=e.slice(0,e.indexOf(Jc))),$(e.length>0,()=>"scheme must not be an empty string.");let n=or.getInstance();$(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 $h(e){if(e.indexOf(Jc)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${or.getSchemes().join(",")}`);return{scheme:e.split(Jc)[0],path:e.split(Jc)[1]}}async function G1(e,t,n=!1){$(e!==t,()=>`Old path and new path are the same: '${e}'`);let r=Ft.getLoadHandlers(e);$(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),$(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);let s=r[0],a=Ft.getSaveHandlers(t);$(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),$(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);let o=a[0],i=$h(e).scheme,c=$h(e).path,l=i===$h(e).scheme,u=await s.load();n&&l&&await or.getManager(i).removeModel(c);let d=await o.save(u);return n&&!l&&await or.getManager(i).removeModel(c),d.modelArtifactsInfo}async function YF(){let e=or.getSchemes(),t={};for(let n of e){let r=await or.getManager(n).listModels();for(let s in r){let a=n+Jc+s;t[a]=r[s]}}return t}async function ZF(e){let t=$h(e);return or.getManager(t.scheme).removeModel(t.path)}async function JF(e,t){return G1(e,t,!1)}async function QF(e,t){return G1(e,t,!0)}var e$=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(J().get("IS_BROWSER")){J().setPlatform("browser",new e$);try{or.registerManager(Uo.URL_SCHEME,new XF)}catch(e){}try{or.registerManager(Vo.URL_SCHEME,new WF)}catch(e){}}var t$={importFetch:()=>iD()},ay,n$=class{constructor(){this.util=Gi("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return J().global.fetch!=null?J().global.fetch(e,t):(ay==null&&(ay=t$.importFetch()),ay(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)}};J().get("IS_NODE")&&J().setPlatform("node",new n$);function ze(e,t="float32",n){return t=t||"float32",Ob(e),new Ut(e,t,n)}function r$(e,t){let n=A(e,"x","cast");if(!u1(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let r={x:n},s={dtype:t};return z.runKernel(Ua,r,s)}var ce=W({cast_:r$});function s$(e){let n={x:A(e,"x","clone","string_or_numeric")};return z.runKernel(so,n)}var Ss=W({clone_:s$});function H1(e,t=!1){console.log(e.toString(t))}E1();var a$={buffer:ze,cast:ce,clone:Ss,print:H1};gF(a$);var Zt={};$e(Zt,{browserFiles:()=>p$,browserHTTPRequest:()=>b$,concatenateArrayBuffers:()=>ey,copyModel:()=>JF,decodeWeights:()=>R1,encodeWeights:()=>NF,fromMemory:()=>v$,getLoadHandlers:()=>LF,getModelArtifactsForJSON:()=>ty,getModelArtifactsInfoForJSON:()=>Hl,getSaveHandlers:()=>MF,http:()=>cy,isHTTPScheme:()=>iy,listModels:()=>YF,loadWeights:()=>h$,moveModel:()=>QF,registerLoadRouter:()=>OF,registerSaveRouter:()=>PF,removeModel:()=>ZF,weightsLoaderFactory:()=>X1,withSaveHandler:()=>x$});var o$="model",i$=".json",c$=".weights.bin";function j1(e){return new Promise(t=>setTimeout(t)).then(e)}var Qc=class{constructor(e){if(!J().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Qc.URL_SCHEME)&&(e=e.slice(Qc.URL_SCHEME.length)),(e==null||e.length===0)&&(e=o$),this.modelJsonFileName=e+i$,this.weightDataFileName=e+c$}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r=M1(e,n),s=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=s,await j1(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await j1(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Hl(e)}}}};Qc.URL_SCHEME="downloads://";var u$=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=r=>{let s=JSON.parse(r.target.result),a=s.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(s.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=ty(s,c=>this.loadWeights(c));e(i)},n.onerror=r=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let r=this.checkManifestAndWeightFiles(e),s=n.map(a=>this.loadWeightsFile(a,r[a]));return Promise.all(s).then(a=>[t,ey(a)])}loadWeightsFile(e,t){return new Promise((n,r)=>{let s=new FileReader;s.onload=a=>{let o=a.target.result;n(o)},s.onerror=a=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(s=>O1(s.name)),r={};for(let s of e)s.paths.forEach(a=>{let o=O1(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);r[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}},l$=e=>J().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Qc.URL_SCHEME)?d$(e.slice(Qc.URL_SCHEME.length)):null;Ft.registerSaveRouter(l$);function d$(e="model"){return new Qc(e)}function p$(e){return new u$(e)}function q1(e,t,n,r){o(e),n=n==null?0:n,r=r==null?1:r,i(n,r);let s=0,a=c=>(c.then(l=>{let u=n+ ++s/e.length*(r-n);return t(u),l}),c);function o(c){$(c!=null&&Array.isArray(c)&&c.length>0,()=>"promises must be a none empty array")}function i(c,l){$(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${c}`),$(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${l}`),$(l>=c,()=>`startFraction must be no more than endFraction, but got startFraction ${c} and endFraction ${l}`)}return Promise.all(e.map(a))}async function K1(e,t){t==null&&(t={});let n=t.fetchFunc==null?J().platform.fetch:t.fetchFunc,r=e.map(d=>n(d,t.requestInit,{isBinary:!0})),s=0,a=.5,i=(t.onProgress==null?await Promise.all(r):await q1(r,t.onProgress,s,a)).map(d=>d.arrayBuffer()),c=.5,l=1;return t.onProgress==null?await Promise.all(i):await q1(i,t.onProgress,c,l)}async function h$(e,t="",n,r){return X1(o=>K1(o,{requestInit:r}))(e,t,n)}function X1(e){return async(t,n="",r)=>{let s=t.map(()=>!1),a={},o=r!=null?r.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let b="quantization"in g?g.quantization.dtype:g.dtype,y=Jb[b]*$t(g.shape),v=()=>{s[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:y})};r!=null?r.forEach((x,k)=>{x===g.name&&(v(),o[k]=!0)}):v(),i.push(g.name),m+=y})}),!o.every(h=>h)){let h=r.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
|
|
Manifest JSON has weights with names: ${i.join(", ")}.`)}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),l=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;l.push(m)})});let u=await e(l),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=u[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let k=new Uint8Array(u[p+x]);b.set(k,y),y+=k.byteLength}a[h].forEach(x=>{let k=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),C=R1(k,[x.manifestEntry]);for(let N in C)d[N]=C[N]}),p+=f}),d}}var f$="application/octet-stream",m$="application/json",oy=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?($(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=J().platform.fetch,$(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&$(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=M1(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:m$}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:f$}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Hl(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(s){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,r=t.weightsManifest;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return ty(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=g$(t),s=this.weightPathPrefix||n,a=[];for(let l of e)a.push(...l.weights);let o=[],i=[];for(let l of e)for(let u of l.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(s+u+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await K1(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,ey(c)]}};oy.URL_SCHEME_REGEX=/^https?:\/\//;function g$(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function iy(e){return e.match(oy.URL_SCHEME_REGEX)!=null}var Y1=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>iy(r)):n=iy(e),n)return cy(e,t)}return null};Ft.registerSaveRouter(Y1);Ft.registerLoadRouter(Y1);function cy(e,t){return new oy(e,t)}function b$(e,t){return cy(e,t)}var uy=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},y$=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function v$(e,t,n,r){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new uy(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 uy({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 uy({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}function x$(e){return new y$(e)}var Z1={};$e(Z1,{confusionMatrix:()=>C$});function w$(e,t,n=!1,r=!1){let s=A(e,"a","matMul"),a=A(t,"b","matMul");[s,a]=_t(s,a);let o={a:s,b:a},i={transposeA:n,transposeB:r};return z.runKernel(Va,o,i)}var Ae=W({matMul_:w$});function k$(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:A(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:r};return z.runKernel(go,a,o)}var eu=W({oneHot_:k$});function I$(e,t){let n=A(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),$(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{$(a>=0&&a<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let r={x:n},s={perm:t};return z.runKernel(Po,r,s)}var Re=W({transpose_:I$});function S$(e,t,n){let r=A(e,"labels","confusionMatrix"),s=A(t,"predictions","confusionMatrix");$(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),$(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),$(s.rank===1,()=>`Expected the rank of predictions to be 1, but got ${s.rank}`),$(r.shape[0]===s.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`),$(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=eu(ce(r,"int32"),n),o=eu(ce(s,"int32"),n),i=Re(a),c=Ae(i,o);return ce(c,"int32")}var C$=W({confusionMatrix_:S$}),Go={};$e(Go,{fromPixels:()=>F$,fromPixelsAsync:()=>A$,toPixels:()=>D$});function Rh(e,t,n){if(Ma(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let r=ns(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return oa(e,t,r,n)}var tu;function J1(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)s=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(s){let f=2;if(s&&e.readyState<f)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Ch(Sh,z.backendName)!=null){let f={pixels:e},m={numChannels:t};return z.runKernel(Sh,f,m)}let[l,u]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,l,u).data:r||n?d=e.data:(a||s||i)&&(tu==null&&(tu=document.createElement("canvas").getContext("2d")),tu.canvas.width=l,tu.canvas.height=u,tu.drawImage(e,0,0,l,u),d=tu.getImageData(0,0,l,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=l*u;p=new Int32Array(f*t);for(let m=0;m<f;m++)for(let g=0;g<t;++g)p[m*t+g]=d[m*4+g]}return Rh(p,[u,l,t],"int32")}function T$(e){return e!=null&&e.data instanceof Uint8Array}function N$(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function _$(e){return e!=null&&e.width!==0&&e.height!==0}function E$(e){return N$()&&!(e instanceof ImageBitmap)&&_$(e)&&!T$(e)}async function A$(e,t=3){let n=null;if(J().getBool("WRAP_TO_IMAGEBITMAP")&&E$(e)){let r;try{r=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(s){r=null}r!=null&&r.width===e.width&&r.height===e.height?n=r:n=e}else n=e;return J1(n,t)}async function D$(e,t){let n=A(e,"img","toPixels");if(!(e instanceof Ee)){let l=n;n=ce(l,"int32"),l.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);let[r,s]=n.shape.slice(0,2),a=n.rank===2?1:n.shape[2];if(a>4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,c=new Uint8ClampedArray(s*r*4);for(let l=0;l<r*s;++l){let u=[0,0,0,255];for(let p=0;p<a;p++){let h=o[l*a+p];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=l*4;c[d+0]=Math.round(u[0]),c[d+1]=Math.round(u[1]),c[d+2]=Math.round(u[2]),c[d+3]=Math.round(u[3])}if(t!=null){t.width=s,t.height=r;let l=t.getContext("2d"),u=new ImageData(c,s,r);l.putImageData(u,0,0)}return n!==e&&n.dispose(),c}var F$=W({fromPixels_:J1}),ly={};$e(ly,{prepareAndValidate:()=>Q1});function Q1(e,t){let n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if($t(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let s=t.shape,a=s[s.length-1],o=1;for(let d=0;d<s.length-1;++d)o*=s[d];let i=e.shape,c=s.slice();c.pop();let l=1;for(let d=a;d<n;++d)l*=i[d],c.push(i[d]);let u=[...Hi(e.shape).map(d=>d/l),1].slice(0,a);return[c,o,l,u]}var dy={};$e(dy,{calculateShapes:()=>ek,validateInput:()=>hy,validateUpdateShape:()=>py});function py(e,t,n){let r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank<s)throw new Error(a+` update.rank < ${s}. `);if(e.length<r+(n.rank-s))throw new Error(a+` Output shape length < ${r+(n.rank-s)}`);if(n.rank!==s+e.length-r)throw new Error(a+` update.rank != ${s+e.length-r}`);for(let o=0;o<s;++o)if(n.shape[o]!==t.shape[o])throw new Error(a+` updates.shape[${o}] (${n.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<n.rank-s;++o)if(n.shape[o+s]!==e[o+r])throw new Error(a+` updates.shape[${o+s}] (${n.shape[o+s]}) != shape[${o+s}] (${e[o+s]})`)}function hy(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}`)}py(n,t,e)}function ek(e,t,n){let r=t.shape.length,s=r>1?t.shape[r-1]:1,a=n.length,o=1;for(let d=s;d<a;++d)o*=n[d];let i=s<1?1:s,c=$t(t.shape)/i,l=[...Hi(n.slice(0,s)),1],u=$t(n);return{sliceRank:s,numUpdates:c,sliceSize:o,strides:l,outputSize:u}}var kn={};$e(kn,{assertParamsValid:()=>$$,computeFlatOffset:()=>P$,computeOutShape:()=>tk,getNormalizedAxes:()=>ak,isSliceContinous:()=>R$,maskToAxes:()=>Ph,parseSliceParams:()=>dk,sliceInfo:()=>O$,startForAxis:()=>uk,startIndicesWithElidedDims:()=>ok,stopForAxis:()=>lk,stopIndicesWithElidedDims:()=>ik,stridesForAxis:()=>ck,stridesWithElidedDims:()=>nk});function $$(e,t,n){let r=e.shape.length;$(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),$(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let s=0;s<r;++s)$(t[s]+n[s]<=e.shape[s],()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`)}function Ph(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function tk(e,t,n){let r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}function nk(e,t,n,r){let s=[...e];for(let a=s.length;a<r.length;a++)s.push(1);for(let a=0;a<n;a++)a===0?s[t]=1:(s.splice(t,0,1),s.pop());return s}function rk(e,t,n){return n<=e?n:n-(t-1)}function sk(e,t){let n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function ak(e,t,n,r,s,a,o,i,c){let l=e.length,u=new Array(l),d=new Array(l),p=new Array(l);if(t.length&&n>0){let h=t[0],f=n+1;u=ok(o,h,f,r,e),d=ik(i,h,f,s,e),p=nk(a,h,f,e)}else for(let h=0;h<l;h++)u[h]=uk(o,r,a,e,h,c),d[h]=lk(i,s,a,e,h,c),p[h]=ck(a,h,c);return{begin:u,end:d,strides:p}}function ok(e,t,n,r,s){let a=[...s],o=sk(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=0;else{let c=rk(t,n,i),l=r[c];e&1<<c&&(l=0),a[i]=l}return a}function ik(e,t,n,r,s){let a=[...s],o=sk(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=Number.MAX_SAFE_INTEGER;else{let c=rk(t,n,i),l=r[c];e&1<<c&&(l=Number.MAX_SAFE_INTEGER),a[i]=l}for(let i=0;i<a.length;i++){let c=s[i];a[i]<0&&(a[i]+=c),a[i]=yl(0,a[i],s[i])}return a}function ck(e,t,n){let r=e[t];return(n&1<<t||r==null)&&(r=1),r}function uk(e,t,n,r,s,a){let o=t[s],i=n[s]||1;(e&1<<s||a&1<<s||o==null)&&(i>0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let c=r[s];return o<0&&(o+=c),o=yl(0,o,c-1),o}function lk(e,t,n,r,s,a){let o=t[s],i=n[s]||1;(e&1<<s||a&1<<s||o==null)&&(i>0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let c=r[s];return o<0&&(o+=c),i>0?o=yl(0,o,c):o=yl(-1,o,c-1),o}function R$(e,t,n){let r=n.length;for(let s=0;s<n.length;s++)if(n[s]>1){r=s;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0}function P$(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function dk(e,t,n){let r,s=e.shape.length;typeof t=="number"?r=[t,...new Array(s-1).fill(0)]:t.length<s?r=t.concat(new Array(s-t.length).fill(0)):r=t.slice(),r.forEach(o=>{$(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(s).fill(-1):typeof n=="number"?a=[n,...new Array(s-1).fill(-1)]:n.length<s?a=n.concat(new Array(s-n.length).fill(-1)):a=n,a=a.map((o,i)=>o>=0?o:($(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-r[i])),[r,a]}function O$(e,t,n,r,s,a,o,i,c){let l=t.slice(),u=n.slice(),d=r;r==null&&(d=new Array(l.length));let p=Ph(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&c!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-l.length,f=Ph(i),m=e.slice();f.forEach(N=>{l[N]=0,u[N]=1,m.splice(N,0,1)});let{begin:g,end:b,strides:y}=ak(m,p,h,l,u,d,s,a,o);l=g,u=b,d=y;let v=Ph(c);v.forEach(N=>{u[N]=l[N]+1,d[N]=1});let x=tk(l,u,d),k=x.filter((N,F)=>v.indexOf(F)===-1);return{nonStrided:d.every(N=>N===1),$begin:l,$end:u,$strides:d,size:x,newShape:m,outShape:k}}var ie={};$e(ie,{Serializable:()=>pk,SerializationMap:()=>Ho,registerClass:()=>ca});var pk=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Ho=class{constructor(){this.classNameMap={}}static getMap(){return Ho.instance==null&&(Ho.instance=new Ho),Ho.instance}static register(e){Ho.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function ca(e){$(e.className!=null,()=>"Class being registered does not have the static className property defined."),$(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),$(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Ho.register(e)}var hk={};$e(hk,{TEST_EPSILON_FLOAT16:()=>fk,encodeStrings:()=>mk,expectArrayBuffersEqual:()=>U$,expectArraysClose:()=>L$,expectArraysEqual:()=>z$,expectNumbersClose:()=>W$,expectPromiseToFail:()=>B$,expectValuesInRange:()=>V$,testEpsilon:()=>fy});var M$=.001,fk=.1;function L$(e,t,n){return n==null&&(n=fy()),my(e,t,(r,s)=>gy(r,s,n))}function fy(){return z.backend.floatPrecision()===32?M$:fk}function my(e,t,n){let r=!0;if((fn(e)||fn(t))&&(r=!1),fn(e)&&fn(t)&&(r=!0),r){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=ns(e),i=ns(t);if(!ks(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let s=fn(e)?e:La(e),a=fn(t)?t:La(t);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.
|
|
Actual: ${s}.
|
|
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${c}.
|
|
Actual: ${s}.
|
|
Expected: ${a}.`)}}function B$(e,t){e().then(()=>t.fail(),()=>t())}function z$(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Zs(e)||Zs(e[0])||Zs(t)||Zs(t[0])?my(e,n,(r,s)=>r==s):my(e,t,(r,s)=>gy(r,s,0))}function W$(e,t,n){if(n==null&&(n=fy()),!gy(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function gy(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function V$(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function U$(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function mk(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?mk(n):e[t]=Ll(n)}return e}var G$="3.10.0";function H$(){J().set("PROD",!0)}function j$(){J().set("DEBUG",!0)}function q$(){J().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function by(e){J().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}bF(by);function K$(){z.disposeVariables()}function Cs(){return z}function Oh(){return z.memory()}function X$(e){return z.profile(e)}function M(e,t){return z.tidy(e,t)}function De(e){Xb(e).forEach(n=>n.dispose())}function Jt(e){return z.keep(e)}function Y$(e){return z.time(e)}function Z$(e){return z.setBackend(e)}function J$(){return z.ready()}function Q$(){return z.backendName}function eR(e){z.removeBackend(e)}function tR(e){return z.findBackend(e)}function nR(e){return z.findBackendFactory(e)}function Mh(e,t,n=1){return z.registerBackend(e,t,n)}function gk(){return z.backend}function rR(e,t){J().setPlatform(e,t)}function sR(e,t){let n=A(e,"a","add"),r=A(t,"b","add");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Qs,s)}var Y=W({add_:sR});function aR(e,t){let n=A(e,"a","floorDiv"),r=A(t,"b","floorDiv");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(to,s)}var Lh=W({floorDiv_:aR});function oR(e,t){let n=A(e,"a","div"),r=A(t,"b","div");if([n,r]=_t(n,r),n.dtype==="int32"&&r.dtype==="int32")return Lh(n,r);let s={a:n,b:r},a={};return z.runKernel(Za,s,a)}var ge=W({div_:oR});function iR(e,t){let n=A(e,"a","mul"),r=A(t,"b","mul");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(mo,s)}var V=W({mul_:iR});function cR(e){let t=A(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(kl,n)}else{let n={x:t};return z.runKernel(Ki,n)}}var Lt=W({abs_:cR});function uR(e){let n={x:A(e,"x","acos")};return z.runKernel(Xi,n)}var yy=W({acos_:uR});function lR(e){let n={x:A(e,"x","acosh")};return z.runKernel(Yi,n)}var vy=W({acosh_:lR});function dR(e){$(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),$(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((s,a)=>A(s,`tensors${a}`,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!ks(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return z.runKernel(Ba,r)}var bk=W({addN_:dR});function pR(e,t=null,n=!1){let s={x:A(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(Zi,s,a)}var Bh=W({all_:pR});function hR(e,t=null,n=!1){let s={x:A(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(Ji,s,a)}var jl=W({any_:hR});function fR(e,t=0){let r={x:A(e,"x","argMax")},s={axis:t};return z.runKernel(za,r,s)}var jo=W({argMax_:fR});function mR(e,t=0){let r={x:A(e,"x","argMin")},s={axis:t};return z.runKernel(xl,r,s)}var xy=W({argMin_:mR});function gR(e){let n={x:A(e,"x","asin")};return z.runKernel(Qi,n)}var wy=W({asin_:gR});function bR(e){let n={x:A(e,"x","asinh")};return z.runKernel(ec,n)}var ky=W({asinh_:bR});function yR(e){let n={x:A(e,"x","atan")};return z.runKernel(tc,n)}var Iy=W({atan_:yR});function vR(e,t){let n=A(e,"a","atan2"),r=A(t,"b","atan2");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(rc,s)}var Sy=W({atan2_:vR});function xR(e){let n={x:A(e,"x","atanh")};return z.runKernel(nc,n)}var Cy=W({atanh_:xR});function wR(e,t,n,r,s="NHWC",a){let o=e[3],i=[...t,o],c=xk(s);return ql(e,i,n,a,r,null,null,c)}function yk(e,t,n,r,s,a,o="channelsLast"){let[i,c]=zh(t),l;if(o==="channelsLast")l=[i,c,e[3],e[3]];else if(o==="channelsFirst")l=[i,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return ql(e,l,n,r,s,a,!1,o)}function kR(e,t,n,r,s,a,o="NDHWC"){let[i,c,l]=Ny(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,c,l,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,c,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return vk(e,u,n,r,s,!1,d,a)}function ql(e,t,n,r,s,a,o=!1,i="channelsLast"){let[c,l,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[c,l,u,d]=e;else if(i==="channelsFirst")[c,d,l,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=zh(n),[b,y]=zh(r),v=nu(p,b),x=nu(h,y),{padInfo:k,outHeight:C,outWidth:N}=CR(s,l,u,m,g,v,x,a,i),F=o?f*d:f,R;return i==="channelsFirst"?R=[c,F,C,N]:i==="channelsLast"&&(R=[c,C,N,F]),{batchSize:c,dataFormat:i,inHeight:l,inWidth:u,inChannels:d,outHeight:C,outWidth:N,outChannels:F,padInfo:k,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:v,effectiveFilterWidth:x,dilationHeight:b,dilationWidth:y,inShape:e,outShape:R,filterShape:t}}function vk(e,t,n,r,s,a=!1,o="channelsLast",i){let[c,l,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[c,l,u,d,p]=e;else if(o==="channelsFirst")[c,p,l,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[b,y,v]=Ny(n),[x,k,C]=Ny(r),N=nu(h,x),F=nu(f,k),R=nu(m,C),{padInfo:O,outDepth:D,outHeight:P,outWidth:T}=TR(s,l,u,d,b,y,v,N,F,R,i),L=a?g*p:g,G;return o==="channelsFirst"?G=[c,L,D,P,T]:o==="channelsLast"&&(G=[c,D,P,T,L]),{batchSize:c,dataFormat:o,inDepth:l,inHeight:u,inWidth:d,inChannels:p,outDepth:D,outHeight:P,outWidth:T,outChannels:L,padInfo:O,strideDepth:b,strideHeight:y,strideWidth:v,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:N,effectiveFilterHeight:F,effectiveFilterWidth:R,dilationDepth:x,dilationHeight:k,dilationWidth:C,inShape:e,outShape:G,filterShape:t}}function IR(e,t,n,r,s){r==null&&(r=Ty(e,t,n));let a=e[0],o=e[1],i=qo((a-t+2*r)/n+1,s),c=qo((o-t+2*r)/n+1,s);return[i,c]}function SR(e,t,n,r,s,a){s==null&&(s=Ty(e,t,r));let o=e[0],i=e[1],c=e[2],l=qo((o-t+2*s)/r+1,a),u=qo((i-t+2*s)/r+1,a),d=qo((c-t+2*s)/r+1,a);return[l,u,d,n]}function Ty(e,t,n,r=1){let s=nu(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function zh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Ny(e){return typeof e=="number"?[e,e,e]:e}function nu(e,t){return t<=1?e:e+(e-1)*(t-1)}function CR(e,t,n,r,s,a,o,i,c){let l,u,d;if(typeof e=="number"){l={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=IR([t,n],a,r,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/r),d=Math.ceil(n/s);let p=Math.max(0,(u-1)*r+a-t),h=Math.max(0,(d-1)*s+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),b=h-g;l={top:f,bottom:m,left:g,right:b,type:"SAME"}}else if(e==="valid")l={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/r),d=Math.ceil((n-o+1)/s);else if(typeof e=="object"){let p=c==="channelsLast"?e[1][0]:e[2][0],h=c==="channelsLast"?e[1][1]:e[2][1],f=c==="channelsLast"?e[2][0]:e[3][0],m=c==="channelsLast"?e[2][1]:e[3][1];l={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=qo((t-a+p+h)/r+1,i),d=qo((n-o+f+m)/s+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:l,outHeight:u,outWidth:d}}function TR(e,t,n,r,s,a,o,i,c,l,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=SR([t,n,r,1],i,1,s,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/s),h=Math.ceil(n/a),f=Math.ceil(r/o);let m=(p-1)*s+i-t,g=(h-1)*a+c-n,b=(f-1)*o+l-r,y=Math.floor(m/2),v=m-y,x=Math.floor(g/2),k=g-x,C=Math.floor(b/2),N=b-C;d={top:x,bottom:k,left:C,right:N,front:y,back:v,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/s),h=Math.ceil((n-c+1)/a),f=Math.ceil((r-l+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function qo(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 ua(e){let[t,n,r]=zh(e);return t===1&&n===1&&r===1}function rs(e,t){return ua(e)||ua(t)}function xk(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function NR(e,t){let r={x:A(e,"x","reshape","string_or_numeric")},s={shape:t};return z.runKernel($c,r,s)}var U=W({reshape_:NR});function _R(e,t,n,r,s){let a=A(e,"x","avgPool","float32"),o=1;$(rs(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,c=!1;a.rank===3&&(c=!0,i=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),$(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),s!=null&&$(Xt(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=z.runKernel(Wa,l,u);return d=ce(d,a.dtype),c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ir=W({avgPool_:_R});function ER(e,t,n,r,s,a="NDHWC"){let o=A(e,"x","avgPool3d","float32"),i=o,c=!1;o.rank===4&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),$(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),s!=null&&$(Xt(r),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel(wl,l,u);return d=ce(d,i.dtype),c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var _y=W({avgPool3d_:ER});function AR(e,t=0){$(e.length>=1,()=>"Pass at least one tensor to concat");let n=Gl(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${a.dtype}. `)}),n.length===1)return Ss(n[0]);let r=n,s={axis:t};return z.runKernel(ac,r,s)}var Ze=W({concat_:AR});function DR(e){let n={x:A(e,"x","sigmoid","float32")};return z.runKernel(No,n)}var cr=W({sigmoid_:DR});function FR(e,t,n){let r=A(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return z.runKernel(Mc,s,a)}var We=W({slice_:FR});function $R(e){let n={x:A(e,"x","tanh","float32")};return z.runKernel(Ro,n)}var Ko=W({tanh_:$R});function RR(e,t,n,r,s,a){let o=A(e,"forgetBias","basicLSTMCell"),i=A(t,"lstmKernel","basicLSTMCell"),c=A(n,"lstmBias","basicLSTMCell"),l=A(r,"data","basicLSTMCell"),u=A(s,"c","basicLSTMCell"),d=A(a,"h","basicLSTMCell"),p=Ze([l,d],1),h=Ae(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=We(f,[0,0],b),v=We(f,[0,g],b),x=We(f,[0,g*2],b),k=We(f,[0,g*3],b),C=Y(V(cr(y),Ko(v)),V(u,cr(Y(o,x)))),N=V(Ko(C),cr(k));return[C,N]}var PR=W({basicLSTMCell_:RR});function OR(e,t,n){let r=A(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);$(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),$(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),$(r.shape[0]%s==0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);let a={x:r},o={blockShape:t,crops:n};return z.runKernel(sc,a,o)}var Kl=W({batchToSpaceND_:OR});function MR(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 LR(e,t,n,r,s,a){a==null&&(a=.001);let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;r!=null&&(u=A(r,"offset","batchNorm")),$(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),$(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),$(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:MR(o),scale:l,offset:u,mean:i,variance:c},h={varianceEpsilon:a},f=z.runKernel(no,p,h);return U(f,o.shape)}var Ts=W({batchNorm_:LR});function BR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),$(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),$(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),$(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),l!=null&&$(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Ts(o,i,c,u,l,a)}var wk=W({batchNorm2d_:BR});function zR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),$(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),$(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),$(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),l!=null&&$(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Ts(o,i,c,u,l,a)}var kk=W({batchNorm3d_:zR});function WR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),$(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),$(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),$(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),l!=null&&$(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&$(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Ts(o,i,c,u,l,a)}var Ik=W({batchNorm4d_:WR});function VR(e,t,n){let r=A(e,"x","bincount"),s=A(t,"weights","bincount");$(r.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),$(n>=0,()=>`size must be non-negative, but got ${n}.`),$(s.size===r.size||s.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`);let a={x:r,weights:s},o={size:n};return z.runKernel(Up,a,o)}var Ey=W({bincount_:VR});function UR(e,t){let n=A(e,"s0","broadcastArgs","int32"),r=A(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(r.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);let s={s0:n,s1:r};return z.runKernel(Gp,s)}var Sk=W({broadcastArgs_:UR});function GR(e,t){let n=A(e,"broadcastTo","x"),r=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 s=n.shape,a=Array.from(t);for(let l=t.length-1;l>=0;l--)if(s[l]===t[l])a[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(a.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return Ss(n);let i={x:n},c={reps:a};return z.runKernel(ta,i,c)}var ru=W({broadcastTo_:GR});function HR(e){let n={x:A(e,"x","ceil","float32")};return z.runKernel(Ga,n)}var Ay=W({ceil_:HR});function jR(e,t,n){let r=A(e,"x","clipByValue");$(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let s={x:r},a={clipValueMin:t,clipValueMax:n};return z.runKernel(ea,s,a)}var Qt=W({clipByValue_:jR});function qR(e){return Ze(e,0)}var Ck=W({concat1d_:qR});function KR(e,t){return Ze(e,t)}var Tk=W({concat2d_:KR});function XR(e,t){return Ze(e,t)}var Nk=W({concat3d_:XR});function YR(e,t){return Ze(e,t)}var _k=W({concat4d_:YR});function ZR(e,t,n,r,s="NHWC",a=[1,1],o){let i=A(e,"x","conv2d","float32"),c=A(t,"filter","conv2d","float32"),l=i,u=!1;i.rank===3&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$(l.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`),$(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),o!=null&&$(Xt(r),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d=s==="NHWC"?l.shape[3]:l.shape[1];$(d===c.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${c.shape[2]}.`),$(rs(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:l,filter:c},h={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},f=z.runKernel(Ha,p,h);return u?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Rt=W({conv2d_:ZR});function JR(e,t,n,r,s="NWC",a=1,o){let i=A(e,"x","conv1d"),c=A(t,"filter","conv1d"),l=i,u=!1;i.rank===2&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1]])),$(l.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`),$(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),o!=null&&$(Xt(r),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`),$(l.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${c.shape[1]}.`),$(rs(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),$(s==="NWC",()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);let d=U(c,[1,c.shape[0],c.shape[1],c.shape[2]]),p=U(l,[l.shape[0],1,l.shape[1],l.shape[2]]),g=Rt(p,d,[1,n],r,"NHWC",[1,a],o);return u?U(g,[g.shape[2],g.shape[3]]):U(g,[g.shape[0],g.shape[2],g.shape[3]])}var Wh=W({conv1d_:JR});function QR(e,t,n,r,s,a="NHWC",o){$(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,c=t,l=!1;t.rank===3&&(l=!0,c=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),$(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),$(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),$(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?c.shape[3]:c.shape[1];$(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),$(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&$(Xt(s),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let p={dy:c,filter:n},h={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,inputShape:i},f=z.runKernel(ja,p,h);return l?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Dy=W({conv2DBackpropInput_:QR});function eP(e,t,n,r,s,a){let o=A(e,"x","conv2dTranspose"),i=A(t,"filter","conv2dTranspose");return Dy(n,o,i,r,s,"NHWC",a)}var Vh=W({conv2dTranspose_:eP});function tP(e,t,n,r,s="NDHWC",a=[1,1,1]){let o=A(e,"x","conv3d"),i=A(t,"filter","conv3d"),c=o,l=!1;o.rank===4&&(l=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),$(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),$(c.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${i.shape[3]}.`),$(rs(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),$(s==="NDHWC",()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`);let u={x:c,filter:i},d={strides:n,pad:r,dataFormat:s,dilations:a},p=z.runKernel(Il,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Fy=W({conv3d_:tP});function nP(e,t,n,r,s){$(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let c=a[4],l=o.shape[4];$(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),$(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),$(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),$(c===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[3]}.`),$(l===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:s,strides:r,inputShape:a},p=z.runKernel(Kp,u,d);return i?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Ek=W({conv3DBackpropInput_:nP});function rP(e,t,n,r,s){let a=A(e,"x","conv3dTranspose"),o=A(t,"filter","conv3dTranspose");return Ek(n,a,o,r,s)}var Ak=W({conv3dTranspose_:rP});function sP(e){let n={x:A(e,"x","cos","float32")};return z.runKernel(qa,n)}var Xl=W({cos_:sP});function aP(e){let n={x:A(e,"x","cosh","float32")};return z.runKernel(Ka,n)}var Uh=W({cosh_:aP});function oP(e,t=0,n=!1,r=!1){let a={x:A(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:r};return z.runKernel(Xa,a,o)}var Gh=W({cumsum_:oP});function iP(e,t,n,r=!1){let s=A(e,"x","denseBincount"),a=A(t,"weights","denseBincount");$(s.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`),$(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),$(n>=0,()=>`size must be non-negative, but got ${n}.`),$(a.size===s.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${a.shape}.`);let o={x:s,weights:a},i={size:n,binaryOutput:r};return z.runKernel(Xp,o,i)}var Dk=W({denseBincount_:iP});function cP(e,t,n="NHWC"){let r=A(e,"x","depthToSpace","float32"),s=n==="NHWC"?r.shape[1]:r.shape[2],a=n==="NHWC"?r.shape[2]:r.shape[3],o=n==="NHWC"?r.shape[3]:r.shape[1];$(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),$(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),$(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${a} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),$(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);let i={x:r},c={blockSize:t,dataFormat:n};return z.runKernel(ic,i,c)}var $y=W({depthToSpace_:cP});function uP(e,t,n,r,s="NHWC",a=[1,1],o){let i=A(e,"x","depthwiseConv2d","float32"),c=A(t,"filter","depthwiseConv2d","float32"),l=i,u=!1;i.rank===3&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),$(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),$(l.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),o!=null&&$(Xt(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:l,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=z.runKernel(Ya,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var la=W({depthwiseConv2d_:uP});function lP(e){let n={x:A(e,"x","diag")};return z.runKernel(Jp,n)}var dP=W({diag_:lP});function pP(e,t,n,r,s=[1,1],a="NHWC"){let o=A(e,"x","dilation2d"),i=A(t,"filter","dilation2d");$(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),$(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),$(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let c=o,l=!1;o.rank===3&&(c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=!0);let u={x:c,filter:i},d={strides:n,pad:r,dilations:s},p=z.runKernel(Sl,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Ry=W({dilation2d_:pP});function hP(e,t){let n=e.length,r=[];for(let s=0;s<n;s++){let a=n-1-s,o=e[a]||1;(t[t.length-1-s]||1)>1&&o===1&&r.unshift(a)}return r}function Gt(e,t){let n=[];for(let r=0;r<t.length;r++){let s=e[e.length-r-1],a=t.length-r-1,o=t[a];(s==null||s===1&&o>1)&&n.unshift(a)}return n}function gt(e,t){let n=[],r=Math.max(e.length,t.length);for(let s=0;s<r;s++){let a=e[e.length-s-1];a==null&&(a=1);let o=t[t.length-s-1];if(o==null&&(o=1),a===1)n.unshift(o);else if(o===1)n.unshift(a);else if(a!==o){let i=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(i)}else n.unshift(a)}return n}function fP(e,t){let n=A(e,"a","equal","string_or_numeric"),r=A(t,"b","equal","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(uc,s)}var Kn=W({equal_:fP});function mP(e,t,n){let r=A(t,"a","where"),s=A(n,"b","where"),a=A(e,"condition","where","bool"),o=gt(gt(a.shape,r.shape),s.shape),i=ru(a,o),c=ru(r,o),l=ru(s,o),u={condition:i,t:c,e:l};return z.runKernel(Pc,u)}var mn=W({where_:mP});function gP(e){let n={x:A(e,"x","zerosLike")};return z.runKernel(qc,n)}var Ue=W({zerosLike_:gP});function bP(e,t){let n=A(e,"a","div"),r=A(t,"b","div");[n,r]=_t(n,r);let s=ge(n,r),a=Ue(s),o=Kn(r,a);return mn(o,a,s)}var Py=W({divNoNan_:bP});function yP(e,t){let n=A(e,"t1","dot"),r=A(t,"t2","dot");$((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);let s=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];if($(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),n.rank===1&&r.rank===1){let o=U(n,[1,-1]),i=U(r,[-1,1]),c=Ae(o,i);return U(c,[])}else if(n.rank===1&&r.rank===2){let o=U(n,[1,-1]),i=U(r,[r.shape[0],r.shape[1]]),c=Ae(o,i);return U(c,[c.size])}else if(n.rank===2&&r.rank===1){let o=U(r,[-1,1]),i=Ae(n,o);return U(i,[i.size])}else{let o=U(r,[r.shape[0],r.shape[1]]);return Ae(n,o)}}var Fk=W({dot_:yP});function vP(e,...t){let n=t.map((s,a)=>A(s,`tensors${a}`,"einsum")),r={equation:e};return z.runKernel(th,n,r)}var $k=W({einsum_:vP});function xP(e){let n={x:A(e,"x","elu","float32")};return z.runKernel(Ja,n)}var su=W({elu_:xP});function wP(e){let t=A(e,"x","erf");$(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return z.runKernel(cc,n)}var Oy=W({erf_:wP});function kP(e){let n={x:A(e,"x","exp")};return z.runKernel(Qa,n)}var gn=W({exp_:kP});function IP(e,t=0){let n=A(e,"x","expandDims","string_or_numeric");$(t<=n.rank,()=>"Axis must be <= rank of the tensor");let r={input:n},s={dim:t};return z.runKernel(lc,r,s)}var bn=W({expandDims_:IP});function SP(e){let n={x:A(e,"x","expm1")};return z.runKernel(dc,n)}var My=W({expm1_:SP});function CP(e,t){let n=A(e,"x","tile","string_or_numeric");$(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let r={x:n},s={reps:t};return z.runKernel(ta,r,s)}var On=W({tile_:CP});function TP(e,t,n,r="float32"){t==null&&(t=e);let s=ze([e,t],r),a=e<=t?e:t;for(let i=0;i<a;++i)s.set(1,i,i);let o=U(s.toTensor(),[e,t]);if(n==null)return o;if(n.length===1)return On(bn(o,0),[n[0],1,1]);if(n.length===2)return On(bn(bn(o,0),0),[n[0],n[1],1,1]);if(n.length===3)return On(bn(bn(bn(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var Ly=W({eye_:TP});function In(e,t,n){let r={shape:e,value:t,dtype:n};return z.runKernel(Cl,{},r)}function NP(e){let n={x:A(e,"x","floor","float32")};return z.runKernel(eo,n)}var au=W({floor_:NP});function _P(e,t,n=0,r=0){let s=A(e,"x","gather"),a=A(t,"indices","gather","int32"),o={x:s,indices:a},i={axis:n,batchDims:r};return z.runKernel(hc,o,i)}var Xo=W({gather_:_P});function EP(e,t){let n=A(e,"a","greater","string_or_numeric"),r=A(t,"b","greater","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(mc,s)}var Mn=W({greater_:EP});function AP(e,t){let n=A(e,"a","greaterEqual","string_or_numeric"),r=A(t,"b","greaterEqual","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(ro,s)}var da=W({greaterEqual_:AP});function DP(e){let n={input:A(e,"input","imag")};return z.runKernel(ah,n)}var Hh=W({imag_:DP});function FP(e){let n={x:A(e,"x","isFinite")};return z.runKernel(gc,n)}var Rk=W({isFinite_:FP});function $P(e){let n={x:A(e,"x","isInf")};return z.runKernel(bc,n)}var Pk=W({isInf_:$P});function RP(e){let n={x:A(e,"x","isNaN")};return z.runKernel(yc,n)}var By=W({isNaN_:RP});function PP(e,t=.2){let r={x:A(e,"x","leakyRelu")},s={alpha:t};return z.runKernel(ao,r,s)}var Yl=W({leakyRelu_:PP});function OP(e,t){let n=A(e,"a","less","string_or_numeric"),r=A(t,"b","less","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(vc,s)}var jh=W({less_:OP});function MP(e,t){let n=A(e,"a","lessEqual","string_or_numeric"),r=A(t,"b","lessEqual","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(xc,s)}var pa=W({lessEqual_:MP});function Ok(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let r={start:e,stop:t,num:n};return z.runKernel(oh,{},r)}function LP(e,t=5,n=1,r=1,s=.5){let a=A(e,"x","localResponseNormalization");$(a.rank===4||a.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${a.rank}.`),$(Xt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let c={x:o},l={depthRadius:t,bias:n,alpha:r,beta:s},u=z.runKernel(_l,c,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var zy=W({localResponseNormalization_:LP});function BP(e){let n={x:A(e,"x","log","float32")};return z.runKernel(oo,n)}var Xn=W({log_:BP});function zP(e){let n={x:A(e,"x","log1p")};return z.runKernel(wc,n)}var Zl=W({log1p_:zP});function WP(e){return $(Js(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=A(t,"x","tf.grad","string_or_numeric"),s=n!=null?A(n,"dy","tf.grad"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(r),[r],s);return s!=null&&xn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),qh(o),o[0]})}}function VP(e){return $(Js(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{$(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=Gl(t,"args","tf.grads","string_or_numeric"),s=n!=null?A(n,"dy","tf.grads"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(...r),r,s);return s!=null&&xn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),qh(o),o})}}function UP(e){return $(Js(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{$(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),$(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=z.gradients(()=>e(t),[t],n);return qh(r),{grad:r[0],value:s}}}function GP(e){return $(Js(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{$(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),$(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=z.gradients(()=>e(...t),t,n);return n!=null&&xn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),qh(r.grads),r}}function Mk(e,t){$(Js(e),()=>"The f passed in variableGrads(f) must be a function"),$(t==null||Array.isArray(t)&&t.every(l=>l instanceof sa),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let l in z.registeredVariables)t.push(z.registeredVariables[l])}let r=n?t.filter(l=>!l.trainable):null,s=t.length;t=t.filter(l=>l.trainable),$(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let a=!0,{value:o,grads:i}=z.gradients(e,t,null,a);$(i.some(l=>l!=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()."),$(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let c={};return t.forEach((l,u)=>{i[u]!=null&&(c[l.name]=i[u])}),r!=null&&r.forEach(l=>c[l.name]=null),{value:o,grads:c}}function ss(e){return z.customGrad(e)}function qh(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
|
|
the f you passed encloses all operations that lead from x to y.`)}function HP(e){let n={x:A(e,"x","neg")};return z.runKernel(Sc,n)}var It=W({neg_:HP});function jP(e){let n={x:A(e,"x","softplus")};return z.runKernel(zc,n)}var Yo=W({softplus_:jP});function qP(e){let t=A(e,"x","logSigmoid");return ss(r=>({value:It(Yo(It(r))),gradFunc:o=>V(o,cr(It(r)))}))(t)}var Lk=W({logSigmoid_:qP});function KP(e,t=null,n=!1){let s={x:A(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(io,s,a)}var kr=W({max_:KP});function XP(e,t){let n=A(e,"a","sub"),r=A(t,"b","sub");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Fo,s)}var fe=W({sub_:XP});function YP(e,t=null,n=!1){let r=A(e,"x","sum");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return z.runKernel(Eo,s,a)}var ve=W({sum_:YP});function ZP(e,t=-1){let n=A(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return ss((s,a)=>{let o=!0,i=kr(s,t,!0),c=fe(s,i),l=fe(ce(c,"float32"),Xn(ve(gn(c),t,o)));return a([l]),{value:l,gradFunc:(d,p)=>{let[h]=p,f=!0,m=gn(h);return fe(d,V(ve(d,t,f),m))}}})(n)}var Kh=W({logSoftmax_:ZP});function Wy(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Bk(e,t,n){let r=e.length+t.length,s=[],a=0,o=0;for(let i=0;i<r;i++)n.indexOf(i)===-1?s.push(e[a++]):s.push(t[o++]);return s}function zk(e,t){let n=[],r=e.length;for(let a=0;a<r;a++)t.indexOf(a)===-1&&n.push(e[a]);let s=t.map(a=>e[a]);return[n,s]}function Zo(e,t){let n=t.map(r=>1);return Bk(e,n,t)}function JP(e,t,n){$(Wy(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Wk(e,t){if(Wy(e,t))return null;let n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function Vy(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function QP(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function e3(e,t=null,n=!1){let r=A(e,"x","logSumExp"),s=xr(t,r.shape),a=kr(r,s,!0),o=fe(r,a),i=gn(o),c=ve(i,s),l=Xn(c),u=Y(U(a,l.shape),l);if(n){let d=Zo(u.shape,s);return U(u,d)}return u}var Uy=W({logSumExp_:e3});function t3(e,t){let n=A(e,"a","logicalAnd","bool"),r=A(t,"b","logicalAnd","bool");gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(kc,s)}var Ir=W({logicalAnd_:t3});function n3(e){let n={x:A(e,"x","logicalNot","bool")};return z.runKernel(Tl,n)}var Jl=W({logicalNot_:n3});function r3(e,t){let n=A(e,"a","logicalOr","bool"),r=A(t,"b","logicalOr","bool");gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Nl,s)}var Xh=W({logicalOr_:r3});function s3(e,t){let n=A(e,"a","logicalXor","bool"),r=A(t,"b","logicalXor","bool");return gt(n.shape,r.shape),Ir(Xh(e,t),Jl(Ir(e,t)))}var Vk=W({logicalXor_:s3});function a3(e,t,n,r,s){let a=A(e,"x","maxPool"),o=1,i=a,c=!1;a.rank===3&&(c=!0,i=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),$(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),$(rs(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),s!=null&&$(Xt(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=z.runKernel(uo,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pt=W({maxPool_:a3});function o3(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=A(e,"x","maxPool3d"),i=o,c=!1;o.rank===4&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),$(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),$(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),s!=null&&$(Xt(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel(El,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Gy=W({maxPool3d_:o3});function i3(e,t,n,r,s=!1){let o={x:A(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},c=z.runKernel(lh,o,i);return{result:c[0],indexes:c[1]}}var Uk=W({maxPoolWithArgmax_:i3});function c3(e,t){let n=A(e,"a","maximum"),r=A(t,"b","maximum");[n,r]=_t(n,r),n.dtype==="bool"&&(n=ce(n,"int32"),r=ce(r,"int32")),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(co,s)}var as=W({maximum_:c3});function u3(e,t=null,n=!1){let s={x:A(e,"x","mean")},a={axis:t,keepDims:n};return z.runKernel(lo,s,a)}var Et=W({mean_:u3});function St(e,t="float32"){if(t==="complex64"){let r=St(e,"float32"),s=St(e,"float32");return aa(r,s)}let n=zp($t(e),t);return z.makeTensor(n,e,t)}function Yn(e,t="float32"){if(t==="complex64"){let r=Yn(e,"float32"),s=St(e,"float32");return aa(r,s)}let n=Pb($t(e),t);return z.makeTensor(n,e,t)}function l3(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let r=A(e,"x","meshgrid",e instanceof Ee?e.dtype:"float32");if(t===void 0)return[r];let s=A(t,"y","meshgrid",t instanceof Ee?t.dtype:"float32"),a=$t(r.shape),o=$t(s.shape);return n==="xy"?(r=U(r,[1,-1]),s=U(s,[-1,1]),[Ae(Yn([o,1],r.dtype),r),Ae(s,Yn([1,a],s.dtype))]):(r=U(r,[-1,1]),s=U(s,[1,-1]),[Ae(r,Yn([1,o],r.dtype)),Ae(Yn([a,1],s.dtype),s)])}function d3(e,t=null,n=!1){let s={x:A(e,"x","min")},a={axis:t,keepDims:n};return z.runKernel(po,s,a)}var Ql=W({min_:d3});function p3(e,t){let n=A(e,"a","minimum"),r=A(t,"b","minimum");[n,r]=_t(n,r),n.dtype==="bool"&&(n=ce(n,"int32"),r=ce(r,"int32")),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(ho,s)}var ou=W({minimum_:p3});function h3(e,t,n){$(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let r=A(e,"x","mirrorPad");if(r.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");$(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);let s=n==="reflect"?1:0;for(let i=0;i<r.rank;i++)$(t[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),$(t[i][0]>=0&&t[i][0]<=r.shape[i]-s&&t[i][1]>=0&&t[i][1]<=r.shape[i]-s,()=>`Padding in dimension ${i} cannot be greater than or equal to ${r.shape[i]-s} or less than 0 for input of shape ${r.shape}`);let a={paddings:t,mode:n},o={x:r};return z.runKernel(fo,o,a)}var Hy=W({mirrorPad_:h3});function f3(e,t){let n=A(e,"a","mod"),r=A(t,"b","mod");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Ic,s)}var jy=W({mod_:f3});function m3(e){let t=A(e,"x","square"),n={};return z.runKernel("Square",{x:t},n)}var ct=W({square_:m3});function g3(e,t=null,n=!1){e=A(e,"x","moments");let r=xr(t,e.shape),s=Et(e,r,n),a=s.shape;n||(a=Zo(s.shape,r));let o=ct(fe(ce(e,"float32"),U(s,a))),i=Et(o,r,n);return{mean:s,variance:i}}var Yh=W({moments_:g3});function b3(e,t,n,r){let s=A(t,"data","multiRNNCell"),a=Gl(n,"c","multiRNNCell"),o=Gl(r,"h","multiRNNCell"),i=s,c=[];for(let d=0;d<e.length;d++){let p=e[d](i,a[d],o[d]);c.push(p[0]),c.push(p[1]),i=p[1]}let l=[],u=[];for(let d=0;d<c.length;d+=2)l.push(c[d]),u.push(c[d+1]);return[l,u]}var y3=W({multiRNNCell_:b3});function v3(e,t,n,r=!1){let s=A(e,"logits","multinomial"),a=s.size,o=s.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let c={logits:o===1?U(s,[1,-1]):s},l={numSamples:t,seed:n,normalized:r},u=z.runKernel(dh,c,l);return o===1?U(u,[u.size]):u}var Gk=W({multinomial_:v3});function x3(e,t){let n=A(e,"a","notEqual","string_or_numeric"),r=A(t,"b","notEqual","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Cc,s)}var Jo=W({notEqual_:x3});function w3(e){let n={x:A(e,"x","onesLike")};return z.runKernel(Ec,n)}var Zn=W({onesLike_:w3});function k3(e,t){let n=A(e,"v1","outerProduct"),r=A(t,"v2","outerProduct");$(n.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);let s=U(n,[-1,1]),a=U(r,[1,-1]);return Ae(s,a)}var I3=W({outerProduct_:k3});function S3(e,t,n=0){let r=A(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let s={paddings:t,constantValue:n},a={x:r};return z.runKernel(bo,a,s)}var ur=W({pad_:S3});function C3(e,t,n=0){return $(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ur(e,[t],n)}var T3=W({pad1d_:C3});function N3(e,t,n=0){return $(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ur(e,t,n)}var _3=W({pad2d_:N3});function E3(e,t,n=0){return $(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."),ur(e,t,n)}var A3=W({pad3d_:E3});function D3(e,t,n=0){return $(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."),ur(e,t,n)}var F3=W({pad4d_:D3});function $3(e,t,n){let r=A(e,"x","spaceToBatchND");$(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),$(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),$(r.shape.reduce((o,i,c)=>c>0&&c<=t.length?o&&(i+n[c-1][0]+n[c-1][1])%t[c-1]==0:o,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let s={x:r},a={blockShape:t,paddings:n};return z.runKernel(Wc,s,a)}var ed=W({spaceToBatchND_:$3});function R3(e,t,n,r,s,a){s==null&&(s=[1,1]),a==null&&(a=1),r===0&&(r="valid");let o=A(e,"x","maxPool"),i=o,c=!1;o.rank===3&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),$(rs(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);let l=yk(i.shape,t,a,s,r),u=[l.dilationHeight,l.dilationWidth],d;r==="same"?d=O3([l.filterHeight,l.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=P3([l.inHeight,l.inWidth],u,d),m=p?r:"valid",g=p?i:ed(i,u,h),y=(n==="avg"?()=>ir(g,t,a,m):()=>Pt(g,t,a,m))(),v=p?y:Kl(y,u,f);return c?U(v,[v.shape[1],v.shape[2],v.shape[3]]):v}function P3(e,t,n){let r=n.map(u=>u[0]),s=n.map(u=>u[1]),a=e.concat(r,s),o=t.map((u,d)=>(u-a[d]%u)%u),i=s.map((u,d)=>u+o[d]),c=t.map((u,d)=>[r[d],i[d]]),l=t.map((u,d)=>[0,o[d]]);return[c,l]}function O3(e,t){let r=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),s=r.map(o=>Math.floor(o/2)),a=r.map((o,i)=>o-s[i]);return r.map((o,i)=>[s[i],a[i]])}var Hk=W({pool_:R3});function M3(e,t){let n=A(e,"base","pow"),r=A(t,"exp","pow");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(yo,s)}var Ns=W({pow_:M3});function L3(e,t){let n=A(e,"x","prelu"),r=A(t,"alpha","prelu"),s={x:n,alpha:r};return z.runKernel(vo,s)}var td=W({prelu_:L3});function B3(e,t=null,n=!1){let r=A(e,"x","prod");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return z.runKernel(Dc,s,a)}var Zh=W({prod_:B3});function z3(e,t,n){let r=$t(e),s=null;if(n==null||n==="float32")s=new Float32Array(r);else if(n==="int32")s=new Int32Array(r);else if(n==="bool")s=new Uint8Array(r);else throw new Error(`Unknown data type ${n}`);for(let a=0;a<r;a++)s[a]=t();return z.makeTensor(s,e,n)}var W3=W({rand_:z3}),qy=Oa(t1()),Ky=class{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=s||Math.random();this.random=qy.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let r=this.nextVal;return this.nextVal=NaN,r}let e,t,n=!1;for(;!n;){let r,s,a;do r=2*this.random()-1,s=2*this.random()-1,a=r*r+s*s;while(a>=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*s*o,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},V3=class{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;let s=r||Math.random();this.randu=qy.alea(s.toString()),this.randn=new Ky(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,a;for(;;){do r=this.randn.nextValue(),a=1+this.c*r;while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},U3=class{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=qy.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function G3(e,t,n=1,r="float32",s){if(n==null&&(n=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);let a=new V3(t,n,r,s),o=ze(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var H3=W({randomGamma_:G3});function j3(e,t=0,n=1,r,s){if(r!=null&&r==="bool")throw new Error(`Unsupported data type ${r}`);let a=new Ky(t,n,r,!1,s),o=ze(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var jk=W({randomNormal_:j3});function q3(e,t=0,n=1,r="float32",s){let a=ze(e,r),o=new U3(t,n,null,s);for(let i=0;i<a.values.length;i++)a.values[i]=o.nextValue();return a.toTensor()}var iu=W({randomUniform_:q3});function cu(e,t,n=1,r="float32"){if(n===0)throw new Error("Cannot have a step of zero");let s={start:e,stop:t,step:n,dtype:r};return z.runKernel(Al,{},s)}function K3(e){let n={input:A(e,"input","real")};return z.runKernel(ph,n)}var nd=W({real_:K3});function X3(e){let n={x:A(e,"x","reciprocal")};return z.runKernel(Fc,n)}var Xy=W({reciprocal_:X3});function Y3(e){let n={x:A(e,"x","relu")};return z.runKernel(xo,n)}var je=W({relu_:Y3});function Z3(e){let n={x:A(e,"x","relu6")};return z.runKernel(ko,n)}var Jh=W({relu6_:Z3});function J3(e,t){let r={x:A(e,"x","reverse")},s={dims:t};return z.runKernel(Io,r,s)}var Jn=W({reverse_:J3});function Q3(e){let t=A(e,"x","reverse");return $(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Jn(t,0)}var eO=W({reverse1d_:Q3});function tO(e,t){let n=A(e,"x","reverse");return $(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Jn(n,t)}var nO=W({reverse2d_:tO});function rO(e,t){let n=A(e,"x","reverse");return $(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Jn(n,t)}var sO=W({reverse3d_:rO});function aO(e,t){let n=A(e,"x","reverse");return $(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Jn(n,t)}var oO=W({reverse4d_:aO});function iO(e){let n={x:A(e,"x","round")};return z.runKernel(So,n)}var Qh=W({round_:iO});function cO(e){let n={x:A(e,"x","rsqrt","float32")};return z.runKernel(Co,n)}var ef=W({rsqrt_:cO});function Se(e,t){if((fn(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"&&fn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return oa(e,[],[],t)}function uO(e){let n={x:A(e,"x","selu")};return z.runKernel(Oc,n)}var tf=W({selu_:uO});function lO(e,t,n,r,s,a=[1,1],o="NHWC"){let i=A(e,"x","separableConv2d"),c=A(t,"depthwiseFilter","separableConv2d"),l=A(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");$(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),$(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),$(l.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),$(l.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`),$(l.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);let p=c.shape[2],h=c.shape[3];$(l.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${l.shape[2]}.`);let f=la(u,c,r,s,o,a),g=Rt(f,l,1,"valid",o);return d?U(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Qo=W({separableConv2d_:lO});async function dO(e,t){let n=A(e,"x","setdiff1d"),r=A(t,"y","setdiff1d");$(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),$(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),$(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);let s=await n.data(),a=await r.data(),o=new Set(a),i=0;for(let u=0;u<s.length;u++)o.has(s[u])||i++;let c=new Ut([i],n.dtype),l=new Ut([i],"int32");for(let u=0,d=0;u<s.length;u++)o.has(s[u])||(c.values[d]=s[u],l.values[d]=u,d++);return[c.toTensor(),l.toTensor()]}var qk=dO;function pO(e){let n={x:A(e,"x","sign")};return z.runKernel(Bc,n)}var Yy=W({sign_:pO});function hO(e){let n={x:A(e,"x","sin","float32")};return z.runKernel(To,n)}var nf=W({sin_:hO});function fO(e){let n={x:A(e,"x","sinh")};return z.runKernel(Lc,n)}var rf=W({sinh_:fO});function mO(e,t,n){let r=A(e,"x","slice1d");return $(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),We(r,[t],[n])}var sf=W({slice1d_:mO});function gO(e,t,n){let r=A(e,"x","slice2d");return $(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),We(r,t,n)}var Zy=W({slice2d_:gO});function bO(e,t,n){let r=A(e,"x","slice3d");return $(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),We(r,t,n)}var uu=W({slice3d_:bO});function yO(e,t,n){let r=A(e,"x","slice4d");return $(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),We(r,t,n)}var rd=W({slice4d_:yO});function vO(e,t=-1){let n=A(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let r={logits:n},s={dim:t};return z.runKernel(Ao,r,s)}var Pr=W({softmax_:vO});function xO(e){$(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(rh,t)}var sd=W({fft_:xO});function wO(e){$(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(sh,t)}var lu=W({ifft_:wO});function kO(e){let t=e.shape[e.shape.length-1],n=e.size/t,r;if(t<=2){let s=U(e,[n,t]);r=lu(s)}else{let s=[n,2*(t-1)],a=U(nd(e),[n,t]),o=U(Hh(e),[n,t]),i=Jn(We(a,[0,1],[n,t-2]),1),c=V(Jn(We(o,[0,1],[n,t-2]),1),Se(-1)),l=Ze([a,i],1),u=Ze([o,c],1),d=U(aa(l,u),[s[0],s[1]]);r=lu(d)}if(r=nd(r),e.rank===3&&e.shape[0]!==0){let s=r,a=e.shape[0];r=U(r,[a,r.shape[0]/a,r.shape[1]]),s.dispose()}return r}var af=W({irfft_:kO});function IO(e,t,n=0){let s={x:A(e,"x","split")},a={numOrSizeSplits:t,axis:n};return z.runKernel(Vc,s,a)}var Ln=W({split_:IO});function SO(e,t){$(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],r=e.size/n,s;if(t!=null&&t<n){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,s=We(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,s=Ze([e,St(f)],e.shape.length-1),n=t}else s=e;let a=Ue(s),o=U(aa(s,a),[r,n]),i=sd(o),c=Math.floor(n/2)+1,l=nd(i),u=Hh(i),d=Ln(l,[c,n-c],l.shape.length-1),p=Ln(u,[c,n-c],u.shape.length-1),h=s.shape.slice();return h[s.shape.length-1]=c,U(aa(d[0],p[0]),h)}var ad=W({rfft_:SO});function CO(e){let n={x:A(e,"x","sqrt","float32")};return z.runKernel(_o,n)}var cn=W({sqrt_:CO});function TO(e,t){let n=A(e,"a","squaredDifference"),r=A(t,"b","squaredDifference");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r},a={};return z.runKernel(Do,s,a)}var of=W({squaredDifference_:TO});function NO(e,t){let n=A(e,"x","squeeze");return U(n,a1(n.shape,t).newShape)}var os=W({squeeze_:NO});function _O(e,t=0){let n=Gl(e,"tensors","stack","string_or_numeric");$(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&$(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let r=n,s={axis:t};return z.runKernel(Ac,r,s)}var Ot=W({stack_:_O});function EO(e,t=0){let r={x:A(e,"x","step")},s={alpha:t};return z.runKernel(na,r,s)}var du=W({step_:EO});function AO(e,t,n,r,s=0,a=0,o=0,i=0,c=0){let u={x:A(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:c};return z.runKernel(Uc,u,d)}var Jy=W({stridedSlice_:AO});function DO(e){let n={x:A(e,"x","tan","float32")};return z.runKernel($o,n)}var Qy=W({tan_:DO});function Ge(e,t){Ma(e);let n=ns(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return oa(e,null,n,t)}function Or(e,t,n){if(Ma(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let r=ns(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return oa(e,t,r,n)}function Mr(e,t,n){if(Ma(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let r=ns(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return oa(e,t,r,n)}function FO(e,t,n){if(Ma(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let r=ns(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return oa(e,t,r,n)}function $O(e,t,n){if(Ma(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let r=ns(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,oa(e,t,r,n)}function RO(e,t=1,n=!0){let r=A(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let s=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${t}`);let a={x:r},o={k:t,sorted:n},[i,c]=z.runKernel(Gc,a,o);return{values:i,indices:c}}var ev=W({topk_:RO});function PO(e,t=0,n=1,r,s){if(r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new Ky(t,n,r,!0,s),o=ze(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var cf=W({truncatedNormal_:PO});function OO(e,t=0){let n=A(e,"x","unique","string_or_numeric");$(n.rank>0,()=>"The input tensor must be at least 1D");let r={x:n},s={axis:t},[a,o]=z.runKernel(Ih,r,s);return{values:a,indices:o}}var uf=W({unique_:OO});function MO(e,t,n){let r=A(e,"x","unsortedSegmentSum"),s=A(t,"segmentIds","unsortedSegmentSum","int32");$(Xt(n),()=>"numSegments must be of dtype int");let a={x:r,segmentIds:s},o={numSegments:n};return z.runKernel($l,a,o)}var tv=W({unsortedSegmentSum_:MO});function LO(e,t=0){let n=A(e,"x","unstack","string_or_numeric");$(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let r={value:n},s={axis:t};return z.runKernel(jc,r,s)}var dt=W({unstack_:LO});function Kk(e,t=!0,n,r){return z.makeVariable(e,t,n,r)}function Xk(e,t){let n=[];for(let a=0;a<t.length;a++)t[a]&&n.push(a);let r=ze(e,"int32"),s=ze([n.length,e.length],"int32");for(let a=0;a<n.length;a++){let o=r.indexToLoc(n[a]),i=a*e.length;s.values.set(o,i)}return s.toTensor()}async function BO(e){let t=A(e,"condition","whereAsync","bool"),n=await t.data(),r=Xk(t.shape,n);return e!==t&&t.dispose(),r}var nv=BO;async function zO(e,t,n){let r=A(e,"tensor","boolMask"),s=A(t,"mask","boolMask","bool"),a=n==null?0:n,o=s.rank,i=r.shape;$(o>0,()=>"mask cannot be scalar"),xn(i.slice(a,a+o),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let m=a;m<a+o;m++)c*=i[m];let l=i.slice(0,a).concat([c],i.slice(a+o)),u=U(r,l),d=U(s,[-1]),p=await nv(d),h=os(p,[1]),f=Xo(u,h,a);return e!==r&&r.dispose(),t!==s&&s.dispose(),h.dispose(),u.dispose(),d.dispose(),p.dispose(),f}var WO=zO;function VO(e,t="euclidean",n=null,r=!1){e=A(e,"x","norm");let s=Yk(e,t,n),a=s.shape;if(r){let o=xr(n,e.shape);a=Zo(s.shape,o)}return U(s,a)}function Yk(e,t,n=null){if(e.rank===0)return Lt(e);if(e.rank!==1&&n===null)return Yk(U(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return ve(Lt(e),n);if(t===1/0)return kr(Lt(e),n);if(t===-1/0)return Ql(Lt(e),n);if(t==="euclidean"||t===2)return cn(ve(Ns(Lt(e),Se(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return kr(ve(Lt(e),n[0]),n[1]-1);if(t===1/0)return kr(ve(Lt(e),n[1]),n[0]);if(t===-1/0)return Ql(ve(Lt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return cn(ve(ct(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var lf=W({norm_:VO});function UO(e,t,n,r,s=!0){let a=A(e,"v","movingAverage"),o=A(t,"x","movingAverage"),i=A(n,"decay","movingAverage");T1(a,o),$(ks(a.shape,o.shape),()=>"Shape mismatch in v and x");let c=Se(1),l=fe(c,i),u=V(fe(o,a),l);if(s){$(r!=null,()=>"When using zeroDebias: true, step is required.");let d=A(r,"step","movingAverage");u=ge(u,fe(c,Ns(i,d)))}return Y(a,u)}var GO=W({movingAverage_:UO});function HO(e,t,n){let r=A(e,"indices","scatterND","int32"),s=A(t,"updates","scatterND");hy(s,r,n);let a={indices:r,updates:s},o={shape:n};return z.runKernel(Rc,a,o)}var Zk=W({scatterND_:HO});function jO(e,t,n,r){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let s=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function qO(e,t,n,r=0){let s=A(e,"sparseIndices","sparseToDense","int32"),a=A(t,"sparseValues","sparseToDense"),o=A(r,"defaultValue","sparseToDense",a.dtype);jO(s,a,n,o);let i={sparseIndices:s,sparseValues:a,defaultValue:o},c={outputShape:n};return z.runKernel(vh,i,c)}var rv=W({sparseToDense_:qO});function KO(e,t){let n=A(t,"indices","gatherND","int32"),s={params:A(e,"x","gatherND","string_or_numeric"),indices:n};return z.runKernel(fc,s)}var Jk=W({gatherND_:KO});function XO(e,t){if(t==null)return e.shape.slice();if(ks(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let r=0;r<e.shape.length;r++)t[r]==null&&e.shape[r]!=null?n.push(e.shape[r]):n.push(t[r]);return n}return t}function YO(e,t,n,r){let s=A(e,"x","dropout");if($(s.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`),$(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ee?s.clone():s;let a=XO(s,n),o=1-t,i=ge(au(Y(iu(a,0,1,"float32",r),o)),o);return V(s,i)}var Qk=W({dropout_:YO});function eI(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function sv(e,t,n){let r=1-e%2,s=new Float32Array(e);for(let a=0;a<e;++a){let o=2*Math.PI*a/(e+r-1);s[a]=t-n*Math.cos(o)}return Ge(s,"float32")}async function ZO(e,t,n=1){let r=A(e,"predictions","inTopK"),s=A(t,"targets","inTopK");$(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),$(r.rank-1===s.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`),xn(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=r.shape[r.shape.length-1];$(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await r.data(),i=await s.data(),[c,l]=[o.length/a,a],u=o1("bool",c);for(let d=0;d<c;d++){let p=d*l,h=o.subarray(p,p+l),f=[];for(let m=0;m<h.length;m++)f.push({value:h[m],index:m});f.sort((m,g)=>g.value-m.value),u[d]=0;for(let m=0;m<n;m++)if(f[m].index===i[d]){u[d]=1;break}}return e!==r&&r.dispose(),t!==s&&s.dispose(),qn(u,s.shape,"bool")}var JO=ZO,ha={};$e(ha,{conv2d:()=>tM,depthwiseConv2d:()=>aM,matMul:()=>iM});function QO(e,t,n,r,s,a="NHWC",o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let c=t;c.rank===3&&(c=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),$(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),$(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),$(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let l=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?c.shape[3]:c.shape[1];$(l===n[2],()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`),$(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&$(Xt(s),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:i,dy:c},p={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,filterShape:n};return z.runKernel(jp,d,p)}var av=W({conv2DBackpropFilter_:QO});function df(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return V(e,du(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function pf(e,t){let n=t,r=Gt(e.shape,t.shape);return r.length>0&&(n=ve(n,r)),U(n,e.shape)}function hf(e,t,n,r){if(t==="linear")return e;if(t==="relu")return je(e);if(t==="elu")return su(e);if(t==="relu6")return Jh(e);if(t==="prelu")return td(e,n);if(t==="leakyrelu")return Yl(e,r);if(t==="sigmoid")return cr(e);throw new Error(`Unknown fused activation ${t}.`)}var ff=(e,t)=>!(e>0)||t==="linear";function eM({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:c="linear",preluActivationWeights:l,leakyreluAlpha:u}){if(c=c||"linear",ff(z.state.gradientDepth,c)===!1){let k=Rt(e,t,n,r,s,a,o);return i!=null&&(k=Y(k,i)),hf(k,c,l,u)}let d=A(e,"x","conv2d","float32"),p=A(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),$(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&$(Xt(r),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`),$(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),$(rs(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),$(s==="NHWC",()=>`Error in conv2d: got dataFormat of ${s} but only NHWC is currently supported.`);let m=ql(h.shape,p.shape,n,a,r,o),g;i!=null&&(g=A(i,"bias","fused conv2d"),[g]=_t(g,d),gt(m.outShape,g.shape));let b;l!=null&&(b=A(l,"prelu weights","fused conv2d"));let y=(k,C)=>{let[N,F,R,O]=C,D=df(k,R,c);$(ua(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let P=Dy(F.shape,D,N,n,r),T=av(F,D,N.shape,n,r),L=[P,T];if(O!=null){let G=pf(O,D);L.push(G)}return L},v={x:h,filter:p,bias:g,preluActivationWeights:b},x={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:c,leakyreluAlpha:u};return i==null?ss((C,N,F)=>{let R=z.runKernel(Mo,v,x);return F([N,C,R]),f&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:y}})(h,p):ss((C,N,F,R)=>{let O=z.runKernel(Mo,v,x);return R([N,C,O,F]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(h,p,g)}var tM=W({fusedConv2d_:eM});function nM(e,t,n,r,s,a=[1,1],o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let c=t;c.rank===3&&(c=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l={x:i,dy:c},u={strides:r,pad:s,dimRoundingMode:o,dilations:a,filterShape:n};return z.runKernel(Yp,l,u)}var tI=W({depthwiseConv2dNativeBackpropFilter_:nM});function rM(e,t,n,r,s,a=[1,1],o){let i=t,c=!1;t.rank===3&&(c=!0,i=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l={dy:i,filter:n},u={strides:r,pad:s,dimRoundingMode:o,dilations:a,inputShape:e},d=z.runKernel(Zp,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var nI=W({depthwiseConv2dNativeBackpropInput_:rM});function sM({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:c="linear",preluActivationWeights:l,leakyreluAlpha:u}){if(ff(z.state.gradientDepth,c)===!1){let k=la(e,t,n,r,s,a,o);return i!=null&&(k=Y(k,i)),hf(k,c,l,u)}let d=A(e,"x","depthwiseConv2d","float32"),p=A(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),$(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),$(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),$(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),$(rs(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&$(Xt(r),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${r}.`);let m=ql(h.shape,p.shape,n,a,r,o,!0),g;i!=null&&(g=A(i,"bias","fused conv2d"),[g]=_t(g,d),gt(m.outShape,g.shape));let b;l!=null&&(b=A(l,"prelu weights","fused depthwiseConv2d"));let y=(k,C)=>{$(ua(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[N,F,R,O]=C,D=df(k,R,c),P=nI(F.shape,D,N,n,r,a,o),T=tI(F,D,N.shape,n,r,a,o);if(O!=null){let L=pf(g,D);return[P,T,L]}return[P,T]},v={x:h,filter:p,bias:g,preluActivationWeights:b},x={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:c,leakyreluAlpha:u};return i==null?ss((C,N,F)=>{let R=z.runKernel(Lo,v,x);return F([N,C,R]),f&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:y}})(h,p):ss((C,N,F,R)=>{let O=z.runKernel(Lo,v,x);return R([N,C,O,F]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(h,p,g)}var aM=W({fusedDepthwiseConv2d_:sM});function oM({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(ff(z.state.gradientDepth,a)===!1){let O=Ae(e,t,n,r);return s!=null&&(O=Y(O,s)),hf(O,a,o,i)}let c=A(e,"a","fused matMul"),l=A(t,"b","fused matMul");[c,l]=_t(c,l);let u=n?c.shape[c.rank-2]:c.shape[c.rank-1],d=r?l.shape[l.rank-1]:l.shape[l.rank-2],p=n?c.shape[c.rank-1]:c.shape[c.rank-2],h=r?l.shape[l.rank-2]:l.shape[l.rank-1],f=c.shape.slice(0,-2),m=l.shape.slice(0,-2),g=$t(f),b=$t(m);$(c.rank>=2&&l.rank>=2&&c.rank===l.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${c.rank} and ${l.rank}.`),$(ks(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${c.shape} and ${l.shape} must match.`),$(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${c.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`);let y=c.shape.slice(0,-2).concat([p,h]),v=n?U(c,[g,u,p]):U(c,[g,p,u]),x=r?U(l,[b,h,d]):U(l,[b,d,h]),k;s!=null&&(k=A(s,"bias","fused matMul"),[k]=_t(k,c),gt(y,k.shape));let C;o!=null&&(C=A(o,"prelu weights","fused matMul"));let N=(O,D)=>{let[P,T,L,G]=D,j=df(U(O,L.shape),L,a),q,K;if(!n&&!r?(q=Ae(j,T,!1,!0),K=Ae(P,j,!0,!1)):!n&&r?(q=Ae(j,T,!1,!1),K=Ae(j,P,!0,!1)):n&&!r?(q=Ae(T,j,!1,!0),K=Ae(P,j,!1,!1)):(q=Ae(T,j,!0,!0),K=Ae(j,P,!0,!0)),s!=null){let ee=pf(G,j);return[q,K,ee]}else return[q,K]},F={a:v,b:x,bias:k,preluActivationWeights:C},R={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:i};return s==null?ss((D,P,T)=>{let L=z.runKernel(Oo,F,R);return T([D,P,L]),{value:U(L,y),gradFunc:N}})(v,x):ss((D,P,T,L)=>{let G=z.runKernel(Oo,F,R);return L([D,P,G,T]),{value:U(G,y),gradFunc:N}})(v,x,k)}var iM=W({fusedMatMul_:oM});function cM(e){return sv(e,.54,.46)}var uM=W({hammingWindow_:cM});function lM(e){return sv(e,.5,.5)}var rI=W({hannWindow_:lM});function dM(e,t,n,r=!1,s=0){let a=0,o=[];for(;a+t<=e.size;)o.push(We(e,a,t)),a+=n;if(r)for(;a<e.size;){let i=a+t-e.size,c=Ze([We(e,a,t-i),In([i],s)]);o.push(c),a+=n}return o.length===0?Or([],[0,t]):U(Ze(o),[o.length,t])}var sI=W({frame_:dM});function pM(e,t,n,r,s=rI){r==null&&(r=eI(t));let a=sI(e,t,n),o=V(a,s(t));return ad(o,r)}var hM=W({stft_:pM});function fM(e,t,n,r,s="bilinear",a=0){let o=A(e,"image","cropAndResize"),i=A(t,"boxes","cropAndResize","float32"),c=A(n,"boxInd","cropAndResize","int32"),l=i.shape[0];$(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),$(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${i.shape}.`),$(c.rank===1&&c.shape[0]===l,()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${i.shape}.`),$(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),$(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),$(s==="bilinear"||s==="nearest",()=>`method must be bilinear or nearest, but was ${s}`);let u={image:o,boxes:i,boxInd:c},d={method:s,extrapolationValue:a,cropSize:r};return z.runKernel(oc,u,d)}var mM=W({cropAndResize_:fM});function gM(e){let t=A(e,"image","flipLeftRight","float32");$(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return z.runKernel(pc,n,{})}var bM=W({flipLeftRight_:gM});function yM(e){let t=A(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];$(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),$(r===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);let s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,On(t,s)}var vM=W({grayscaleToRGB_:yM});function xM(e,t,n=0,r=.5){let s=A(e,"image","rotateWithOffset","float32");$(s.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);let a={image:s},o={radians:t,fillValue:n,center:r};return z.runKernel(Kc,a,o)}var wM=W({rotateWithOffset_:xM});function pu(e,t,n,r,s,a){r==null&&(r=.5),s==null&&(s=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),$(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),$(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),$(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),$(t.rank===1,()=>"scores must be a 1D tensor"),$(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),$(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}function kM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){let a=A(e,"boxes","nonMaxSuppression","float32"),o=A(t,"scores","nonMaxSuppression","float32"),i=pu(a,o,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;let c={maxOutputSize:n,iouThreshold:r,scoreThreshold:s};return z.runKernel(Tc,{boxes:a,scores:o},c)}var IM=W({nonMaxSuppression_:kM});function SM(e,t,n){let r=CM(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function CM(e,t,n){return NM(e,t,n||TM)}function TM(e,t){return e>t?1:e<t?-1:0}function NM(e,t,n){let r=0,s=e.length,a=0,o=!1;for(;r<s;){a=r+(s-r>>>1);let i=n(t,e[a]);i>0?r=a+1:(s=a,o=!i)}return o?r:-r-1}function aI(e,t,n,r,s){return ov(e,t,n,r,s,0)}function oI(e,t,n,r,s,a){return ov(e,t,n,r,s,0,!1,a,!0)}function iI(e,t,n,r,s,a){return ov(e,t,n,r,s,a,!0)}function ov(e,t,n,r,s,a,o=!1,i=!1,c=!1){let l=[];for(let g=0;g<t.length;g++)t[g]>s&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(cI);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length<n&&l.length>0;){let g=l.pop(),{score:b,boxIndex:y,suppressBeginIndex:v}=g;if(b<s)break;let x=!1;for(let k=d.length-1;k>=v;--k){let C=_M(e,y,d[k]);if(C>=r){x=!0;break}if(g.score=g.score*EM(r,u,C),g.score<=s)break}g.suppressBeginIndex=d.length,x||(g.score===b?(d.push(y),p.push(g.score)):g.score>s&&SM(l,g,cI))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),c&&(m.validOutputs=h),m}function _M(e,t,n){let r=e.subarray(t*4,t*4+4),s=e.subarray(n*4,n*4+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),l=Math.min(s[0],s[2]),u=Math.min(s[1],s[3]),d=Math.max(s[0],s[2]),p=Math.max(s[1],s[3]),h=(i-a)*(c-o),f=(d-l)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,l),g=Math.max(o,u),b=Math.min(i,d),y=Math.min(c,p),v=Math.max(b-m,0)*Math.max(y-g,0);return v/(h+f-v)}function EM(e,t,n){let r=Math.exp(t*n*n);return n<=e?r:0}function cI(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function AM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){let a=A(e,"boxes","nonMaxSuppressionAsync"),o=A(t,"scores","nonMaxSuppressionAsync"),i=pu(a,o,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;let c=await Promise.all([a.data(),o.data()]),l=c[0],u=c[1],{selectedIndices:d}=aI(l,u,n,r,s);return a!==e&&a.dispose(),o!==t&&o.dispose(),Ge(d,"int32")}var DM=AM;function FM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){let o=A(e,"boxes","nonMaxSuppression"),i=A(t,"scores","nonMaxSuppression"),c=pu(o,i,n,r,s,a);n=c.maxOutputSize,r=c.iouThreshold,s=c.scoreThreshold,a=c.softNmsSigma;let l={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a},d=z.runKernel(_c,l,u);return{selectedIndices:d[0],selectedScores:d[1]}}var $M=W({nonMaxSuppressionWithScore_:FM});async function RM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){let o=A(e,"boxes","nonMaxSuppressionAsync"),i=A(t,"scores","nonMaxSuppressionAsync"),c=pu(o,i,n,r,s,a);n=c.maxOutputSize,r=c.iouThreshold,s=c.scoreThreshold,a=c.softNmsSigma;let l=await Promise.all([o.data(),i.data()]),u=l[0],d=l[1],{selectedIndices:p,selectedScores:h}=iI(u,d,n,r,s,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ge(p,"int32"),selectedScores:Ge(h)}}var PM=RM;function OM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){let o=A(e,"boxes","nonMaxSuppression"),i=A(t,"scores","nonMaxSuppression"),c=pu(o,i,n,r,s,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:l,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=z.runKernel(Nc,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var MM=W({nonMaxSuppressionPadded_:OM});async function LM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){let o=A(e,"boxes","nonMaxSuppressionAsync"),i=A(t,"scores","nonMaxSuppressionAsync"),c=pu(o,i,n,r,s,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=oI(p,h,l,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ge(f,"int32"),validOutputs:Se(m,"int32")}}var BM=LM;function zM(e,t,n=!1,r=!1){let s=A(e,"images","resizeBilinear");$(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),$(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),$(r===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=U(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let[]=t,i={images:a},c={alignCorners:n,halfPixelCenters:r,size:t},l=z.runKernel(wo,i,c);return o?U(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var uI=W({resizeBilinear_:zM});function WM(e,t,n=!1,r=!1){let s=A(e,"images","resizeNearestNeighbor");$(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),$(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),$(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),$(r===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=U(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let[]=t,i={images:a},c={alignCorners:n,halfPixelCenters:r,size:t},l=z.runKernel(Dl,i,c);return o?U(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var lI=W({resizeNearestNeighbor_:WM});function VM(e,t="binary",n=!1,r=.5){let s=A(e,"image","threshold"),a=.2989,o=.587,i=.114,c=s.shape[0]*s.shape[1],l=V(Ge([r]),255),u,d,p,h;if($(s.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`),$(s.shape[2]===3||s.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`),$(s.dtype==="int32"||s.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),$(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),s.shape[2]===3){[u,d,p]=Ln(s,[1,1,1],-1);let g=V(u,a),b=V(d,o),y=V(p,i);h=Y(Y(g,b),y)}else h=e;if(t==="otsu"){let g=Ey(ce(Qh(h),"int32"),qn([]),256);l=UM(g,c)}let f=n?pa(h,l):Mn(h,l);return ce(V(f,255),"int32")}function UM(e,t){let n=Ge([-1]),r=Ge([0]),s=Ge([0]),a,o,i,c,l,u;for(let d=0;d<e.size-1;d++){a=We(e,0,d+1),o=We(e,d+1),l=ge(ve(a),t),u=ge(ve(o),t);let p=ve(V(a,cu(0,a.size)));i=ge(p,ve(a));let h=In(o.shape,a.size),f=Y(cu(0,o.size),h),m=V(o,f);c=ge(ve(m),ve(o));let g=fe(i,c),b=fe(i,c),y=V(l,u);s=V(V(y,g),b);let v=Mn(s,r);r=mn(v,s,r),n=mn(v,Ge([d]),n)}return n}var GM=W({threshold_:VM});function HM(e,t,n="nearest",r="constant",s=0,a){let o=A(e,"image","transform","float32"),i=A(t,"transforms","transform","float32");$(o.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`),$(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),$(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let c={image:o,transforms:i},l={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return z.runKernel(Hc,c,l)}var jM=W({transform_:HM});function qM(e,t,n){$(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),$(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let r=A(e,"a","bandPart");$(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);let s=r.shape,[a,o]=r.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=U(cu(0,a,1,"int32"),[-1,1]),c=cu(0,o,1,"int32"),l=fe(i,c),u=Ir(pa(l,Se(+t,"int32")),da(l,Se(-n,"int32"))),d=St([a,o],r.dtype);return U(Ot(dt(U(r,[-1,a,o])).map(p=>mn(u,p,d))),s)}var KM=W({bandPart_:qM});function XM(e){let t;if(Array.isArray(e)){t=!1,$(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let s=e[0].shape[0];for(let a=1;a<e.length;++a)$(e[a].shape[0]===s,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${s})`)}else t=!0,e=Ln(e,e.shape[0],0).map(s=>os(s,[0]));$(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],r=e;for(let s=0;s<e.length;++s)n.push(z.tidy(()=>{let a=r[s];if(s>0)for(let o=0;o<s;++o){let i=V(ve(V(n[o],a)),n[o]);a=fe(a,i)}return ge(a,lf(a,"euclidean"))}));return t?Ot(n,0):n}var YM=W({gramSchmidt_:XM});function ZM(e,t=!1){if($(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return dI(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((c,l)=>c*l),r=dt(U(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];r.forEach(c=>{let[l,u]=dI(c,t);s.push(l),a.push(u)});let o=U(Ot(s,0),e.shape),i=U(Ot(a,0),e.shape);return[o,i]}}function dI(e,t=!1){return z.tidy(()=>{$(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],r=e.shape[1],s=Ly(n),a=Ss(e),o=Or([[1]],[1,1]),i=Ss(o),c=n>=r?r:n;for(let l=0;l<c;++l){let u=a,d=i,p=s;[i,a,s]=z.tidy(()=>{let h=We(a,[l,l],[n-l,1]),f=lf(h),m=We(a,[l,l],[1,1]),g=mn(Mn(m,0),Or([[-1]]),Or([[1]])),b=fe(m,V(g,f)),y=ge(h,b);y.shape[0]===1?i=Ss(o):i=Ze([o,We(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let v=It(ge(Ae(g,b),f)),x=We(a,[l,0],[n-l,r]),k=V(v,i),C=Re(i);if(l===0)a=fe(x,Ae(k,Ae(C,x)));else{let R=fe(x,Ae(k,Ae(C,x)));a=Ze([We(a,[0,0],[l,r]),R],0)}let N=Re(k),F=We(s,[0,l],[n,s.shape[1]-l]);if(l===0)s=fe(F,Ae(Ae(F,i),N));else{let R=fe(F,Ae(Ae(F,i),N));s=Ze([We(s,[0,0],[n,l]),R],1)}return[i,a,s]}),De([u,d,p])}return!t&&n>r&&(s=We(s,[0,0],[n,r]),a=We(a,[0,0],[r,r])),[s,a]})}var JM=W({qr_:ZM}),Sn;(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"})(Sn||(Sn={}));function QM(e,t,n=Sn.SUM_BY_NONZERO_WEIGHTS){let r=A(e,"losses","computeWeightedLoss"),s=null;t!=null&&(s=A(t,"weights","computeWeightedLoss"));let a=s==null?r:V(r,s);if(n===Sn.NONE)return a;if(n===Sn.SUM)return ve(a);if(n===Sn.MEAN){if(s==null)return Et(a);{let o=r.size/s.size,i=ge(ve(a),ve(s));return o>1?ge(i,Se(o)):i}}if(n===Sn.SUM_BY_NONZERO_WEIGHTS){if(s==null)return ge(ve(a),Se(r.size));{let o=V(s,Yn(r.shape)),i=ce(ve(Jo(o,Se(0))),"float32");return ge(ve(a),i)}}throw Error(`Unknown reduction: ${n}`)}var _s=W({computeWeightedLoss_:QM});function eL(e,t,n,r=Sn.SUM_BY_NONZERO_WEIGHTS){let s=A(e,"labels","absoluteDifference"),a=A(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=A(n,"weights","absoluteDifference")),xn(s.shape,a.shape,"Error in absoluteDifference: ");let i=Lt(fe(s,a));return _s(i,o,r)}var tL=W({absoluteDifference_:eL});function nL(e,t,n,r,s=Sn.SUM_BY_NONZERO_WEIGHTS){let a=A(e,"labels","cosineDistance"),o=A(t,"predictions","cosineDistance"),i=null;r!=null&&(i=A(r,"weights","cosineDistance")),xn(a.shape,o.shape,"Error in cosineDistance: ");let c=Se(1),l=fe(c,ve(V(a,o),n,!0));return _s(l,i,s)}var rL=W({cosineDistance_:nL});function sL(e,t,n,r=Sn.SUM_BY_NONZERO_WEIGHTS){let s=A(e,"labels","hingeLoss"),a=A(t,"predictions","hingeLoss"),o=null;n!=null&&(o=A(n,"weights","hingeLoss")),xn(s.shape,a.shape,"Error in hingeLoss: ");let i=Se(1);s=fe(V(Se(2),s),i);let c=je(fe(i,V(s,a)));return _s(c,o,r)}var aL=W({hingeLoss_:sL});function oL(e,t,n,r=1,s=Sn.SUM_BY_NONZERO_WEIGHTS){let a=A(e,"labels","huberLoss"),o=A(t,"predictions","huberLoss"),i=null;n!=null&&(i=A(n,"weights","huberLoss")),xn(a.shape,o.shape,"Error in huberLoss: ");let c=Se(r),l=Lt(fe(o,a)),u=ou(l,c),d=fe(l,u),p=Y(V(Se(.5),ct(u)),V(c,d));return _s(p,i,s)}var iL=W({huberLoss_:oL});function cL(e,t,n,r=1e-7,s=Sn.SUM_BY_NONZERO_WEIGHTS){let a=A(e,"labels","logLoss"),o=A(t,"predictions","logLoss"),i=null;n!=null&&(i=A(n,"weights","logLoss")),xn(a.shape,o.shape,"Error in logLoss: ");let c=Se(1),l=Se(r),u=It(V(a,Xn(Y(o,l)))),d=V(fe(c,a),Xn(Y(fe(c,o),l))),p=fe(u,d);return _s(p,i,s)}var uL=W({logLoss_:cL});function lL(e,t,n,r=Sn.SUM_BY_NONZERO_WEIGHTS){let s=A(e,"labels","meanSquaredError"),a=A(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=A(n,"weights","meanSquaredError")),xn(s.shape,a.shape,"Error in meanSquaredError: ");let i=of(s,a);return _s(i,o,r)}var dL=W({meanSquaredError_:lL});function pL(e,t){let n=A(e,"labels","sigmoidCrossEntropyWithLogits"),r=A(t,"logits","sigmoidCrossEntropyWithLogits");xn(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");let s=je(r),a=V(r,n),o=Zl(gn(It(Lt(r))));return Y(fe(s,a),o)}function hL(e,t,n,r=0,s=Sn.SUM_BY_NONZERO_WEIGHTS){let a=A(e,"multiClassLabels","sigmoidCrossEntropy"),o=A(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=A(n,"weights","sigmoidCrossEntropy")),xn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){let l=Se(r),u=Se(1),d=Se(.5);a=Y(V(a,fe(u,l)),V(d,l))}let c=pL(a,o);return _s(c,i,s)}var fL=W({sigmoidCrossEntropy_:hL});function mL(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return ss((s,a,o)=>{let c=Uy(a,[n],!0),l=fe(ce(a,"float32"),c);o([s,l]);let u=It(V(l,s));return{value:ve(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,b=Zo(h.shape,[n]);return[V(U(h,b),fe(ce(m,"float32"),gn(g))),V(U(h,b),fe(gn(g),ce(m,"float32")))]}}})(e,t)}function gL(e,t,n,r=0,s=Sn.SUM_BY_NONZERO_WEIGHTS){let a=A(e,"onehotLabels","softmaxCrossEntropy"),o=A(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=A(n,"weights","softmaxCrossEntropy")),xn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){let l=Se(r),u=Se(1),d=Se(a.shape[1]);a=Y(V(a,fe(u,l)),ge(l,d))}let c=mL(a,o);return _s(c,i,s)}var bL=W({softmaxCrossEntropy_:gL});function yL(e,t,n,r){let s=A(e,"indices","sparseFillEmptyRows"),a=A(t,"values","sparseFillEmptyRows"),o=A(n,"denseShape","sparseFillEmptyRows"),i=A(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(s.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let c={indices:s,values:a,denseShape:o,defaultValue:i},l=z.runKernel(mh,c);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var vL=W({sparseFillEmptyRows_:yL});function xL(e,t,n){let r=A(e,"inputIndices","sparseReshape"),s=A(t,"inputShape","sparseReshape"),a=A(n,"newShape","sparseReshape");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${r.shape}`);if(s.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:r,inputShape:s,newShape:a},i=z.runKernel(gh,o);return{outputIndices:i[0],outputShape:i[1]}}var wL=W({sparseReshape_:xL});function kL(e,t,n){let r=A(e,"data","sparseSegmentMean"),s=A(t,"indices","sparseSegmentMean"),a=A(n,"segmentIds","sparseSegmentMean");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(bh,o)}var IL=W({sparseSegmentMean_:kL});function SL(e,t,n){let r=A(e,"data","sparseSegmentSum"),s=A(t,"indices","sparseSegmentSum"),a=A(n,"segmentIds","sparseSegmentSum");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(yh,o)}var CL=W({sparseSegmentSum_:SL});function TL(e,t,n,r,s,a,o,i){let c=A(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error(`Data must be a vector, saw: ${c.shape}`);let l=A(t,"dataSplits","stringNGrams");if(l.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:c,dataSplits:l},p=z.runKernel(xh,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var NL=W({stringNGrams_:TL});function _L(e,t,n=!0){let r=A(e,"input","stringSplit","string"),s=A(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(s.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);let a={skipEmpty:n},o={input:r,delimiter:s},i=z.runKernel(wh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var EL=W({stringSplit_:_L});function AL(e,t){let n=A(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return z.runKernel(kh,s,r)}var DL=W({stringToHashBucketFast_:AL}),FL={fft:sd,ifft:lu,rfft:ad,irfft:af},$L={hammingWindow:uM,hannWindow:rI,frame:sI,stft:hM},Qn={flipLeftRight:bM,grayscaleToRGB:vM,resizeNearestNeighbor:lI,resizeBilinear:uI,rotateWithOffset:wM,cropAndResize:mM,nonMaxSuppression:IM,nonMaxSuppressionAsync:DM,nonMaxSuppressionWithScore:$M,nonMaxSuppressionWithScoreAsync:PM,nonMaxSuppressionPadded:MM,nonMaxSuppressionPaddedAsync:BM,threshold:GM,transform:jM},pI={bandPart:KM,gramSchmidt:YM,qr:JM},RL={absoluteDifference:tL,computeWeightedLoss:_s,cosineDistance:rL,hingeLoss:aL,huberLoss:iL,logLoss:uL,meanSquaredError:dL,sigmoidCrossEntropy:fL,softmaxCrossEntropy:bL},od={sparseFillEmptyRows:vL,sparseReshape:wL,sparseSegmentMean:IL,sparseSegmentSum:CL},mf={stringNGrams:NL,stringSplit:EL,stringToHashBucketFast:DL},Es=class extends pk{minimize(e,t=!1,n){let{value:r,grads:s}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:s[o.name]}));this.applyGradients(a)}else this.applyGradients(s);return De(s),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Mk(e,t)}dispose(){this.iterations_!=null&&De(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Se(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(Es,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var gf=class extends Es{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:M(()=>Ue(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:M(()=>Ue(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;M(()=>{let l=Y(V(i,this.rho),V(ct(o),1-this.rho)),u=V(ge(cn(Y(c,this.epsilon)),cn(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ct(u),1-this.rho));i.assign(l),c.assign(d);let p=Y(V(u,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(De(this.accumulatedGrads.map(e=>e.variable)),De(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};gf.className="Adadelta";ca(gf);var bf=class extends Es{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n];if(this.accumulatedGrads[r]==null){let i=!1;this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:M(()=>In(s.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[r].variable;M(()=>{let i=Y(o,ct(a));o.assign(i);let c=Y(V(ge(a,cn(Y(i,z.backend.epsilon()))),-this.learningRate),s);s.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&De(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)}};bf.className="Adagrad";ca(bf);var yf=class extends Es{constructor(e,t,n,r=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],M(()=>{this.accBeta1=Se(t).variable(),this.accBeta2=Se(n).variable()}),r==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);M(()=>{let n=fe(1,this.accBeta1),r=fe(1,this.accBeta2);t.forEach((s,a)=>{let o=z.registeredVariables[s],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:M(()=>Ue(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:M(()=>Ue(o).variable(i))});let c=Array.isArray(e)?e[a].tensor:e[s];if(c==null)return;let l=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=Y(V(l,this.beta1),V(c,1-this.beta1)),p=Y(V(u,this.beta2),V(ct(c),1-this.beta2)),h=ge(d,n),f=ge(p,r);l.assign(d),u.assign(p);let m=Y(V(ge(h,Y(cn(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(V(this.accBeta1,this.beta1)),this.accBeta2.assign(V(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&De(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&De(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),M(()=>{this.accBeta1.assign(Ns(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ns(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};yf.className="Adam";ca(yf);var vf=class extends Es{constructor(e,t,n,r=null,s=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],M(()=>{this.iteration=Se(0).variable(),this.accBeta1=Se(t).variable()}),r==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);M(()=>{let n=fe(1,this.accBeta1),r=ge(-this.learningRate,Y(V(this.iteration,this.decay),1));t.forEach((s,a)=>{let o=z.registeredVariables[s],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:Ue(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:Ue(o).variable(i)});let c=Array.isArray(e)?e[a].tensor:e[s];if(c==null)return;let l=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=Y(V(l,this.beta1),V(c,1-this.beta1)),p=V(u,this.beta2),h=Lt(c),f=as(p,h);l.assign(d),u.assign(f);let m=Y(V(ge(r,n),ge(d,Y(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(Y(this.iteration,1)),this.accBeta1.assign(V(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&De(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&De(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)}};vf.className="Adamax";ca(vf);var id=class extends Es{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=Array.isArray(e)?e[r].tensor:e[n];if(s==null)return;let a=z.registeredVariables[n];M(()=>{let o=Y(V(this.c,s),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Jt(Se(-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)}};id.className="SGD";ca(id);var xf=class extends id{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Se(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n];if(this.accumulations[r]==null){let i=!1;this.accumulations[r]={originalName:`${n}/momentum`,variable:M(()=>Ue(s).variable(i))}}let a=this.accumulations[r].variable,o=Array.isArray(e)?e[r].tensor:e[n];o!=null&&M(()=>{let i,c=Y(V(this.m,a),o);this.useNesterov?i=Y(V(this.c,Y(o,V(c,this.m))),s):i=Y(V(this.c,c),s),a.assign(c),s.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&De(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)}};xf.className="Momentum";ca(xf);var wf=class extends Es{constructor(e,t=.9,n=0,r=null,s=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,r==null&&(this.epsilon=z.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:M(()=>Ue(s).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:M(()=>Ue(s).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:M(()=>Ue(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[r].variable,c=this.accumulatedMoments[r].variable;M(()=>{let l=Y(V(i,this.decay),V(ct(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[r].variable,d=Y(V(u,this.decay),V(o,1-this.decay)),p=ge(V(o,this.learningRate),cn(fe(l,Y(ct(d),this.epsilon)))),h=Y(V(c,this.momentum),p);i.assign(l),u.assign(d),c.assign(h);let f=fe(s,h);s.assign(f)}else{let u=Y(V(i,this.decay),V(ct(o),1-this.decay)),d=Y(V(c,this.momentum),ge(V(o,this.learningRate),cn(Y(u,this.epsilon))));i.assign(u),c.assign(d);let p=fe(s,d);s.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&De(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&De(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&De(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};wf.className="RMSProp";ca(wf);var ei=class{static sgd(e){return new id(e)}static momentum(e,t,n=!1){return new xf(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new wf(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new yf(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new gf(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new vf(e,t,n,r,s)}static adagrad(e,t=.1){return new bf(e,t)}},ti={sgd:ei.sgd,momentum:ei.momentum,adadelta:ei.adadelta,adagrad:ei.adagrad,rmsprop:ei.rmsprop,adamax:ei.adamax,adam:ei.adam},PL=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function hI(){return new Promise(e=>PL(()=>e()))}var _={};$e(_,{ERF_A1:()=>jL,ERF_A2:()=>qL,ERF_A3:()=>KL,ERF_A4:()=>XL,ERF_A5:()=>YL,ERF_P:()=>HL,PARALLELIZE_THRESHOLD:()=>iv,SELU_SCALE:()=>mI,SELU_SCALEALPHA:()=>fI,applyActivation:()=>hf,assertAndGetBroadcastShape:()=>gt,assertAxesAreInnerMostDims:()=>JP,assertParamsConsistent:()=>OL,assignToTypedArray:()=>nB,axesAreInnerMostDims:()=>Wy,calculateShapes:()=>ek,checkEinsumDimSizes:()=>cB,combineLocations:()=>Bk,complexWithEvenIndex:()=>QL,complexWithOddIndex:()=>eB,computeConv2DInfo:()=>ql,computeConv3DInfo:()=>vk,computeDefaultPad:()=>Ty,computeDilation2DInfo:()=>wR,computeOptimalWindowSize:()=>LL,computeOutAndReduceShapes:()=>zk,computeOutShape:()=>ML,computePool2DInfo:()=>yk,computePool3DInfo:()=>kR,convertConv2DDataFormat:()=>xk,decodeEinsumEquation:()=>oB,eitherStridesOrDilationsAreOne:()=>rs,expandShapeToKeepDim:()=>Zo,exponent:()=>sB,exponents:()=>rB,fromStringArrayToUint8:()=>bB,fromUint8ToStringArray:()=>gB,getAxesPermutation:()=>Wk,getBroadcastDims:()=>hP,getComplexWithIndex:()=>tB,getEinsumComputePath:()=>uB,getEinsumPermutation:()=>iB,getFusedBiasGradient:()=>pf,getFusedDyActivation:()=>df,getImageCenter:()=>BL,getInnerMostAxes:()=>QP,getPermuted:()=>WL,getReductionAxes:()=>Gt,getReshaped:()=>zL,getReshapedPermuted:()=>VL,getSliceBeginCoords:()=>UL,getSliceSize:()=>GL,getUndoAxesPermutation:()=>Vy,isIdentityPermutation:()=>lB,log:()=>UD,mergeRealAndImagArrays:()=>ZL,prepareAndValidate:()=>Q1,prepareSplitSize:()=>pB,segment_util:()=>yI,shouldFuse:()=>ff,slice_util:()=>kn,splitRealAndImagArrays:()=>JL,tupleValuesAreOne:()=>ua,upcastType:()=>wr,validateInput:()=>hy,validateUpdateShape:()=>py,warn:()=>es});function OL(e,t){let n=e[0].length;e.forEach((s,a)=>{$(s.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),$(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let r=e[0];e.forEach((s,a)=>{for(let o=0;o<n;o++)$(o===t||s[o]===r[o],()=>`Error in concat${n}D: Shape of tensors[${a}] (${s}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function ML(e,t){let n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var iv=30;function LL(e){return e<=iv?e:Bp(e,Math.floor(Math.sqrt(e)))}function BL(e,t,n){let r=n*(typeof e=="number"?e:e[0]),s=t*(typeof e=="number"?e:e[1]);return[r,s]}function zL(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);let a=t.length;for(let o=0;o<a;++o)s=s.concat([e[o+1]/t[o],t[o]]);s=s.concat(e.slice(a+1))}return s}function WL(e,t,n=!0){let r=[];if(n){r.push(t);for(let s=t+1;s<e;++s)s<=2*t?(r.push(s),r.push(s-(t+1))):r.push(s)}else{let s=[],a=[];for(let o=1;o<e;++o)o>=t*2+1||o%2==1?a.push(o):s.push(o);r.push(...s),r.push(0),r.push(...a)}return r}function VL(e,t,n,r=!0){let s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let a=1;a<e.length;++a)a<=t.length?r?s.push(t[a-1]*e[a]):s.push(e[a]/t[a-1]):s.push(e[a]);return s}function UL(e,t){let n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function GL(e,t,n){let r=e.slice(0,1);for(let s=0;s<n;++s)r.push(e[s+1]-t[s][0]-t[s][1]);return r}var fI=1.7580993408473768,mI=1.0507009873554805,HL=.3275911,jL=.254829592,qL=-.284496736,KL=1.421413741,XL=-1.453152027,YL=1.061405429;function ZL(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let n=new Float32Array(e.length*2);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function JL(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function QL(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let s=0;s<e.length;s+=4)n[Math.floor(s/4)]=e[s],r[Math.floor(s/4)]=e[s+1];return{real:n,imag:r}}function eB(e){let t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let s=2;s<e.length;s+=4)n[Math.floor(s/4)]=e[s],r[Math.floor(s/4)]=e[s+1];return{real:n,imag:r}}function tB(e,t){let n=e[t*2],r=e[t*2+1];return{real:n,imag:r}}function nB(e,t,n,r){e[r*2]=t,e[r*2+1]=n}function rB(e,t){let n=new Float32Array(e/2),r=new Float32Array(e/2);for(let s=0;s<Math.ceil(e/2);s++){let a=(t?2:-2)*Math.PI*(s/e);n[s]=Math.cos(a),r[s]=Math.sin(a)}return{real:n,imag:r}}function sB(e,t,n){let r=(n?2:-2)*Math.PI*(e/t),s=Math.cos(r),a=Math.sin(r);return{real:s,imag:a}}var cv="->",aB=/->/g,gI=",",bI="...";function oB(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(aB,"").length)/cv.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${cv}").`);let[r,s]=e.split(cv);$(r.indexOf(bI)===-1,()=>`The ellipsis notation ("${bI}") is not supported yet.`);let a=r.split(gI),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;p<s.length;++p){let h=s[p];if(!a.some(f=>f.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;p<r.length;++p){let h=r[p];i.indexOf(h)===-1&&h!==gI&&i.push(h)}let c=new Array(a.length);for(let p=0;p<o;++p){if(new Set(a[p].split("")).size!==a[p].length)throw new Error(`Found duplicate axes in input component ${a[p]}. Support for duplicate axes in input is not implemented yet.`);c[p]=[];for(let h=0;h<a[p].length;++h)c[p].push(i.indexOf(a[p][h]))}let l=i.length,u=s.length,d=[];for(let p=u;p<l;++p)d.push(p);return{allDims:i,summedDims:d,idDims:c}}function iB(e,t){let n=new Array(e);n.fill(-1);for(let s=0;s<t.length;++s)n[t[s]]=s;let r=[];for(let s=0;s<e;++s)n[s]===-1&&r.push(s);return n=n.filter(s=>s!==-1),{permutationIndices:n,expandDims:r}}function cB(e,t,n){let r=new Array(e);for(let s=0;s<n.length;++s){let a=n[s].shape;for(let o=0;o<t[s].length;++o)r[t[s][o]]===void 0?r[t[s][o]]=a[o]:$(r[t[s][o]]===a[o],()=>`Expected dimension ${r[t[s][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function uB(e,t){let n=e,r=[],s=0;e.length===0&&n.push(-1),s=e.length+1;for(let o=0;o<s;++o)r.push([]);let a=[];for(let o=0;o<n.length;++o){let i=n[o],c=dB(t,i);for(let l of c)a.indexOf(l)===-1&&(r[o].push(l),a.push(l))}return{path:n,steps:r}}function lB(e){return e.every((t,n)=>t===n)}function dB(e,t){let n=[];for(let r=0;r<e.length;++r)(e[r].length===0||e[r].indexOf(t)!==-1||t===-1)&&n.push(r);return n}function pB(e,t,n=0){let r=[];if(typeof t=="number")$(e.shape[n]%t==0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{let s=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);$(s<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,c)=>c>0?i+c:i);t[a]=e.shape[n]-o}$(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}var yI={};$e(yI,{collectGatherOpShapeInfo:()=>mB,computeOutShape:()=>fB,segOpComputeOptimalWindowSize:()=>hB});function hB(e,t){let n=!1,r;for(e<=iv?(r=e,n=!0):r=Bp(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=Bp(e,r+1);return r}function fB(e,t,n){let r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function mB(e,t,n,r){let s=t.shape.length,a=e.shape.length;if(r!==0&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) (
|
|
${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let o=e.shape[n],i=[],c=1,l=1,u=1;for(let d=0;d<r;++d)i.push(e.shape[d]),c*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<s;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),u*=e.shape[d];return{batchSize:c,sliceSize:u,outerSize:l,dimSize:o,outputShape:i}}function gB(e){try{return e.map(t=>Eh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function bB(e){return e.map(t=>Ll(t))}var is={};$e(is,{nonMaxSuppressionV3Impl:()=>aI,nonMaxSuppressionV4Impl:()=>oI,nonMaxSuppressionV5Impl:()=>iI,whereImpl:()=>Xk});var vI={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,du(ce(n,"float32"),-1))}}},yB={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ct(ce(n,"float32")),s=cn(fe(Se(1),r));return It(ge(e,s))}}}},vB={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=cn(fe(ct(ce(n,"float32")),1));return ge(e,r)}}}},xB={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=e,c=Gt(n.shape,s);return c.length>0&&(i=ve(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Gt(r.shape,s);return c.length>0&&(i=ve(i,c)),U(i,r.shape)}}}},wB={kernelName:Ba,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},kB={kernelName:za,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ue(n)}}},IB={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ue(n)}}},SB={kernelName:Qi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,cn(fe(Se(1),ct(ce(n,"float32")))))}}},CB={kernelName:ec,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=cn(Y(Se(1),ct(ce(n,"float32"))));return ge(e,r)}}}},TB={kernelName:rc,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=Y(ct(n),ct(r)),c=V(e,ge(r,i)),l=Gt(n.shape,s);return l.length>0&&(c=ve(c,l)),U(c,n.shape)},b:()=>{let i=Y(ct(n),ct(r)),c=It(V(e,ge(n,i))),l=Gt(r.shape,s);return l.length>0&&(c=ve(c,l)),U(c,r.shape)}}}},NB={kernelName:tc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(ct(ce(n,"float32")),1))}}},_B={kernelName:nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,fe(Se(1),ct(ce(n,"float32"))))}}};function EB(e,t,n,r,s,a){let o=A(e,"dy","avgPool3dGrad"),i=A(t,"input","avgPool3dGrad"),c=o,l=i,u=!1;i.rank===4&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),$(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),$(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),a!=null&&$(Xt(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:l},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=z.runKernel(Vp,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var AB=W({avgPool3dGrad_:EB}),DB={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>AB(e,r,s,a,o,i)}}};function FB(e,t,n,r,s){let a=A(e,"dy","avgPoolGrad"),o=A(t,"input","avgPoolGrad");$(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,c=a,l=!1;o.rank===3&&(l=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),$(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),$(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:c,input:i},d={filterSize:n,strides:r,pad:s},p=z.runKernel(Wp,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var $B=W({avgPoolGrad_:FB}),RB={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o}=n;return{x:()=>$B(e,r,s,a,o)}}},PB={kernelName:Va,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[r,s]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>Ae(e,s,!1,!0),b:()=>Ae(r,e,!0,!1)}:!a&&o?{a:()=>Ae(e,s,!1,!1),b:()=>Ae(e,r,!0,!1)}:a&&!o?{a:()=>Ae(s,e,!1,!0),b:()=>Ae(r,e,!1,!1)}:{a:()=>Ae(s,e,!0,!0),b:()=>Ae(e,r,!0,!0)}}},OB={kernelName:sc,gradFunc:(e,t,n)=>{let{blockShape:r,crops:s}=n;return{x:()=>ed(e,r,s)}}},MB={kernelName:b1,gradFunc:(e,t,n)=>{let r=n,s=r.inputShape,a=r.shape,o=Array.from(a);for(let c=s.length-1;c>=0;c--)if(s[c]===a[c])o[c]=1;else if(s[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);let i=[];for(let c=0;c<o.length;c++)o[c]>1&&i.push(c);return{x:()=>ve(e,i,!0)}}},LB={kernelName:Ua,gradFunc:e=>({x:()=>e.clone()})},BB={kernelName:Ga,gradFunc:e=>({x:()=>Ue(e)})},zB={kernelName:ea,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{clipValueMin:s,clipValueMax:a}=n;return{x:()=>mn(Ir(da(r,s),pa(r,a)),e,Ue(e))}}},WB={kernelName:kl,inputsToSave:["x"],gradFunc:vI.gradFunc},VB={kernelName:ac,saveAllInputs:!0,gradFunc:(e,t,n)=>{let r=t.map(c=>c.shape),{axis:s}=n,a=xr(s,t[0].shape)[0],o=r.map(c=>c[a]);return Ln(e,o,a).map(c=>()=>c)}},UB={kernelName:Ha,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,{dilations:a,strides:o,pad:i,dataFormat:c}=n;return $(ua(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>Dy(r.shape,e,s,o,i,c),filter:()=>av(r,e,s.shape,o,i,c)}}},GB={kernelName:ja,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:c}=n;return{dy:()=>Rt(e,s,a,o,i,1,c),filter:()=>av(e,r,s.shape,a,o,i,c)}}};function HB(e,t,n,r,s){let a=e;e.rank===4&&(a=U(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),$(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),$(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),$(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),$(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),$(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},c={strides:r,pad:s,filterShape:n};return z.runKernel(qp,i,c)}var jB=W({conv3DBackpropFilter_:HB}),qB={kernelName:Il,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:r,strides:s,pad:a}=n;$(ua(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);let[o,i]=t;return{x:()=>Ek(o.shape,e,i,s,a),filter:()=>jB(o,e,i.shape,s,a)}}},KB={kernelName:qa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(It(nf(ce(n,"float32"))),e)}}},XB={kernelName:Ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(rf(ce(n,"float32")),e)}}},YB={kernelName:Xa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{axis:s,exclusive:a,reverse:o}=n;return{x:()=>{let i=Wk([s],r.rank),c=Gh(e,s,a,!o);return i!=null&&(c=Re(c,i)),c}}}},ZB={kernelName:Ya,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:r,strides:s,pad:a,dimRoundingMode:o}=n,i=r==null?[1,1]:r;$(ua(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[c,l]=t;return $(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),$(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`),$(c.shape[3]===l.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),$(rs(s,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'.`),o!=null&&$(Xt(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>nI(c.shape,e,l,s,a,i,o),filter:()=>tI(c,e,l.shape,s,a,i,o)}}},JB={kernelName:Sl,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,a={x:r,filter:s,dy:e},o={x:r,filter:s,dy:e};return{x:()=>z.runKernel(Qp,a,n),filter:()=>z.runKernel(eh,o,n)}}},QB={kernelName:Ja,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,r={dy:e,y:n};return{x:()=>z.runKernel(nh,r)}}},ez={kernelName:cc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,r=V(gn(It(ct(n))),2/Math.sqrt(Math.PI));return{x:()=>V(e,r)}}},tz={kernelName:Qa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,n)}}},nz={kernelName:lc,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>U(e,n.shape)}}},rz={kernelName:dc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,gn(n))}}},sz={kernelName:eo,gradFunc:e=>({x:()=>Ue(e)})},az={kernelName:to,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=ge(e,ce(r,"float32")),c=Gt(n.shape,s);return c.length>0?U(ve(i,c),n.shape):i},b:()=>{let i=V(e,ce(n,"float32")),c=Gt(r.shape,s);c.length>0&&(i=U(ve(i,c),r.shape));let l=ct(r);return It(ge(i,ce(l,"float32")))}}}},oz={kernelName:no,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:r}=n,[s,a,o,i]=t,c=i==null?Se(1):i,l=Gt(a.shape,s.shape),u=[];if(a.rank===1){for(let x=0;x<s.shape.length-1;++x)u.push(s.shape[x]);u.push(1)}let d=fe(s,a),p=V(e,c),h=ef(Y(o,Se(r))),f=V(V(V(h,h),h),Se(-.5));return{x:()=>a.rank===1?U(V(V(e,On(U(h,[1,1,1,a.shape[0]]),u)),c),s.shape):U(V(V(e,h),c),s.shape),mean:()=>{let x=V(V(h,Se(-1)),p);return a.rank===1&&(x=ve(x,l)),U(x,a.shape)},variance:()=>{let x=V(V(f,d),p);return a.rank===1&&(x=ve(x,l)),U(x,a.shape)},scale:()=>{let x=V(d,h),k=V(e,x);return a.rank===1&&(k=ve(k,l)),U(k,a.shape)},offset:()=>{let x=e;return a.rank===1&&(x=ve(x,l)),U(x,a.shape)}}}},iz={kernelName:hc,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[r,s]=t,{axis:a}=n,o=xr(a,r.shape)[0];return{x:()=>{let c=r.shape,l=s.size,u=c.slice(0,o),d=u.length,p=c.slice(a,c.length).slice(1),h=p.length,f=xI(0,d),m=xI(d+1,d+1+h),g=wI([u,[l],p]),b=U(e,g),y=U(s,[l]),v=wI([[d],f,m]),x=Re(b,v),k=tv(x,y,r.shape[o]),C=Vy(v);return k=Re(k,C),k},indices:()=>s}}};function xI(e,t){let n=[];for(let r=e;r<t;++r)n.push(r);return n}function wI(e){let t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}var cz={kernelName:ro,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>Ue(n),b:()=>Ue(r)}}},uz={kernelName:so,gradFunc:e=>({x:()=>ce(e,"float32")})},lz={kernelName:gc,gradFunc:e=>({x:()=>Ue(e)})},dz={kernelName:bc,gradFunc:e=>({x:()=>Ue(e)})},pz={kernelName:yc,gradFunc:e=>({x:()=>Ue(e)})},hz={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{alpha:s}=n,a=Mn(r,0);return{x:()=>mn(a,e,V(e,s))}}},fz={kernelName:wc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(n,1))}}},mz={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ce(n,"float32"))}}},gz={kernelName:y1,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r]=t,{axis:s}=n;return{logits:()=>{let a=!0,o=gn(r);return fe(e,V(ve(e,s,a),o))}}}};function bz(e,t,n,r=5,s=1,a=1,o=.5){let i={x:e,y:t,dy:n},c={depthRadius:r,bias:s,alpha:a,beta:o};return z.runKernel(ih,i,c)}var yz=W({localResponseNormalizationBackprop_:bz}),vz={kernelName:_l,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{depthRadius:a,bias:o,alpha:i,beta:c}=n;return{x:()=>yz(r,s,e,a,o,i,c)}}};function kI(e,t,n,r){return t.rank<n.rank&&(t=U(t,Zo(t.shape,r))),e.rank<n.rank&&(e=U(e,Zo(e.shape,r))),{x:()=>V(e,ce(Kn(n,t),e.dtype))}}var II={kernelName:io,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let r=n,{reductionIndices:s}=r,a=t[0],o=t[1],i=xr(s,a.shape),c=kI(e,o,a,i);return{x:()=>c.x()}}},xz={kernelName:co,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>V(e,ce(da(n,r),"float32")),b:()=>V(e,ce(jh(n,r),"float32"))}}};function wz(e,t,n,r,s,a,o){let i=A(e,"dy","maxPool3dGrad"),c=A(t,"input","maxPool3dGrad"),l=A(n,"output","maxPool3dGrad"),u=i,d=c,p=l,h=!1;c.rank===4&&(h=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=U(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),p=U(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),$(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),$(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),$(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&$(Xt(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:r,strides:s,pad:a,dimRoundingMode:o},g=z.runKernel(uh,f,m);return h?U(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var kz=W({maxPool3dGrad_:wz}),Iz={kernelName:El,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=n;return{x:()=>kz(e,r,s,a,o,i,c)}}};function Sz(e,t,n,r,s,a,o){let i=A(e,"dy","maxPoolGrad"),c=A(t,"input","maxPoolGrad"),l=A(n,"output","maxPoolGrad");$(c.rank===i.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${i.rank})`),$(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),$(c.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${c.rank}.`),o!=null&&$(Xt(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:c,output:l},d={filterSize:r,strides:s,pad:a,dimRoundingMode:o};return z.runKernel(ch,u,d)}var Cz=W({maxPoolGrad_:Sz}),Tz={kernelName:uo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>Cz(e,r,s,a,o,i)}}},Nz={kernelName:lo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{axis:s}=n,a=xr(s,r.shape),i=zk(r.shape,a)[1],c=$t(i);return{x:()=>{let u=r.shape.slice();a.forEach(h=>{u[h]=1});let d=U(e,u);return ge(V(d,Yn(r.shape,"float32")),c)}}}},_z={kernelName:po,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let r=n,{axis:s}=r,[a,o]=t,i=xr(s,a.shape),c=kI(e,o,a,i);return{x:()=>c.x()}}},Ez={kernelName:ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>V(e,ce(pa(n,r),"float32")),b:()=>V(e,ce(Mn(n,r),"float32"))}}},Az={kernelName:fo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let r=t[0],{paddings:s}=n,a=s.map(o=>o[0]);return{x:()=>We(e,a,r.shape)}}},Dz={kernelName:Ic,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=Gt(n.shape,s);return i.length>0?U(ve(e,i),n.shape):e},b:()=>{let i=V(e,It(au(ge(n,r)))),c=Gt(r.shape,s);return c.length>0?U(ve(i,c),r.shape):i}}}},Fz={kernelName:mo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=V(e,ce(r,"float32")),c=Gt(n.shape,s);return c.length>0?U(ve(i,c),n.shape):i},b:()=>{let i=V(e,ce(n,"float32")),c=Gt(r.shape,s);return c.length>0?U(ve(i,c),r.shape):i}}}},$z={kernelName:Sc,gradFunc:e=>({x:()=>It(e)})},Rz={kernelName:go,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>St(n.shape,"float32")}}},Pz={kernelName:Ec,gradFunc:e=>({x:()=>Ue(e)})},Oz={kernelName:Ac,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:r}=n;return dt(e,r).map(a=>()=>a)}},SI={kernelName:bo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let r=t[0],{paddings:s}=n,a=s.map(o=>o[0]);return{x:()=>We(e,a,r.shape)}}},Mz={kernelName:yo,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,r,s]=t,a=n,o=r,i=gt(a.shape,o.shape);return{a:()=>{let u=ce(o,"float32"),d=V(e,V(u,Ns(a,fe(u,Se(1))))),p=Gt(a.shape,i);return p.length>0&&(d=ve(d,p)),U(d,a.shape)},b:()=>{let u=Mn(a,0),d=mn(u,Xn(a),Ue(a)),p=V(e,V(s,d)),h=Gt(o.shape,i);return h.length>0&&(p=ve(p,h)),U(p,o.shape)}}}},Lz={kernelName:vo,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,r]=t,s=Mn(n,0);return{x:()=>mn(s,e,V(e,r)),alpha:()=>{let a=mn(s,Ue(e),V(e,n)),o=Gt(r.shape,e.shape);return o.length>0&&(a=ve(a,o)),U(a,r.shape)}}}},Bz={kernelName:Za,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=ge(e,ce(r,"float32")),c=Gt(n.shape,s);return c.length>0?U(ve(i,c),n.shape):i},b:()=>{let i=V(e,ce(n,"float32")),c=Gt(r.shape,s);c.length>0&&(i=U(ve(i,c),r.shape));let l=ct(r);return It(ge(i,ce(l,"float32")))}}}},zz={kernelName:Fc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,It(ct(n)))}}},Wz={kernelName:ko,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,r=V(pa(n,6),du(n));return{x:()=>V(e,ce(r,"float32"))}}},Vz={kernelName:xo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,ce(du(n),"float32"))}}},Uz={kernelName:$c,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>U(e,n.shape)}}},Gz={kernelName:wo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[r]=t,s={dy:e,images:r};return{images:()=>z.runKernel(fh,s,n)}}},Hz={kernelName:Dl,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[r]=t,s={dy:e,images:r};return{images:()=>z.runKernel(hh,s,n)}}},jz={kernelName:Io,gradFunc:(e,t,n)=>{let{dims:r}=n,s=xr(r,e.shape);return{x:()=>Jn(e,s)}}},qz={kernelName:So,gradFunc:e=>({x:()=>Ue(e)})},Kz={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>It(ge(e,V(Ns(n,1.5),2)))}}},Xz={kernelName:Pc,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>ce(Ue(n),"float32"),t:()=>V(e,ce(n,e.dtype)),e:()=>V(e,ce(Jl(n),e.dtype))}}},Yz={kernelName:Oc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=Mn(n,Se(0)),s=Se(fI),a=Se(mI),o=V(e,a),i=V(V(e,s),gn(ce(n,"float32")));return mn(r,o,i)}}}},Zz={kernelName:No,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,V(n,fe(Se(1),n)))}}},Jz={kernelName:Bc,gradFunc:e=>({x:()=>Ue(e)})},Qz={kernelName:To,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(Xl(ce(n,"float32")),e)}}},e4={kernelName:Lc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(Uh(ce(n,"float32")),e)}}},t4={kernelName:Mc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{begin:s,size:a}=n,o=r.shape,[i,c]=dk(r,s,a),l=[];for(let u=0;u<e.rank;u++)l.push([i[u],o[u]-i[u]-c[u]]);return{x:()=>ur(e,l)}}},n4={kernelName:Ao,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r]=t,{dim:s}=n,a=!0,o=V(e,r);return{logits:()=>fe(o,V(ve(o,[s],a),r))}}},r4={kernelName:zc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,cr(n))}}},CI={kernelName:Wc,gradFunc:(e,t,n)=>{let{blockShape:r,paddings:s}=n;return{x:()=>Kl(e,r,s)}}},TI={kernelName:Vc,gradFunc:(e,t,n)=>{let{axis:r}=n;return{x:()=>Ze(e,r)}}},s4={kernelName:_o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,V(cn(ce(n,"float32")),2))}}},a4={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,V(ce(n,"float32"),2))}}},o4={kernelName:Do,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=Se(2);return{a:()=>V(e,V(s,fe(n,r))),b:()=>V(e,V(s,fe(r,n)))}}},i4={kernelName:na,gradFunc:e=>({x:()=>Ue(e)})},c4={kernelName:Fo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=e,c=Gt(n.shape,s);return c.length>0&&(i=ve(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Gt(r.shape,s);return c.length>0&&(i=ve(i,c)),U(It(i),r.shape)}}}},u4={kernelName:Eo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,s=r.shape.slice(),{axis:a}=n;xr(a,r.shape).forEach(l=>{s[l]=1});let i=U(e,s),c=V(i,Yn(r.shape,"float32"));return{x:()=>c}}},l4={kernelName:$o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ct(Xl(n)))}}},d4={kernelName:Ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(fe(Se(1),ct(n)),e)}}},p4={kernelName:ta,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{reps:s}=n;return{x:()=>{let o=Ue(r);if(r.rank===1)for(let i=0;i<s[0];++i)o=Y(o,We(e,[i*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(let i=0;i<s[0];++i)for(let c=0;c<s[1];++c)o=Y(o,We(e,[i*r.shape[0],c*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(let i=0;i<s[0];++i)for(let c=0;c<s[1];++c)for(let l=0;l<s[2];++l)o=Y(o,We(e,[i*r.shape[0],c*r.shape[1],l*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else if(r.rank===4)for(let i=0;i<s[0];++i)for(let c=0;c<s[1];++c)for(let l=0;l<s[2];++l)for(let u=0;u<s[3];++u)o=Y(o,We(e,[i*r.shape[0],c*r.shape[1],l*r.shape[2],u*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);return o}}}},h4={kernelName:Po,gradFunc:(e,t,n)=>{let r=n,{perm:s}=r,a=Vy(s);return{x:()=>Re(e,a)}}},f4={kernelName:jc,gradFunc:(e,t,n)=>{let r=n,{axis:s}=r;return{value:()=>Ot(e,s)}}},m4={kernelName:$l,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>g4(e,n)}}};function g4(e,t){let n=as(t,Ue(t)),r=Xo(e,n),s=da(t,Se(0,"int32")),a=r.rank-s.rank;for(let i=0;i<a;++i)s=bn(s,i+1);s=Ir(s,Yn(r.shape,"bool"));let o=Ue(r);return mn(s,r,o)}var b4={kernelName:qc,gradFunc:e=>({x:()=>Ue(e)})},y4=[vI,yB,vB,xB,wB,kB,IB,SB,CB,TB,NB,_B,DB,RB,PB,OB,MB,LB,BB,zB,WB,VB,GB,UB,qB,KB,XB,YB,ZB,JB,Bz,QB,ez,tz,nz,rz,az,sz,oz,iz,cz,uz,lz,dz,pz,hz,fz,mz,gz,vz,II,II,xz,Iz,Tz,Nz,_z,Ez,Az,Dz,Fz,$z,Rz,Pz,Oz,SI,SI,Mz,Lz,zz,Wz,Vz,Uz,Gz,Hz,jz,qz,Kz,Xz,Yz,Zz,Jz,Qz,e4,t4,n4,r4,CI,CI,TI,TI,s4,o4,a4,i4,c4,u4,l4,d4,p4,h4,f4,m4,b4];for(let e of y4)v1(e);Q().prototype.abs=function(){return this.throwIfDisposed(),Lt(this)};Q().prototype.acos=function(){return this.throwIfDisposed(),yy(this)};Q().prototype.acosh=function(){return this.throwIfDisposed(),vy(this)};Q().prototype.add=function(e){return this.throwIfDisposed(),Y(this,e)};Q().prototype.all=function(e,t){return this.throwIfDisposed(),Bh(this,e,t)};Q().prototype.any=function(e,t){return this.throwIfDisposed(),jl(this,e,t)};Q().prototype.argMax=function(e){return this.throwIfDisposed(),jo(this,e)};Q().prototype.argMin=function(e){return this.throwIfDisposed(),xy(this,e)};Q().prototype.asScalar=function(){return this.throwIfDisposed(),$(this.size===1,()=>"The array must have only 1 element."),U(this,[])};Q().prototype.asType=function(e){return this.throwIfDisposed(),ce(this,e)};Q().prototype.as1D=function(){return this.throwIfDisposed(),U(this,[this.size])};Q().prototype.as2D=function(e,t){return this.throwIfDisposed(),U(this,[e,t])};Q().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),U(this,[e,t,n])};Q().prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),U(this,[e,t,n,r])};Q().prototype.as5D=function(e,t,n,r,s){return this.throwIfDisposed(),U(this,[e,t,n,r,s])};Q().prototype.asin=function(){return this.throwIfDisposed(),wy(this)};Q().prototype.asinh=function(){return this.throwIfDisposed(),ky(this)};Q().prototype.atan=function(){return this.throwIfDisposed(),Iy(this)};Q().prototype.atan2=function(e){return this.throwIfDisposed(),Sy(this,e)};Q().prototype.atanh=function(){return this.throwIfDisposed(),Cy(this)};Q().prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),ir(this,e,t,n,r)};Q().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Kl(this,e,t)};Q().prototype.batchNorm=function(e,t,n,r,s){return this.throwIfDisposed(),Ts(this,e,t,n,r,s)};Q().prototype.broadcastTo=function(e){return this.throwIfDisposed(),ru(this,e)};Q().prototype.cast=function(e){return this.throwIfDisposed(),ce(this,e)};Q().prototype.ceil=function(){return this.throwIfDisposed(),Ay(this)};Q().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Qt(this,e,t)};Q().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ee&&(e=[e]),Ze([this,...e],t)};Q().prototype.conv1d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Wh(this,e,t,n,r,s,a)};Q().prototype.conv2dTranspose=function(e,t,n,r,s){return this.throwIfDisposed(),Vh(this,e,t,n,r,s)};Q().prototype.conv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Rt(this,e,t,n,r,s,a)};Q().prototype.cos=function(){return this.throwIfDisposed(),Xl(this)};Q().prototype.cosh=function(){return this.throwIfDisposed(),Uh(this)};Q().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Gh(this,e,t,n)};Q().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),$y(this,e,t)};Q().prototype.depthwiseConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),la(this,e,t,n,r,s,a)};Q().prototype.dilation2d=function(e,t,n,r,s){return this.throwIfDisposed(),Ry(this,e,t,n,r,s)};Q().prototype.divNoNan=function(e){return this.throwIfDisposed(),Py(this,e)};Q().prototype.div=function(e){return this.throwIfDisposed(),ge(this,e)};Q().prototype.dot=function(e){return this.throwIfDisposed(),Fk(this,e)};Q().prototype.elu=function(){return this.throwIfDisposed(),su(this)};Q().prototype.equal=function(e){return this.throwIfDisposed(),Kn(this,e)};Q().prototype.erf=function(){return this.throwIfDisposed(),Oy(this)};Q().prototype.exp=function(){return this.throwIfDisposed(),gn(this)};Q().prototype.expandDims=function(e){return this.throwIfDisposed(),bn(this,e)};Q().prototype.expm1=function(){return this.throwIfDisposed(),My(this)};Q().prototype.fft=function(){return this.throwIfDisposed(),sd(this)};Q().prototype.flatten=function(){return this.throwIfDisposed(),U(this,[this.size])};Q().prototype.floor=function(){return this.throwIfDisposed(),au(this)};Q().prototype.floorDiv=function(e){return this.throwIfDisposed(),Lh(this,e)};Q().prototype.gather=function(e,t){return this.throwIfDisposed(),Xo(this,e,t)};Q().prototype.greaterEqual=function(e){return this.throwIfDisposed(),da(this,e)};Q().prototype.greater=function(e){return this.throwIfDisposed(),Mn(this,e)};Q().prototype.ifft=function(){return this.throwIfDisposed(),lu(this)};Q().prototype.irfft=function(){return this.throwIfDisposed(),af(this)};Q().prototype.isFinite=function(){return this.throwIfDisposed(),Rk(this)};Q().prototype.isInf=function(){return this.throwIfDisposed(),Pk(this)};Q().prototype.isNaN=function(){return this.throwIfDisposed(),By(this)};Q().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Yl(this,e)};Q().prototype.lessEqual=function(e){return this.throwIfDisposed(),pa(this,e)};Q().prototype.less=function(e){return this.throwIfDisposed(),jh(this,e)};Q().prototype.localResponseNormalization=function(e,t,n,r){return this.throwIfDisposed(),zy(this,e,t,n,r)};Q().prototype.logSigmoid=function(){return this.throwIfDisposed(),Lk(this)};Q().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Kh(this,e)};Q().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Uy(this,e,t)};Q().prototype.log=function(){return this.throwIfDisposed(),Xn(this)};Q().prototype.log1p=function(){return this.throwIfDisposed(),Zl(this)};Q().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Ir(this,e)};Q().prototype.logicalNot=function(){return this.throwIfDisposed(),Jl(this)};Q().prototype.logicalOr=function(e){return this.throwIfDisposed(),Xh(this,e)};Q().prototype.logicalXor=function(e){return this.throwIfDisposed(),Vk(this,e)};Q().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Ae(this,e,t,n)};Q().prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),Pt(this,e,t,n,r)};Q().prototype.max=function(e,t){return this.throwIfDisposed(),kr(this,e,t)};Q().prototype.maximum=function(e){return this.throwIfDisposed(),as(this,e)};Q().prototype.mean=function(e,t){return this.throwIfDisposed(),Et(this,e,t)};Q().prototype.min=function(e,t){return this.throwIfDisposed(),Ql(this,e,t)};Q().prototype.minimum=function(e){return this.throwIfDisposed(),ou(this,e)};Q().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),Hy(this,e,t)};Q().prototype.mod=function(e){return this.throwIfDisposed(),jy(this,e)};Q().prototype.mul=function(e){return this.throwIfDisposed(),V(this,e)};Q().prototype.neg=function(){return this.throwIfDisposed(),It(this)};Q().prototype.norm=function(e,t,n){return this.throwIfDisposed(),lf(this,e,t,n)};Q().prototype.notEqual=function(e){return this.throwIfDisposed(),Jo(this,e)};Q().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),eu(this,e,t,n)};Q().prototype.onesLike=function(){return this.throwIfDisposed(),Zn(this)};Q().prototype.pad=function(e,t){return this.throwIfDisposed(),ur(this,e,t)};Q().prototype.pool=function(e,t,n,r,s){return this.throwIfDisposed(),Hk(this,e,t,n,r,s)};Q().prototype.pow=function(e){return this.throwIfDisposed(),Ns(this,e)};Q().prototype.prelu=function(e){return this.throwIfDisposed(),td(this,e)};Q().prototype.prod=function(e,t){return this.throwIfDisposed(),Zh(this,e,t)};Q().prototype.reciprocal=function(){return this.throwIfDisposed(),Xy(this)};Q().prototype.relu=function(){return this.throwIfDisposed(),je(this)};Q().prototype.relu6=function(){return this.throwIfDisposed(),Jh(this)};Q().prototype.reshapeAs=function(e){return this.throwIfDisposed(),U(this,e.shape)};Q().prototype.reshape=function(e){return this.throwIfDisposed(),U(this,e)};Q().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),uI(this,e,t,n)};Q().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),lI(this,e,t,n)};Q().prototype.reverse=function(e){return this.throwIfDisposed(),Jn(this,e)};Q().prototype.rfft=function(){return this.throwIfDisposed(),ad(this)};Q().prototype.round=function(){return this.throwIfDisposed(),Qh(this)};Q().prototype.rsqrt=function(){return this.throwIfDisposed(),ef(this)};Q().prototype.selu=function(){return this.throwIfDisposed(),tf(this)};Q().prototype.separableConv2d=function(e,t,n,r,s,a){return this.throwIfDisposed(),Qo(this,e,t,n,r,s,a)};Q().prototype.sigmoid=function(){return this.throwIfDisposed(),cr(this)};Q().prototype.sign=function(){return this.throwIfDisposed(),Yy(this)};Q().prototype.sin=function(){return this.throwIfDisposed(),nf(this)};Q().prototype.sinh=function(){return this.throwIfDisposed(),rf(this)};Q().prototype.slice=function(e,t){return this.throwIfDisposed(),We(this,e,t)};Q().prototype.softmax=function(e){return this.throwIfDisposed(),Pr(this,e)};Q().prototype.softplus=function(){return this.throwIfDisposed(),Yo(this)};Q().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),ed(this,e,t)};Q().prototype.split=function(e,t){return this.throwIfDisposed(),Ln(this,e,t)};Q().prototype.sqrt=function(){return this.throwIfDisposed(),cn(this)};Q().prototype.square=function(){return this.throwIfDisposed(),ct(this)};Q().prototype.squaredDifference=function(e){return this.throwIfDisposed(),of(this,e)};Q().prototype.squeeze=function(e){return this.throwIfDisposed(),os(this,e)};Q().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Ee?[this,e]:[this,...e];return Ot(n,t)};Q().prototype.step=function(e){return this.throwIfDisposed(),du(this,e)};Q().prototype.stridedSlice=function(e,t,n,r,s,a,o,i){return this.throwIfDisposed(),Jy(this,e,t,n,r,s,a,o,i)};Q().prototype.sub=function(e){return this.throwIfDisposed(),fe(this,e)};Q().prototype.sum=function(e,t){return this.throwIfDisposed(),ve(this,e,t)};Q().prototype.tan=function(){return this.throwIfDisposed(),Qy(this)};Q().prototype.tanh=function(){return this.throwIfDisposed(),Ko(this)};Q().prototype.tile=function(e){return this.throwIfDisposed(),On(this,e)};Q().prototype.toBool=function(){return this.throwIfDisposed(),ce(this,"bool")};Q().prototype.toFloat=function(){return this.throwIfDisposed(),ce(this,"float32")};Q().prototype.toInt=function(){return this.throwIfDisposed(),ce(this,"int32")};Q().prototype.topk=function(e,t){return this.throwIfDisposed(),ev(this,e,t)};Q().prototype.transpose=function(e){return this.throwIfDisposed(),Re(this,e)};Q().prototype.unique=function(e){return this.throwIfDisposed(),uf(this,e)};Q().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),tv(this,e,t)};Q().prototype.unstack=function(e){return this.throwIfDisposed(),dt(this,e)};Q().prototype.where=function(e,t){return this.throwIfDisposed(),mn(e,this,t)};Q().prototype.zerosLike=function(){return this.throwIfDisposed(),Ue(this)};var NI={};$e(NI,{maxNorm:()=>k4,minMaxNorm:()=>C4,nonNeg:()=>S4,unitNorm:()=>I4});var uv;function Ht(){return uv==null&&(uv=gk().epsilon()),uv}function Lr(){return"channelsLast"}var As=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,As.prototype)}},Br=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Br.prototype)}},H=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,H.prototype)}},Fe=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Fe.prototype)}},_I=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,_I.prototype)}};function ni(e,t){if(Array.isArray(e)){let n=[];for(let r=0;r<t;r++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function cs(e,t){if(!e)throw new _I(t)}function EI(e,t){let n=0;for(let r of e)r===t&&n++;return n}function Bn(e){return e.length===1?e[0]:e}function bt(e){return Array.isArray(e)?e:[e]}function Ds(e){let n=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return n[0]!=="_"?n:"private"+n}function ri(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var Sr={};function lv(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function dv(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>dv(t));else{let t=Object.keys(e);for(let n of t){let r=e[n];r!=null&&typeof r=="object"&&(!Array.isArray(r)&&r.type==="ndarray"&&typeof r.value=="number"?e[n]=r.value:dv(r))}}}function cd(e,t={},n={},r="object",s=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Sr)o=Sr[a];else if(o=t[a],o==null)throw new H(`Unknown ${r}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new H(`${r}: Improper config format: ${JSON.stringify(a)}.
|
|
'className' and 'config' must set.`);let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in Sr?[i,c]=Sr.className:o in t&&([i,c]=t[o]),i==null)throw new H(`Unknown ${r}: ${o}. This may be due to one of the following reasons:
|
|
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){let l={};for(let h of Object.keys(Sr))l[h]=Sr[h];for(let h of Object.keys(n))l[h]=n[h];let u=a.config;u.customObjects=l;let d=Object.assign({},Sr);for(let h of Object.keys(n))Sr[h]=n[h];dv(a.config);let p=c(i,a.config,n,s);return Sr=Object.assign({},d),p}else{let l=Object.assign({},Sr);for(let d of Object.keys(n))Sr[d]=n[d];let u=new i(a.config);return Sr=Object.assign({},l),u}}}function v4(e,t){return e<t?-1:e>t?1:0}function kf(e,t){return-1*v4(e,t)}function fa(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function x4(e){if(e==null)throw new H(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function si(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new H(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function pv(e,t,n=0,r=1/0){return cs(n>=0),cs(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function en(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>en(n,`element ${r+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${AI(e)}.`)}function AI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>AI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function w4(e,t,n){let r=n!=null?n():w.now(),s;return(...o)=>{let i=n!=null?n():w.now();return i-r<t||(r=i,s=e(...o)),s}}function DI(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function hv(e,t){return M(()=>cn(ve(V(e,e),t,!0)))}var ud=class extends ie.Serializable{getConfig(){return{}}},fv=class extends ud{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 M(()=>{let t=hv(e,this.axis),n=Qt(t,0,this.maxValue);return V(e,ge(n,Y(Ht(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};fv.className="MaxNorm";ie.registerClass(fv);var mv=class extends ud{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>ge(e,Y(Ht(),hv(e,this.axis))))}getConfig(){return{axis:this.axis}}};mv.className="UnitNorm";ie.registerClass(mv);var gv=class extends ud{apply(e){return je(e)}};gv.className="NonNeg";ie.registerClass(gv);var bv=class extends ud{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 M(()=>{let t=hv(e,this.axis),n=Y(V(this.rate,Qt(t,this.minValue,this.maxValue)),V(1-this.rate,t));return V(e,ge(n,Y(Ht(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};bv.className="MinMaxNorm";ie.registerClass(bv);var FI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function jt(e){return lv(e)}function $I(e,t={}){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"constraint")}function qt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in FI?FI[e]:e,config:{}};return $I(n)}else return e instanceof ud?e:$I(e)}function k4(e){return new fv(e)}function I4(e){return new mv(e)}function S4(){return new gv}function C4(e){return new bv(e)}var RI={};$e(RI,{constant:()=>K4,glorotNormal:()=>tW,glorotUniform:()=>eW,heNormal:()=>nW,heUniform:()=>rW,identity:()=>J4,leCunNormal:()=>sW,leCunUniform:()=>aW,ones:()=>q4,orthogonal:()=>oW,randomNormal:()=>Y4,randomUniform:()=>X4,truncatedNormal:()=>Z4,varianceScaling:()=>Q4,zeros:()=>j4});var T4=["channelsFirst","channelsLast"],N4=["nearest","bilinear"],_4=["valid","same","causal"],E4=["max","avg"],A4=["sum","mul","concat","ave"],hu=new Map;function Mt(e){si(T4,"DataFormat",e)}function D4(e){si(N4,"InterpolationFormat",e)}function lr(e){si(_4,"PaddingMode",e)}function PI(e){si(E4,"PoolMode",e)}var ld=[],OI="/";function ai(e,t){ld.push(e);try{let n=t();return ld.pop(),n}catch(n){throw ld.pop(),n}}function F4(){return ld.length===0?"":ld.join(OI)+OI}function MI(e){if(!BI(e))throw new Error("Not a valid tensor name: '"+e+"'");return F4()+e}function LI(e){if(!BI(e))throw new Error("Not a valid tensor name: '"+e+"'");hu.has(e)||hu.set(e,0);let t=hu.get(e);if(hu.set(e,hu.get(e)+1),t>0){let n=`${e}_${t}`;return hu.set(n,1),n}else return e}var $4=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function BI(e){return!!e.match($4)}function R4(e){return e===parseInt(e.toString(),10)}function ma(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let r=1;for(let s=t;s<n;++s)r*=e[s];return r}function fu(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r<t&&(t=r)}return t}function ga(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r>t&&(t=r)}return t}function zr(e,t){if(t<e)throw new H(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let r=e;r<t;++r)n.push(r);return n}function If(e,t){return ce(e,t)}function dd(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),U(e,n)}function P4(e,t){return M(()=>{if(e.shape.length!==2)throw new H(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=dd(e,1);return xv(n,[1,t,1])})}function O4(e){let t=[ma(e.shape)];return U(e,t)}function M4(e){if(e.rank<=1)throw new H(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],ma(e.shape,1)];return U(e,t)}function oi(e,t,n){return M(()=>{switch(e.rank){case 1:return sf(e,t,n);case 2:return Zy(e,[t,0],[n,e.shape[1]]);case 3:return uu(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return rd(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 H(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function yv(e,t,n){return M(()=>{switch(e.rank){case 1:return sf(e,t,n);case 2:return Zy(e,[0,t],[e.shape[0],n]);case 3:return uu(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return rd(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Sf(e,t,n,r){return M(()=>{switch(e.rank){case 1:return sf(e,t,n);case 2:switch(r){case 1:return oi(e,t,n);case 2:return yv(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return oi(e,t,n);case 2:return uu(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return yv(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return oi(e,t,n);case 2:return rd(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return rd(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return yv(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${r}`)}default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function vv(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Ze(e,t)}function zI(e,t){switch(e.rank){case 1:return Ck([e,t]);case 2:return Tk([e,t],0);case 3:return Nk([e,t],0);case 4:return _k([e,t],0);default:throw new H(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function xv(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new H(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return On(e,t)}function Cf(e,t=0,n=1,r,s){return jk(e,t,n,r,s)}function us(e,t,n,r){if(e.rank<2||t.rank<2)throw new Fe(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let s=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(s!==a)throw new Fe(`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 s=!1,a=!1;return ha.matMul({a:e,b:t,transposeA:s,transposeB:a,bias:r?wv(e.rank,r,Lr()):null,activation:n})}else{let s=e.shape.slice(),a=s.pop();e=U(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),c=o.pop(),l=[...o,i],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=U(Re(t,u),[c,-1]);let d=[...s,...l],p=!1,h=!1;return U(ha.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:r?wv(e.rank,r,Lr()):null,activation:n}),d)}}function WI(e,t,n){return M(()=>(Array.isArray(t)?t=Ge(t,"int32"):t=ce(t,"int32"),Xo(e,t,n)))}function pd(e){return V(e,e)}function wv(e,t,n){let r=t.shape;if(t.rank!==1&&t.rank!==e)throw new H(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return r.length===1?U(t,[1,r[0],1,1,1]):U(t,[1,r[3],r[0],r[1],r[2]]);if(n==="channelsLast")return r.length===1?U(t,[1,1,1,1,r[0]]):U(t,[1].concat(r))}else if(e===4){if(n==="channelsFirst")return r.length===1?U(t,[1,r[0],1,1]):U(t,[1,r[2],r[0],r[1]]);if(n==="channelsLast")return r.length===1?U(t,[1,1,1,r[0]]):U(t,[1].concat(r))}else if(e===3){if(n==="channelsFirst")return r.length===1?U(t,[1,r[0],1]):U(t,[1,r[1],r[0]]);if(n==="channelsLast")return r.length===1?U(t,[1,1,r[0]]):U(t,[1].concat(r))}else if(e<3)return t;throw new H(`Unsupported input rank by biasAdd: ${t.rank}`)}function Wr(e,t,n){return M(()=>(n==null&&(n=Lr()),Mt(n),Y(e,wv(e.rank,t,n))))}function L4(e,t=1){if(t!==1)throw new Fe(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return su(e)}function B4(e){return M(()=>ge(e,Y(Lt(e),1)))}function VI(e,t,n,r){return M(()=>Qk(e,t,n,r))}function z4(e){return M(()=>{let t=Y(.5,V(.2,e));return Qt(t,0,1)})}function hd(e,t,n=!1){return n?e():t()}var W4=["fanIn","fanOut","fanAvg"],V4=["normal","uniform","truncatedNormal"];function U4(e){si(W4,"FanMode",e)}function G4(e){si(V4,"Distribution",e)}var Cr=class extends ie.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},kv=class extends Cr{apply(e,t){return St(e,t)}};kv.className="Zeros";ie.registerClass(kv);var Tf=class extends Cr{apply(e,t){return Yn(e,t)}};Tf.className="Ones";ie.registerClass(Tf);var Iv=class extends Cr{constructor(e){super();if(typeof e!="object")throw new H(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new H(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return M(()=>V(Se(this.value),Yn(e,t)))}getConfig(){return{value:this.value}}};Iv.className="Constant";ie.registerClass(Iv);var Sv=class extends Cr{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 iu(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Sv.className="RandomUniform";ie.registerClass(Sv);var Cv=class extends Cr{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 Fe(`randomNormal does not support dType ${t}.`);return Cf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Cv.className="RandomNormal";ie.registerClass(Cv);var Tv=class extends Cr{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 Fe(`truncatedNormal does not support dType ${t}.`);return cf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Tv.className="TruncatedNormal";ie.registerClass(Tv);var Nv=class extends Cr{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return M(()=>{if(e.length!==2||e[0]!==e[1])throw new H("Identity matrix initializer can only be used for 2D square matrices.");return V(this.gain,Ly(e[0]))})}getConfig(){return{gain:this.gain}}};Nv.className="Identity";ie.registerClass(Nv);function H4(e,t="channelsLast"){let n,r;if(Mt(t),e.length===2)n=e[0],r=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let s=ma(e,2);n=e[1]*s,r=e[0]*s}else if(t==="channelsLast"){let s=ma(e,0,e.length-2);n=e[e.length-2]*s,r=e[e.length-1]*s}}else{let s=ma(e);n=Math.sqrt(s),r=Math.sqrt(s)}return[n,r]}var zn=class extends Cr{constructor(e){super();if(e.scale<0)throw new H(`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,U4(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,G4(this.distribution),this.seed=e.seed}apply(e,t){let n=H4(e),r=n[0],s=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,r):this.mode==="fanOut"?a/=Math.max(1,s):a/=Math.max(1,(r+s)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Fe(`${this.getClassName()} does not support dType ${t}.`);return cf(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return iu(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};zn.className="VarianceScaling";ie.registerClass(zn);var Nf=class extends zn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zn.className}};Nf.className="GlorotUniform";ie.registerClass(Nf);var _f=class extends zn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zn.className}};_f.className="GlorotNormal";ie.registerClass(_f);var Ef=class extends zn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zn.className}};Ef.className="HeNormal";ie.registerClass(Ef);var Af=class extends zn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zn.className}};Af.className="HeUniform";ie.registerClass(Af);var Df=class extends zn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zn.className}};Df.className="LeCunNormal";ie.registerClass(Df);var Ff=class extends zn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zn.className}};Ff.className="LeCunNormal";ie.registerClass(Ff);var _v=class extends Cr{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 Fe("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return M(()=>{if(e.length<2)throw new Fe("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let n=e[0]>e[1]?[e[1],e[0]]:e,r=Cf(n,0,1,"float32"),s=pI.gramSchmidt(r);return e[0]>e[1]&&(s=Re(s)),V(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};_v.className="Orthogonal";ie.registerClass(_v);var UI={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 GI(e,t={}){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"initializer")}function At(e){return lv(e)}function Ct(e){if(typeof e=="string"){let t=e in UI?UI[e]:e;if(t==="GlorotNormal")return new _f;if(t==="GlorotUniform")return new Nf;if(t==="HeNormal")return new Ef;if(t==="HeUniform")return new Af;if(t==="LeCunNormal")return new Df;if(t==="LeCunUniform")return new Ff;{let n={};return n.className=t,n.config={},GI(n)}}else return e instanceof Cr?e:GI(e)}function j4(){return new kv}function q4(){return new Tf}function K4(e){return new Iv(e)}function X4(e){return new Sv(e)}function Y4(e){return new Cv(e)}function Z4(e){return new Tv(e)}function J4(e){return new Nv(e)}function Q4(e){return new zn(e)}function eW(e){return new Nf(e)}function tW(e){return new _f(e)}function nW(e){return new Ef(e)}function rW(e){return new Af(e)}function sW(e){return new Df(e)}function aW(e){return new Ff(e)}function oW(e){return new _v(e)}var HI={};$e(HI,{Layer:()=>qe,RNN:()=>ps,RNNCell:()=>kd,activation:()=>VV,add:()=>ZV,alphaDropout:()=>RU,average:()=>JV,averagePooling1d:()=>jx,averagePooling2d:()=>qx,averagePooling3d:()=>Kx,avgPool1d:()=>iU,avgPool2d:()=>uU,avgPool3d:()=>dU,avgPooling1d:()=>cU,avgPooling2d:()=>lU,avgPooling3d:()=>pU,batchNormalization:()=>sU,bidirectional:()=>TU,concatenate:()=>QV,conv1d:()=>$V,conv2d:()=>RV,conv2dTranspose:()=>PV,conv3d:()=>OV,conv3dTranspose:()=>MV,convLstm2d:()=>kU,convLstm2dCell:()=>IU,cropping2D:()=>BV,dense:()=>UV,depthwiseConv2d:()=>WV,dot:()=>rU,dropout:()=>GV,elu:()=>NV,embedding:()=>YV,flatten:()=>jV,gaussianDropout:()=>$U,gaussianNoise:()=>FU,globalAveragePooling1d:()=>hU,globalAveragePooling2d:()=>fU,globalMaxPool1d:()=>_U,globalMaxPool2d:()=>EU,globalMaxPooling1d:()=>eC,globalMaxPooling2d:()=>tC,gru:()=>gU,gruCell:()=>bU,input:()=>SS,inputLayer:()=>TV,layerNormalization:()=>aU,leakyReLU:()=>EV,lstm:()=>yU,lstmCell:()=>vU,masking:()=>PU,maxPool1d:()=>AU,maxPool2d:()=>DU,maxPooling1d:()=>nC,maxPooling2d:()=>rC,maxPooling3d:()=>mU,maximum:()=>eU,minimum:()=>tU,multiply:()=>nU,permute:()=>XV,prelu:()=>AV,reLU:()=>_V,repeatVector:()=>qV,reshape:()=>KV,rnn:()=>SU,separableConv2d:()=>LV,simpleRNN:()=>xU,simpleRNNCell:()=>wU,softmax:()=>DV,spatialDropout1d:()=>HV,stackedRNNCells:()=>CU,thresholdedReLU:()=>FV,timeDistributed:()=>NU,upSampling2d:()=>zV,zeroPadding2d:()=>oU});var iW=0;function jI(){return iW++}var $f={};function Rf(e=""){return e in $f||($f[e]=0),$f[e]+=1,e+$f[e].toString()}function Ev(e){return Array.isArray(e)&&Array.isArray(e[0])}function Pf(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Oe(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new H(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function at(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new H(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Of(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((r,s)=>r*s);return t}var qI="Variable",KI=class{constructor(e,t="float32",n=qI,r=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=jI(),n=n==null?qI:n,this.originalName=MI(n),this.name=LI(this.originalName),this.trainable_=r,this.constraint=s,this.val=Kk(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),cW(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 cW(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Av(e){return e.map(t=>t.read())}function Dv(e){e.forEach(t=>{t[0].write(t[1])})}var Bt=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||{}}},Vr=class{constructor(e,t,n,r,s,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=s,this.outputTensorIndex=o,this.id=jI(),a!=null&&(this.originalName=MI(a),this.name=LI(this.originalName)),this.rank=t.length}},uW=0,Mf=class{constructor(e,t){this.callArgs=t,this.id=uW++,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}}},lW=0,qe=class extends ie.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=lW++,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=Ds(n)+"_"+Rf(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let s=null;e.batchSize!=null&&(s=e.batchSize),n=[s].concat(e.inputShape)}this.batchInputShape=n;let r=e.dtype;r==null&&(r=e.inputDType),r==null&&(r="float32"),this.dtype=r}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Br(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new H(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Bn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Bn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new As(`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 As(`Layer ${this.name} is not connected, no input to return.`);return Bn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new As(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new As(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Bn(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=bt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=bt(this.inputSpec);if(e.length!==t.length)throw new H(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let r=e[n],s=t[n];if(s==null)continue;let a=r.rank;if(s.ndim!=null&&a!==s.ndim)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(s.maxNDim!=null&&a>s.maxNDim)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(s.minNDim!=null&&a<s.minNDim)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(s.dtype!=null&&r.dtype!==s.dtype)throw new H(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${r.dtype}.`);if(s.axes){let o=r.shape;for(let i in s.axes){let c=Number(i),l=s.axes[i],u=c>=0?o[c]:o[o.length+c];if(l!=null&&[l,null].indexOf(u)===-1)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected axis ${c} of input shape to have value ${l} but got shape ${o}.`)}}if(s.shape!=null)for(let o=0;o<s.shape.length;++o){let i=s.shape[o],c=r.shape[o];if(i!=null&&c!=null&&i!==c)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${r.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let n=bt(e),r=!0;for(let a of n)if(!(a instanceof Vr)){r=!1;break}let s=!0;for(let a of n)if(a instanceof Vr){s=!1;break}if(r===s)throw new H("Arguments to apply() must be all SymbolicTensors or all Tensors");return ai(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of bt(e))a.push(o.shape);this.build(Bn(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let a=this.call(e,t),o=bt(a),i=[];for(let c of o)n.indexOf(c)!==-1&&(c=c.clone()),i.push(c);if(a=Bn(i),this.activityRegularizer!=null)throw new Fe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=dW(e),o=this.computeOutputShape(a),i,c=pW(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((l,u)=>new Vr(c,l,this,bt(e),t,this.name,u)):i=new Vr(c,o,this,bt(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Fe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,r)=>{n!=null&&e[r]!=null&&e[r]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new As(`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 As(`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 Br(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Of(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Av(e?this.trainableWeights:this.weights)}setWeights(e){M(()=>{let t=this.weights;if(t.length!==e.length)throw new H(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],r=Av(t);for(let s=0;s<r.length;++s){let a=r[s],o=t[s],i=e[s];if(!w.arraysEqual(a.shape,i.shape))throw new H(`Layer weight shape ${a.shape} not compatible with provided weight shape ${i.shape}`);n.push([o,i])}Dv(n)})}addWeight(e,t,n,r,s,a,o,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new H(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(r=i!=null?i():Ct("zeros"));let c=r.apply(t,n),l=new KI(c,n,e,a,o);return c.dispose(),s!=null&&this.addLoss(()=>s.apply(l.read())),a==null&&(a=!0),a?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=bt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,r,s,a,o=null){let i=bt(e);t=bt(t),n=bt(n),r=bt(r),s=Pf(s),a=Pf(a);let c=[],l=[],u=[];for(let d of i)c.push(d.sourceLayer),l.push(d.nodeIndex),u.push(d.tensorIndex);new Mf({outboundLayer:this,inboundLayers:c,nodeIndices:l,tensorIndices:u,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:s,outputShapes:a},o);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}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 dW(e){e=bt(e);let t=[];for(let n of e)t.push(n.shape);return Bn(t)}function pW(e){return"float32"}function XI(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let r=t.inboundNodes[n];if(r.inboundLayers.length===0)return r.inputTensors;{let s=[];for(let a=0;a<r.inboundLayers.length;a++){let o=r.inputTensors[a],i=r.inboundLayers[a],c=r.nodeIndices[a],l=XI(o,i,c);for(let u of l)s.indexOf(u)===-1&&s.push(u)}return s}}}var mu=class extends qe{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Rf("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 H("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 H("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new H("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let r=new Vr(this.dtype,this.batchInputShape,this,[],{},this.name);r.nodeIndex=0,r.tensorIndex=0,new Mf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[r],outputTensors:[r],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new H(`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}}};mu.className="InputLayer";ie.registerClass(mu);function YI(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 H("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 mu({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}async function ba(e){if(e==null)return;let t=[],n=[],r=[];for(let s in e){let a=e[s];if(typeof a!="number"){let o=a;t.push(o.data()),n.push(s),r.push(o)}}if(t.length>0){let s=await Promise.all(t);for(let a=0;a<s.length;++a)e[n[a]]=s[a][0];De(r)}}function ZI(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var JI;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(JI||(JI={}));var hW=125,gu=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){}},QI=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)}},fW=class extends gu{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let r in t){let s=t[r];if(typeof s=="number")this.totals.hasOwnProperty(r)||(this.totals[r]=0),this.totals[r]=this.totals[r]+s*n;else{let a;r in this.totals?a=this.totals[r]:this.totals[r]=0;let o=M(()=>Y(this.totals[r],V(s,n)));this.totals[r]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:M(()=>{let r=V(ge(1,this.seen),this.totals[n]);t[n]=r,this.totals[n].dispose(),Jt(t[n])}))}},eS=class extends gu{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let s in this.history){let a=this.history[s];for(let o=0;o<a.length;++o)if(typeof a[o]!="number"){let i=a[o];e.push(i.data()),t.push(s),n.push(o)}}let r=await Promise.all(e);for(let s=0;s<r.length;++s)this.history[t[s]][n[s]].dispose(),this.history[t[s]][n[s]]=r[s][0]}},tS=class extends gu{constructor(e,t){super();if(this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||hI,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=hW),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=w4(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){let r=[];this.yield!=null&&(await ba(n),r.push(this.yield(e,t,n))),r.push(this.nextFrameFunc()),await Promise.all(r)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await ba(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await ba(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await ba(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await ba(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(this.nextFrameFunc()):w.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await ba(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await ba(e),await this.trainEnd(e))}};function nS(e,t){return e==null&&(e={}),e instanceof gu?[e]:Array.isArray(e)&&e[0]instanceof gu?e:bt(e).map(r=>new tS(r,t))}var Tr=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}`),Tr.checkForDuplicate(t),Tr.constructors[e]==null&&(Tr.constructors[e]=[]),Tr.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Tr.constructors)Tr.constructors[+t].forEach(r=>{if(r===e)throw new H("Duplicate callback constructor.")})}static clear(){Tr.constructors={}}static createCallbacks(e){let t=[];for(let n in Tr.constructors){let r=+n;e>=r&&t.push(...Tr.constructors[r])}return t.map(n=>new n)}};Tr.constructors={};function rS(e,t,n,r,s,a,o,i,c){let l=new eS,u=[new fW,...Tr.createCallbacks(t)];e!=null&&u.push(...e),u.push(l);let d=new QI(u);return d.setParams({epochs:n,initialEpoch:r,samples:s,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:c}),{callbackList:d,history:l}}function Ur(e,t={},n=!1){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"layer",n)}function Lf(e,t){return M(()=>{e.dtype!=="float32"&&(e=ce(e,"float32"));let n=ve(pd(e),t,!0),r=In(n.shape,Ht()),s=cn(as(n,r));return ge(e,s)})}function ii(e,t){return M(()=>Et(pd(fe(t,e)),-1))}function Bf(e,t){return M(()=>Et(Lt(fe(t,e)),-1))}function bu(e,t){return M(()=>{let n=fe(e,t),r=Qt(Lt(e),Ht(),Number.MAX_VALUE),s=Lt(ge(n,r));return V(100,Et(s,-1))})}function mW(e,t){return M(()=>{let n=Qt(t,Ht(),Number.MAX_VALUE),r=Xn(Y(1,n)),s=Qt(e,Ht(),Number.MAX_VALUE),a=Xn(Y(1,s));return Et(pd(fe(r,a)),-1)})}function gW(e,t){return M(()=>{let n=as(0,fe(1,V(e,t)));return Et(pd(n),-1)})}function bW(e,t){return M(()=>{let n=as(0,fe(1,V(e,t)));return Et(n,-1)})}function yW(e,t){return M(()=>{let n=ve(V(e,t),-1),r=kr(V(fe(1,e),t),-1);return as(0,Y(1,fe(r,n)))})}function vW(e,t){return M(()=>{let n=Math.log(2),r=fe(t,e),s=fe(Y(r,Yo(V(-2,r))),n);return Et(s,-1)})}function fd(e,t,n=!1){return M(()=>{if(n)t=Pr(t);else{let r=ve(t,t.shape.length-1,!0);t=ge(t,r)}return t=Qt(t,Ht(),1-Ht()),It(ve(V(ce(e,"float32"),Xn(t)),t.shape.length-1))})}function zf(e,t,n=!1){return M(()=>{let r=ce(au(O4(e)),"int32");t=Qt(t,Ht(),1-Ht());let s=t.shape,a=U(eu(r,s[s.length-1]),s);return fd(a,t,n)})}function xW(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new H(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return M(()=>{let n=je(t),r=It(Lt(t));return Y(fe(n,V(t,e)),Zl(gn(r)))})}function Wf(e,t){return M(()=>{let n;return n=Qt(t,Ht(),1-Ht()),n=Xn(ge(n,fe(1,n))),Et(xW(e,n),-1)})}function wW(e,t){return M(()=>{let n=Qt(e,Ht(),1),r=Qt(t,Ht(),1);return ve(V(e,Xn(ge(n,r))),-1)})}function kW(e,t){return M(()=>{let n=Xn(Y(Ht(),t));return Et(fe(t,V(e,n)),-1)})}function Fv(e,t){return M(()=>{let n=Lf(e,-1),r=Lf(t,-1),s=V(n,r);return It(ve(s,-1))})}var Vf={meanSquaredError:ii,meanAbsoluteError:Bf,meanAbsolutePercentageError:bu,meanSquaredLogarithmicError:mW,squaredHinge:gW,hinge:bW,categoricalHinge:yW,logcosh:vW,categoricalCrossentropy:fd,sparseCategoricalCrossentropy:zf,binaryCrossentropy:Wf,kullbackLeiblerDivergence:wW,poisson:kW,cosineProximity:Fv};function $v(e){if(typeof e=="string"){if(e in Vf)return Vf[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 H(t)}else return e}function Rv(e,t){return M(()=>{let n=V(.5,Zn(t)),r=If(Mn(t,n),e.dtype);return Et(Kn(e,r),-1)})}function Pv(e,t){return M(()=>If(Kn(jo(e,-1),jo(t,-1)),"float32"))}function sS(e,t){return M(()=>ce(ve(Ir(Kn(e,1),Kn(t,1))),"float32"))}function IW(e,t){return M(()=>ce(ve(Ir(Kn(e,1),Kn(t,0))),"float32"))}function SW(e,t){return M(()=>ce(ve(Ir(Kn(e,0),Kn(t,1))),"float32"))}function aS(e,t){return M(()=>{let n=sS(e,t),r=SW(e,t),s=Y(n,r);return ce(mn(Mn(s,0),ge(n,s),0),"float32")})}function CW(e,t){return M(()=>{let n=sS(e,t),r=IW(e,t),s=Y(n,r);return ce(mn(Mn(s,0),ge(n,s),0),"float32")})}function oS(e,t){return Wf(e,t)}function iS(e,t){return e.rank===t.rank&&(e=os(e,[e.rank-1])),t=jo(t,-1),t.dtype!==e.dtype&&(t=ce(t,e.dtype)),ce(Kn(e,t),"float32")}var TW=ii,NW=ii,_W=Bf,EW=Bf,AW=bu,DW=bu,Ov=fd,FW=Fv,cS=zf,Uf={binaryAccuracy:Rv,categoricalAccuracy:Pv,precision:aS,categoricalCrossentropy:Ov,sparseCategoricalCrossentropy:cS,mse:TW,MSE:NW,mae:_W,MAE:EW,mape:AW,MAPE:DW,cosine:FW};function $W(e){if(typeof e=="string"&&e in Uf)return Uf[e];if(typeof e!="string"&&e!=null)return e;throw new H(`Unknown metric ${e}`)}function Gf(e){if(cs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(Vf))if(Vf[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Uf))if(Uf[n]===e){t=n;break}return t!==void 0?t:e.name}}function RW(e){let t={Adagrad:()=>ti.adagrad(.01),Adadelta:()=>ti.adadelta(1,.95,Ht()),Adam:()=>ti.adam(.001,.9,.999,Ht()),Adamax:()=>ti.adamax(.002,.9,.999,Ht(),0),RMSProp:()=>ti.rmsprop(.001,.9,0,Ht()),SGD:()=>ti.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 H(`Unknown Optimizer ${e}`)}var uS=1*1024*1024;function lS(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Mv(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let r=JSON.stringify(e);r.length>uS&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${r.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${uS}.`)}}function Mv(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"||!Mv(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Mv(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function PW(e,t,n,r=console.log){let s=MW(e),a=["Layer (type)","Output shape","Param #"];s?(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 o;if(!s){a.push("Receives inputs"),o=[];for(let u in e.nodesByDepth)o.push(...e.nodesByDepth[u])}r("_".repeat(t)),Hf(a,n,r),r("=".repeat(t));let i=e.layers;for(let u=0;u<i.length;++u)s?LW(i[u],n,r):BW(i[u],n,o,r),r((u===i.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let c=OW(e),l=Of(e.nonTrainableWeights);r(`Total params: ${c+l}`),r(`Trainable params: ${c}`),r(`Non-trainable params: ${l}`),r("_".repeat(t))}function OW(e){let t;return e.collectedTrainableWeights!=null?t=Of(e.collectedTrainableWeights):t=Of(e.trainableWeights),t}function MW(e){let t=!0,n=[],r=[];for(let s in e.nodesByDepth)n.push(e.nodesByDepth[s]);for(let s of n){if(s.length>1||s.length===1&&s[0].inboundLayers.length>1){t=!1;break}r.push(...s)}if(t)for(let s of e.layers){let a=!1;for(let o of s.inboundNodes)if(r.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function Hf(e,t,n=console.log){let r="";for(let s=0;s<e.length;++s)s>0&&(r=r.slice(0,r.length-1)+" "),r+=e[s],r=r.slice(0,t[s]),r+=" ".repeat(t[s]-r.length);n(r)}function LW(e,t,n){let r;try{r=JSON.stringify(e.outputShape)}catch(i){r="multiple"}let s=e.name,a=e.getClassName(),o=[`${s} (${a})`,r,e.countParams().toString()];Hf(o,t,n)}function BW(e,t,n,r){let s;try{s=JSON.stringify(e.outputShape)}catch(u){s="multiple"}let a=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let d=0;d<u.inboundLayers.length;++d){let p=u.inboundLayers[d].name,h=u.nodeIndices[d],f=u.tensorIndices[d];a.push(`${p}[${h}][${f}]`)}let o=e.name,i=e.getClassName(),c=a.length===0?"":a[0],l=[`${o} (${i})`,s,e.countParams().toString(),c];Hf(l,t,r);for(let u=1;u<a.length;++u)Hf(["","","",a[u]],t,r)}function dS(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function md(e,t){if(e===null)return null;if(typeof e=="string")return ri(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],r=e.length;for(let s=0;s<r;++s){let a=e[s];dS(t,s,a)?n.push(a):n.push(md(a,t))}return n}else{let n={};for(let r of Object.keys(e)){let s=e[r];if(r==="name"&&typeof s=="string")n[r]=s;else{let a=ri(r);n[a]=md(s,a)}}return n}}function Lv(e,t){if(e==null)return null;if(typeof e=="string")return Ds(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],r=e.length;for(let s=0;s<r;++s){let a=e[s];dS(t,s,a)?n.push(a):n.push(Lv(a,t))}return n}else{let n={};for(let r of Object.keys(e)){let s=e[r],a=Ds(r);(r==="name"||r==="className")&&typeof s=="string"?n[a]=s:n[a]=Lv(s,r)}return n}}var Bv="3.10.0";function zW(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ce(t,e.dtype)}catch(n){throw new H(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var ci=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof ci)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]=zW(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new H(`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 Vr){if(this.id2Value[e.id]==null)throw new H(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new H(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Vr){if(this.id2Value[e.id]==null)throw new H(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new H(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&De(this.id2Mask)}},zv={},pS={};function gd(e,t,n,r){let s=n==null?!1:n.training,a=Array.isArray(e),o=a?e:[e],i=o.map(f=>f.name),c=[],l=t.names();for(let f of i)l.indexOf(f)!==-1?c.push(t.getValue(f)):c.push(null);r!=null&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);let u=i.join(",")+"|"+t.names().join(","),d,p;if(zv[u]==null){let f=WW(o,t);d=f.sorted,p=f.recipientCounts,zv[u]=d,pS[u]=p}d=zv[u],p={},s||Object.assign(p,pS[u]);let h=new ci(t);for(let f=0;f<d.length;++f){if(r!=null){let R=Oh().numTensors;R>r.maxNumTensors&&(r.maxNumTensors=R),R<r.minNumTensors&&(r.minNumTensors=R)}let m=d[f],g=m.sourceLayer;if(g instanceof mu)continue;let b=[],y=[],v=[],x=!1;for(let R of m.inputs){let O=h.getValue(R),D=h.getMask(R);b.push(O),y.push(D),D!=null&&(x=!0),s||(p[R.name]--,p[R.name]===0&&!t.hasKey(R)&&i.indexOf(R.name)===-1&&!O.isDisposed&&R.sourceLayer.stateful!==!0&&v.push(O))}x&&(n=n||{},n.mask=y[0]);let k=bt(g.apply(b,n)),C=null;g.supportsMasking&&(C=g.computeMask(b,y));let N=UW(m),F=Array.isArray(N)?N:[N];for(let R=0;R<F.length;++R){h.hasKey(F[R])||h.add(F[R],k[R],Array.isArray(C)?C[0]:C);let O=i.indexOf(F[R].name);O!==-1&&(c[O]=k[R])}s||De(v)}return h.disposeMasks(),a?c:c[0]}function WW(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],r={};if(e.length===1){let s=hS(e[0],t);n=s.sorted,r=s.recipientMap}else{let s=new Set;for(let a of e){let{sorted:o,recipientMap:i}=hS(a,t);for(let c of o)s.has(c.name)||(n.push(c),s.add(c.name));for(let c in i)r[c]==null&&(r[c]=new Set),i[c].forEach(l=>r[c].add(l))}}return{sorted:n,recipientCounts:VW(r)}}function VW(e){let t={};for(let n in e)t[n]=e[n].size;return t}function hS(e,t){let n=new Set,r=[],s={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let c=o[o.length-1]===a.length-1;if(i.inputs.length===0||c)a.pop(),r.push(i),n.add(i.name),c&&o.pop();else{o.push(a.length-1);for(let l of i.inputs)s[l.name]==null&&(s[l.name]=new Set),s[l.name].add(i.name),!n.has(l.name)&&a.push(l)}}return{sorted:r,recipientMap:s}}function UW(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let r=0;r<e.sourceLayer.inboundNodes.length;++r)for(let s of e.sourceLayer.inboundNodes[r].outputTensors)if(s.id===e.id){n=r;break}t=e.sourceLayer.getOutputAt(n)}return t}var ls=class extends qe{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=Rf(b)}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],fa(this.inputs).length!==this.inputs.length)throw new H(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);fa(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(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let b of this.outputs){let y=b.sourceLayer,v=b.nodeIndex,x=b.tensorIndex;this.outputLayers.push(y),this.outputLayersNodeIndices.push(v),this.outputLayersTensorIndices.push(x)}for(let b of this.inputs){let y=b.sourceLayer,v=b.nodeIndex,x=b.tensorIndex;cs(v===0,"input layer has >1 nodes"),cs(x===0,"input layer has >1 tensors"),this.inputLayers.push(y),this.inputLayersNodeIndices.push(v),this.inputLayersTensorIndices.push(x)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let y=this.inputLayers[b];if(!(y instanceof mu))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${y.getClassName()}.`);this.inputNames.push(y.name),this.feedInputShapes.push(y.batchInputShape),this.feedInputNames.push(y.name)}for(let b of this.outputLayers)this.outputNames.push(b.name);this.internalInputShapes=this.inputs.map(b=>b.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);let t={},n={},r={},s={},a={},o=[],i=(b,y,v,x,k,C)=>{(x==null||k==null||C==null)&&(x=b.sourceLayer,k=b.nodeIndex,C=b.tensorIndex);let N=x.inboundNodes[k];if(v.indexOf(N)!==-1)throw new Br(`The tensor ${b.name} at layer "${x.name}" is part of a cycle.`);if(y.indexOf(N)!==-1)return;this.containerNodes.add(ls.nodeKey(x,k)),x.id in a||(a[x.id]=Object.keys(a).length),v.indexOf(N)===-1&&v.push(N);let F=N.inboundLayers.length;for(let R=0;R<F;R++){let O=N.inputTensors[R],D=N.inboundLayers[R],P=N.nodeIndices[R],T=N.tensorIndices[R];i(O,y,v,D,P,T)}for(y.push(N);v.indexOf(N)>=0;)v.splice(v.indexOf(N),1);o.push(N)},c=[],l=[];for(let b of this.outputs)i(b,c,l);let u=o.slice().reverse();for(let b of u){n[b.id]=b,b.id in t||(t[b.id]=0);let y=t[b.id],v=r[b.outboundLayer.id]==null?0:r[b.outboundLayer.id];y=Math.max(y,v),r[b.outboundLayer.id]=y,s[b.outboundLayer.id]=b.outboundLayer,t[b.id]=y;for(let x=0;x<b.inboundLayers.length;x++){let k=b.inboundLayers[x],C=b.nodeIndices[x],N=k.inboundNodes[C],F=t[N.id]==null?0:t[N.id];t[N.id]=Math.max(y+1,F),n[N.id]=N}}let d={};for(let b in t){let y=t[b];y in d||(d[y]=[]),d[y].push(n[b])}let p={};for(let b in r){let y=r[b];y in p||(p[y]=[]),p[y].push(s[b])}let h=Object.keys(p).map(b=>parseInt(b,10)).sort(kf);this.layers=[];for(let b of h){let y=p[b];y.sort((v,x)=>{let k=a[v.id],C=a[x.id];return k<C?-1:k>C?1:0});for(let v of y)v instanceof ls&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=p,h=Object.keys(d).map(b=>parseInt(b,10)).sort(kf);let f=this.inputs.slice(),m=[];for(let b of h)for(let y of d[b]){let v=y.outboundLayer;if(v!=null){for(let x of y.inputTensors)if(f.indexOf(x)===-1)throw new Br(`Graph disconnected: cannot obtain value for tensor ${x} at layer "${v.name}". The following previous layers were accessed without issue: ${m}`);for(let x of y.outputTensors)f.push(x);m.push(v.name)}}this.nodesByDepth=d;let g=this.layers.map(b=>b.name);for(let b of g){let y=g.filter(v=>v===b).length;if(y!==1)throw new Br(`The name "${b}" is used ${y} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Mf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(b=>null),outputMasks:this.outputs.map(b=>null),inputShapes:this.inputs.map(b=>b.shape),outputShapes:this.outputs.map(b=>b.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 H("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},r=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new H(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,r++}let s=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)s.push([n[o],e[a]]);else if(t)throw new H(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new H(`${a.length} of ${r} weights are not set: ${a}`)}Dv(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Bv}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=Lv(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return M(()=>{e=bt(e);let n=new ci;for(let r=0;r<this.inputs.length;++r)n.add(this.inputs[r],e[r]);return gd(this.outputs,n,t)})}computeMask(e,t){return M(()=>{e=bt(e);let n;return t==null?n=ni(null,e.length):n=bt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=Pf(e);if(t.length!==this.inputLayers.length)throw new H(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;o<t.length;o++){let i=this.inputLayers[o],c=t[o],l=i.name+"_0_0";n[l]=c}let r=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(kf);if(r.length>1)for(let o of r){let i=this.nodesByDepth[o];for(let c of i){let l=c.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(l.id)!==-1)continue;let u=[];for(let f=0;f<c.inboundLayers.length;f++){let m=c.inboundLayers[f],g=c.nodeIndices[f],b=c.tensorIndices[f],y=`${m.name}_${g}_${b}`,v=n[y];u.push(v)}let d=l.computeOutputShape(Bn(u)),p=Pf(d),h=l.inboundNodes.indexOf(c);for(let f=0;f<p.length;f++){let m=`${l.name}_${h}_${f}`;n[m]=p[f]}}}let s=[],a=[];for(let o=0;o<this.outputLayers.length;o++){let i=this.outputLayers[o],c=this.outputLayersNodeIndices[o],l=this.outputLayersTensorIndices[o],u=`${i.name}_${c}_${l}`;a.push(u)}for(let o=0;o<a.length;o++){let i=a[o];cs(i in n),s.push(n[i])}return Bn(s)}runInternalGraph(e,t){t==null&&(t=ni(null,e.length));let n={};for(let i=0;i<this.inputs.length;++i){let c=this.inputs[i],l=e[i],u=t[i];n[c.id]=[l,u]}let r=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(kf);for(let i of r){let c=this.nodesByDepth[i];for(let l of c){let u=l.outboundLayer,d=l.inputTensors,p=l.outputTensors,h=new Array;for(let f of d)f.id in n&&h.push(n[f.id]);if(h.length===d.length){let f={},m,g,b,y;if(l.callArgs!=null&&(f=l.callArgs),h.length===1){let[v,x]=h[0];f.mask==null&&(f.mask=x),b=bt(u.call(v,f)),y=bt(u.computeMask(v,x)),m=[v],g=[x]}else m=h.map(v=>v[0]),g=h.map(v=>v[1]),f.mask==null&&(f.mask=g),b=bt(u.call(m,f)),y=bt(u.computeMask(m,g));if(u.activityRegularizer)throw new Fe("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let v=0;v<p.length;++v){let x=p[v],k=b[v],C=y[v];n[x.id]=[k,C]}}}}let s=[],a=[],o=[];for(let i of this.outputs){cs(i.id in n,`Could not compute output ${i.name} : ${i.id}`);let[c,l]=n[i.id];o.push(c.shape),s.push(c),a.push(l)}return[s,a,o]}buildNodeConversionMap(e){let t={},n;for(let r of this.layers){n=r instanceof ls?1:0;for(let s=0;s<r.inboundNodes.length;s++){let a=ls.nodeKey(r,s);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new H(`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 H("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new H(`No such layer: ${e}`)}calculateLosses(){return M(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let r=ls.nodeKey(t,n);this.containerNodes.has(r)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let a of this.layers){let o=a.getClassName(),i=a.getConfig(),c=[];for(let u=0;u<a.inboundNodes.length;u++){let d=a.inboundNodes[u],p=ls.nodeKey(a,u),h={};if(this.containerNodes.has(p)){if(d.callArgs)try{JSON.stringify(d.callArgs),h=d.callArgs}catch(f){console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${d.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(d.inboundLayers.length>0){let f=[];for(let m=0;m<d.inboundLayers.length;m++){let g=d.inboundLayers[m],b=d.nodeIndices[m],y=d.tensorIndices[m],v=ls.nodeKey(g,b),x=t[v];x==null&&(x=0),f.push([g.name,x,y,h])}c.push(f)}}}let l={};l.name=a.name,l.className=o,l.config=i,l.inboundNodes=c,n.push(l)}e.layers=n;let r=[];for(let a=0;a<this.inputLayers.length;a++){let o=this.inputLayers[a],i=this.inputLayersNodeIndices[a],c=ls.nodeKey(o,i);if(!this.containerNodes.has(c))continue;let l=t[c];l==null&&(l=0);let u=this.inputLayersTensorIndices[a];r.push([o.name,l,u])}e.inputLayers=r;let s=[];for(let a=0;a<this.outputLayers.length;a++){let o=this.outputLayers[a],i=this.outputLayersNodeIndices[a],c=ls.nodeKey(o,i);if(!this.containerNodes.has(c))continue;let l=t[c];l==null&&(l=0);let u=this.outputLayersTensorIndices[a];s.push([o.name,l,u])}return e.outputLayers=s,e}static fromConfig(e,t,n={},r=!1){let s={},a={};function o(m,g){m.name in a?a[m.name].push(g):a[m.name]=[g]}function i(m,g){let b=[],y;for(let v of g){let x=v[0],k=v[1],C=v[2];if(y=v[3]==null?{}:v[3],!(x in s)){o(m,g);return}let N=s[x];if(N.inboundNodes.length<=k){o(m,g);return}let F=N.inboundNodes[k];b.push(F.outputTensors[C])}b.length>0&&m.apply(Bn(b),y)}function c(m){let g=m.name,b=Ur(m,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(r),s[g]=b,m.inboundNodes.forEach(v=>{if(!(v instanceof Array))throw new H(`Corrupted configuration, expected array for nodeData: ${v}`);o(b,v)})}let l=t.name,u=t.layers;for(let m of u)c(m);for(;!x4(a);)for(let m of u){let g=s[m.name];if(g.name in a){let b=a[g.name];delete a[g.name];for(let y of b)i(g,y)}}let d=[],p=[],h=t.inputLayers;for(let m of h){let g=m[0],b=m[1],y=m[2];cs(g in s);let x=s[g].inboundNodes[b].outputTensors;d.push(x[y])}let f=t.outputLayers;for(let m of f){let g=m[0],b=m[1],y=m[2];cs(g in s);let x=s[g].inboundNodes[b].outputTensors;p.push(x[y])}return new e({inputs:d,outputs:p,name:l})}get stateful(){if(this._stateful)throw new H("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(){M(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function GW(e,t,n){let r=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(s=>null);if(r===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let s=[];return t.forEach(a=>{a in e?s.push(e[a]):s.push(null)}),s}else throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function fS(e,t){return GW(e,t,"classWeight")}async function mS(e,t,n,r){if(t!=null||r!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let s=M(()=>{if(e.shape.length===1)return Ss(e);if(e.shape.length===2){if(e.shape[1]>1)return jo(e,1);if(e.shape[1]===1)return U(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await s.data());De(s);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Ge(o,"float32")}else return null}function HW(e,t){return V(e,t)}var jW=32;function gS(e,t){let n,r,s=t;n=s.xs,r=s.ys,w.assert(n!=null&&r!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=bS("input",e.inputNames,n),o=bS("output",e.outputNames,r),i=a[0].shape[0];w.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let c=0;c<a.length;c++)w.assert(a[c].shape[0]===i,()=>`Batch size mismatch: input ${e.inputNames[c]} has ${a[c].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let c=0;c<o.length;c++)w.assert(o[c].shape[0]===i,()=>`Batch size mismatch: output ${e.outputNames[c]} has ${o[c].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function bS(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 r=[];for(let s of t){if(n[s]==null)throw new H(`The feature data generated by the dataset lacks the required ${e} key '${s}'.`);r.push(n[s])}return r}}function qW(e){if(e.length===3)throw new Fe("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function KW(e,t,n){let r=n.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),w.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),w.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let s=n.validationData!=null,a,o;if(s)if(yS(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=qW(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),c=e.getDedupedMetricsNames(),l;s?l=c.slice().concat(c.map(g=>"val_"+g)):l=c.slice();let u=nS(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:p,history:h}=rS(u,d,n.epochs,null,null,XW(t,n),null,s,l);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){let g={};await p.onEpochBegin(f);let b=0,y=0;for(r||(m=await t.iterator());r?b<n.batchesPerEpoch:!0;){let v=await m.next();if(r&&v.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${b} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(v.value!=null){let{xs:x,ys:k}=gS(e,v.value),C={};C.batch=y,C.size=x[0].shape[0],await p.onBatchBegin(y,C);let N=[];if(n.classWeight!=null){let O=fS(n.classWeight,e.outputNames);for(let D=0;D<O.length;++D)N.push(await mS(k[D],null,O[D]))}let F=x.concat(k).concat(N),R=i(F);De(F);for(let O=0;O<c.length;++O){let D=c[O],P=R[O];C[D]=P,Jt(P)}await p.onBatchEnd(y,C),ZI(C),y++,b++}if(r?b>=n.batchesPerEpoch:v.done){if(s){let x;yS(n.validationData)?x=bt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):x=bt(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?jW:n.validationBatchSize,verbose:0}));for(let k=0;k<e.metricsNames.length;++k)g[`val_${e.metricsNames[k]}`]=x[k]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(f,g),f++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function XW(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function yS(e){return typeof e.iterator=="function"}function YW(e){return typeof e.next=="function"}async function ZW(e,t,n){n=n||{};let r=n.batches!=null,s=e.testFunction,a=[];if(n.verbose>0)throw new Fe("Verbose mode is not implemented yet.");w.assert(!r||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=YW(t)?t:await t.iterator(),i=0,c=0;for(;r?c<n.batches:!0;){let l=await o.next();if(a=M(()=>{if(l.value){let{xs:u,ys:d}=gS(e,l.value),p=u.concat(d),h=M(()=>s(p));if(De(p),c===0)for(let m=0;m<h.length;++m)a.push(Se(0));let f=p[0].shape[0];for(let m=0;m<h.length;++m){let g=h[m],b=a[m];a[m]=M(()=>Y(a[m],V(f,g))),c>0&&De(b)}De(h),i+=f,++c}return a}),l.done){r&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let l=0;l<a.length;++l){let u=a[l];a[l]=ge(a[l],i),De(u)}return Bn(a)}function Wv(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function bd(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(r=>oi(r,t,n-t)):oi(e,t,n-t)}function Vv(e,t){return M(()=>e==null?null:Array.isArray(e)?e.map(n=>Vv(n,t)):WI(e,t.dtype==="int32"?t:ce(t,"int32")))}function Uv(e,t){let n=[],r=0,s=null;for(;r<e;)s=r+t,s>=e&&(s=e),n.push([r,s]),r=s;return n}async function JW(e,t,n,r,s,a,o,i,c,l,u,d,p,h,f){s==null&&(s=32),a==null&&(a=1),u==null&&(u=!0),p==null&&(p=0);let m=!1;if(c!=null&&l!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new H("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,s,h,"steps_per_epoch"),b;g!=null&&(b=zr(0,g)),o==null&&(o=1);let{callbackList:y,history:v}=rS(i,o,a,p,g,h,s,m,d);y.setModel(e),e.history=v,await y.onTrainBegin(),e.stopTraining_=!1;for(let x=p;x<a;++x){await y.onEpochBegin(x);let k={};if(h!=null)throw new Fe("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new Fe("batch shuffling is not implemneted yet");u&&w.shuffle(b);let C=Ge(b),N=Uv(g,s);for(let F=0;F<N.length;++F){let R={};if(await y.onBatchBegin(F,R),M(()=>{let O=N[F][0],D=N[F][1],P=oi(C,O,D-O);R.batch=F,R.size=D-O;let T=Vv(n,P),L=t(T);for(let G=0;G<r.length;++G){let j=r[G],q=L[G];R[j]=q,Jt(q)}if(F===N.length-1&&m){let G=e.testLoop(c,l,s);for(let j=0;j<r.length;++j){let q=r[j],K=G[j];Jt(K),k["val_"+q]=K}}}),await y.onBatchEnd(F,R),ZI(R),e.stopTraining_)break}C.dispose()}if(await y.onEpochEnd(x,k),e.stopTraining_)break}return await y.onTrainEnd(),await e.history.syncData(),e.history}async function QW(e,t,n,r={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let s,a,o,i,c,l,u;try{let d=r.batchSize==null?32:r.batchSize;Wv(d);let p=!1,h=await e.standardizeUserData(t,n,r.sampleWeight,r.classWeight,p,d);s=h[0],a=h[1],u=h[2];let f=!1,m;if(r.validationData!=null&&r.validationData.length>0){if(f=!0,r.validationData.length===2)o=r.validationData[0],i=r.validationData[1];else throw r.validationData.length===3?new Fe("validationData including sample weights is not supported yet."):new H(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);let N=!0,F=await e.standardizeUserData(o,i,null,null,N,d);c=F[0],l=F[1],m=c.concat(l)}else if(r.validationSplit!=null&&r.validationSplit>0&&r.validationSplit<1){f=!0;let N=Math.floor(s[0].shape[0]*(1-r.validationSplit)),F=s[0].shape[0];c=bd(s,N,F),s=bd(s,0,N),l=bd(a,N,F),a=bd(a,0,N),m=c.concat(l)}else r.validationSteps!=null&&(f=!0);let g=s.concat(a).concat(u);e.checkTrainableWeightsConsistency();let b=e.makeTrainFunction(),y=e.getDedupedMetricsNames(),v,x;f?(e.makeTestFunction(),v=e.testFunction,x=y.slice().concat(y.map(N=>"val_"+N))):(v=null,m=[],x=y.slice());let k=nS(r.callbacks,r.yieldEvery);return await JW(e,b,g,y,d,r.epochs,r.verbose,k,v,m,r.shuffle,x,r.initialEpoch,null,null)}finally{e.isTraining=!1,ui(s,t),ui(a,n),ui(c,o),ui(l,i),u!=null&&De(u)}}function vS(e){let t=[];e instanceof Ee&&(e=[e]);for(let n=0;n<e.length;++n){let r=e[n];if(r.rank===1)t.push(dd(r,1));else{if(r.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function ui(e,t){if(e==null)return;let n=[];if(t instanceof Ee)n.push(t.id);else if(Array.isArray(t))t.forEach(s=>n.push(s.id));else if(t!=null)for(let s in t){let a=t[s];n.push(a.id)}let r=[];if(e instanceof Ee)n.indexOf(e.id)===-1&&r.push(e);else if(Array.isArray(e))e.forEach(s=>{n.indexOf(s.id)===-1&&r.push(s)});else if(e!=null)for(let s in e){let a=e[s];n.indexOf(a.id)===-1&&r.push(a)}r.forEach(s=>{s.isDisposed||s.dispose()})}function eV(e){return e instanceof Ee}function Gv(e){return Array.isArray(e)}function xS(e){return!eV(e)&&!Gv(e)}function wS(e,t,n,r=!0,s=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(Gv(e)&&e.length>0)o=!0;else if(xS(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new H(`Error when checking model ${s} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(xS(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new H(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(Gv(e)){if(e=e,e.length!==t.length)throw new H(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new H(`The model ${s} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=vS(a),n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new H(`Error when checking ${s}: expected ${t[o]} to have ${n[o].length} dimension(s). but got array with shape ${i.shape}`);for(let c=0;c<n[o].length;++c){if(c===0&&!r)continue;let l=i.shape[c],u=n[o][c];if(u!=null&&u>=0&&l!==u)throw new H(`${s} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${s} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function tV(e,t,n){let r=fa(e.map(a=>a.shape[0]));r.sort();let s=fa(t.map(a=>a.shape[0]));if(s.sort(),r.length>1)throw new H(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(s.length>1)throw new H(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(r.length>0&&s.length>0&&!w.arraysEqual(r,s))throw new H(`Input Tensors should have the same number of samples as target Tensors. Found ${r[0]} input sample(s) and ${s[0]} target sample(s).`)}function nV(e,t,n){let r=[ii,Wf,fd];for(let s=0;s<e.length;++s){let a=e[s],o=t[s],i=n[s];if(o!=null){if(o===fd&&a.shape[a.shape.length-1]===1)throw new H(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(r.indexOf(o)!==-1){let c=a.shape.slice(1),l=i.slice(1);for(let u=0;u<c.length;++u){let d=c[u],p=l[u];if(p!=null&&d!==p)throw new H(`A target Tensor with shape ${a.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function kS(e,t,n,r=!0,s=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new H(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new H(`The model expects ${t.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new H(`Error when checking ${s}: expected ${t[o]} to have ${n[o].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let c=0;c<n[o].length;++c){if(c===0&&!r)continue;let l=i.shape[c],u=n[o][c];if(u!=null&&u!==l)throw new H(`Error when checking ${s}: expected ${t[o]} to have shape ${JSON.stringify(n[o])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function rV(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(r=>n);{let r=[];for(let s of t){let a=n.hasOwnProperty(s)?n[s]:[];Array.isArray(a)||(a=[a]),r.push(a)}return r}}var sV="layers-model",Fs=class extends ls{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new H("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).");PW(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=RW(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Es))throw new H("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new H(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push($v(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new H(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>$v(o))}else{let a=$v(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a<this.outputs.length;++a){let o=this.internalOutputShapes[a],i=this.outputNames[a];this.feedOutputNames.push(i),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[a])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ai("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=this.lossFunctions[a];this.outputs.length>1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let r=rV(e.metrics,this.outputNames),s=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};ai("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=r[a];(c=>{let l="",u,d,p;for(let h of c){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===Wf?["accuracy","acc"].indexOf(h)!==-1?d=Rv:["crossentropy","ce"].indexOf(h)!==-1&&(d=oS):this.lossFunctions[a]===zf?["accuracy","acc"].indexOf(h)!==-1?d=iS:["crossentropy","ce"].indexOf(h)!==-1&&(d=cS):["accuracy","acc"].indexOf(h)!==-1?d=Pv:["crossentropy","ce"].indexOf(h)!==-1&&(d=Ov);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),p=d,u=l+g}else p=$W(h),u=l+Gf(h);let f;ai(u,()=>{f=p}),s(a,u,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let r=n.batchSize==null?32:n.batchSize;Wv(r);let s=!0,a=this.standardizeUserDataXY(e,t,s,r);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,c=this.testLoop(i,o,r,n.verbose,n.steps);return Bn(c)}finally{ui(a[0],e),ui(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),ZW(this,e,t)}checkNumSamples(e,t,n,r="steps"){let s;if(n!=null){if(s=null,t!=null)throw new H(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?s=e[0].shape[0]:s=e.shape[0];else throw new H(`Either the input data should have a defined shape, or ${r} shoud be specified.`);return s}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new H("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),r=n?t:[t],s=this.retrieveSymbolicTensors(r),a=new ci;if(e instanceof Ee&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new H(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;i<this.inputs.length;++i)a.add(this.inputs[i],e[i])}else for(let i of this.inputs){let c=e[i.name];if(c==null)throw new H(`No value is provided for the model's input ${i.name}`);a.add(i,c)}let o=gd(s,a);return n?o:o[0]}retrieveSymbolicTensors(e){let t=ni(null,e.length),n=e.length;for(let r of this.layers){let s=Array.isArray(r.output)?r.output:[r.output],a=s.map(o=>o.name);for(let o=0;o<e.length;++o){let i=a.indexOf(e[o]);if(i!==-1&&(t[o]=s[i],n--),n===0)break}if(n===0)break}if(n>0){let r=[];throw t.forEach((s,a)=>{s==null&&r.push(e[a])}),new H(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(r)}`)}return t}predictLoop(e,t=32,n=!1){return M(()=>{let r=this.checkNumSamples(e);if(n)throw new Fe("Verbose predictLoop() is not implemented yet.");let s=Uv(r,t),a=this.outputs.map(o=>[]);for(let o=0;o<s.length;++o)M(()=>{let c=s[o][0],l=s[o][1],u=bd(e,c,l),d=[];if(Array.isArray(u))for(let h=0;h<u.length;++h)d.push({key:this.inputs[h],value:u[h]});else d.push({key:this.inputs[0],value:u});let p=new ci(d);return gd(this.outputs,p)}).forEach((c,l)=>a[l].push(c));return Bn(a.map(o=>Ze(o,0)))})}predict(e,t={}){let n=vS(e);kS(n,this.inputNames,this.feedInputShapes,!1);try{let r=t.batchSize==null?32:t.batchSize;return Wv(r),this.predictLoop(n,r)}finally{ui(n,e)}}predictOnBatch(e){kS(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(this.optimizer_==null)throw new Br("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a<this.feedOutputShapes.length;++a){let o=this.feedOutputShapes[a];this.feedLossFns[a]===zf?s.push(o.slice(0,o.length-1).concat([1])):s.push(o)}if(e=wS(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=wS(t,this.feedOutputNames,s,!1,"target"),tV(e,t,null),nV(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&r!=null&&r>0&&e[0].shape[0]%r!=0)throw new H(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,s=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,s,a);if(n!=null)throw new Error("sample weight is not supported yet.");let c=null;if(r!=null){let l=fS(r,this.outputNames);c=[];for(let u=0;u<l.length;++u)c.push(await mS(i[u],null,l[u]))}return[o,i,c]}testLoop(e,t,n,r=0,s){return M(()=>{let a=this.checkNumSamples(t,n,s,"steps"),o=[];if(r>0)throw new Fe("Verbose mode is not implemented yet.");if(s!=null)throw new Fe("steps mode in testLoop() is not implemented yet");{let i=Uv(a,n),c=Ge(zr(0,a));for(let l=0;l<i.length;++l){let u=i[l][0],d=i[l][1],p=oi(c,u,d-u),h=Vv(t,p),f=e(h);if(l===0)for(let m=0;m<f.length;++m)o.push(Se(0));for(let m=0;m<f.length;++m){let g=f[m];o[m]=Y(o[m],V(d-u,g))}}for(let l=0;l<o.length;++l)o[l]=ge(o[l],a)}return o})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let r=e[n],s=r;EI(e,r)>1&&(s+=`_${EI(e.slice(0,n),r)}`),t.push(s)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let u=[];for(let f=0;f<this.inputs.length;++f)u.push({key:this.inputs[f],value:n[f]});let d=new ci(u),p=gd(this.outputs,d,{training:!0}),h;for(let f=0;f<this.lossFunctions.length;++f){let g=this.lossFunctions[f](r[f],p[f]);s[f]!=null&&(g=HW(g,s[f]));let b=Et(g);t.push(b),f===0?h=g:h=Y(h,g)}for(let f=0;f<this.metricsTensors.length;++f){let m;if(this.outputs.length>1&&f<this.outputs.length)m=t[f];else{let g=this.metricsTensors[f][0],b=this.metricsTensors[f][1];m=Et(g(r[b],p[b]))}Jt(m),a.push(m)}return h=Et(h),this.calculateLosses().forEach(f=>{h=Y(h,f)}),h},i=this.collectedTrainableWeights.map(u=>u.read()),c=!0;return[this.optimizer_.minimize(o,c,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>M(()=>{let t=[],n,r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let c=0;c<this.inputs.length;++c)a.push({key:this.inputs[c],value:r[c]});let o=new ci(a),i=gd(this.outputs,o);for(let c=0;c<this.lossFunctions.length;++c){let l=this.lossFunctions[c],u=Et(l(s[c],i[c]));c===0?n=u:n=Y(n,u),t.push(n)}for(let c=0;c<this.metricsTensors.length;++c){let l=this.metricsTensors[c][0],u=this.metricsTensors[c][1],d=Et(l(s[u],i[u]));t.push(d)}return t})}async fit(e,t,n={}){return QW(this,e,t,n)}async fitDataset(e,t){return KW(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),r=n[0],s=n[1],o=this.makeTrainFunction()(r.concat(s)),i=[];for(let c of o){let l=await c.data();i.push(l[0])}return De(o),Bn(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,r=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let a=0;a<r.length;++a)n&&!r[a].trainable||t.push({name:r[a].originalName,tensor:s[a]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=Oh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Oh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Ds(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=>Ds(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let r of t)if(typeof n[r]=="string")e[r]=Ds(n[r]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[Ds(Gf(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Ds(Gf(e)));{let e={};for(let t in this.metrics)e[t]=Ds(Gf(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=md(e.optimizer_config),n=Ur(t),r;if(typeof e.loss=="string")r=ri(e.loss);else if(Array.isArray(e.loss))r=e.loss.map(a=>ri(a));else if(e.loss!=null){r={};for(let a in e.loss)r[a]=ri(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>ri(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=ri(e.metrics[a])}this.compile({loss:r,metrics:s,optimizer:n})}async save(e,t){if(typeof e=="string"){let c=Zt.getSaveHandlers(e);if(c.length===0)throw new H(`Cannot find any save handlers for URL '${e}'`);if(c.length>1)throw new H(`Found more than one (${c.length}) save handlers for URL '${e}'`);e=c[0]}if(e.save==null)throw new H("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Zt.encodeWeights(this.getNamedWeights(t)),r=!1,s=null,o={modelTopology:this.toJSON(s,r),format:sV,generatedBy:`TensorFlow.js tfjs-layers v${Bv}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let c="optimizer",{data:l,specs:u}=await Zt.encodeWeights(await this.optimizer.getWeights(),c);n.specs.push(...u),n.data=Zt.concatenateArrayBuffers([n.data,l])}if(this.userDefinedMetadata!=null){let c=!0;lS(this.userDefinedMetadata,this.name,c),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){lS(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Fs.className="Model";ie.registerClass(Fs);var IS=class extends Fs{};IS.className="Functional";ie.registerClass(IS);async function aV(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let r=md(n),s=Ur(r,t);if(e.weightsManifest!=null){let a=await Zt.loadWeights(e.weightsManifest,e.pathPrefix,s.weights.map(i=>i.originalName)),o={};for(let i of s.weights)o[i.originalName]=a[i.originalName];s.loadWeights(o),De(a)}return s}async function oV(e,t){if(t==null&&(t={}),typeof e=="string"){let n=Zt.getLoadHandlers(e,t);if(n.length===0)n.push(Zt.browserHTTPRequest(e,t));else if(n.length>1)throw new H(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return iV(e,void 0,t)}async function iV(e,t,n){if(n==null&&(n={}),e.load==null)throw new H("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let r=await e.load(),s=r.modelTopology;s.model_config!=null&&(s=s.model_config);let a=n.strict==null?!0:n.strict,o=r.weightData!=null&&r.weightSpecs!=null&&a,i=Ur(md(s),t,o),c=r.trainingConfig;if(c!=null&&i.loadTrainingConfig(c),r.userDefinedMetadata!=null&&i.setUserDefinedMetadata(r.userDefinedMetadata),r.weightData!=null){if(r.weightSpecs==null)throw new H("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:l,optimizerWeights:u}=cV(r.weightData,r.weightSpecs);i.loadWeights(l,a),i.optimizer!=null&&u.length>0&&await i.optimizer.setWeights(u),De(l),De(u.map(d=>d.tensor))}return i}function cV(e,t){let n=Zt.decodeWeights(e,t),r={},s=[];return t.forEach(a=>{a.group==="optimizer"?s.push({name:a.name,tensor:n[a.name]}):r[a.name]=n[a.name]}),{modelWeights:r,optimizerWeights:s}}var yu=class extends Fs{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Rf("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new H(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof yu||e instanceof Fs,n;if(t){if(n=e,n.outputs.length!==1)throw new H("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 H("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 H("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let r=YI({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(r)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new H(`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 H("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=XI(this.outputs[0])}this.inboundNodes=[],new Mf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ni(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(r=>r.shape),outputShapes:this.outputs[0].shape})}else{let r=e.apply(this.outputs[0]);if(Array.isArray(r))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[r],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(at(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Fs({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 Br("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 Br("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 Br("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 Br("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},r=!1){let s,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new H("Legacy serialization format not supported yet.");s=t}else w.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),s=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof yu))throw new Fe(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of s){let l=Ur(i,void 0,r);r&&l.setFastWeightInitDuringBuild(!0),o.add(l)}return o}set stopTraining(e){if(this.model==null)throw new H("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 H("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}}};yu.className="Sequential";ie.registerClass(yu);function uV(e){return new Fs(e)}function lV(e){return new yu(e)}function dV(e,t){return t==null&&(t={}),oV(e,t)}function SS(e){return YI(e)}function pV(e,t){Tr.registerCallbackConstructor(e,t)}var Wn=class extends ie.Serializable{getConfig(){return{}}},CS=class extends Wn{apply(e,t=1){return L4(e,t)}};CS.className="elu";ie.registerClass(CS);var TS=class extends Wn{apply(e){return tf(e)}};TS.className="selu";ie.registerClass(TS);var NS=class extends Wn{apply(e){return je(e)}};NS.className="relu";ie.registerClass(NS);var _S=class extends Wn{apply(e){return M(()=>ou(6,je(e)))}};_S.className="relu6";ie.registerClass(_S);var ES=class extends Wn{apply(e){return e}};ES.className="linear";ie.registerClass(ES);var AS=class extends Wn{apply(e){return cr(e)}};AS.className="sigmoid";ie.registerClass(AS);var DS=class extends Wn{apply(e){return z4(e)}};DS.className="hardSigmoid";ie.registerClass(DS);var FS=class extends Wn{apply(e){return Yo(e)}};FS.className="softplus";ie.registerClass(FS);var $S=class extends Wn{apply(e){return B4(e)}};$S.className="softsign";ie.registerClass($S);var RS=class extends Wn{apply(e){return Ko(e)}};RS.className="tanh";ie.registerClass(RS);var Hv=class extends Wn{apply(e,t=-1){return Pr(e,t)}};Hv.className="softmax";ie.registerClass(Hv);var PS=class extends Wn{apply(e,t=-1){return Kh(e,t)}};PS.className="logSoftmax";ie.registerClass(PS);var OS=class extends Wn{apply(e,t=1){return M(()=>V(cr(V(e,t)),e))}};OS.className="swish";ie.registerClass(OS);var MS=class extends Wn{apply(e){return M(()=>V(e,Ko(Yo(e))))}};MS.className="mish";ie.registerClass(MS);function ya(e){return e.getClassName()}function jv(e,t={}){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"activation")}function va(e){if(e==null){let t={};return t.className="linear",t.config={},jv(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},jv(t)}else return e instanceof Wn?e:jv(e)}function qv(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 LS=class extends ie.Serializable{},yd=class extends LS{constructor(e){super();qv(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 M(()=>{let t=St([1]);return this.hasL1&&(t=Y(t,ve(V(this.l1,Lt(e))))),this.hasL2&&(t=Y(t,ve(V(this.l2,pd(e))))),U(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};yd.className="L1L2";ie.registerClass(yd);function hV(e){return qv(e),new yd({l1:e!=null?e.l1:null,l2:0})}function fV(e){return qv(e),new yd({l2:e!=null?e.l2:null,l1:0})}var BS={l1l2:"L1L2"};function pt(e){return lv(e)}function zS(e,t={}){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"regularizer")}function Tt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in BS?BS[e]:e,config:{}};return zS(n)}else return e instanceof LS?e:zS(e)}var Kv=class extends qe{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Oe(e);let n=je(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}};Kv.className="ReLU";ie.registerClass(Kv);var Xv=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Oe(e);return Yl(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Xv.className="LeakyReLU";ie.registerClass(Xv);var Yv=class extends qe{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ct(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Tt(e.alphaRegularizer),this.alphaConstraint=qt(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 H(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=at(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let r of this.sharedAxes)t[r-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let r=1;r<e.length;++r)n[r]=e[r];this.inputSpec=[new Bt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Oe(e),td(e,this.alpha.read())}getConfig(){let e={alphaInitializer:At(this.alphaInitializer),alphaRegularizer:pt(this.alphaRegularizer),alphaConstraint:jt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};Yv.className="PReLU";ie.registerClass(Yv);var Zv=class extends qe{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Fe(`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=Oe(e);return su(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Zv.className="ELU";ie.registerClass(Zv);var Jv=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Oe(e);return V(n,ce(Mn(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};Jv.className="ThresholdedReLU";ie.registerClass(Jv);var Qv=class extends qe{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Hv().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Oe(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}};Qv.className="Softmax";ie.registerClass(Qv);function vu(e,t,n){if(typeof e=="number")return ni(e,t);if(e.length!==t)throw new H(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let r=0;r<t;++r){let s=e[r];if(!R4(s))throw new H(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e}function Gr(e,t,n,r,s=1){if(e==null)return e;let a=t+(t-1)*(s-1),o;return n==="same"?o=e:o=e-a+1,Math.floor((o+r-1)/r)}function ds(e,t,n,r){if(e==null)return null;if(r==="valid")e=e*t+ga([n-t,0]);else if(r==="same")e=e*t;else throw new H(`Unsupport padding mode: ${r}.`);return e}function ex(e,t){return M(()=>(Mt(t),t==="channelsFirst"?Re(e,[0,2,3,1]):e))}function WS(e,t){return M(()=>(Mt(t),t==="channelsFirst"?Re(e,[0,2,3,4,1]):e))}function mV(e,t,n,r=1,s="valid",a,o=1){return M(()=>{if(a==null&&(a=Lr()),Mt(a),e.shape.length!==3)throw new H(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new H(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new H(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=Re(e,[0,2,1])),s==="causal")throw new Fe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=Wh(e,t,r,s==="same"?"same":"valid","NWC",o);return n!=null&&(i=Wr(i,n)),i})}function VS(e,t,n,r=[1,1],s="valid",a,o,i=null){return M(()=>{if(a==null&&(a=Lr()),Mt(a),e.rank!==3&&e.rank!==4)throw new H(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new H(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let c=ex(e,a);if(s==="causal")throw new Fe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return c=ha.conv2d({x:c,filter:t,strides:r,pad:s==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(c=Re(c,[0,3,1,2])),c})}function gV(e,t,n,r=[1,1,1],s="valid",a,o){return M(()=>{if(a==null&&(a=Lr()),Mt(a),e.rank!==4&&e.rank!==5)throw new H(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new H(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=WS(e,a);if(s==="causal")throw new Fe("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Fy(i,t,r,s==="same"?"same":"valid","NDHWC",o),n!=null&&(i=Wr(i,n)),a==="channelsFirst"&&(i=Re(i,[0,4,1,2,3])),i})}var tx=class extends qe{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",tx.verifyArgs(t),this.rank=e,en(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Fe(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=vu(t.kernelSize,e,"kernelSize"),this.strides=vu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,lr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Mt(this.dataFormat),this.activation=va(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Ct(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=qt(t.biasConstraint),this.biasRegularizer=Tt(t.biasRegularizer),this.activityRegularizer=Tt(t.activityRegularizer),this.dilationRate=vu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new H(`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 H(`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 H(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(cs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!pv(e.kernelSize,"number",1,3))throw new H(`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:ya(this.activation),useBias:this.useBias,biasInitializer:At(this.biasInitializer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),biasConstraint:jt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},vd=class extends tx{constructor(e,t){super(e,t);this.kernel=null,vd.verifyArgs(t),this.filters=t.filters,en(this.filters,"filters"),this.kernelInitializer=Ct(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=qt(t.kernelConstraint),this.kernelRegularizer=Tt(t.kernelRegularizer)}build(e){e=at(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return M(()=>{e=Oe(e);let n,r=this.bias==null?null:this.bias.read(),s=DI(this.activation.getClassName());if(s!=null&&this.rank===2)n=VS(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=mV(e,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=VS(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=gV(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Fe("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=at(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let s=0;s<n.length;++s){let a=Gr(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(a)}let r=[e[0]];return this.dataFormat==="channelsLast"?(r=r.concat(t),r.push(this.filters)):(r.push(this.filters),r=r.concat(t)),r}getConfig(){let e={filters:this.filters,kernelInitializer:At(this.kernelInitializer),kernelRegularizer:pt(this.kernelRegularizer),kernelConstraint:jt(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 H(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},xd=class extends vd{constructor(e){super(2,e);xd.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!pv(e.kernelSize,"number",1,2))throw new H(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};xd.className="Conv2D";ie.registerClass(xd);var wd=class extends vd{constructor(e){super(3,e);wd.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 H(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};wd.className="Conv3D";ie.registerClass(wd);var nx=class extends xd{constructor(e){super(e);if(this.inputSpec=[new Bt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=at(e),e.length!==4)throw new H("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 H("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Bt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return M(()=>{let n=Oe(e);if(n.shape.length!==4)throw new H(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let r=n.shape,s=r[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=r[a],c=r[o],l=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],p=this.strides[1],h=ds(i,d,l,this.padding),f=ds(c,p,u,this.padding),m=[s,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=Re(n,[0,2,3,1]));let g=Vh(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Re(g,[0,3,1,2])),this.bias!=null&&(g=Wr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=at(e);let t=e.slice(),n,r,s;this.dataFormat==="channelsFirst"?(n=1,r=2,s=3):(n=3,r=1,s=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],c=this.strides[1];return t[n]=this.filters,t[r]=ds(t[r],i,a,this.padding),t[s]=ds(t[s],c,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};nx.className="Conv2DTranspose";ie.registerClass(nx);var rx=class extends wd{constructor(e){super(e);if(this.inputSpec=[new Bt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=at(e),e.length!==5)throw new H("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Bt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return M(()=>{let n=Oe(e);if(n.shape.length!==5)throw new H(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let r=n.shape,s=r[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let c=r[i],l=r[a],u=r[o],d=this.kernelSize[0],p=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],b=ds(c,f,d,this.padding),y=ds(l,m,p,this.padding),v=ds(u,g,h,this.padding),x=[s,b,y,v,this.filters];this.dataFormat!=="channelsLast"&&(n=Re(n,[0,2,3,4,1]));let k=Ak(n,this.kernel.read(),x,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(k=Re(k,[0,4,1,2,3])),this.bias!==null&&(k=Wr(k,this.bias.read(),this.dataFormat)),this.activation!==null&&(k=this.activation.apply(k)),k})}computeOutputShape(e){e=at(e);let t=e.slice(),n,r,s,a;this.dataFormat==="channelsFirst"?(n=1,r=2,s=3,a=4):(n=4,r=1,s=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],c=this.kernelSize[2],l=this.strides[0],u=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[r]=ds(t[r],l,o,this.padding),t[s]=ds(t[s],u,i,this.padding),t[a]=ds(t[a],d,c,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};rx.className="Conv3DTranspose";ie.registerClass(rx);var US=class extends vd{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 H("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new H("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 H(`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=Ct(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Tt(t.depthwiseRegularizer),this.depthwiseConstraint=qt(t.depthwiseConstraint),this.pointwiseInitializer=Ct(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Tt(t.pointwiseRegularizer),this.pointwiseConstraint=qt(t.pointwiseConstraint)}build(e){if(e=at(e),e.length<this.rank+2)throw new H(`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 H(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],r=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let o=0;o<this.rank;++o)s.push(1);s.push(n*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new Bt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return M(()=>{e=Oe(e);let n;if(this.rank===1)throw new Fe("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Re(e,[0,2,3,1])),n=Qo(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Wr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Re(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=At(this.depthwiseInitializer),e.pointwiseInitializer=At(this.pointwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.pointwiseRegularizer=pt(this.pointwiseRegularizer),e.depthwiseConstraint=jt(this.depthwiseConstraint),e.pointwiseConstraint=jt(this.pointwiseConstraint),e}};US.className="SeparableConv";var sx=class extends US{constructor(e){super(2,e)}};sx.className="SeparableConv2D";ie.registerClass(sx);var jf=class extends vd{constructor(e){super(1,e);jf.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"&&!pv(e.kernelSize,"number",1,1))throw new H(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};jf.className="Conv1D";ie.registerClass(jf);var ax=class extends qe{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return M(()=>{if(e=Oe(e),this.dataFormat==="channelsLast"){let n=Sf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Sf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Sf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Sf(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}};ax.className="Cropping2D";ie.registerClass(ax);var ox=class extends qe{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,D4(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 M(()=>{let n=Oe(e),r=n.shape;if(this.dataFormat==="channelsFirst"){n=Re(n,[0,2,3,1]);let s=this.size[0]*r[2],a=this.size[1]*r[3],o=this.interpolation==="nearest"?Qn.resizeNearestNeighbor(n,[s,a]):Qn.resizeBilinear(n,[s,a]);return Re(o,[0,3,1,2])}else{let s=this.size[0]*r[1],a=this.size[1]*r[2];return this.interpolation==="nearest"?Qn.resizeNearestNeighbor(n,[s,a]):Qn.resizeBilinear(n,[s,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};ox.className="UpSampling2D";ie.registerClass(ox);function bV(e,t,n=[1,1],r="valid",s,a){return M(()=>{s==null&&(s=Lr()),Mt(s);let o=ex(e,s);if(e.rank!==4)throw new H(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new H(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=la(o,t,n,r==="same"?"same":"valid","NHWC",a),s==="channelsFirst"&&(o=Re(o,[0,3,1,2])),o})}var ix=class extends tx{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ct(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=qt(e.depthwiseConstraint),this.depthwiseRegularizer=Tt(e.depthwiseRegularizer)}build(e){if(e=at(e),e.length<4)throw new H(`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 H(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return M(()=>{e=Oe(e);let n=bV(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Wr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=at(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=Gr(t,this.kernelSize[0],this.padding,this.strides[0]),a=Gr(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],r,s,a]:[e[0],s,a,r]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=At(this.depthwiseInitializer),e.depthwiseRegularizer=pt(this.depthwiseRegularizer),e.depthwiseConstraint=jt(this.depthwiseRegularizer),e}};ix.className="DepthwiseConv2D";ie.registerClass(ix);function GS(e,t,n,r){if(Array.isArray(e)){if(t!=null||n!=null)throw new H("When inputs is an array, neither initialState or constants should be provided");r!=null&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function s(a){return a==null||Array.isArray(a)?a:[a]}return t=s(t),n=s(n),{inputs:e,initialState:t,constants:n}}function HS(e,t,n,r=!1,s,a,o=!1,i=!1){return M(()=>{let c=t.shape.length;if(c<3)throw new H(`Input should be at least 3D, but is ${c}D.`);let l=[1,0].concat(zr(2,c));if(t=Re(t,l),a!=null)throw new Fe("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),s!=null&&(s=ce(ce(s,"bool"),"float32"),s.rank===c-1&&(s=bn(s,-1)),s=Re(s,l)),r&&(t=Jn(t,0),s!=null&&(s=Jn(s,0)));let u=[],d,p=n,h=t.shape[0],f=dt(t),m;s!=null&&(m=dt(s));for(let b=0;b<h;++b){let y=f[b],v=M(()=>e(y,p));if(s==null)d=v[0],p=v[1];else{let x=M(()=>{let k=m[b],C=fe(Zn(k),k),N=Y(V(v[0],k),V(p[0],C)),F=p.map((R,O)=>Y(V(v[1][O],k),V(R,C)));return{output:N,newStates:F}});d=x.output,p=x.newStates}i&&u.push(d)}let g;return i&&(g=Ot(u,1)),[d,g,p]})}var ps=class extends qe{constructor(e){super(e);let t;if(e.cell==null)throw new H("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Xf({cells:e.cell}):t=e.cell,t.stateSize==null)throw new H("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 Bt({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 zr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Ev(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],r;if(this.returnSequences?r=[e[0],e[1],n]:r=[e[0],n],this.returnState){let s=[];for(let a of t)s.push([e[0],a]);return[r].concat(s)}else return r}computeMask(e,t){return M(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let r=this.states.map(s=>null);return[n].concat(r)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){let t=null;if(this.numConstants!=null)throw new Fe("Constants support is not implemented in RNN yet.");Ev(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new Bt({shape:[n,null,...r]});let s=[e[0]].concat(e.slice(2));if(t!=null)throw new Fe("Constants support is not implemented in RNN yet.");this.cell.build(s);let a;if(Array.isArray(this.cell.stateSize)?a=this.cell.stateSize:a=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(o=>o.shape[o.shape.length-1]),a))throw new H(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Bt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){M(()=>{if(!this.stateful)throw new As("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new H("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>St([n,r])):this.states_=[St([n,this.cell.stateSize])];else if(e==null)De(this.states_),this.keptStates!=null&&(De(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>St([n,r])):this.states_[0]=St([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`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()):De(this.states_);for(let r=0;r<this.states_.length;++r){let s=e[r],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[r]:this.cell.stateSize,o=[n,a];if(!w.arraysEqual(s.shape,o))throw new H(`State ${r} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${s.shape}`);this.states_[r]=s}}this.states_=this.states_.map(r=>Jt(r.clone()))})}apply(e,t){let n=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});let s=GS(e,n,r,this.numConstants);e=s.inputs,n=s.initialState,r=s.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let c of n)this.stateSpec.push(new Bt({shape:c.shape}));o=o.concat(this.stateSpec)}if(r!=null&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof Vr){let c=[e].concat(a),l=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=l;let d=super.apply(c,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return M(()=>{let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;e=Oe(e),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new H(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:r},c=HS((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),l=c[0],u=c[1],d=c[2];this.stateful&&this.resetStates(d,r);let p=this.returnSequences?u:l;return this.returnState?[p].concat(d):p})}getInitialState(e){return M(()=>{let t=St(e.shape);return t=ve(t,[1,2]),t=dd(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?xv(t,[1,n]):t):this.cell.stateSize>1?[xv(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()===ps.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let r=t.cell,s=Ur(r,n);return new e(Object.assign(t,{cell:s}))}};ps.className="RNN";ie.registerClass(ps);var kd=class extends qe{},qf=class extends kd{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,en(this.units,"units"),this.activation=va(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ct(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ct(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ct(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=qt(e.kernelConstraint),this.recurrentConstraint=qt(e.recurrentConstraint),this.biasConstraint=qt(e.biasConstraint),this.dropout=fu([1,ga([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fu([1,ga([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=at(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return M(()=>{if(e=e,e.length!==2)throw new H(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let r=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xa({ones:()=>Zn(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xa({ones:()=>Zn(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));let s,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?s=us(V(e,a),this.kernel.read()):s=us(e,this.kernel.read()),this.bias!=null&&(s=Wr(s,this.bias.read())),o!=null&&(n=V(n,o));let i=Y(s,us(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ya(this.activation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:jt(this.kernelConstraint),recurrentConstraint:jt(this.recurrentConstraint),biasConstraint:jt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};qf.className="SimpleRNNCell";ie.registerClass(qf);var cx=class extends ps{constructor(e){e.cell=new qf(e);super(e)}call(e,t){return M(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return new e(t)}};cx.className="SimpleRNN";ie.registerClass(cx);var Kf=class extends kd{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 H("GRUCell does not support reset_after parameter set to true.");this.units=e.units,en(this.units,"units"),this.activation=va(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=va(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ct(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ct(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ct(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=qt(e.kernelConstraint),this.recurrentConstraint=qt(e.recurrentConstraint),this.biasConstraint=qt(e.biasConstraint),this.dropout=fu([1,ga([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fu([1,ga([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=at(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return M(()=>{if(e=e,e.length!==2)throw new H(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,r=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xa({ones:()=>Zn(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xa({ones:()=>Zn(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,a=this.recurrentDropoutMask,o,i,c;0<this.dropout&&this.dropout<1&&(e=V(e,s[0]));let l=us(e,this.kernel.read());this.useBias&&(l=Wr(l,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(r=V(r,a[0]));let u=this.recurrentKernel.read(),[d,p]=Ln(u,[2*this.units,this.units],u.rank-1),h=us(r,d),[f,m,g]=Ln(l,3,l.rank-1),[b,y]=Ln(h,2,h.rank-1);o=this.recurrentActivation.apply(Y(f,b)),i=this.recurrentActivation.apply(Y(m,y));let v=us(V(i,r),p);c=this.activation.apply(Y(g,v));let x=Y(V(o,r),V(Y(1,It(o)),c));return[x,x]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ya(this.activation),recurrentActivation:ya(this.recurrentActivation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:jt(this.kernelConstraint),recurrentConstraint:jt(this.recurrentConstraint),biasConstraint:jt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Kf.className="GRUCell";ie.registerClass(Kf);var ux=class extends ps{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 Kf(e);super(e)}call(e,t){return M(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};ux.className="GRU";ie.registerClass(ux);var Id=class extends kd{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,en(this.units,"units"),this.activation=va(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=va(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ct(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ct(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ct(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Tt(e.kernelRegularizer),this.recurrentRegularizer=Tt(e.recurrentRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.kernelConstraint=qt(e.kernelConstraint),this.recurrentConstraint=qt(e.recurrentConstraint),this.biasConstraint=qt(e.biasConstraint),this.dropout=fu([1,ga([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fu([1,ga([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=at(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let r;if(this.useBias){if(this.unitForgetBias){let s=this.biasInitializer,a=this.units;r=new(t=class extends Cr{apply(i,c){let l=s.apply([a]),u=new Tf().apply([a]),d=s.apply([a*2]);return zI(zI(l,u),d)}},t.className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return M(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new H(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1],s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xa({ones:()=>Zn(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xa({ones:()=>Zn(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,c,l,u;0<this.dropout&&this.dropout<1&&(e=V(e,a[0]));let d=us(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(r=V(r,o[0])),d=Y(d,us(r,this.recurrentKernel.read())),this.useBias&&(d=Wr(d,this.bias.read()));let[p,h,f,m]=Ln(d,4,d.rank-1);i=this.recurrentActivation.apply(p),c=this.recurrentActivation.apply(h),l=Y(V(c,s),V(i,this.activation.apply(f))),u=this.recurrentActivation.apply(m);let g=V(u,this.activation.apply(l));return[g,g,l]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ya(this.activation),recurrentActivation:ya(this.recurrentActivation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),recurrentInitializer:At(this.recurrentInitializer),biasInitializer:At(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:pt(this.kernelRegularizer),recurrentRegularizer:pt(this.recurrentRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:jt(this.kernelConstraint),recurrentConstraint:jt(this.recurrentConstraint),biasConstraint:jt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};Id.className="LSTMCell";ie.registerClass(Id);var lx=class extends ps{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 Id(e);super(e)}call(e,t){return M(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};lx.className="LSTM";ie.registerClass(lx);var Xf=class extends kd{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 M(()=>{e=e;let n=e.slice(1),r=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?r.push(n.splice(0,o.stateSize.length)):r.push(n.splice(0,1));r.reverse();let s=[],a;for(let o=0;o<this.cells.length;++o){let i=this.cells[o];n=r[o],o===0?a=[e[0]].concat(n):a=[a[0]].concat(n),a=i.call(a,t),s.push(a.slice(1))}n=[];for(let o of s.slice().reverse())n.push(...o);return[a[0]].concat(n)})}build(e){Ev(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,r)=>{ai(`RNNCell_${r}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=s=>({className:s.getClassName(),config:s.getConfig()}),r={cells:this.cells.map(t)};return Object.assign({},e,r)}static fromConfig(e,t,n={}){let r=[];for(let s of t.cells)r.push(Ur(s,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return Av(e)}setWeights(e){let t=[];for(let n of this.cells){let r=n.weights.length,s=e.splice(r);for(let a=0;a<n.weights.length;++a)t.push([n.weights[a],s[a]])}Dv(t)}};Xf.className="StackedRNNCells";ie.registerClass(Xf);function xa(e){let{ones:t,rate:n,training:r=!1,count:s=1,dropoutFunc:a}=e,o=()=>a!=null?a(t(),n):VI(t(),n),i=()=>hd(o,t,r);return!s||s<=1?Jt(i().clone()):Array(s).fill(void 0).map(i).map(l=>Jt(l.clone()))}var yV=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n},jS=class extends ps{constructor(e){if(e.unroll)throw new Fe("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Fe("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Bt({ndim:5})]}call(e,t){return M(()=>{if(this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new H("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return M(()=>{let{stateSize:t}=this.cell,n=e.shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)],a=St(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){M(()=>{if(!this.stateful)throw new As("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)];if(n[0]==null)throw new H("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(()=>St(s)):this.states_=[St(s)];else if(e==null)De(this.states_),this.keptStates!=null&&(De(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>St(s)):this.states_[0]=St(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`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()):De(this.states_);for(let o=0;o<this.states_.length;++o){let i=e[o],c=s;if(!w.arraysEqual(i.shape,c))throw new H(`State ${o} is incompatible with layer ${this.name}: expected shape=${c}, received shape=${i.shape}`);this.states_[o]=i}}this.states_=this.states_.map(o=>Jt(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:r,padding:s,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",c=e[i?3:2],l=e[i?4:3],u=Gr(c,r[0],s,a[0],o[0]),d=Gr(l,r[1],s,a[1],o[1]);return[...e.slice(0,2),...i?[n,u,d]:[u,d,n]]}};jS.className="ConvRNN2D";var Yf=class extends Id{constructor(e){let{filters:t,kernelSize:n,strides:r,padding:s,dataFormat:a,dilationRate:o}=e;super(Object.assign({},e,{units:t}));this.filters=t,en(this.filters,"filters"),this.kernelSize=vu(n,2,"kernelSize"),this.kernelSize.forEach(i=>en(i,"kernelSize")),this.strides=vu(r||1,2,"strides"),this.strides.forEach(i=>en(i,"strides")),this.padding=s||"valid",lr(this.padding),this.dataFormat=a||"channelsLast",Mt(this.dataFormat),this.dilationRate=vu(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>en(i,"dilationRate"))}build(e){var t;e=at(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new H(`The channel dimension of the input should be defined. Found ${e[n]}`);let r=e[n],s=4,a=this.kernelSize.concat([r,this.filters*s]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*s]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let c=this.biasInitializer,l=this.filters;i=new(t=class extends Cr{apply(d,p){let h=c.apply([l]),f=Yn([l]),m=c.apply([l*2]);return vv([h,f,m])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*s],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return M(()=>{if(e.length!==3)throw new H(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,r=e[0],s=e[1],a=e[2],o=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=xa({ones:()=>Zn(r),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,c=(ee,te,ne)=>!te||!te[ne]?ee:V(te[ne],ee),l=c(r,i,0),u=c(r,i,1),d=c(r,i,2),p=c(r,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=xa({ones:()=>Zn(s),rate:this.recurrentDropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,f=c(s,h,0),m=c(s,h,1),g=c(s,h,2),b=c(s,h,3),y=3,[v,x,k,C]=Ln(this.kernel.read(),o,y),[N,F,R,O]=this.useBias?Ln(this.bias.read(),o):[null,null,null,null];l=this.inputConv(l,v,N,this.padding),u=this.inputConv(u,x,F,this.padding),d=this.inputConv(d,k,R,this.padding),p=this.inputConv(p,C,O,this.padding);let[D,P,T,L]=Ln(this.recurrentKernel.read(),o,y);f=this.recurrentConv(f,D),m=this.recurrentConv(m,P),g=this.recurrentConv(g,T),b=this.recurrentConv(b,L);let G=this.recurrentActivation.apply(Y(l,f)),j=this.recurrentActivation.apply(Y(u,m)),q=Y(V(j,a),V(G,this.activation.apply(Y(d,g)))),K=V(this.recurrentActivation.apply(Y(p,b)),this.activation.apply(q));return[K,K,q]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=yV(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,r)}inputConv(e,t,n,r){let s=Rt(e,t,this.strides,r||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Wr(s,n,this.dataFormat):s}recurrentConv(e,t){return Rt(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Yf.className="ConvLSTM2DCell";ie.registerClass(Yf);var dx=class extends jS{constructor(e){let t=new Yf(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};dx.className="ConvLSTM2D";ie.registerClass(dx);var Zf=class extends qe{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let r=0;r<this.noiseShape.length;++r)n.push(this.noiseShape[r]==null?t[r]:this.noiseShape[r]);return n}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);if(0<this.rate&&this.rate<1){let r=t.training==null?!1:t.training,s=this.getNoiseShape(n);return hd(()=>VI(n,this.rate,s,this.seed),()=>n,r)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Zf.className="Dropout";ie.registerClass(Zf);var px=class extends Zf{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};px.className="SpatialDropout1D";ie.registerClass(px);var hx=class extends qe{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,en(this.units,"units"),this.activation=va(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Ct(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ct(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=qt(e.kernelConstraint),this.biasConstraint=qt(e.biasConstraint),this.kernelRegularizer=Tt(e.kernelRegularizer),this.biasRegularizer=Tt(e.biasRegularizer),this.activityRegularizer=Tt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=at(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=at(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e),r=DI(this.activation.getClassName()),s;return r!=null?s=us(n,this.kernel.read(),r,this.bias?this.bias.read():null):(s=us(n,this.kernel.read()),this.bias!=null&&(s=Wr(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:ya(this.activation),useBias:this.useBias,kernelInitializer:At(this.kernelInitializer),biasInitializer:At(this.biasInitializer),kernelRegularizer:pt(this.kernelRegularizer),biasRegularizer:pt(this.biasRegularizer),activityRegularizer:pt(this.activityRegularizer),kernelConstraint:jt(this.kernelConstraint),biasConstraint:jt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};hx.className="Dense";ie.registerClass(hx);var fx=class extends qe{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=at(e);for(let t of e.slice(1))if(t==null)throw new H(`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],ma(e,1)]}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let r=[0];for(let s=2;s<n.rank;++s)r.push(s);r.push(1),n=Re(n,r)}return M4(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};fx.className="Flatten";ie.registerClass(fx);var mx=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.activation=va(e.activation)}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);return this.activation.apply(n)})}getConfig(){let e={activation:ya(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};mx.className="Activation";ie.registerClass(mx);var gx=class extends qe{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return M(()=>(e=Oe(e),P4(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};gx.className="RepeatVector";ie.registerClass(gx);var bx=class extends qe{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",r=t.slice(),s=1,a=null;for(let i=0;i<r.length;++i){let c=r[i];if(this.isUnknown(c))if(a===null)a=i;else throw new H("Can only specifiy one unknown dimension.");else s*=c}let o=ma(e);if(a!==null){if(s===0||o%s!=0)throw new H(n);r[a]=o/s}else if(o!==s)throw new H(n);return r}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e),r=n.shape,s=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return U(n,s)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};bx.className="Reshape";ie.registerClass(bx);var yx=class extends qe{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=zr(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 Bt({ndim:this.dims.length+1})]}computeOutputShape(e){e=at(e);let t=e.slice();return this.dims.forEach((n,r)=>{t[r+1]=e[n]}),t}call(e,t){return Re(Oe(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};yx.className="Permute";ie.registerClass(yx);var vx=class extends qe{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Oe(e),r=-1;return jl(Jo(n,this.maskValue),r)}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e),r=-1,s=!0,a=jl(Jo(n,this.maskValue),r,s);return V(n,ce(a,n.dtype))})}};vx.className="Masking";ie.registerClass(vx);var xx=class extends qe{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(bt(e.inputLength))}this.inputDim=e.inputDim,en(this.inputDim,"inputDim"),this.outputDim=e.outputDim,en(this.outputDim,"outputDim"),this.embeddingsInitializer=Ct(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Tt(e.embeddingsRegularizer),this.activityRegularizer=Tt(e.activityRegularizer),this.embeddingsConstraint=qt(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 M(()=>this.maskZero?(e=Oe(e),Jo(e,Ue(e))):null)}computeOutputShape(e){if(e=at(e),this.inputLength==null)return[...e,this.outputDim];let t=bt(this.inputLength);if(t.length!==e.length-1)throw new H(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r<t.length;++r){let s=t[r],a=e[r+1];if(s!=null&&a!=null&&s!==a)throw new H(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);n.dtype!=="int32"&&(n=If(n,"int32"));let r=WI(this.embeddings.read(),U(n,[n.size]));return U(r,at(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:At(this.embeddingsInitializer),embeddingsRegularizer:pt(this.embeddingsRegularizer),activityRegularizer:pt(this.activityRegularizer),embeddingsConstraint:jt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};xx.className="Embedding";ie.registerClass(xx);var li=class extends qe{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Fe}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let r=0;r<t.length;++r){let s=e[e.length-t.length+r],a=t[r];if(s==null||a==null||s<0||a<0)n.push(null);else if(s===1)n.push(a);else if(a===1)n.push(s);else{if(s!==a)throw new H("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(s)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[at(e)]),e=e,e.length<2)throw new H(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let s of e)s!=null&&s[0]!==null&&t.push(s[0]);if(t=fa(t),t.length>1)throw new H(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let s=1;s<e.length;++s){let a=e[s]==null?null:e[s].slice(1);n=this.computeElementwiseOpOutputShape(n,a)}let r=e.map(s=>s.length);e.indexOf(null)===-1&&fa(r).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return M(()=>{if(e=e,this.reshapeRequired){let n=[],r=e.map(s=>s.rank);if(r.indexOf(null)===-1){let s=ga(r);for(let a of e){let o=a.rank;for(let i=0;i<s-o;++i)a=dd(a,1);n.push(a)}return this.mergeFunction(n)}else{let s=!1;for(let i of e){let c=i.rank;if(c==null){let l=i.shape,u=l[0],d=l.slice(1).concat([u]),p=U(i,[u].concat(ma(l.slice(1))));p=Re(p,[1,0]),p=U(p,d),n.push(p),s=!0}else if(c>1){let l=zr(1,c).concat([0]);n.push(Re(i,l)),s=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(s){if(o==null){let i=a.shape,c=i.length,l=i[c-1],u=[l].concat(i.slice(0,i.length-1));a=U(Re(U(a,[-1,l]),[1,0]),u)}else if(o>1){let i=[o-1].concat(zr(0,o-1));a=Re(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let r=1;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let n=[];for(let r of e)r!=null&&r[0]!==null&&n.push(r[0]);return n=fa(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return M(()=>{if(t==null)return null;if(!Array.isArray(t))throw new H("`mask` should be an Array");if(!Array.isArray(e))throw new H("`inputs` should be an Array");if(t.length!==e.length)throw new H(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(r=>r==null))return null;t=t.map(r=>r==null?r:bn(r,0));let n=t[0];for(let r=1;r<t.length-1;++r)n=Ir(n,t[r]);return n})}},wx=class extends li{constructor(e){super(e)}mergeFunction(e){return M(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Y(t,e[n]);return t})}};wx.className="Add";ie.registerClass(wx);var kx=class extends li{constructor(e){super(e)}mergeFunction(e){return M(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=V(t,e[n]);return t})}};kx.className="Multiply";ie.registerClass(kx);var Ix=class extends li{constructor(e){super(e)}mergeFunction(e){return M(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Y(t,e[n]);return V(1/e.length,t)})}};Ix.className="Average";ie.registerClass(Ix);var Sx=class extends li{constructor(e){super(e)}mergeFunction(e){return M(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=as(t,e[n]);return t})}};Sx.className="Maximum";ie.registerClass(Sx);var Cx=class extends li{constructor(e){super(e)}mergeFunction(e){return M(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ou(t,e[n]);return t})}};Cx.className="Minimum";ie.registerClass(Cx);var Tx=class extends li{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 H("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let r of e)if(r!=null){t=!1;break}if(t)return;let n=[];for(let r=0;r<e.length;++r){let s=e[r].slice();s.splice(this.axis,1);let a=!1;for(let o of n)if(w.arraysEqual(o,s)){a=!0;break}a||n.push(s)}if(n.length>1)throw new H("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return M(()=>vv(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new H("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(let s of t.slice(1)){if(n[r]==null||s[r]==null){n[r]=null;break}n[r]+=s[r]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new H("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new H("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new H(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return M(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let r=[];for(let a=0;a<e.length;++a)t[a]==null?r.push(ce(Zn(e[a]),"bool")):t[a].rank<e[a].rank?r.push(bn(t[a],-1)):r.push(t[a]);let s=Ze(r,this.axis);return Bh(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Tx.className="Concatenate";ie.registerClass(Tx);function Sd(e,t){for(;e<0;)e+=t;return e}function vV(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Fe("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 Fe("batchDot is not implemented for complex64-type Tensors yet.");let r=e.shape.length,s=t.shape.length;n==null&&(n=[r-1,s-2]);let a=n;return M(()=>{let o;if(r>s){o=r-s;let c=[];for(let l=0;l<o;++l)c.push(1);t=U(t,t.shape.concat(c))}else if(s>r){o=s-r;let c=[];for(let l=0;l<o;++l)c.push(1);e=U(e,e.shape.concat(c))}else o=0;let i;if(e.shape.length===2&&t.shape.length===2)a[0]===a[1]?i=ve(V(e,t),a[0]):i=ve(V(Re(e,[1,0]),t),a[1]);else{let c=a[0]!==e.shape.length-1,l=a[1]===t.shape.length-1;i=Ae(e,t,c,l)}if(o>0){let c;r>s?c=r+s-3:c=r-1;let l=[];for(let u=c;u<c+o;++u)l.push(u);i=os(i,l)}return i.shape.length===1&&(i=bn(i,1)),i})}var Nx=class extends li{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 Fe("Dot layer does not support tensors of 4D or higher rank yet.");let r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new H(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(e.length!==2)throw new H(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],r;return Array.isArray(this.axes)?r=this.axes.map((s,a)=>Sd(s,e[a].shape.length)):r=[Sd(this.axes,t.shape.length),Sd(this.axes,n.shape.length)],this.normalize&&(t=Lf(t,r[0]),n=Lf(n,r[1])),vV(t,n,r)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Sd(this.axes,e.length),Sd(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 Fe("Dot layer does not support tensors of 4D or higher rank yet.");let r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);let s=t.concat(n);return s.length===1&&s.push(1),s}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};Nx.className="Dot";ie.registerClass(Nx);var _x=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);return hd(()=>Y(Cf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};_x.className="GaussianNoise";ie.registerClass(_x);var Ex=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return M(()=>{this.invokeCallHook(e,t);let n=Oe(e);return this.rate>0&&this.rate<1?hd(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return V(n,Cf(n.shape,1,s))},()=>n,t.training||!1):n})}};Ex.className="GaussianDropout";ie.registerClass(Ex);var Ax=class extends qe{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Oe(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 M(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return hd(()=>{let s=Oe(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,c=da(iu(n),this.rate);c=If(c,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate,d=Y(V(s,c),V(Y(c,-1),i));return Y(V(d,l),u)},()=>Oe(e),t.training||!1)}return e})}};Ax.className="AlphaDropout";ie.registerClass(Ax);function Cd(e,t,n,r,s,a=.001){let o;if(e.rank===2)o=wk(e,t,n,r,s,a);else if(e.rank===3)o=kk(e,t,n,r,s,a);else if(e.rank===4)o=Ik(e,t,n,r,s,a);else throw new Fe(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function xV(e,t,n,r,s=.001){return M(()=>{let a=Yh(e,r),o=a.mean,i=a.variance;return[Cd(e,o,i,n,t,s),o,i]})}function wV(e,t,n,r,s=.001){return M(()=>{let a=Yh(e,r),o=a.mean,i=a.variance,c=[];for(let f of zr(0,e.rank))r.indexOf(f)!==-1?c.push(1):c.push(e.shape[f]);let l=U(o,c),u=U(i,c),d=t==null?null:U(t,c),p=n==null?null:U(n,c);return[Cd(e,l,u,p,d,s),o,i]})}function kV(e,t,n,r,s=.001){return w.arraysEqual(r.slice().sort(),zr(0,e.rank-1))?xV(e,t,n,r,s):wV(e,t,n,r,s)}var Dx=class extends qe{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Ct(e.betaInitializer||"zeros"),this.gammaInitializer=Ct(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ct(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ct(e.movingVarianceInitializer||"ones"),this.betaConstraint=qt(e.betaConstraint),this.gammaConstraint=qt(e.gammaConstraint),this.betaRegularizer=Tt(e.betaRegularizer),this.gammaRegularizer=Tt(e.gammaRegularizer)}build(e){e=at(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new H(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Bt({ndim:e.length,axes:{[t]:n}})];let r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return M(()=>{let n=t.training==null?!1:t.training,r=Oe(e),s=r.shape,a=s.length,o=zr(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let c=ni(1,a);c[i]=s[i];let l=o.slice();l.sort();let u=!w.arraysEqual(l,zr(0,a).slice(0,a-1)),d=()=>{if(u){let b=U(this.movingMean.read(),c),y=U(this.movingVariance.read(),c),v=this.center?U(this.beta.read(),c):null,x=this.scale?U(this.gamma.read(),c):null;return Cd(r,b,y,v,x,this.epsilon)}else return Cd(r,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[p,h,f]=kV(r,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(b,y,v)=>{M(()=>{let x=1-v,k=b.read(),C=V(fe(k,y),x);b.write(fe(k,C))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:At(this.betaInitializer),gammaInitializer:At(this.gammaInitializer),movingMeanInitializer:At(this.movingMeanInitializer),movingVarianceInitializer:At(this.movingVarianceInitializer),betaRegularizer:pt(this.betaRegularizer),gammaRegularizer:pt(this.gammaRegularizer),betaConstraint:jt(this.betaConstraint),gammaConstraint:jt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Dx.className="BatchNormalization";ie.registerClass(Dx);var Fx=class extends qe{constructor(e){e==null&&(e={});super(e);if(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=Ct(e.betaInitializer||"zeros"),this.gammaInitializer=Ct(e.gammaInitializer||"ones"),this.betaRegularizer=Tt(e.betaRegularizer),this.gammaRegularizer=Tt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=at(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let s=0;s<this.axis.length;++s)this.axis[s]<0&&(this.axis[s]+=t);for(let s of this.axis)if(s<0||s>=t)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==fa(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(s=>e[s]),r=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){let n=Oe(e),r=n.shape,s=r.length;return M(()=>{let a=!0,{mean:o,variance:i}=Yh(n,this.axis,a),c=ni(1,s);for(let f of this.axis)c[f]=r[f];let l=f=>f!=null&&f.shape.length!==s?U(f,c):f,u=l(this.gamma.read()),d=l(this.beta.read()),p=[],h=[];for(let f=0;f<s;++f)this.axis.indexOf(f)!==-1?(p.push(r[f]),h.push(1)):(p.push(1),h.push(r[f]));return o=On(o,p),i=On(i,p),u=On(u,h),d=On(d,h),Cd(n,o,i,d,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:At(this.betaInitializer),gammaInitializer:At(this.gammaInitializer),betaRegularizer:pt(this.betaRegularizer),gammaRegularizer:pt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Fx.className="LayerNormalization";ie.registerClass(Fx);function IV(e,t,n){return M(()=>{if(e.rank!==4)throw new H(`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 H("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=Lr()),n!=="channelsLast"&&n!=="channelsFirst")throw new H(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let r;return n==="channelsFirst"?r=[[0,0],[0,0],t[0],t[1]]:r=[[0,0],t[0],t[1],[0,0]],ur(e,r)})}var $x=class extends qe{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?Lr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new H(`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 H(`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 H(`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 Bt({ndim:4})]}computeOutputShape(e){e=at(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return M(()=>IV(Oe(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};$x.className="ZeroPadding2D";ie.registerClass($x);function Jf(e,t,n,r,s,a){return M(()=>{Mt(s),PI(a),lr(r),n==null&&(n=[1,1]),r==null&&(r="valid"),s==null&&(s=Lr()),a==null&&(a="max"),e=ex(e,s);let o,i=r==="same"?"same":"valid";return a==="max"?o=Pt(e,t,n,i):o=ir(e,t,n,i),s==="channelsFirst"&&(o=Re(o,[0,3,1,2])),o})}function qS(e,t,n,r,s,a){return M(()=>{Mt(s),PI(a),lr(r),n==null&&(n=[1,1,1]),r==null&&(r="valid"),s==null&&(s=Lr()),a==null&&(a="max"),e=WS(e,s);let o,i=r==="same"?"same":"valid";return a==="max"?o=Gy(e,t,n,i):o=_y(e,t,n,i),s==="channelsFirst"&&(o=Re(o,[0,4,1,2,3])),o})}var KS=class extends qe{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(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 H(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(en(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 H(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);en(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,lr(this.padding),this.inputSpec=[new Bt({ndim:3})]}computeOutputShape(e){e=at(e);let t=Gr(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return M(()=>{this.invokeCallHook(e,t),e=dd(Oe(e),2);let n=this.poolingFunction(Oe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return os(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Rx=class extends KS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),Jf(e,t,n,r,s,"max")}};Rx.className="MaxPooling1D";ie.registerClass(Rx);var Px=class extends KS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),Jf(e,t,n,r,s,"avg")}};Px.className="AveragePooling1D";ie.registerClass(Px);var XS=class extends qe{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(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 H(`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];en(this.poolSize,"poolSize"),en(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),lr(this.padding),this.inputSpec=[new Bt({ndim:4})]}computeOutputShape(e){e=at(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Gr(t,this.poolSize[0],this.padding,this.strides[0]),n=Gr(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 M(()=>(this.invokeCallHook(e,t),this.poolingFunction(Oe(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}},Ox=class extends XS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),Jf(e,t,n,r,s,"max")}};Ox.className="MaxPooling2D";ie.registerClass(Ox);var Mx=class extends XS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),Jf(e,t,n,r,s,"avg")}};Mx.className="AveragePooling2D";ie.registerClass(Mx);var YS=class extends qe{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(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 H(`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];en(this.poolSize,"poolSize"),en(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),lr(this.padding),this.inputSpec=[new Bt({ndim:5})]}computeOutputShape(e){e=at(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Gr(t,this.poolSize[0],this.padding,this.strides[0]),n=Gr(n,this.poolSize[1],this.padding,this.strides[1]),r=Gr(r,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return M(()=>(this.invokeCallHook(e,t),this.poolingFunction(Oe(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}},Lx=class extends YS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),qS(e,t,n,r,s,"max")}};Lx.className="MaxPooling3D";ie.registerClass(Lx);var Bx=class extends YS{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Mt(s),lr(r),qS(e,t,n,r,s,"avg")}};Bx.className="AveragePooling3D";ie.registerClass(Bx);var ZS=class extends qe{constructor(e){super(e);this.inputSpec=[new Bt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Fe}},zx=class extends ZS{constructor(e){super(e||{})}call(e,t){return M(()=>{let n=Oe(e);return Et(n,1)})}};zx.className="GlobalAveragePooling1D";ie.registerClass(zx);var Wx=class extends ZS{constructor(e){super(e||{})}call(e,t){return M(()=>{let n=Oe(e);return kr(n,1)})}};Wx.className="GlobalMaxPooling1D";ie.registerClass(Wx);var JS=class extends qe{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Mt(this.dataFormat),this.inputSpec=[new Bt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Fe}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Vx=class extends JS{call(e,t){return M(()=>{let n=Oe(e);return this.dataFormat==="channelsLast"?Et(n,[1,2]):Et(n,[2,3])})}};Vx.className="GlobalAveragePooling2D";ie.registerClass(Vx);var Ux=class extends JS{call(e,t){return M(()=>{let n=Oe(e);return this.dataFormat==="channelsLast"?kr(n,[1,2]):kr(n,[2,3])})}};Ux.className="GlobalMaxPooling2D";ie.registerClass(Ux);var QS=class extends qe{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let r=t.layer,s=Ur(r,n);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},Gx=class extends QS{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=at(e),e.length<3)throw new H(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=at(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return M(()=>(e=Oe(e),HS((a,o)=>[Oe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Gx.className="TimeDistributed";ie.registerClass(Gx);function SV(e){si(A4,"BidirectionalMergeMode",e)}var CV="concat",Hx=class extends QS{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Ur(n),t.goBackwards=t.goBackwards!==!0;let r={};if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=Ur(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?CV:e.mergeMode,SV(this.mergeMode),e.weights)throw new Fe("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,r,s;return this.returnState&&(s=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,r=[n]):this.mergeMode==null?r=[n,n.slice()]:r=[n],this.returnState?this.mergeMode==null?r.concat(s).concat(s.slice()):[n].concat(s).concat(s.slice()):Bn(r)}apply(e,t){let n=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});let s=GS(e,n,r,this.numConstants);if(e=s.inputs,n=s.initialState,r=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&r==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let c=n.length;if(c%2>0)throw new H("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let l=n.map(u=>new Bt({shape:u.shape}));this.forwardLayer.stateSpec=l.slice(0,c/2),this.backwardLayer.stateSpec=l.slice(c/2),o.push(...l)}if(r!=null)throw new Fe("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof Vr;for(let c of a)if(c instanceof Vr!==i)throw new H("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let c=[e].concat(a),l=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=l;let d=super.apply(c,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return M(()=>{let n=t.initialState,r,s;if(n==null)r=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),c=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:c}))}let a;this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(s.slice(1))),r=r[0],s=s[0]),this.returnSequences&&(s=Jn(s,1));let o;return this.mergeMode==="concat"?o=vv([r,s]):this.mergeMode==="sum"?o=Y(r,s):this.mergeMode==="ave"?o=V(.5,Y(r,s)):this.mergeMode==="mul"?o=V(r,s):this.mergeMode==null&&(o=[r,s]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){ai(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),ai(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let s=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(s).concat(s):[n].concat(s).concat(s)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=Ur(t.layer);if(delete t.layer,t.numConstants!=null)throw new Fe("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let r=t;return r.layer=n,new e(r)}};Hx.className="Bidirectional";ie.registerClass(Hx);function TV(e){return new mu(e)}function NV(e){return new Zv(e)}function _V(e){return new Kv(e)}function EV(e){return new Xv(e)}function AV(e){return new Yv(e)}function DV(e){return new Qv(e)}function FV(e){return new Jv(e)}function $V(e){return new jf(e)}function RV(e){return new xd(e)}function PV(e){return new nx(e)}function OV(e){return new wd(e)}function MV(e){return new rx(e)}function LV(e){return new sx(e)}function BV(e){return new ax(e)}function zV(e){return new ox(e)}function WV(e){return new ix(e)}function VV(e){return new mx(e)}function UV(e){return new hx(e)}function GV(e){return new Zf(e)}function HV(e){return new px(e)}function jV(e){return new fx(e)}function qV(e){return new gx(e)}function KV(e){return new bx(e)}function XV(e){return new yx(e)}function YV(e){return new xx(e)}function ZV(e){return new wx(e)}function JV(e){return new Ix(e)}function QV(e){return new Tx(e)}function eU(e){return new Sx(e)}function tU(e){return new Cx(e)}function nU(e){return new kx(e)}function rU(e){return new Nx(e)}function sU(e){return new Dx(e)}function aU(e){return new Fx(e)}function oU(e){return new $x(e)}function jx(e){return new Px(e)}function iU(e){return jx(e)}function cU(e){return jx(e)}function qx(e){return new Mx(e)}function uU(e){return qx(e)}function lU(e){return qx(e)}function Kx(e){return new Bx(e)}function dU(e){return Kx(e)}function pU(e){return Kx(e)}function hU(e){return new zx(e)}function fU(e){return new Vx(e)}function eC(e){return new Wx(e)}function tC(e){return new Ux(e)}function nC(e){return new Rx(e)}function rC(e){return new Ox(e)}function mU(e){return new Lx(e)}function gU(e){return new ux(e)}function bU(e){return new Kf(e)}function yU(e){return new lx(e)}function vU(e){return new Id(e)}function xU(e){return new cx(e)}function wU(e){return new qf(e)}function kU(e){return new dx(e)}function IU(e){return new Yf(e)}function SU(e){return new ps(e)}function CU(e){return new Xf(e)}function TU(e){return new Hx(e)}function NU(e){return new Gx(e)}var _U=eC,EU=tC,AU=nC,DU=rC;function FU(e){return new _x(e)}function $U(e){return new Ex(e)}function RU(e){return new Ax(e)}function PU(e){return new vx(e)}var sC={};$e(sC,{MAPE:()=>jU,MSE:()=>XU,binaryAccuracy:()=>OU,binaryCrossentropy:()=>MU,categoricalAccuracy:()=>BU,categoricalCrossentropy:()=>zU,cosineProximity:()=>UU,mape:()=>qU,meanAbsoluteError:()=>GU,meanAbsolutePercentageError:()=>HU,meanSquaredError:()=>KU,mse:()=>YU,precision:()=>WU,recall:()=>VU,sparseCategoricalAccuracy:()=>LU});function OU(e,t){return Rv(e,t)}function MU(e,t){return oS(e,t)}function LU(e,t){return iS(e,t)}function BU(e,t){return Pv(e,t)}function zU(e,t){return Ov(e,t)}function WU(e,t){return aS(e,t)}function VU(e,t){return CW(e,t)}function UU(e,t){return Fv(e,t)}function GU(e,t){return Bf(e,t)}function HU(e,t){return bu(e,t)}function jU(e,t){return bu(e,t)}function qU(e,t){return bu(e,t)}function KU(e,t){return ii(e,t)}function XU(e,t){return ii(e,t)}function YU(e,t){return ii(e,t)}var aC={};$e(aC,{modelFromJSON:()=>aV});var oC={};$e(oC,{l1:()=>JU,l1l2:()=>ZU,l2:()=>QU});function ZU(e){return new yd(e)}function JU(e){return hV(e)}function QU(e){return fV(e)}var iC=class extends gu{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Fs))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Qf(e,t){return e<t}function cC(e,t){return e>t}var uC=class extends iC{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Fe("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=Qf:this.mode==="max"?this.monitorFunc=cC:this.monitor.indexOf("acc")!==-1?this.monitorFunc=cC:this.monitorFunc=Qf,this.monitorFunc===Qf&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Qf?1/0:-1/0}async onEpochEnd(e,t){await ba(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 eG(e){return new uC(e)}var tG={earlyStopping:eG},Hr;(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"})(Hr||(Hr={}));var lC;(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={}))})(lC||(lC={}));var Xx={};function nG(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Xx[e]=n}function dC(e){return Xx[e]}function rG(e){delete Xx[e]}function I(e,t,n,r,s){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,c=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Cn(t.inputNames[a.inputIndexStart],n,r,s);if(a.type==="tensors")return t.inputNames.slice(i,c).map(p=>Cn(p,n,r,s));let l=Cn(t.inputNames.slice(i)[0],n,r,s),u=l.dataSync();return a.type==="number"?u[0]:w.toNestedArray(l.shape,u)}let o=t.attrParams[e];return o&&o.value}function Cn(e,t,n,r){let[s,a]=er(e);if(r!=null){let i=r.getHashTableHandleByName(s);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[em(s,i)]);return o!==void 0?t[em(s,o)][a]:void 0}function sG(e,t,n){return t[em(e,n.currentContextId)]}function $s(e,t){let[n,r,s]=er(e);return[em(n,t&&t.currentContextId),r,s]}function em(e,t){return t?`${e}-${t}`:e}function er(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],r=t.length===3?t[1]:void 0,s=Number(t[t.length-1]);return[n,s,r]}function tm(e,t,n){let r=I("pad",e,t,n);if(r==="explicit"){r=I("explicitPaddings",e,t,n);let s=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)s[a][0]=r[a*2],s[a][1]=r[a*2+1];return s}return r}function Rs(e){return e.kept?e:Ss(e)}var pC={};$e(pC,{json:()=>aG});var aG=[{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}]}],hC={};$e(hC,{json:()=>oG});var oG=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],fC={};$e(fC,{json:()=>iG});var iG=[{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"}]}],mC={};$e(mC,{json:()=>cG});var cG=[{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"}]}],gC={};$e(gC,{json:()=>uG});var uG=[{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"}]}],bC={};$e(bC,{json:()=>lG});var lG=[{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}]}],yC={};$e(yC,{json:()=>dG});var dG=[{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"}]}],vC={};$e(vC,{json:()=>pG});var pG=[{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"}]}],xC={};$e(xC,{json:()=>hG});var hG=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],wC={};$e(wC,{json:()=>fG});var fG=[{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"}]}],kC={};$e(kC,{json:()=>mG});var mG=[{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}]}],IC={};$e(IC,{json:()=>gG});var gG=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],SC={};$e(SC,{json:()=>bG});var bG=[{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}]}],CC={};$e(CC,{json:()=>yG});var yG=[{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"}]}],TC={};$e(TC,{json:()=>vG});var vG=[{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}]}],NC={};$e(NC,{json:()=>xG});var xG=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],_C={};$e(_C,{json:()=>wG});var wG=[{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}]}],EC={};$e(EC,{json:()=>kG});var kG=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],AC={};$e(AC,{json:()=>IG});var IG=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],DC=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[pC,hC,fC,mC,gC,bC,yC,vC,xC,wC,kC,IC,SC,CC,TC,NC,_C,EC,AC],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,r)=>(n[r.tfOpName]=r,n),{})}transformGraph(e,t={}){let n=e.node,r=[],s=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?r.push(f[m.name]):m.op==="Const"?s.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],c=[],l={},u={};t!=null&&(l=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(o);d.forEach(f=>{let m=o[f];m.inputNames.forEach((g,b)=>{let[y,,v]=$s(g),x=o[y];if(x.outputs!=null){let k=x.outputs.indexOf(v);if(k!==-1){let C=`${y}:${k}`;m.inputNames[b]=C}}m.inputs.push(x),x.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=o[f];m.children.length===0&&c.push(m)}):Object.keys(u).forEach(f=>{let[m]=$s(f),g=o[m];g!=null&&(g.signatureKey=u[f],c.push(g))}),Object.keys(l).length>0?Object.keys(l).forEach(f=>{let[m]=$s(f),g=o[m];g&&(g.signatureKey=l[f],i.push(g))}):i=r;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:c,weights:s,placeholders:r,signature:t,functions:p};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=dC(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(r=>r.startsWith("^")?r.substr(1):r),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((r,s)=>(r[s.name]={type:s.type,inputIndexStart:s.start,inputIndexEnd:s.end},r),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((r,s)=>{let a=s.type,o;switch(s.type){case"string":o=Yx(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Yx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":o=sw(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=sw(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":o=Jx(e.attr,s.tfName,s.defaultValue||0),o===void 0&&!!s.tfDeprecatedName&&(o=Jx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":o=rw(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=rw(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":o=Zx(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Zx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":o=ow(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=ow(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":o=nw(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=nw(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":o=aw(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=aw(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":o=ew(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=ew(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":o=tw(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=tw(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":o=$C(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=$C(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${s.type} for op: ${e.op}`)}return r[s.name]={value:o,type:a},r},{})),n}mapFunction(e){let t=e.nodeDef,n=[],r=[],s={};t!=null&&(s=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&r.push(u[d.name]),u),{}));let a=[],o=[];e.signature.inputArg.forEach(u=>{let[d]=$s(u.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Qx(u.type),type:"dtype"}},children:[]};p.signatureKey=u.name,a.push(p),s[d]=p}),Object.keys(s).forEach(u=>{let d=s[u];d.inputNames.forEach((p,h)=>{let[f,,m]=$s(p),g=s[f];if(g.outputs!=null){let b=g.outputs.indexOf(m);if(b!==-1){let y=`${f}:${b}`;d.inputNames[h]=y}}d.inputs.push(g),g.children.push(d)})});let c=e.ret;e.signature.outputArg.forEach(u=>{let[d,p]=$s(c[u.name]),h=s[d];h!=null&&(h.defaultOutput=p,o.push(h))});let l=this.mapArgsToSignature(e);return{nodes:s,inputs:a,outputs:o,weights:r,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 SG(e){let t=J().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 FC(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):SG(e);return t?n:n.toLowerCase()}function Yx(e,t,n,r=!1){let s=e[t];return s!=null?FC(s.s,r):n}function Zx(e,t,n){let r=e[t];return r?r.b:n}function Jx(e,t,n){let r=e[t]||{},s=r.i!=null?r.i:r.f!=null?r.f:n;return typeof s=="number"?s:parseInt(s,10)}function Qx(e){switch(typeof e=="string"&&(e=Hr[e]),e){case Hr.DT_FLOAT:return"float32";case Hr.DT_INT32:case Hr.DT_INT64:case Hr.DT_INT8:case Hr.DT_UINT8:return"int32";case Hr.DT_BOOL:return"bool";case Hr.DT_DOUBLE:return"float32";case Hr.DT_STRING:return"string";default:return null}}function $C(e,t,n){let r=e[t];return r&&r.func?r.func.name:n}function ew(e,t,n){let r=e[t];return r&&r.type?Qx(r.type):n}function tw(e,t,n){let r=e[t];return r&&r.list&&r.list.type?r.list.type.map(s=>Qx(s)):n}function RC(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function nw(e,t,n){let r=e[t];return r&&r.shape?RC(r.shape):n}function rw(e,t,n){let r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(s=>typeof s=="number"?s:parseInt(s,10)):n}function sw(e,t,n,r=!1){let s=e[t];return s&&s.list&&s.list.s?s.list.s.map(a=>FC(a,r)):n}function aw(e,t,n){let r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(s=>RC(s)):n}function ow(e,t,n){let r=e[t];return r&&r.list&&r.list.b?r.list.b:n}var CG=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(r=>this.getInput(r)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((r,s)=>(r[s]=this.getAttr(s),r),{}))}getInput(e){return Cn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Cn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return Jx(this.node.rawAttrs,e,t);if(n.s!=null)return Yx(this.node.rawAttrs,e,t);if(n.b!=null)return Zx(this.node.rawAttrs,e,t);if(n.shape!=null)return nw(this.node.rawAttrs,e,t);if(n.type!=null)return ew(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return rw(this.node.rawAttrs,e,t);if(n.list.s!=null)return sw(this.node.rawAttrs,e,t);if(n.list.shape!=null)return aw(this.node.rawAttrs,e,t);if(n.list.b!=null)return ow(this.node.rawAttrs,e,t);if(n.list.type!=null)return tw(this.node.rawAttrs,e,t)}return t}},TG=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[Y(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[bk(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[jy(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[V(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[ge(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[Py(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[Lh(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[fe(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[ou(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[as(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[Ns(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[of(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},NG=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Lt(I("x",e,t,n))];case"Acos":return[yy(I("x",e,t,n))];case"Acosh":return[vy(I("x",e,t,n))];case"Asin":return[wy(I("x",e,t,n))];case"Asinh":return[ky(I("x",e,t,n))];case"Atan":return[Iy(I("x",e,t,n))];case"Atan2":return[Sy(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[Cy(I("x",e,t,n))];case"Ceil":return[Ay(I("x",e,t,n))];case"Complex":return[aa(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[Xl(I("x",e,t,n))];case"Cosh":return[Uh(I("x",e,t,n))];case"Elu":return[su(I("x",e,t,n))];case"Erf":return[Oy(I("x",e,t,n))];case"Exp":return[gn(I("x",e,t,n))];case"Expm1":return[My(I("x",e,t,n))];case"Floor":return[au(I("x",e,t,n))];case"Log":return[Xn(I("x",e,t,n))];case"Log1p":return[Zl(I("x",e,t,n))];case"Imag":return[Hh(I("x",e,t,n))];case"Neg":return[It(I("x",e,t,n))];case"Reciprocal":return[Xy(I("x",e,t,n))];case"Real":return[nd(I("x",e,t,n))];case"Relu":return[je(I("x",e,t,n))];case"Round":return[Qh(I("x",e,t,n))];case"Selu":return[tf(I("x",e,t,n))];case"Sigmoid":return[cr(I("x",e,t,n))];case"Sin":return[nf(I("x",e,t,n))];case"Sign":return[Yy(I("x",e,t,n))];case"Sinh":return[rf(I("x",e,t,n))];case"Softplus":return[Yo(I("x",e,t,n))];case"Sqrt":return[cn(I("x",e,t,n))];case"Square":return[ct(I("x",e,t,n))];case"Tanh":return[Ko(I("x",e,t,n))];case"Tan":return[Qy(I("x",e,t,n))];case"ClipByValue":return[Qt(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[Jh(I("x",e,t,n))];case"Rsqrt":return[ef(Cn(e.inputNames[0],t,n))];case"Prod":return[Zh(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[Yl(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[td(I("x",e,t,n),I("alpha",e,t,n))];case"IsNan":return[By(Cn(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Nr(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;r<e.length;r++){let s=e[r],a=t[r];w.assert(s<0||a<0||s===a,()=>n+` Shapes ${e} and ${t} must match`)}}}function PC(e){return!(typeof e=="number"||e.some(t=>t<0))}function Td(e,t,n){let r=iw(e,n),s=!PC(r);if(s&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach(a=>{r=iw(a.shape,r)}),!PC(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function iw(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let r=0;r<e.length;++r){let s=e[r],a=t[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}var _G=class{constructor(e,t,n,r,s,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Se(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),Nr(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,r)=>this.write(n,t[r]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let r=0;r<this.size();r++)e.push(r)}if(e.length===0)return qn([],[0].concat(this.elementShape));let n=this.readMany(e);return Nr(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ot(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return qn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Nr(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Ze(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,dt(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,a=[];M(()=>{t=U(t,[1,n,s]);for(let i=0;i<e.length;++i){let c=i===0?0:r[i-1],l=[0,c,0],u=[1,e[i],s];a[i]=U(We(t,l,u),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},Nd=class{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);Nr(t,s.shape,"TensorList shape mismatch: "),Jt(s)}),this.idTensor=Se(0),this.maxNumElements=r,Jt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Nd([...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.`);Nr(e,this.elementShape,"TensorList shape mismatch: ");let r=Td(this.elementShape,this.tensors,e);return M(()=>{let s=this.tensors.map(a=>U(a,r));return Ot(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Td(this.elementShape,this.tensors,e),r=this.tensors.pop();return Nr(r.shape,e,"TensorList shape mismatch: "),U(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Nr(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.`);Nr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r=Td(this.elementShape,this.tensors,t);return U(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Nr(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}`);Nr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r=Td(this.elementShape,this.tensors,n);return e.length===0?qn([],[0].concat(r)):M(()=>{let s=e.map(a=>U(this.tensors[a],r));return Ot(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Nr(this.elementShape,t,"TensorList shape mismatch: ");let n=Td(this.elementShape,this.tensors,t);return this.size()===0?qn([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return Ze(r,0)})}};function EG(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let s=e.shape.slice(1);Nr(s,t,"TensorList shape mismatch: ");let a=dt(e);return new Nd(a,t,r)}function AG(e,t,n){return new Nd([],e,t,n)}function DG(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let s=Math.max(...t);if(r!=null&&r!==-1&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);let a=new Nd([],n,e.dtype,r),o=dt(e,0);return t.forEach((i,c)=>{a.setItem(i,o[c])}),a}function FG(e,t,n){let r=0,s=t.map(u=>(r+=u,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${r}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=iw(a,n),i=r===0?0:e.size/r,c=M(()=>{let u=[];e=U(e,[1,r,i]);for(let d=0;d<t.length;++d){let p=d===0?0:s[d-1],h=[0,p,0],f=[1,t[d],i];u[d]=U(We(e,h,f),o)}return e.dispose(),u}),l=new Nd([],n,e.dtype,t.length);for(let u=0;u<c.length;u++)l.setItem(u,c[u]);return l}var $G=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),c=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let l=a;for(;c[0];){let u=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);let d=l.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);c=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return l}case"LoopCond":{let r=I("pred",e,t,n);return[Rs(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=Rs(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>Cn(s,t,n)!==void 0);if(r){let s=Cn(r,t,n);return[Rs(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[Rs(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[Rs(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[Rs(r)]}case"TensorArrayV3":{let r=I("size",e,t,n),s=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),c=I("identicalElementShapes",e,t,n),l=I("name",e,t,n),u=new _G(l,s,r,a,c,o,i);return n.addTensorArray(u),[u.idTensor,Se(1)]}case"TensorArrayWriteV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=I("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{let r=I("tensorArrayId",e,t,n),s=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return[Se(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let r=I("indices",e,t,n),s=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=DG(s,r,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let r=I("elementShape",e,t,n),s=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=AG(r,s,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let r=I("tensorListId",e,t,n),s=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,o,a)]}case"TensorListStack":{let r=I("tensorListId",e,t,n),s=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=I("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,o)]}case"TensorListFromTensor":{let r=I("tensor",e,t,n),s=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=EG(r,s,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let r=I("tensorListId",e,t,n),s=n.getTensorList(r.id),a=I("dtype",e,t,n),o=I("elementShape",e,t,n);return[s.concat(a,o)]}case"TensorListPushBack":{let r=I("tensorListId",e,t,n),s=I("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{let r=I("tensorListId",e,t,n),s=I("elementShape",e,t,n),a=I("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{let r=I("tensor",e,t,n),s=I("elementShape",e,t,n),a=I("lengths",e,t,n),o=FG(r,a,s);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function OC(e,t,n){let[r,s]=I("fusedOps",e,t,n),a=r==="biasadd",o=!a,i=s==="prelu",c=r==="fusedbatchnorm",l=I("numArgs",e,t,n);if(a){if(i&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(c)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=I("strides",e,t,n),d=tm(e,t,n),p=I("dataFormat",e,t,n).toUpperCase(),h=I("dilations",e,t,n),[f,m]=I("args",e,t,n);o&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,n);return{stride:u,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:g}}var RG=(e,t,n)=>{switch(e.op){case"Conv1D":{let r=I("stride",e,t,n),s=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilation",e,t,n);return[Wh(I("x",e,t,n),I("filter",e,t,n),r,s,a,o)]}case"Conv2D":{let r=I("strides",e,t,n),s=tm(e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[Rt(I("x",e,t,n),I("filter",e,t,n),[r[1],r[2]],s,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:r,pad:s,dataFormat:a,dilations:o,biasArg:i,preluArg:c,activationFunc:l,leakyreluAlpha:u}=OC(e,t,n);return[ha.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:l,preluActivationWeights:c,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:a,dilations:o,biasArg:i,preluArg:c,activationFunc:l,leakyreluAlpha:u}=OC(e,t,n);return[ha.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:l,preluActivationWeights:c,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=I("outputShape",e,t,n),s=I("strides",e,t,n),a=tm(e,t,n);return[Vh(I("x",e,t,n),I("filter",e,t,n),r,[s[1],s[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=I("strides",e,t,n),s=tm(e,t,n),a=I("dilations",e,t,n),o=I("dataFormat",e,t,n).toUpperCase();return[la(I("input",e,t,n),I("filter",e,t,n),[r[1],r[2]],s,o,[a[1],a[2]])]}case"Conv3D":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[Fy(I("x",e,t,n),I("filter",e,t,n),[r[1],r[2],r[3]],s,a,[o[1],o[2],o[3]])]}case"AvgPool":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[ir(I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPool":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Pt(I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("kernelSize",e,t,n),o=I("includeBatchInIndex",e,t,n),{result:i,indexes:c}=Uk(I("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s,o);return[i,c]}case"AvgPool3D":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[_y(I("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Gy(I("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{let r=I("strides",e,t,n),s=I("pad",e,t,n),a=I("dilations",e,t,n),o=r[1],i=r[2],c=a[1],l=a[2];return[Ry(I("x",e,t,n),I("filter",e,t,n),[o,i],s,[c,l],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},PG=(e,t,n)=>{switch(e.op){case"Fill":{let r=I("shape",e,t,n),s=I("dtype",e,t,n),a=I("value",e,t,n);return[In(r,a,s)]}case"LinSpace":{let r=I("start",e,t,n),s=I("stop",e,t,n),a=I("num",e,t,n);return[Ok(r,s,a)]}case"Multinomial":{let r=I("logits",e,t,n),s=I("numSamples",e,t,n),a=I("seed",e,t,n);return[Gk(r,s,a)]}case"OneHot":{let r=I("indices",e,t,n),s=I("depth",e,t,n),a=I("onValue",e,t,n),o=I("offValue",e,t,n);return[eu(r,s,a,o)]}case"Ones":return[Yn(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[Zn(I("x",e,t,n))];case"RandomUniform":return[iu(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let r=I("start",e,t,n),s=I("stop",e,t,n),a=I("step",e,t,n);return[cu(r,s,a,I("dtype",e,t,n))]}case"TruncatedNormal":{let r=I("shape",e,t,n),s=I("mean",e,t,n),a=I("stdDev",e,t,n),o=I("seed",e,t,n);return[cf(r,s,a,I("dtype",e,t,n),o)]}case"Zeros":return[St(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[Ue(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function cw(e,t,n){let r=I("boxes",e,t,n),s=I("scores",e,t,n),a=I("maxOutputSize",e,t,n),o=I("iouThreshold",e,t,n),i=I("scoreThreshold",e,t,n),c=I("softNmsSigma",e,t,n);return{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:c}}var OG=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:c}=cw(e,t,n),l=await Qn.nonMaxSuppressionWithScoreAsync(r,s,a,o,i,c);return[l.selectedIndices,l.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=cw(e,t,n),c=I("padToMaxOutputSize",e,t,n),l=await Qn.nonMaxSuppressionPaddedAsync(r,s,a,o,i,c);return[l.selectedIndices,l.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=cw(e,t,n);return[await Qn.nonMaxSuppressionAsync(r,s,a,o,i)]}case"Where":{let r=ce(I("condition",e,t,n),"bool"),s=[await nv(r)];return r.dispose(),s}case"ListDiff":return qk(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},MG=(e,t,n)=>{switch(e.op){case"TopKV2":{let r=I("x",e,t,n),s=I("k",e,t,n),a=I("sorted",e,t,n),o=ev(r,s,a);return[o.values,o.indices]}case"Unique":{let r=I("x",e,t,n),s=uf(r);return[s.values,s.indices]}case"UniqueV2":{let r=I("x",e,t,n),s=I("axis",e,t,n),a=uf(r,s);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},LG=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=I("default",e,t,n);return[Cn(e.name,t,n)||r];case"Placeholder":return[Cn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let l=I("x",e,t,n);return[Rs(l)]}case"IdentityN":return I("x",e,t,n).map(l=>Rs(l));case"Snapshot":let s=I("x",e,t,n);return[Rs(s)];case"Shape":return[Ge(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(l=>Ge(l.shape));case"Size":return[Se(I("x",e,t,n).size,"int32")];case"Rank":return[Se(I("x",e,t,n).rank,"int32")];case"NoOp":return[Se(1)];case"Print":let a=I("x",e,t,n),o=I("data",e,t,n),i=I("message",e,t,n),c=I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let l=0;l<o.length;l++)console.log(Array.prototype.slice.call(o[l].dataSync()).slice(0,c));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}},BG=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Se(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}tensorSize(){return Se(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(r=>r.dispose()),this.tensorMap.clear(),M(()=>{let r=dt(t),s=n.length,a=r.length;w.assert(s===a,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);for(let o=0;o<s;o++){let i=n[o],c=r[o];Jt(c),this.tensorMap.set(i,c)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return M(()=>{let r=[];for(let s=0;s<n.length;s++){let a=n[s],o=this.findWithDefault(a,t);r.push(o)}return Ot(r)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},zG=async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{let s=I("keyDType",e,t,n),a=I("valueDType",e,t,n),o=new BG(s,a);return r.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let s=I("tableHandle",e,t,n,r),a=I("keys",e,t,n),o=I("values",e,t,n);return[await r.getHashTableById(s.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let s=I("tableHandle",e,t,n,r),a=I("keys",e,t,n),o=I("defaultValue",e,t,n);return[await r.getHashTableById(s.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let s=I("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},WG=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let r=I("images",e,t,n),s=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[Qn.resizeBilinear(r,[s[0],s[1]],a,o)]}case"ResizeNearestNeighbor":{let r=I("images",e,t,n),s=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[Qn.resizeNearestNeighbor(r,[s[0],s[1]],a,o)]}case"CropAndResize":{let r=I("image",e,t,n),s=I("boxes",e,t,n),a=I("boxInd",e,t,n),o=I("cropSize",e,t,n),i=I("method",e,t,n),c=I("extrapolationValue",e,t,n);return[Qn.cropAndResize(r,s,a,o,i,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},VG=(e,t,n)=>{switch(e.op){case"Equal":return[Kn(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[Jo(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[Mn(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[da(I("a",e,t,n),I("b",e,t,n))];case"Less":return[jh(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[pa(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[Ir(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Jl(I("a",e,t,n))];case"LogicalOr":return[Xh(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[mn(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},UG=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Ae(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Einsum":return[$k(I("equation",e,t,n),...I("tensors",e,t,n))];case"Transpose":return[Re(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[r,s]=I("fusedOps",e,t,n),a=r==="biasadd",o=s==="prelu",i=I("numArgs",e,t,n),c=I("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[l,u]=I("args",e,t,n);return[ha.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:l,activation:s,preluActivationWeights:u,leakyreluAlpha:c})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},GG=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Ts(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[Ts(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[zy(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[Pr(I("x",e,t,n))];case"LogSoftmax":return[Kh(I("x",e,t,n))];case"SparseToDense":return[rv(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},HG=(e,t,n)=>{switch(e.op){case"Max":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[kr(I("x",e,t,n),o,i)]}case"Mean":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Et(I("x",e,t,n),o,i)]}case"Min":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Ql(I("x",e,t,n),o,i)]}case"Sum":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[ve(I("x",e,t,n),o,i)]}case"All":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Bh(I("x",e,t,n),o,i)]}case"Any":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[jl(I("x",e,t,n),o,i)]}case"ArgMax":{let o=I("axis",e,t,n);return[jo(I("x",e,t,n),o)]}case"ArgMin":{let o=I("axis",e,t,n);return[xy(I("x",e,t,n),o)]}case"Prod":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Zh(I("x",e,t,n),o,i)]}case"Cumsum":{let o=I("axis",e,t,n),i=I("exclusive",e,t,n),c=I("reverse",e,t,n);return[Gh(I("x",e,t,n),o,i,c)]}case"Bincount":let r=I("x",e,t,n),s=I("weights",e,t,n),a=I("size",e,t,n);return[Ey(r,s,a)];case"DenseBincount":{let o=I("x",e,t,n),i=I("weights",e,t,n),c=I("size",e,t,n),l=I("binaryOutput",e,t,n);return[Dk(o,i,c,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},jG=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=I("n",e,t,n),s=I("axis",e,t,n),a=I("tensors",e,t,n);return a=a.slice(0,r),[Ze(a,s)]}case"Gather":{let r=I("x",e,t,n),s=I("indices",e,t,n);return[Xo(r,ce(s,"int32"),0)]}case"GatherV2":{let r=I("axis",e,t,n),s=I("batchDims",e,t,n),a=I("x",e,t,n),o=I("indices",e,t,n);return[Xo(a,ce(o,"int32"),r,s)]}case"Reverse":{let r=I("dims",e,t,n),s=[];for(let o=0;o<r.length;o++)r[o]&&s.push(o);let a=I("x",e,t,n);return[Jn(a,s)]}case"ReverseV2":{let r=I("axis",e,t,n),s=I("x",e,t,n);return[Jn(s,r)]}case"Slice":{let r=I("begin",e,t,n),s=I("size",e,t,n);return[We(I("x",e,t,n),r,s)]}case"StridedSlice":{let r=I("begin",e,t,n),s=I("end",e,t,n),a=I("strides",e,t,n),o=I("beginMask",e,t,n),i=I("endMask",e,t,n),c=I("ellipsisMask",e,t,n),l=I("newAxisMask",e,t,n),u=I("shrinkAxisMask",e,t,n),d=I("x",e,t,n);return[Jy(d,r,s,a,o,i,c,l,u)]}case"Pack":return M(()=>{let r=I("axis",e,t,n),s=I("tensors",e,t,n),a=s[0].shape,o=os(s[0]).shape,i=s.map(c=>{let l=w.arraysEqual(c.shape,a);if(!l&&!w.arraysEqual(os(c).shape,o))throw new Error("the input tensors shape does not match");return l?c:U(c,a)});return[Ot(i,r)]});case"Unpack":{let r=I("axis",e,t,n),s=I("tensor",e,t,n);return dt(s,r)}case"Tile":{let r=I("reps",e,t,n);return[On(I("x",e,t,n),r)]}case"Split":case"SplitV":{let r=I("axis",e,t,n),s=I("numOrSizeSplits",e,t,n),a=I("x",e,t,n);return Ln(a,s,r)}case"ScatterNd":{let r=I("indices",e,t,n),s=I("values",e,t,n),a=I("shape",e,t,n);return[Zk(r,s,a)]}case"GatherNd":{let r=I("x",e,t,n),s=I("indices",e,t,n);return[Jk(r,s)]}case"SparseToDense":{let r=I("sparseIndices",e,t,n),s=I("outputShape",e,t,n),a=I("sparseValues",e,t,n),o=I("defaultValue",e,t,n);return[rv(r,a,s,a.dtype===o.dtype?o:ce(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},qG=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:s,emptyRowIndicator:a,reverseIndexMap:o}=od.sparseFillEmptyRows(I("indices",e,t,n),I("values",e,t,n),I("denseShape",e,t,n),I("defaultValue",e,t,n));return[r,s,a,o]}case"SparseReshape":{let{outputIndices:r,outputShape:s}=od.sparseReshape(I("inputIndices",e,t,n),I("inputShape",e,t,n),I("newShape",e,t,n));return[r,s]}case"SparseSegmentMean":return[od.sparseSegmentMean(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];case"SparseSegmentSum":return[od.sparseSegmentSum(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},KG=(e,t,n)=>{switch(e.op){case"FFT":return[sd(I("x",e,t,n))];case"IFFT":return[lu(I("x",e,t,n))];case"RFFT":return[ad(I("x",e,t,n))];case"IRFFT":return[af(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},XG=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:r,nGramsSplits:s}=mf.stringNGrams(I("data",e,t,n),I("dataSplits",e,t,n),I("separator",e,t,n),I("nGramWidths",e,t,n),I("leftPad",e,t,n),I("rightPad",e,t,n),I("padWidth",e,t,n),I("preserveShortSequences",e,t,n));return[r,s]}case"StringSplit":{let{indices:r,values:s,shape:a}=mf.stringSplit(I("input",e,t,n),I("delimiter",e,t,n),I("skipEmpty",e,t,n));return[r,s,a]}case"StringToHashBucketFast":return[mf.stringToHashBucketFast(I("input",e,t,n),I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},YG=(e,t,n)=>{switch(e.op){case"Cast":return[ce(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let r=I("axis",e,t,n);return[bn(I("x",e,t,n),r)]}case"Squeeze":{let r=I("axis",e,t,n);return[os(I("x",e,t,n),r)]}case"Reshape":return[U(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[Hy(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[ur(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let r=I("blockShape",e,t,n),s=I("paddings",e,t,n);return[ed(I("x",e,t,n),r,s)]}case"BatchToSpaceND":{let r=I("blockShape",e,t,n),s=I("crops",e,t,n);return[Kl(I("x",e,t,n),r,s)]}case"DepthToSpace":{let r=I("blockSize",e,t,n),s=I("dataFormat",e,t,n).toUpperCase();return[$y(I("x",e,t,n),r,s)]}case"BroadcastTo":return[ru(I("x",e,t,n),I("shape",e,t,n))];case"BroadcastArgs":return[Sk(I("s0",e,t,n),I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function MC(e,t,n,r){let s=((a,o,i)=>{switch(a.category){case"arithmetic":return M(()=>TG(a,o,i));case"basic_math":return M(()=>NG(a,o,i));case"control":return $G(a,o,i);case"convolution":return M(()=>RG(a,o,i));case"creation":return M(()=>PG(a,o,i));case"dynamic":return OG(a,o,i);case"evaluation":return M(()=>MG(a,o,i));case"image":return M(()=>WG(a,o,i));case"graph":return M(()=>LG(a,o,i));case"logical":return M(()=>VG(a,o,i));case"matrices":return M(()=>UG(a,o,i));case"normalization":return M(()=>GG(a,o,i));case"reduction":return M(()=>HG(a,o,i));case"slice_join":return M(()=>jG(a,o,i));case"sparse":return M(()=>qG(a,o,i));case"spectral":return M(()=>KG(a,o,i));case"string":return M(()=>XG(a,o,i));case"transformation":return M(()=>YG(a,o,i));case"hash_table":return zG(a,o,i,r);case"custom":let c=dC(a.op);if(c&&c.customExecutor)return c.customExecutor(new CG(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return w.isPromise(s)?s.then(a=>[].concat(a)):[].concat(s)}var LC=class{constructor(e={},t={},n={},r={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function BC(e,t,n,r){let s=new Set,a=[],o=null,i=null,c=new Set,l=Object.keys(e).map(p=>er(p)[0]),u=[];r!=null&&(u=r.map(p=>er(p.name)[0]));let d=[...t];for(;d.length>0;){let p=d.pop();if((zC(p)||tH(p)||nH(p))&&o==null&&(o=p,i=o.children.map(h=>h.name).filter(h=>s.has(h))),s.add(p.name),n[p.name]==null&&l.indexOf(p.name)===-1&&u.indexOf(p.name)===-1){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(h=>{c.has(h.name)||(c.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:o,syncInputs:i}}function ZG(e,t,n){let{usedNodes:r,inputs:s}=n,a=[],o=Object.keys(s).map(u=>er(u)[0]).map(u=>e.nodes[u]),i=e.initNodes;o.forEach(u=>{r.has(u.name)&&a.push(u)}),e.weights.forEach(u=>{r.has(u.name)&&a.push(u)}),i!=null&&i.forEach(u=>{r.has(u.name)&&a.push(u)});let c=new Set,l=[];for(;a.length>0;){let u=a.pop();c.add(u.name),t[u.name]||l.push(u),u.children.forEach(d=>{!c.has(d.name)&&r.has(d.name)&&d.inputs.every(p=>c.has(p.name))&&a.push(d)})}return l}var JG=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],QG=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],eH=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function zC(e){return JG.indexOf(e.op)>=0}function tH(e){return QG.indexOf(e.op)>=0}function nH(e){return eH.indexOf(e.op)>=0}var uw=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 uw(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(r=>r.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(s=>s.name).sort(),r=t.map(s=>s.name).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){let n=BC(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){let o=t.map(c=>c.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${r}]`)}return ZG(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let r=n.map(u=>this.graph.nodes[er(u)[0]]),s=t.map(u=>er(u)[0]),a=s.map(u=>this.graph.nodes[u]);a.length===0&&(a=this._outputs);let o=this.getCompilationKey(r,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let c={},l={};return M(()=>{let u=new LC(this.weightMap,c,l,this.functionExecutorMap),d=Object.assign({},this.weightMap);Object.keys(e).forEach(f=>{let[m,g]=er(f),b=[];b[g]=e[f],d[m]=b});let p=this.getFrozenTensorIds(d),h={};for(let f=0;f<i.length;f++){let m=i[f];if(!d[m.name]){let g=MC(m,d,u,this._resourceManager);if(w.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);d[m.name]=g,this.checkTensorForDisposal(m.name,m,d,u,p,s,h)}}return this.parent==null&&u.dispose(p),t.map(f=>Cn(f,d,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(r=>r.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,s,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let c=sG(i.name,n,r);c!=null&&c.forEach(l=>{if(l&&!l.kept&&!s.has(l.id)){let u=o[l.id];u===1?(l.dispose(),delete o[l.id]):u!=null&&o[l.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,r={},s={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let a=new LC(this.weightMap,r,s,this.functionExecutorMap),o=await this.executeWithControlFlow(e,a,t,n),i=t.map(d=>Cn(d,o,a)),c=i.map(d=>d.id),l=Object.keys(e).map(d=>e[d].id),u=new Set([...c,...l,...this.weightIds]);return Object.keys(o).forEach(d=>{o[d].forEach(h=>{h&&!h.kept&&!h.isDisposed&&!u.has(h.id)&&h.dispose()})}),this.parent==null&&a.dispose(u),i}async executeFunctionAsync(e,t,n){let r=e.reduce((s,a,o)=>(s[this.inputs[o].name]=a,s),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){let s=Object.keys(e),a=s.map(y=>this.graph.nodes[er(y)[0]]),o=n.map(y=>er(y)[0]),i=o.map(y=>this.graph.nodes[y]);i.length===0&&(i=this._outputs);let{usedNodes:c,missingInputs:l,dynamicNode:u,syncInputs:d}=BC(e,i,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(y=>({node:y,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(y=>{let[v,x]=er(y),k=[];k[x]=e[y],h[v]=k});let f={},m=this.getFrozenTensorIds(h),g={};for(;p.length>0;){let y=this.processStack(a,p,t,h,g,m,o,f,c);await Promise.all(y)}u==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let b=i.filter(y=>!zC(y)&&!Cn(y.name,h,t)).map(y=>y.name);if(b.length>0){let y="";throw u!=null&&(y=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${l}]. ${y}`)}return h}processStack(e,t,n,r,s,a,o,i,c){let l=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let d="";if(u.node.op==="Enter"&&I("isConstant",u.node,r,n)&&([d]=$s(u.node.name,n)),r[u.node.name]==null){let p=MC(u.node,r,n,this._resourceManager);d||([d]=$s(u.node.name,n));let h=n.currentContext;w.isPromise(p)?l.push(p.then(f=>(r[d]=f,n.currentContext=h,this.checkTensorForDisposal(d,u.node,r,n,a,o,i),this.processChildNodes(u.node,t,n,r,s,c),f))):(r[d]=p,this.checkTensorForDisposal(d,u.node,r,n,a,o,i),this.processChildNodes(u.node,t,n,r,s,c))}else this.processChildNodes(u.node,t,n,r,s,c)}return l}processChildNodes(e,t,n,r,s,a){e.children.forEach(o=>{let[i]=$s(o.name,n);s[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(c=>!!Cn(c,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(c=>!!Cn(c,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[r]=er(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){let a=s.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,c)=>a[c]===-1||a[c]===i);w.assert(o,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&w.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let r=this._signature.inputs[n];t[r.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[r]=er(n);return this.graph.nodes[r]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=er(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},rH=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]}},sH="?tfjs-format=file",aH="model.json",WC=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new rH}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=Zt.browserHTTPRequest(e,this.loadOptions);else{let t=Zt.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Zt.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let r=Zt.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new uw(DC.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let s=DC.Instance.transformGraph(e.modelInitializer);this.initializer=new uw(s),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=Zt.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,r)=>(t[n]=e[r],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}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 oH(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}${aH}${sH}`);let n=new WC(e,t);return await n.load(),n}var iH="3.10.0",VC={};$e(VC,{CSVDataset:()=>eT,Dataset:()=>wu,FileDataSource:()=>iT,TextLineDataset:()=>ZC,URLDataSource:()=>cT,array:()=>AH,csv:()=>WH,func:()=>VH,generator:()=>UH,microphone:()=>HH,version_data:()=>jH,webcam:()=>GH,zip:()=>DH});var cH=Oa(n1()),uH=Oa(n1());function lH(e,t){return nm(e,t)}function nm(e,t,n=new Map,r=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let s=t(e);if(s.recurse&&s.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse)if(xu(e)){let a=Array.isArray(e)?[]:{};r.add(e);for(let o in e){let i=e[o],c=nm(i,t,n,r);a[o]=c}return r.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,s.value),s.value}function dH(e,t=GC){return UC(e,t)}function UC(e,t,n=new Set){let r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");let s=t(e);if(s.recurse&&s.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse)if(xu(r)){let a=Array.isArray(r)?[]:{};n.add(r);for(let o in r){let i=e.map(l=>l[o]),c=UC(i,t,n);a[o]=c}return n.delete(r),a}else throw new Error(`Can't recurse into non-iterable type: ${r}`);else return s.value}function GC(e){return e===null?null:xu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function HC(e,t){let n=new Map;nm(e,t,n);for(let s of Array.from(n.keys())){let a=n.get(s);if(w.isPromise(a)){let o=await a;n.set(s,o)}}return nm(e,t,n)}function xu(e){let t=!1;if(J().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=r1();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ee)&&!(e instanceof Promise)&&!t)}function pH(e){return e==null||hH(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ee||w.isTypedArray(e)}function hH(e){return e===null||typeof e!="object"&&typeof e!="function"}function fH(e){return lH(e,mH)}function mH(e){return e instanceof Ee?{value:e.clone(),recurse:!1}:xu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var jC=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}},lw=class extends jC{constructor(){super(lw.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let r=0;r<n;r++)t[r]=this.get(this.wrap(this.begin+r));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};lw.INITIAL_CAPACITY=32;function qC(e){return new yH(e)}function dw(e){return new vH(e)}function gH(e,t){return new XC(e,t)}function bH(e,t=wa.FAIL){return new _H(e,t)}var tn=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 TH(this,e)}filter(e){return new SH(this,e)}map(e){return new CH(this,e)}mapAsync(e){return new KC(this,e)}serialMapAsync(e){return new KC(this,e).serial()}flatmap(e){return new NH(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 IH(this,e,t)}columnMajorBatch(e,t=!0,n=GC){return this.rowMajorBatch(e,t).map(s=>dH(s,n))}concatenate(e,t){return new XC(qC([this,e]),t)}take(e){return e<0||e==null?this:new kH(this,e)}skip(e){return e<0||e==null?this:new wH(this,e)}prefetch(e){return new YC(this,e)}shuffle(e,t){return new EH(this,e,t)}serial(){return new xH(this)}},yH=class extends tn{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:fH(e),done:!1}}},vH=class extends tn{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}}},xH=class extends tn{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()}},wH=class extends tn{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;De(e.value)}return this.upstream.next()}},kH=class extends tn{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()}},IH=class extends tn{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}}},SH=class extends tn{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;De(e.value)}}},CH=class extends tn{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=$r.getTensorsInContainer(e.value),n=this.transform(e.value),r=$r.getTensorsInContainer(n);for(let s of t)$r.isTensorInList(s,r)||s.dispose();return{value:n,done:!1}}},TH=class extends tn{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}}}},KC=class extends tn{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=$r.getTensorsInContainer(e.value),n=await this.transform(e.value),r=$r.getTensorsInContainer(n);for(let s of t)$r.isTensorInList(s,r)||s.dispose();return{value:n,done:!1}}},pw=class extends tn{constructor(){super();this.outputQueue=new lw,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}}},NH=class extends pw{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=$r.getTensorsInContainer(e.value),n=this.transform(e.value),r=$r.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let s of t)$r.isTensorInList(s,r)||s.dispose();return!0}},XC=class extends tn{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}},wa;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(wa||(wa={}));var _H=class extends tn{constructor(e,t=wa.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 r(a){return a instanceof tn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let s=await HC(this.iterators,r);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case wa.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case wa.SHORTEST:return{value:null,done:!0};case wa.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},YC=class extends tn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new jC(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()}},EH=class extends YC{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=uH.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}}},wu=class{constructor(){this.size=null}batch(e,t=!0){let n=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),tr(async()=>(await n.iterator()).columnMajorBatch(e,t,FH),r)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,tr(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,tr(async()=>(await t.iterator()).filter(r=>M(()=>e(r))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return tr(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return tr(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 tr(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,tr(async()=>{let r=dw(async()=>({value:await t.iterator(),done:!1}));return gH(r.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,tr(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let r=this,s=cH.alea(t||w.now().toString());return tr(async()=>{let a=s.int32();return n&&(a+=s.int32()),(await r.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,tr(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};wu.MAX_BUFFER_SIZE=1e4;function tr(e,t=null){return new class extends wu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function AH(e){return tr(async()=>qC(e),e.length)}function DH(e){if(!xu(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 tr(async()=>{let n=await HC(e,r=>{if(r instanceof wu)return{value:r.iterator(),recurse:!1};if(xu(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return bH(n,wa.SHORTEST)},t)}function FH(e){if(e===null)return null;let t=e[0];return pH(t)?{value:$H(e),recurse:!1}:{value:null,recurse:!0}}function $H(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?Ot(e):qn(e)}var ZC=class extends wu{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(r=>(r.endsWith("\r")&&(r=r.slice(0,-1)),r))}},rm='"',_d=Symbol("out"),JC=Symbol("field"),sm=Symbol("quote"),hw=Symbol("quoteafterquote"),QC=Symbol("quoteinquote"),eT=class extends wu{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 ZC(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);c=void 0}else{let l=Number(i);if(isNaN(l))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=l;else switch(o.dtype){case"float32":c=l;break;case"int32":c=Math.floor(l);break;case"bool":c=this.getBoolean(i);break;default:c=l}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=_d;for(let o=0;o<s;o++)switch(a){case _d:switch(e.charAt(o)){case rm:r=o+1,a=sm;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=_d;break;default:a=JC,r=o;break}break;case JC:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=_d,r=o+1;break;default:}break;case sm:switch(e.charAt(o)){case rm:a=hw;break;default:}break;case hw:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=_d,r=o+1;break;case rm:a=sm;break;default:a=QC;break}break;case QC:switch(e.charAt(o)){case rm:a=sm;break;default:}break;default:}if(a===hw?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},tT=class extends tn{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(J().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new tT(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let r=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let r=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(r,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(r=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),r({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((r,s)=>n.set(r,s*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(w.sizeFromShape(t));return n.set(e,n.length-e.length),qn(n,t)}},nT=class extends tn{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=Ge([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,r=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-n)/2,a=(1-r)/2,o=s+n,i=r+a;this.cropBox=Or([a,s,i,o],[1,4])}else this.cropBox=Or([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(J().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 nT(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=Go.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 M(()=>{let t=bn(ce(e,"float32"),0),n;n=Qn.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let r=n.shape;return U(n,r.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},rT=class{},sT=class extends tn{split(e){return new RH(this,e)}},RH=class extends sT{constructor(e,t){super();this.upstream=e,this.impl=new PH(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},PH=class extends pw{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}},OH=class extends tn{decodeUTF8(){return new MH(this)}},MH=class extends sT{constructor(e){super();this.upstream=e,this.impl=new LH(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},LH=class extends pw{constructor(e){super();if(this.upstream=e,J().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=r1();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 J().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},aT=class extends OH{constructor(e,t={}){super();this.file=e,this.options=t,w.assert(e instanceof Uint8Array||(J().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,r)));else{let s=new FileReader;s.onload=o=>{let i=s.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},s.onabort=o=>n(new Error("Aborted")),s.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,r);s.readAsArrayBuffer(a)}this.offset=r}),done:!1}}};async function BH(e,t={},n){let r,s;typeof e=="string"?r=e:(r=e.url,s=zH(e));let a=await(n||w.fetch)(r,s);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new aT(o,t)}else throw new Error(a.statusText)}var zH=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 oT(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var iT=class extends rT{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(oT(this.input)&&J().get("IS_NODE")){let e=Gi("fs");this.input=e.readFileSync(this.input.substr(7))}return new aT(this.input,this.options)}},cT=class extends rT{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return oT(this.url)?new iT(this.url,this.fileOptions).iterator():BH(this.url,this.fileOptions)}};function WH(e,t={}){return new eT(new cT(e),t)}function VH(e){let t=dw(e);return tr(async()=>t)}function UH(e){return tr(async()=>{let t=await e();return dw(()=>t.next())})}async function GH(e,t){return nT.create(e,t)}async function HH(e){return tT.create(e)}var jH="3.10.0";function Ie(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 qH=is.whereImpl,fw=class extends bl{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Op(this,Cs())}nextDataId(){return fw.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,J().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 r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return Cs().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Ie([e],"where");let t=this.readSync(e.dataId);return qH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};fw.nextDataId=0;var uT={};$e(uT,{addImpl:()=>dT,bincountImpl:()=>gw,bincountReduceImpl:()=>pT,ceilImpl:()=>hT,concatImpl:()=>bw,equalImpl:()=>fT,expImpl:()=>gT,expm1Impl:()=>yT,floorImpl:()=>vT,gatherNdImpl:()=>xT,gatherV2Impl:()=>wT,greaterEqualImpl:()=>IT,greaterImpl:()=>kT,lessEqualImpl:()=>CT,lessImpl:()=>ST,linSpaceImpl:()=>TT,logImpl:()=>NT,maxImpl:()=>_T,maximumImpl:()=>ET,minimumImpl:()=>AT,multiplyImpl:()=>yw,negImpl:()=>DT,notEqualImpl:()=>FT,prodImpl:()=>$T,rangeImpl:()=>xw,rsqrtImpl:()=>RT,sigmoidImpl:()=>P6,simpleAbsImpl:()=>lT,sliceImpl:()=>im,sparseFillEmptyRowsImpl:()=>OT,sparseReshapeImpl:()=>MT,sparseSegmentReductionImpl:()=>ww,sqrtImpl:()=>L6,squaredDifferenceImpl:()=>LT,stridedSliceImpl:()=>BT,stringNGramsImpl:()=>zT,stringSplitImpl:()=>WT,stringToHashBucketFastImpl:()=>VT,subImpl:()=>UT,tileImpl:()=>GT,topKImpl:()=>jT,transposeImpl:()=>vw,uniqueImpl:()=>qT});function lT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var KH=e=>{let{x:t}=e.inputs,n=e.backend;Ie(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=lT(s),n.makeOutput(r,t.shape,t.dtype)},XH={kernelName:Ki,backendName:"cpu",kernelFunc:KH};function zt(e){return(t,n,r,s,a)=>{let o=_.assertAndGetBroadcastShape(t,n),i=o.length,c=w.computeStrides(o),l=w.sizeFromShape(o),u=w.getTypedArrayFromDType(a,l),d=t.length,p=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=_.getBroadcastDims(t,o),g=_.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<u.length;++b)u[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<u.length;++b){let y=w.indexToLoc(b,i,c),v=y.slice(-d);m.forEach(N=>v[N]=0);let x=w.locToIndex(v,d,h),k=y.slice(-p);g.forEach(N=>k[N]=0);let C=w.locToIndex(k,p,f);u[b]=e(r[x],s[C])}return[u,o]}}function nr(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=n.makeTensorInfo(r.shape,"complex64"),c=n.data.get(i.dataId);return c.complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",o)},i}var YH={kernelName:Hp,backendName:"cpu",kernelFunc:nr};function am(e,t,n="float32"){if(n==="complex64"){let s=am(e,t,"float32"),a=am(e,t,"float32");return nr({inputs:{real:s,imag:a},backend:e})}let r=w.makeZerosTypedArray(w.sizeFromShape(t),n);return e.makeTensorInfo(t,n,r)}function hs(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var ZH={kernelName:so,backendName:"cpu",kernelFunc:hs};function di(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.real,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}var JH={kernelName:ph,backendName:"cpu",kernelFunc:di};function ka(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return hs({inputs:{x:s},backend:n});let o=am(n,s.shape,s.dtype),i=ka({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=nr({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=di({inputs:{input:s},backend:n}),i=ka({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=hs({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(s.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(s.shape,"int32",i)}if(a==="bool"){let o=n.data.get(s.dataId).values,i=w.toTypedArray([0],s.dtype),[c,l]=zt((u,d)=>u!==d?1:0)(s.shape,[],o,i,"bool");return n.makeTensorInfo(l,"bool",c)}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}var QH={kernelName:Ua,backendName:"cpu",kernelFunc:ka};function nn(e,t,n,r){return n==null?({inputs:s,backend:a})=>{let{a:o,b:i}=s,c=a;Ie([o,i],e);let l=c.data.get(o.dataId).values,u=c.data.get(i.dataId).values,d=o.dtype==="string"?_.fromUint8ToStringArray(l):l,p=o.dtype==="string"?_.fromUint8ToStringArray(u):u,h=r||o.dtype,[f,m]=t(o.shape,i.shape,d,p,h);return c.makeTensorInfo(m,h,f)}:({inputs:s,backend:a})=>{let{a:o,b:i}=s,c=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let l=ka({inputs:{x:o},backend:c,attrs:{dtype:"complex64"}}),u=c.data.get(l.dataId),d=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,h=c.data.get(d.dataId).values,f=c.data.get(p.dataId).values,m=ka({inputs:{x:i},backend:c,attrs:{dtype:"complex64"}}),g=c.data.get(m.dataId),b=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,v=c.data.get(b.dataId).values,x=c.data.get(y.dataId).values,[k,C,N]=n(o.shape,i.shape,h,f,v,x),F=c.makeTensorInfo(N,"float32",k),R=c.makeTensorInfo(N,"float32",C),O=nr({inputs:{real:F,imag:R},backend:c});return c.disposeIntermediateTensorInfo(l),c.disposeIntermediateTensorInfo(m),c.disposeIntermediateTensorInfo(F),c.disposeIntermediateTensorInfo(R),O}else{let l=c.data.get(o.dataId).values,u=c.data.get(i.dataId).values,d=r||o.dtype,[p,h]=t(o.shape,i.shape,l,u,d);return c.makeTensorInfo(h,d,p)}}}function mw(e){return(t,n,r,s,a,o)=>{let i=_.assertAndGetBroadcastShape(t,n),c=w.sizeFromShape(i),l=i.length,u=w.computeStrides(i),d=w.getTypedArrayFromDType("float32",c),p=w.getTypedArrayFromDType("float32",c),h=_.getBroadcastDims(t,i),f=_.getBroadcastDims(n,i),m=_.mergeRealAndImagArrays(r,s),g=_.mergeRealAndImagArrays(a,o),b=t.length,y=w.computeStrides(t),v=n.length,x=w.computeStrides(n);if(h.length+f.length===0)for(let k=0;k<d.length;k++){let C=k%m.length,N=k%g.length,F=e(m[C*2],m[C*2+1],g[N*2],g[N*2+1]);d[k]=F.real,p[k]=F.imag}else for(let k=0;k<d.length;k++){let C=w.indexToLoc(k,l,u),N=C.slice(-b);h.forEach(P=>N[P]=0);let F=w.locToIndex(N,b,y),R=C.slice(-v);f.forEach(P=>R[P]=0);let O=w.locToIndex(R,v,x),D=e(m[F*2],m[F*2+1],g[O*2],g[O*2+1]);d[k]=D.real,p[k]=D.imag}return[d,p,i]}}var dT=zt((e,t)=>e+t),e6=mw((e,t,n,r)=>({real:e+n,imag:t+r})),Ed=nn(Qs,dT,e6),t6={kernelName:Qs,backendName:"cpu",kernelFunc:Ed};function gw(e,t,n,r,s){let a=w.sizeFromShape(r),o=w.makeZerosTypedArray(s,n);for(let i=0;i<e.length;i++){let c=e[i];if(c<0)throw new Error("Input x must be non-negative!");c>=s||(a>0?o[c]+=t[i]:o[c]+=1)}return o}function pT(e,t,n,r=!1){let s=e.shape[0],a=e.shape[1],o=ze([s,n],t.dtype);for(let i=0;i<s;i++)for(let c=0;c<a;c++){let l=e.get(i,c);if(l<0)throw new Error("Input x must be non-negative!");l>=n||(r?o.set(1,i,l):t.size>0?o.set(o.get(i,l)+t.get(i,c),i,l):o.set(o.get(i,l)+1,i,l))}return o}function Ia(e){return(t,n,r)=>{let s=w.getTypedArrayFromDType(n,t.length);for(let a=0;a<t.length;++a)s[a]=e(t[a],r);return s}}function ot(e,t,n){return({inputs:r,attrs:s,backend:a})=>{let{x:o}=r;if(Ie(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,c=i.data.get(o.dataId).values,l=w.sizeFromShape(o.shape),u=n||o.dtype,d=w.getArrayFromDType(u,l);for(let p=0;p<l;++p)d[p]=t(c[p],s);return i.makeTensorInfo(o.shape,u,d)}}function ku(e,t,n){return({inputs:r,attrs:s,backend:a})=>{let{x:o}=r;if(Ie(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,c=i.data.get(o.dataId).values,l=n||o.dtype,u=t(c,l,s);return i.makeTensorInfo(o.shape,l,u)}}var hT=Ia(e=>Math.ceil(e)),n6=ku(Ga,hT),r6={kernelName:Ga,backendName:"cpu",kernelFunc:n6};function bw(e,t,n,r){let s=w.getArrayFromDType(n,w.sizeFromShape(t));if(r&&n!=="string"){let a=0;e.forEach(o=>{let i=w.sizeFromShape(o.shape);s.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?_.fromUint8ToStringArray(o.vals):o.vals,c=0;for(let l=0;l<o.shape[0];++l){let u=l*t[1]+a;for(let d=0;d<o.shape[1];++d)s[u+d]=i[c++]}a+=o.shape[1]})}return s}var fT=zt((e,t)=>e===t?1:0),mT=nn(uc,fT,null,"bool"),s6={kernelName:uc,backendName:"cpu",kernelFunc:mT},gT=Ia(e=>Math.exp(e)),bT=ku(Qa,gT,"float32"),a6={kernelName:Qa,backendName:"cpu",kernelFunc:bT},yT=Ia(e=>Math.expm1(e)),o6=ku(dc,yT),i6={kernelName:dc,backendName:"cpu",kernelFunc:o6},vT=Ia(e=>Math.floor(e)),c6=ku(eo,vT),u6={kernelName:eo,backendName:"cpu",kernelFunc:c6};function xT(e,t,n,r,s,a,o,i,c){let l=ze([r,a],n);for(let u=0;u<r;u++){let d=[],p=0;for(let h=0;h<s;h++){let f=e[u*s+h];p+=f*o[h],d.push(f)}if(p<0||p>=c/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let h=0;h<a;h++)l.values[u*a+h]=t.get(...t.indexToLoc(p*a+h))}return l}function wT(e,t,n){let r=ze(n,e.dtype);for(let s=0;s<r.size;++s){let o=r.indexToLoc(s).slice(),i=o[0],c=o[2],l=t.locToIndex([i,c]);o[2]=t.values[l];let u=e.locToIndex(o);r.values[s]=e.values[u]}return r}var kT=zt((e,t)=>e>t?1:0),l6=nn(mc,kT,null,"bool"),d6={kernelName:mc,backendName:"cpu",kernelFunc:l6},IT=zt((e,t)=>e>=t?1:0),p6=nn(ro,IT,null,"bool"),h6={kernelName:ro,backendName:"cpu",kernelFunc:p6},ST=zt((e,t)=>e<t?1:0),f6=nn(vc,ST,null,"bool"),m6={kernelName:vc,backendName:"cpu",kernelFunc:f6},CT=zt((e,t)=>e<=t?1:0),g6=nn(xc,CT,null,"bool"),b6={kernelName:xc,backendName:"cpu",kernelFunc:g6};function TT(e,t,n){let r=(t-e)/(n-1),s=w.makeZerosTypedArray(n,"float32");s[0]=e;for(let a=1;a<s.length;a++)s[a]=s[a-1]+r;return s}var NT=Ia(e=>Math.log(e)),y6=ku(oo,NT),v6={kernelName:oo,backendName:"cpu",kernelFunc:y6};function _T(e,t,n,r){let s=w.getTypedArrayFromDType(r,w.sizeFromShape(n));for(let a=0;a<s.length;++a){let o=a*t,i=e[o];for(let c=0;c<t;++c){let l=e[o+c];(Number.isNaN(l)||l>i)&&(i=l)}s[a]=i}return s}var ET=zt((e,t)=>Math.max(e,t)),x6=nn(co,ET),w6={kernelName:co,backendName:"cpu",kernelFunc:x6},AT=zt((e,t)=>Math.min(e,t)),k6=nn(ho,AT),I6={kernelName:ho,backendName:"cpu",kernelFunc:k6},yw=zt((e,t)=>e*t),S6=mw((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n})),om=nn(mo,yw,S6),C6={kernelName:mo,backendName:"cpu",kernelFunc:om};function DT(e,t,n){let r=w.createScalarValue(-1,n);return yw([],t,r,e,n)}function T6(e){let{inputs:t,backend:n}=e,{x:r}=t;Ie(r,"neg");let s=n.data.get(r.dataId).values,[a,o]=DT(s,r.shape,r.dtype);return n.makeTensorInfo(o,r.dtype,a)}var N6={kernelName:Sc,backendName:"cpu",kernelFunc:T6},FT=zt((e,t)=>e!==t?1:0),_6=nn(Cc,FT,null,"bool"),E6={kernelName:Cc,backendName:"cpu",kernelFunc:_6};function vw(e,t,n,r,s){let a=t.length,o=w.sizeFromShape(t),i=w.computeStrides(t),c=w.computeStrides(s),l=w.getTypedArrayFromDType(n,w.sizeFromShape(s));for(let u=0;u<o;++u){let d=w.indexToLoc(u,a,i),p=new Array(d.length);for(let f=0;f<p.length;f++)p[f]=d[r[f]];let h=w.locToIndex(p,a,c);l[h]=e[u]}return l}function dr(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{perm:a}=n;Ie(s,"transpose");let o=s.shape.length,i=new Array(o);for(let d=0;d<i.length;d++)i[d]=s.shape[a[d]];let c=r.data.get(s.dataId).values,l=vw(c,s.shape,s.dtype,a,i);return{dataId:r.write(l,i,s.dtype),shape:i,dtype:s.dtype}}var A6={kernelName:Po,backendName:"cpu",kernelFunc:dr};function $T(e,t,n,r){let[s,a]=_.computeOutAndReduceShapes(e,r),o=wr(t,"int32"),i=w.makeZerosTypedArray(w.sizeFromShape(s),o),c=w.sizeFromShape(a);for(let l=0;l<i.length;++l){let u=l*c,d=1;for(let p=0;p<c;++p)d*=n[u+p];i[l]=d}return{outVals:i,outShape:s,outDtype:o}}function D6(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ie(s,"prod");let i=s.shape.length,c=w.parseAxisParam(a,s.shape),l=_.getAxesPermutation(c,i),u=c,d=s,p=[];l!=null&&(d=dr({inputs:{x:s},backend:n,attrs:{perm:l}}),p.push(d),u=_.getInnerMostAxes(u.length,i));let h=n.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=$T(d.shape,d.dtype,h,u),b=m;return o&&(b=_.expandShapeToKeepDim(m,c)),p.forEach(y=>n.disposeIntermediateTensorInfo(y)),n.makeTensorInfo(b,g,f)}var F6={kernelName:Dc,backendName:"cpu",kernelFunc:D6};function xw(e,t,n,r){let s=e===t,a=e<t&&n<0,o=t<e&&n>1;if(s||a||o)return w.makeZerosTypedArray(0,r);let i=Math.abs(Math.ceil((t-e)/n)),c=w.makeZerosTypedArray(i,r);t<e&&n===1&&(n=-1),c[0]=e;for(let l=1;l<c.length;l++)c[l]=c[l-1]+n;return c}var RT=Ia(e=>1/Math.sqrt(e)),$6=ku(Co,RT),R6={kernelName:Co,backendName:"cpu",kernelFunc:$6},P6=Ia(e=>1/(1+Math.exp(-e))),PT=ot(No,e=>1/(1+Math.exp(-e))),O6={kernelName:No,backendName:"cpu",kernelFunc:PT};function im(e,t,n,r,s){let a=kn.isSliceContinous(r,t,n),o=w.sizeFromShape(n),i=w.computeStrides(r);if(a){let d=kn.computeFlatOffset(t,i);return s==="string"?e.slice(d,d+o):e.subarray(d,d+o)}let c=s==="string"?_.fromUint8ToStringArray(e):e,l=ze(r,s,c),u=ze(n,s);for(let d=0;d<u.size;++d){let p=u.indexToLoc(d),h=p.map((f,m)=>f+t[m]);u.set(l.get(...h),...p)}return s==="string"?_.fromStringArrayToUint8(u.values):u.values}function pi(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r;Ie(s,"slice");let[i,c]=kn.parseSliceParams(s,a,o);kn.assertParamsValid(s,i,c);let l=n.data.get(s.dataId).values,u=im(l,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,u)}var M6={kernelName:Mc,backendName:"cpu",kernelFunc:pi};function OT(e,t,n,r,s,a,o){let i=t[0],c=a[0],l=new Array(c),u=new Array(i),d=t[1];if(c===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${i}`);let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(s,0);return[g,[0,d],b,l,u]}let p=!0,h=0,f=new Array(c).fill(0);for(let g=0;g<i;++g){let b=e[g*d];if(b<0)throw new Error(`indices(${g}, 0) is invalid: ${b} < 0`);if(b>=c)throw new Error(`indices(${g}, 0) is invalid: ${b} >= ${c}`);++f[b],p=p&&b>=h,h=b}let m=!0;for(let g=0;g<c;++g){let b=f[g]===0;l[g]=b,m=m&&!b,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){let g=e,b=r;for(let y=0;y<i;++y)u[y]=y;return[g,[i,d],b,l,u]}else{let g=f[c-1],b=w.getArrayFromDType(n,g*d),y=w.getArrayFromDType(s,g),v=new Array(c).fill(0);for(let x=0;x<i;++x){let k=e[x*d],C=v[k],N=(k===0?0:f[k-1])+C;v[k]++;for(let F=0;F<d;++F)b[N*d+F]=e[x*d+F];y[N]=r[x],u[x]=N}for(let x=0;x<c;++x)if(v[x]===0){let C=x===0?0:f[x-1];b[C*d+0]=x;for(let N=1;N<d;++N)b[C*d+N]=0;y[C]=o}return[b,[g,d],y,l,u]}}function MT(e,t,n,r,s){let a=w.sizeFromShape(r),o=t[0],i=s.length,c=[],l=1,u=-1;for(let g=0;g<i;++g){let b=s[g];if(b===-1){if(u!==-1)throw new Error(`only one output dimension may be -1, not both ${u} and ${g}`);u=g,c.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);l*=b,c.push(b)}}if(u!==-1){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(a/l);if(l*g!==a)throw new Error(`Input to reshape is a SparseTensor with ${a}
|
|
dense values, but the requested shape requires a multiple of ${l}. inputShape=${r} outputShape= ${c}`);c[u]=g}let d=w.sizeFromShape(c);if(d!==a)throw new Error(`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${d}. inputShape=${r} outputShape=${c}`);let p=r.length,h=[];if(p>0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*r[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*c[g+1]}let m=w.getArrayFromDType(n,o*i);for(let g=0;g<o;++g){let b=0;for(let y=0;y<p;++y)b+=e[g*p+y]*h[y];for(let y=0;y<i;++y)m[g*i+y]=Math.trunc(b/f[y]),b%=f[y]}return[m,[o,i],c]}function ww(e,t,n,r,s,a=!1,o=0){let i=r.length;if(i!==s.length)throw new Error("segmentIds and indices should have same size.");let c=[t[0],e.length/t[0]],l=c[1],d=i>0?s[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((v,x)=>v*x,1),f=w.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,b=0,y=s[m];for(;;){let v=0;if(g<i){if(v=s[g],y===v){++g;continue}if(y>=v)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>b&&f.fill(o,b*l,y*l);for(let x=m;x<g;++x){let k=r[x];if(k<0||k>=c[0])throw new Error(`Bad: indices[${x}] == ${r[x]} out of range [0, ${c[0]})`);for(let C=0;C<l;C++)f[y*l+C]+=e[k*l+C]}if(a)for(let x=0;x<l;x++)f[y*l+x]/=g-m;if(m=g,++g,b=y+1,y=v,g>i)break}return b<d&&f.fill(o,b*l,d*l),[f,p]}var L6=Ia(e=>Math.sqrt(e)),B6=ot(_o,e=>Math.sqrt(e)),z6={kernelName:_o,backendName:"cpu",kernelFunc:B6},LT=zt((e,t)=>{let n=e-t;return n*n}),W6=nn(Do,LT),V6={kernelName:Do,backendName:"cpu",kernelFunc:W6};function BT(e,t,n,r){let s=ze(e,t.dtype);for(let a=0;a<s.size;a++){let o=s.indexToLoc(a),i=new Array(o.length);for(let c=0;c<i.length;c++)i[c]=o[c]*n[c]+r[c];s.set(t.get(...i),...o)}return s}var U6=class{constructor(e,t,n,r,s,a){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let o=0;o<s;++o){let i=this.getPadWidth(a),c=Math.max(0,i-o),l=Math.max(0,i-(s-(o+1))),u=a-(c+l),d=t+(c>0?0:o-i),p=0;p+=c*this.leftPad.length;for(let b=0;b<u;++b)p+=e[d+b].length;p+=l*this.rightPad.length,p+=(c+l+u-1)*this.separator.length,n[r+o]=new Uint8Array(p);let f=n[r+o],m=0,g=b=>b.forEach(y=>f[m++]=y);for(let b=0;b<c;++b)g(this.leftPad),g(this.separator);for(let b=0;b<u-1;++b)g(e[d+b]),g(this.separator);if(u>0){g(e[d+u-1]);for(let b=0;b<l;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<l-1;++b)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,r=t.length;if(r>0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let c=1;c<r;++c){let l=t[c]>=i;if(l=l&&t[c]<=n,!l)throw new Error(`Invalid split value ${t[c]}, must be in [${i}, ${n}]`);i=t[c]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let s=r-1,a=w.getArrayFromDType("int32",r);if(n===0||r===0){let i=new Array(n);for(let c=0;c<=s;++c)a[c]=0;return[i,a]}a[0]=0;for(let i=1;i<=s;++i){let c=t[i]-t[i-1],l=0;this.nGramWidths.forEach(u=>{l+=this.getNumNGrams(c,u)}),this.preserveShort&&c>0&&l===0&&(l=1),a[i]=a[i-1]+l}let o=new Array(a[s]);for(let i=0;i<s;++i){let c=t[i],l=a[i];if(this.nGramWidths.forEach(u=>{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,c,o,l,p,u),l+=p}),this.preserveShort&&l===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,c,o,l,p,d)}}return[o,a]}};function zT(e,t,n,r,s,a,o,i){return new U6(n,r,s,a,o,i).compute(e,t)}function G6(e,t,n,r){if(!e.length)return;if(t.length===0){for(let a=0;a<e.length;++a)r.push(e.subarray(a,a+1));return}if(t.length===1){let a=t[0],o=e.indexOf(a);for(;o!==-1;){let i=e.subarray(0,o);(!n||i.length!==0)&&r.push(i),e=e.subarray(o+1),o=e.indexOf(a)}(!n||e.length!==0)&&r.push(e);return}let s=0;for(let a=0;a<e.length+1;a++)if(a===e.length||t.indexOf(e[a])!==-1){let o=e.subarray(s,a);(!n||o.length!==0)&&r.push(o),s=a+1}}function WT(e,t,n){let r=e.length,s=[],a=0,o=0,i=new Array(r);for(let p=0;p<r;++p){let h=s.length;G6(e[p],t,n,s);let f=s.length-h;i[p]=f,a+=f,o=Math.max(o,f)}let c=w.getArrayFromDType("int32",a*2),l=new Array(a),u=[r,o],d=0;for(let p=0;p<r;++p)for(let h=0;h<i[p];++h)c[d*2]=p,c[d*2+1]=h,l[d]=s[d],++d;return[c,l,u]}function VT(e,t){let n=w.getArrayFromDType("int32",e.length);for(let r=0;r<e.length;++r)n[r]=w.fingerPrint64(e[r]).modulo(t).getLowBitsUnsigned();return n}var UT=zt((e,t)=>e-t),H6=mw((e,t,n,r)=>({real:e-n,imag:t-r})),kw=nn(Fo,UT,H6),j6={kernelName:Fo,backendName:"cpu",kernelFunc:kw};function GT(e,t){let n=new Array(e.rank);for(let s=0;s<n.length;s++)n[s]=e.shape[s]*t[s];let r=ze(n,e.dtype);for(let s=0;s<r.values.length;++s){let a=r.indexToLoc(s),o=new Array(e.rank);for(let c=0;c<o.length;c++)o[c]=a[c]%e.shape[c];let i=e.locToIndex(o);r.values[s]=e.values[i]}return r}var Ad=(e,t)=>{let n=t.value-e.value;return n===0?e.index-t.index:n};function HT(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){let i=r-n+1,c=t-n+1,l=Math.log(i),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(i-u)/i)*Math.sign(c-i/2),p=Math.max(n,Math.floor(t-c*u/i+d)),h=Math.min(r,Math.floor(t+(i-c)*u/i+d));HT(e,t,p,h)}let s=e[t],a=n,o=r;for(w.swap(e,n,t),Ad(e[r],s)>0&&w.swap(e,n,r);a<o;){for(w.swap(e,a,o),a++,o--;Ad(e[a],s)<0;)a=a+1;for(;Ad(e[o],s)>0;)o=o-1}Ad(e[n],s)===0?w.swap(e,n,o):(o=o+1,w.swap(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}function jT(e,t,n,r,s){let a=t[t.length-1],[o,i]=[e.length/a,a],c=w.getTypedArrayFromDType(n,o*r),l=w.getTypedArrayFromDType("int32",o*r);for(let d=0;d<o;d++){let p=d*i,h=e.subarray(p,p+i),f=new Array(h.length);h.forEach((y,v)=>f[v]={value:y,index:v}),r<f.length&&(HT(f,r),f=f.slice(0,r)),s&&f.sort(Ad);let m=d*r,g=c.subarray(m,m+r),b=l.subarray(m,m+r);for(let y=0;y<r;y++)g[y]=f[y].value,b[y]=f[y].index}let u=t.slice();return u[u.length-1]=r,[ze(u,n,c),ze(u,"int32",l)]}function qT(e,t,n,r){let s=w.parseAxisParam(t,n)[0],a=[1,n[0],1];for(let f=0;f<s;f++)a[0]*=n[f];a[1]=n[s];for(let f=s+1;f<n.length;f++)a[2]*=n[f];let o={},i=new Int32Array(n[s]),c=new Ut(a,r,e),l=[],u=a[0]===1&&a[2]===1;for(let f=0;f<n[s];f++){let m;if(u)m=e[f].toString();else{let g=[];for(let b=0;b<a[0];b++)for(let y=0;y<a[2];y++)g.push(c.get(b,f,y));m=g.join(",")}if(o[m]!==void 0)i[f]=o[m];else{let g=Object.keys(o).length;o[m]=g,i[f]=g,l.push(f)}}let d=a.slice();d[1]=Object.keys(o).length;let p=new Ut(d,r);l.forEach((f,m)=>{for(let g=0;g<a[0];g++)for(let b=0;b<a[2];b++)p.set(c.get(g,f,b),g,m,b)});let h=n.slice();return h[s]=d[1],{outputValues:p.values,outputShape:h,indices:i}}Mh("cpu",()=>new fw,1);var KT=ot(Ja,e=>e>=0?e:Math.exp(e)-1),q6={kernelName:Ja,backendName:"cpu",kernelFunc:KT};function XT(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r;Ie([s],"leakyRelu");let o=w.sizeFromShape(s.shape),i=n.data.get(s.dataId).values,c=w.getTypedArrayFromDType("float32",o);for(let l=0;l<i.length;l++)c[l]=i[l]<0?a*i[l]:i[l];return n.makeTensorInfo(s.shape,"float32",c)}var K6={kernelName:ao,backendName:"cpu",kernelFunc:XT},X6=zt((e,t)=>e<0?t*e:e);function YT(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t;Ie([r,s],"prelu");let a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,[i,c]=X6(r.shape,s.shape,a,o,"float32");return n.makeTensorInfo(c,"float32",i)}var Y6={kernelName:vo,backendName:"cpu",kernelFunc:YT},ZT=ot(xo,e=>Math.max(0,e)),Z6={kernelName:xo,backendName:"cpu",kernelFunc:ZT},JT=ot(ko,e=>Math.min(Math.max(0,e),6)),J6={kernelName:ko,backendName:"cpu",kernelFunc:JT};function Iw(e,t,n,r,s){if(n==="linear")return hs({inputs:{x:t},backend:e});if(n==="relu")return ZT({inputs:{x:t},backend:e});if(n==="elu")return KT({inputs:{x:t},backend:e});if(n==="relu6")return JT({inputs:{x:t},backend:e});if(n==="prelu")return YT({inputs:{x:t,alpha:r},backend:e});if(n==="leakyrelu")return XT({inputs:{x:t},backend:e,attrs:{alpha:s}});if(n==="sigmoid")return PT({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function yt(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=w.sizeFromShape(s.shape),i=w.inferFromImplicitShape(a,o),c=w.sizeFromShape(i);w.assert(o===c,()=>`The new shape (${i}) has ${c} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(s.dataId);let l=n.data.get(s.dataId);if(l.complexTensorInfos!=null){let u=l.complexTensorInfos.real,d=l.complexTensorInfos.imag;u.shape=i,d.shape=i}return{dataId:s.dataId,shape:i,dtype:s.dtype}}var Q6={kernelName:$c,backendName:"cpu",kernelFunc:yt};function QT(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;Ie([s,a],"matMul");let c=s.shape.length,l=a.shape.length,u=o?s.shape[c-2]:s.shape[c-1],d=i?a.shape[l-1]:a.shape[l-2],p=o?s.shape[c-1]:s.shape[c-2],h=i?a.shape[l-2]:a.shape[l-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=w.sizeFromShape(f),b=w.sizeFromShape(m),y=g===b||g===1||b===1;w.assert(c>=2&&l>=2&&y,()=>`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 (${m}).`);let x=(g>b?s.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);w.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let k=o?[g,u,p]:[g,p,u],C=i?[b,h,d]:[b,d,h],N=yt({inputs:{x:s},backend:n,attrs:{shape:k}}),F=yt({inputs:{x:a},backend:n,attrs:{shape:C}}),R=o?N.shape[1]:N.shape[2],O=o?N.shape[2]:N.shape[1],D=i?F.shape[1]:F.shape[2],P=Math.max(g,b),T=n.data.get(N.dataId).values,L=n.data.get(F.dataId).values,G=w.computeStrides(N.shape),j=w.computeStrides(F.shape),[q,K,ee]=o?[G[0],1,G[1]]:[G[0],G[1],1],[te,ne,ae]=i?[1,j[1],j[0]]:[j[1],1,j[0]],se=O*D,re=ze([P,O,D],N.dtype),ue=re.values,de=n.blockSize;for(let me=0;me<P;me++)for(let we=0;we<O;we+=de)for(let Ce=0;Ce<D;Ce+=de)for(let _e=0;_e<R;_e+=de){let Me=Math.min(we+de,O),Be=Math.min(Ce+de,D),Ke=Math.min(_e+de,R);for(let st=we;st<Me;st++)for(let et=Ce;et<Be;et++){let tt=0;for(let it=_e;it<Ke;it++){let lt=Math.min(me,g-1)*q,xt=Math.min(me,b-1)*ae,Nt=T[lt+st*K+it*ee],$n=L[it*te+et*ne+xt];tt+=Nt*$n}ue[me*se+(st*D+et)]+=tt}}return n.disposeIntermediateTensorInfo(N),n.disposeIntermediateTensorInfo(F),n.makeTensorInfo(x,re.dtype,re.values)}var e5={kernelName:Va,backendName:"cpu",kernelFunc:QT};function t5(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r,p,h,f,m=[];p=QT({inputs:{a:s,b:a},attrs:{transposeA:c,transposeB:l},backend:n}),o&&(h=Ed({inputs:{a:p,b:o},backend:n}),m.push(p),p=h),u&&(f=Iw(n,p,u,i,d),m.push(p),p=f);for(let b of m)n.disposeIntermediateTensorInfo(b);return p}var n5={kernelName:Oo,backendName:"cpu",kernelFunc:t5},r5=ot(Xi,e=>Math.acos(e)),s5={kernelName:Xi,backendName:"cpu",kernelFunc:r5},a5=ot(Yi,e=>Math.acosh(e)),o5={kernelName:Yi,backendName:"cpu",kernelFunc:a5};function i5(e){let{inputs:t,backend:n}=e,r=t;Ie(t,"addN");let s=r.map(i=>n.data.get(i.dataId).values),a=ze(r[0].shape,r[0].dtype),o=a.values;for(let i=0;i<r.length;i++){let c=s[i];for(let l=0;l<o.length;l++)o[l]+=c[l]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}var c5={kernelName:Ba,backendName:"cpu",kernelFunc:i5};function u5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ie(s,"all");let i=w.parseAxisParam(a,s.shape),c=i,l=_.getAxesPermutation(c,s.shape.length),u=s;l!=null&&(u=dr({inputs:{x:s},backend:n,attrs:{perm:l}}),c=_.getInnerMostAxes(c.length,s.shape.length)),_.assertAxesAreInnerMostDims("all",c,u.shape.length);let[d,p]=_.computeOutAndReduceShapes(u.shape,c),h=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let b=0;b<f.length;++b){let y=b*h,v=m[y];for(let x=0;x<h;++x){let k=m[y+x];v=v&&k}f[b]=v}l!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let b=_.expandShapeToKeepDim(d,i),y=yt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var l5={kernelName:Zi,backendName:"cpu",kernelFunc:u5};function d5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ie(s,"any");let i=w.parseAxisParam(a,s.shape),c=i,l=_.getAxesPermutation(c,s.shape.length),u=s;l!=null&&(u=dr({inputs:{x:s},backend:n,attrs:{perm:l}}),c=_.getInnerMostAxes(c.length,s.shape.length)),_.assertAxesAreInnerMostDims("any",c,u.shape.length);let[d,p]=_.computeOutAndReduceShapes(u.shape,c),h=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let b=0;b<f.length;++b){let y=b*h,v=m[y];for(let x=0;x<h;++x){let k=m[y+x];v=v||k}f[b]=v}l!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let b=_.expandShapeToKeepDim(d,i),y=yt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var p5={kernelName:Ji,backendName:"cpu",kernelFunc:d5};function h5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;Ie(s,"argMax");let o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=dr({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),o=[o[0]],_.assertAxesAreInnerMostDims("argMax",o,c.shape.length);let[u,d]=_.computeOutAndReduceShapes(c.shape,o),p=w.sizeFromShape(u),h=w.makeZerosTypedArray(p,"int32"),f=w.sizeFromShape(d),m=n.data.get(c.dataId).values;for(let g=0;g<h.length;++g){let b=g*f,y=m[b],v=0;for(let x=0;x<f;++x){let k=m[b+x];k>y&&(y=k,v=x)}h[g]=v}return l.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var f5={kernelName:za,backendName:"cpu",kernelFunc:h5};function m5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;Ie(s,"argMin");let o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=dr({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),o=[o[0]],_.assertAxesAreInnerMostDims("argMin",o,c.shape.length);let[u,d]=_.computeOutAndReduceShapes(c.shape,o),p=w.sizeFromShape(u),h=w.makeZerosTypedArray(p,"int32"),f=w.sizeFromShape(d),m=n.data.get(c.dataId).values;for(let g=0;g<h.length;++g){let b=g*f,y=m[b],v=0;for(let x=0;x<f;++x){let k=m[b+x];k<y&&(y=k,v=x)}h[g]=v}return l.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var g5={kernelName:xl,backendName:"cpu",kernelFunc:m5},b5=ot(Qi,e=>Math.asin(e)),y5={kernelName:Qi,backendName:"cpu",kernelFunc:b5},v5=ot(ec,e=>Math.asinh(e)),x5={kernelName:ec,backendName:"cpu",kernelFunc:v5},w5=ot(tc,e=>Math.atan(e)),k5={kernelName:tc,backendName:"cpu",kernelFunc:w5},I5=zt((e,t)=>Math.atan2(e,t)),S5=nn(rc,I5),C5={kernelName:rc,backendName:"cpu",kernelFunc:S5},T5=ot(nc,e=>Math.atanh(e)),N5={kernelName:nc,backendName:"cpu",kernelFunc:T5};function Sw(e,t,n,r,s,a){let o=s.strideHeight,i=s.strideWidth,c=s.dilationHeight,l=s.dilationWidth,u=s.effectiveFilterHeight,d=s.effectiveFilterWidth,p=s.padInfo.top,h=s.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=ze(s.outShape,n),g=m.values,b=s.outShape[1]*s.outShape[2]*s.outShape[3],y=s.outShape[2]*s.outShape[3],v=s.outShape[3];for(let x=0;x<s.batchSize;++x){let k=x*b,C=x*r[0];for(let N=0;N<s.inChannels;++N)for(let F=0;F<s.outHeight;++F){let R=F*o-p,O=Math.max(0,R),D=Math.min(s.inHeight,u+R),P=k+F*y;for(let T=0;T<s.outWidth;++T){let L=T*i-h,G=Math.max(0,L),j=Math.min(s.inWidth,d+L),q=f,K=0,ee=0;for(let ne=O;ne<D;ne+=c){let ae=C+ne*r[1];for(let se=G;se<j;se+=l){let re=ae+se*r[2],ue=e[re+N];a==="max"&&ue>q?q=ue:a==="avg"&&(K+=ue,ee++)}if(isNaN(q))break}let te=P+T*v+N;g[te]=a==="avg"?K/ee:q}}}return m}function e2(e,t,n,r,s=!1,a=!1){let o=ze(r.outShape,"int32"),i=r.strideHeight,c=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,d=r.effectiveFilterHeight,p=r.effectiveFilterWidth,h=r.padInfo.top,f=r.padInfo.left,m=ze(t,n,e);for(let g=0;g<r.batchSize;++g)for(let b=0;b<r.inChannels;++b)for(let y=0;y<r.outHeight;++y){let v=y*i-h,x=v;for(;x<0;)x+=l;let k=Math.min(r.inHeight,d+v);for(let C=0;C<r.outWidth;++C){let N=C*c-f,F=N;for(;F<0;)F+=u;let R=Math.min(r.inWidth,p+N),O=Number.NEGATIVE_INFINITY,D=-1;for(let P=x;P<k;P+=l){let T=P-v;for(let L=F;L<R;L+=u){let G=L-N,j=m.get(g,P,L,b);j>O&&(O=j,s?D=a?((g*r.inHeight+P)*r.inWidth+L)*r.inChannels+b:(P*r.inWidth+L)*r.inChannels+b:D=T*p+G)}}o.set(D,g,y,C,b)}}return o}function t2(e,t,n,r,s,a){let o=s.strideDepth,i=s.strideHeight,c=s.strideWidth,l=s.dilationDepth,u=s.dilationHeight,d=s.dilationWidth,p=s.effectiveFilterDepth,h=s.effectiveFilterHeight,f=s.effectiveFilterWidth,m=s.padInfo.front,g=s.padInfo.top,b=s.padInfo.left,y=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=ze(s.outShape,n),x=v.values,k=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],C=s.outShape[2]*s.outShape[3]*s.outShape[4],N=s.outShape[3]*s.outShape[4],F=s.outShape[4];for(let R=0;R<s.batchSize;++R){let O=R*k,D=R*r[0];for(let P=0;P<s.inChannels;++P)for(let T=0;T<s.outDepth;++T){let L=T*o-m,G=L;for(;G<0;)G+=l;let j=Math.min(s.inDepth,p+L),q=O+T*C;for(let K=0;K<s.outHeight;++K){let ee=K*i-g,te=ee;for(;te<0;)te+=u;let ne=Math.min(s.inHeight,h+ee),ae=q+K*N;for(let se=0;se<s.outWidth;++se){let re=se*c-b,ue=re;for(;ue<0;)ue+=d;let de=Math.min(s.inWidth,f+re),me=ae+se*F,we=y,Ce=0,_e=0;for(let Be=G;Be<j;Be+=l){let Ke=D+Be*r[1];for(let st=te;st<ne;st+=u){let et=Ke+st*r[2];for(let tt=ue;tt<de;tt+=d){let it=et+tt*r[3],lt=e[it+P];if(a==="max"&<>we?we=lt:a==="avg"&&(Ce+=lt,_e++),isNaN(we))break}if(isNaN(we))break}if(isNaN(we))break}let Me=me+P;x[Me]=a==="avg"?Ce/_e:we}}}}return v}function _5(e,t){let n=ze(t.outShape,"int32"),r=t.strideDepth,s=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let b=0;b<t.outDepth;++b){let y=b*r-p,v=y;for(;v<0;)v+=o;let x=Math.min(t.inDepth,l+y);for(let k=0;k<t.outHeight;++k){let C=k*s-h,N=C;for(;N<0;)N+=i;let F=Math.min(t.inHeight,u+C);for(let R=0;R<t.outWidth;++R){let O=R*a-f,D=O;for(;D<0;)D+=c;let P=Math.min(t.inWidth,d+O),T=Number.NEGATIVE_INFINITY,L=-1;for(let G=v;G<x;G+=o){let j=G-y;for(let q=N;q<F;q+=i){let K=q-C;for(let ee=D;ee<P;ee+=c){let te=ee-O,ne=e.get(m,G,q,ee,g);ne>=T&&(T=ne,L=j*u*d+K*u+te)}}}n.set(L,m,b,k,R,g)}}}return n}function E5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ie(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c),d;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))d=hs({inputs:{x:s},backend:n});else{let p=n.data.get(s.dataId).values,h=w.computeStrides(s.shape),f=Sw(p,s.shape,s.dtype,h,u,"avg");d=n.makeTensorInfo(u.outShape,s.dtype,f.values)}return d}var A5={kernelName:Wa,backendName:"cpu",kernelFunc:E5};function D5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r;Ie(s,"avgPool3d");let u=_.computePool3DInfo(s.shape,a,o,1,i,c,l),d=n.data.get(s.dataId).values,p=t2(d,s.shape,s.dtype,w.computeStrides(s.shape),u,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var F5={kernelName:wl,backendName:"cpu",kernelFunc:D5};function $5(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:o,strides:i,pad:c,dimRoundingMode:l}=r;Ie([s,a],"avgPool3DGrad");let u=_.computePool3DInfo(a.shape,o,i,1,c,l),d=u.strideDepth,p=u.strideHeight,h=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,b=u.dilationDepth,y=u.dilationHeight,v=u.dilationWidth,x=u.effectiveFilterDepth,k=u.effectiveFilterHeight,C=u.effectiveFilterWidth,N=x-1-u.padInfo.front,F=C-1-u.padInfo.left,R=k-1-u.padInfo.top,O=ze(a.shape,"float32"),D=1/(f*m*g),P=n.bufferSync(s);for(let T=0;T<u.batchSize;++T)for(let L=0;L<u.inChannels;++L)for(let G=0;G<u.inDepth;++G)for(let j=0;j<u.inHeight;++j)for(let q=0;q<u.inWidth;++q){let K=G-N,ee=j-R,te=q-F,ne=0;for(let ae=0;ae<x;ae+=b){let se=(K+ae)/d;if(!(se<0||se>=u.outDepth||Math.floor(se)!==se))for(let re=0;re<k;re+=y){let ue=(ee+re)/p;if(!(ue<0||ue>=u.outHeight||Math.floor(ue)!==ue))for(let de=0;de<C;de+=v){let me=(te+de)/h;if(me<0||me>=u.outWidth||Math.floor(me)!==me)continue;ne+=P.get(T,se,ue,me,L)}}}O.set(ne*D,T,G,j,q,L)}return n.makeTensorInfo(O.shape,O.dtype,O.values)}var R5={kernelName:Vp,backendName:"cpu",kernelFunc:$5};function P5(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Ie([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:l}=r,u=_.computePool2DInfo(o.shape,i,c,1,l),d=u.strideHeight,p=u.strideWidth,h=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,b=u.effectiveFilterHeight,y=u.effectiveFilterWidth,v=y-1-u.padInfo.left,x=b-1-u.padInfo.top,k=ze(o.shape,"float32"),C=1/(h*f),N=n.data.get(s.dataId).values,F=ze(s.shape,"float32",N);for(let R=0;R<u.batchSize;++R)for(let O=0;O<u.inChannels;++O)for(let D=0;D<u.inHeight;++D)for(let P=0;P<u.inWidth;++P){let T=D-x,L=P-v,G=0;for(let j=0;j<b;j+=m){let q=(T+j)/d;if(!(q<0||q>=u.outHeight||Math.floor(q)!==q))for(let K=0;K<y;K+=g){let ee=(L+K)/p;if(ee<0||ee>=u.outWidth||Math.floor(ee)!==ee)continue;G+=F.get(R,q,ee,O)}}k.set(G*C,R,D,P,O)}return n.makeTensorInfo(k.shape,k.dtype,k.values)}var O5={kernelName:Wp,backendName:"cpu",kernelFunc:P5};function M5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,scale:a,offset:o,mean:i,variance:c}=t;w.assert(i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ie([s,i,c,a,o],"batchNorm");let{varianceEpsilon:l}=r;l==null&&(l=.001);let u=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,p=n.data.get(c.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,b=h.length,y=p.length,v=d.length,x=0,k=0,C=0,N=0;for(let F=0;F<u.length;++F)m[F]=f[x++]+(u[F]-d[k++])*h[C++]/Math.sqrt(p[N++]+l),x>=g&&(x=0),k>=v&&(k=0),C>=b&&(C=0),N>=y&&(N=0);return n.makeTensorInfo(s.shape,s.dtype,m)}var L5={kernelName:no,backendName:"cpu",kernelFunc:M5};function B5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;Ie([s],"batchToSpaceND");let i=a.reduce((b,y)=>b*y),c=_.getReshaped(s.shape,a,i),l=_.getPermuted(c.length,a.length),u=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(u,o,a.length),h=yt({inputs:{x:s},backend:n,attrs:{shape:c}}),f=dr({inputs:{x:h},backend:n,attrs:{perm:l}}),m=yt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=pi({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var z5={kernelName:sc,backendName:"cpu",kernelFunc:B5};function W5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,l=gw(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}var V5={kernelName:Up,backendName:"cpu",kernelFunc:W5};function U5(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=_.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var G5={kernelName:Gp,backendName:"cpu",kernelFunc:U5},H5=ot(ea,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),j5={kernelName:ea,backendName:"cpu",kernelFunc:H5},q5=e=>{let{x:t}=e.inputs,n=e.backend,r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId),a=s.complexTensorInfos.real,o=s.complexTensorInfos.imag,i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values;for(let l=0;l<i.length;l++){let u=i[l],d=c[l];r[l]=Math.hypot(u,d)}return n.makeOutput(r,t.shape,"float32")},K5={kernelName:kl,backendName:"cpu",kernelFunc:q5};function Iu(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.imag,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}var X5={kernelName:ah,backendName:"cpu",kernelFunc:Iu};function Su(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(m=>m.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>w.sizeFromShape(m.shape)>0);if(i.length===1)return hs({inputs:{x:i[0]},backend:n});let c=i.map(m=>m.shape);if(_.assertParamsConsistent(c,a),i[0].dtype==="complex64"){let m=i.map(x=>di({inputs:{input:x},backend:n})),g=i.map(x=>Iu({inputs:{input:x},backend:n})),b=Su({inputs:m,backend:n,attrs:{axis:a}}),y=Su({inputs:g,backend:n,attrs:{axis:a}}),v=nr({inputs:{real:b,imag:y},backend:n});return m.forEach(x=>n.disposeIntermediateTensorInfo(x)),g.forEach(x=>n.disposeIntermediateTensorInfo(x)),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),v}let l=i.map(m=>{let g=w.sizeFromShape(m.shape.slice(a));return yt({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),u=l.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=_.computeOutShape(l.map(m=>m.shape),1);let d=l[0].shape[0]===1,p=bw(u,o,t[0].dtype,d),h=_.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,p);return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Y5={kernelName:ac,backendName:"cpu",kernelFunc:Su};function n2(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:l,dimRoundingMode:u}=r;Ie([s,a],"conv2d");let d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,b=p.padInfo.left,y=p.padInfo.top,v=p.dataFormat==="channelsLast",x=new Ut(p.outShape,s.dtype),k=w.computeStrides(s.shape),C=w.computeStrides(a.shape),N=k[0],F=v?k[1]:k[2],R=v?k[2]:1,O=v?1:k[1],D=x.strides[0],P=v?x.strides[1]:x.strides[2],T=v?x.strides[2]:1,L=v?1:x.strides[1],G=n.data.get(s.dataId).values,j=n.data.get(a.dataId).values,q=x.values;for(let K=0;K<p.batchSize;++K){let ee=K*N,te=K*D;for(let ne=0;ne<p.outHeight;++ne){let ae=te+ne*P,se=ne*p.strideHeight-y;for(let re=0;re<h;++re){let ue=se+re*m;if(ue<0||ue>=p.inHeight)continue;let de=re*C[0],me=ee+ue*F;for(let we=0;we<p.outWidth;++we){let Ce=ae+we*T,_e=we*p.strideWidth-b;for(let Me=0;Me<f;++Me){let Be=_e+Me*g;if(Be<0||Be>=p.inWidth)continue;let Ke=de+Me*C[1],st=me+Be*R,et=Ke;for(let tt=0;tt<p.inChannels;++tt){let it=G[st+tt*O];for(let lt=0;lt<p.outChannels;++lt)q[Ce+lt*L]+=it*j[et+lt];et+=p.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,q)}var Z5={kernelName:Ha,backendName:"cpu",kernelFunc:n2};function J5(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,filterShape:u}=r;Ie([s,a],"conv2dBackpropFilter");let d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,u,o,1,i,l,!1,d),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=p,b=p.dataFormat==="channelsLast",y=new Ut(p.filterShape,"float32"),v=p.padInfo.left,x=p.padInfo.top,k=n.data.get(s.dataId).values,C=n.data.get(a.dataId).values,N=new Ut(s.shape,s.dtype,k),F=new Ut(a.shape,a.dtype,C);for(let R=0;R<m;++R){let O=Math.max(0,Math.ceil((x-R)/h)),D=Math.min(p.outHeight,(p.inHeight+x-R)/h);for(let P=0;P<g;++P){let T=Math.max(0,Math.ceil((v-P)/f)),L=Math.min(p.outWidth,(p.inWidth+v-P)/f);for(let G=0;G<p.inChannels;++G)for(let j=0;j<p.outChannels;++j){let q=0;for(let K=0;K<p.batchSize;++K)for(let ee=O;ee<D;++ee){let te=R+ee*h-x;for(let ne=T;ne<L;++ne){let ae=P+ne*f-v;b?q+=N.get(K,te,ae,G)*F.get(K,ee,ne,j):q+=N.get(K,G,te,ae)*F.get(K,j,ee,ne)}}y.set(q,R,P,G,j)}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var Q5={kernelName:jp,backendName:"cpu",kernelFunc:J5};function ej(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:l,dimRoundingMode:u}=r;Ie([s,a],"conv2dBackpropInput");let d=w.computeStrides(a.shape),p=w.computeStrides(s.shape),h=_.convertConv2DDataFormat(l),f=_.computeConv2DInfo(o,a.shape,i,1,c,u,!1,h),m=new Ut(f.inShape,"float32"),g=m.values,b=n.data.get(s.dataId).values,y=n.data.get(a.dataId).values,[v,x,k]=d,{batchSize:C,filterHeight:N,filterWidth:F,inChannels:R,inHeight:O,inWidth:D,outChannels:P,outHeight:T,outWidth:L,strideHeight:G,strideWidth:j}=f;h=f.dataFormat;let q=N-1-f.padInfo.top,K=F-1-f.padInfo.left,ee=h==="channelsLast",te=m.strides[0],ne=ee?m.strides[1]:m.strides[2],ae=ee?m.strides[2]:1,se=ee?1:m.strides[1],re=p[0],ue=ee?p[1]:p[2],de=ee?p[2]:1,me=ee?1:p[1];for(let we=0;we<C;++we)for(let Ce=0;Ce<R;++Ce)for(let _e=0;_e<O;++_e){let Me=_e-q,Be=Math.max(0,Math.ceil(Me/G)),Ke=Math.min(T,(N+Me)/G);for(let st=0;st<D;++st){let et=st-K,tt=Math.max(0,Math.ceil(et/j)),it=Math.min(L,(F+et)/j),lt=0;for(let Nt=Be;Nt<Ke;++Nt){let $n=Nt*G-Me;for(let sn=tt;sn<it;++sn){let Dr=sn*j-et,yn=re*we+ue*Nt+de*sn,Hn=v*(N-1-$n)+x*(F-1-Dr)+k*Ce;for(let br=0;br<P;++br){let ar=b[yn+me*br],an=y[Hn+br];lt+=ar*an}}}let xt=te*we+ne*_e+ae*st+se*Ce;g[xt]=lt}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var tj={kernelName:ja,backendName:"cpu",kernelFunc:ej};function nj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r;Ie([s,a],"conv3d");let l=_.computeConv3DInfo(s.shape,a.shape,o,c,i),{filterDepth:u,filterHeight:d,filterWidth:p,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=l,b=g.front,y=g.left,v=g.top,x=new Ut(l.outShape,s.dtype),k=n.data.get(s.dataId).values,C=n.data.get(a.dataId).values,N=x.values,F=w.computeStrides(s.shape),R=w.computeStrides(a.shape);for(let O=0;O<l.batchSize;++O){let D=O*F[0],P=O*x.strides[0];for(let T=0;T<l.outDepth;++T){let L=P+T*x.strides[1],G=T*l.strideDepth-b;for(let j=0;j<u;++j){let q=G+j*h;if(q<0||q>=l.inDepth)continue;let K=j*R[0],ee=D+q*F[1];for(let te=0;te<l.outHeight;++te){let ne=L+te*x.strides[2],ae=te*l.strideHeight-v;for(let se=0;se<d;++se){let re=ae+se*f;if(re<0||re>=l.inHeight)continue;let ue=K+se*R[1],de=ee+re*F[2];for(let me=0;me<l.outWidth;++me){let we=ne+me*l.outChannels,Ce=me*l.strideWidth-y;for(let _e=0;_e<p;++_e){let Me=Ce+_e*m;if(Me<0||Me>=l.inWidth)continue;let Be=ue+_e*R[2],Ke=de+Me*l.inChannels,st=Be;for(let et=0;et<l.inChannels;++et){let tt=k[Ke+et];for(let it=0;it<l.outChannels;++it)N[we+it]+=tt*C[st+it];st+=l.outChannels}}}}}}}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}var rj={kernelName:Il,backendName:"cpu",kernelFunc:nj};function sj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r;Ie([s,a],"conv3dBackpropFilterV2");let l=w.computeStrides(s.shape),u=w.computeStrides(a.shape),d=_.computeConv3DInfo(s.shape,c,o,1,i),p=d.strideDepth,h=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,b=d.filterWidth,y=new Ut(d.filterShape,"float32"),v=y.values,[x,k,C,N]=y.strides,F=n.data.get(a.dataId).values,[R,O,D,P]=u,T=n.data.get(s.dataId).values,[L,G,j,q]=l,K=d.padInfo.front,ee=d.padInfo.left,te=d.padInfo.top;for(let ne=0;ne<m;++ne){let ae=Math.max(0,Math.ceil((K-ne)/p)),se=Math.min(d.outDepth,(d.inDepth+K-ne)/p),re=ne*x;for(let ue=0;ue<g;++ue){let de=Math.max(0,Math.ceil((te-ue)/h)),me=Math.min(d.outHeight,(d.inHeight+te-ue)/h),we=ue*k+re;for(let Ce=0;Ce<b;++Ce){let _e=Math.max(0,Math.ceil((ee-Ce)/f)),Me=Math.min(d.outWidth,(d.inWidth+ee-Ce)/f),Be=Ce*C+we;for(let Ke=0;Ke<d.inChannels;++Ke){let st=Ke*N+Be;for(let et=0;et<d.outChannels;++et){let tt=0;for(let it=0;it<d.batchSize;++it){let lt=it*L,xt=it*R;for(let Nt=ae;Nt<se;++Nt){let sn=(ne+Nt*p-K)*G+lt,Dr=Nt*O+xt;for(let yn=de;yn<me;++yn){let br=(ue+yn*h-te)*j+sn,ar=yn*D+Dr;for(let an=_e;an<Me;++an){let hn=(Ce+an*f-ee)*q+br,Zr=an*P+ar;tt+=T[hn+Ke]*F[Zr+et]}}}}v[st+et]=tt}}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var aj={kernelName:qp,backendName:"cpu",kernelFunc:sj};function oj(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r;Ie([s],"conv3dBackpropInputV2");let l=w.computeStrides(s.shape),u=w.computeStrides(a.shape),d=_.computeConv3DInfo(c,a.shape,i,1,o),p=new Ut(d.inShape,"float32"),h=p.values,[f,m,g,b]=p.strides,y=n.data.get(s.dataId).values,[v,x,k,C]=l,N=n.data.get(a.dataId).values,[F,R,O,D]=u,{batchSize:P,filterDepth:T,filterHeight:L,filterWidth:G,inChannels:j,inDepth:q,inHeight:K,inWidth:ee,outChannels:te,outDepth:ne,outHeight:ae,outWidth:se,strideDepth:re,strideHeight:ue,strideWidth:de}=d,me=T-1-d.padInfo.front,we=L-1-d.padInfo.top,Ce=G-1-d.padInfo.left;for(let _e=0;_e<P;++_e)for(let Me=0;Me<j;++Me)for(let Be=0;Be<q;++Be){let Ke=Be-me,st=Math.max(0,Math.ceil(Ke/re)),et=Math.min(ne,(T+Ke)/re);for(let tt=0;tt<K;++tt){let it=tt-we,lt=Math.max(0,Math.ceil(it/ue)),xt=Math.min(ae,(L+it)/ue);for(let Nt=0;Nt<ee;++Nt){let $n=Nt-Ce,sn=Math.max(0,Math.ceil($n/de)),Dr=Math.min(se,(G+$n)/de),yn=0;for(let Hn=st;Hn<et;++Hn){let br=Hn*re-Ke;for(let ar=lt;ar<xt;++ar){let an=ar*ue-it;for(let Yr=sn;Yr<Dr;++Yr){let hn=Yr*de-$n,Zr=v*_e+x*Hn+k*ar+C*Yr,Jr=F*(T-1-br)+R*(L-1-an)+O*(G-1-hn)+D*Me;for(let Gs=0;Gs<te;++Gs){let sl=y[Zr+Gs],Fr=N[Jr+Gs];yn+=sl*Fr}}}}h[f*_e+m*Be+g*tt+b*Nt+Me]=yn}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}var ij={kernelName:Kp,backendName:"cpu",kernelFunc:oj},cj=ot(qa,e=>Math.cos(e)),uj={kernelName:qa,backendName:"cpu",kernelFunc:cj},lj=ot(Ka,e=>Math.cosh(e)),dj={kernelName:Ka,backendName:"cpu",kernelFunc:lj};function pj(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:l}=r,[u,d,p,h]=s.shape,f=a.shape[0],[m,g]=i,b=ze([f,m,g,h],"float32"),y=n.data.get(a.dataId).values,v=n.data.get(o.dataId).values,x=n.data.get(s.dataId).values,k=w.computeStrides(s.shape),C=w.computeStrides(b.shape);for(let N=0;N<f;N++){let F=N*4,R=y[F],O=y[F+1],D=y[F+2],P=y[F+3],T=v[N];if(T>=u)continue;let L=m>1?(D-R)*(d-1)/(m-1):0,G=g>1?(P-O)*(p-1)/(g-1):0;for(let j=0;j<m;j++){let q=m>1?R*(d-1)+j*L:.5*(R+D)*(d-1);if(q<0||q>d-1){for(let K=0;K<g;K++)for(let ee=0;ee<h;ee++){let te=ee+K*C[2]+j*C[1]+N*C[0];b.values[te]=l}continue}if(c==="bilinear"){let K=Math.floor(q),ee=Math.ceil(q),te=q-K;for(let ne=0;ne<g;ne++){let ae=g>1?O*(p-1)+ne*G:.5*(O+P)*(p-1);if(ae<0||ae>p-1){for(let de=0;de<h;de++){let me=de+ne*C[2]+j*C[1]+N*C[0];b.values[me]=l}continue}let se=Math.floor(ae),re=Math.ceil(ae),ue=ae-se;for(let de=0;de<h;de++){let me=de+se*k[2]+K*k[1]+T*k[0],we=x[me];me=de+re*k[2]+K*k[1]+T*k[0];let Ce=x[me];me=de+se*k[2]+ee*k[1]+T*k[0];let _e=x[me];me=de+re*k[2]+ee*k[1]+T*k[0];let Me=x[me],Be=we+(Ce-we)*ue,Ke=_e+(Me-_e)*ue;me=de+ne*C[2]+j*C[1]+N*C[0],b.values[me]=Be+(Ke-Be)*te}}}else for(let K=0;K<g;++K){let ee=g>1?O*(p-1)+K*G:.5*(O+P)*(p-1);if(ee<0||ee>p-1){for(let ae=0;ae<h;ae++){let se=ae+K*C[2]+j*C[1]+N*C[0];b.values[se]=l}continue}let te=Math.round(ee),ne=Math.round(q);for(let ae=0;ae<h;ae++){let se=ae+te*k[2]+ne*k[1]+T*k[0],re=ae+K*C[2]+j*C[1]+N*C[0];b.values[re]=x[se]}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var hj={kernelName:oc,backendName:"cpu",kernelFunc:pj};function fj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;Ie(s,"cumsum");let c=_.getAxesPermutation([a],s.shape.length),l=s;c!=null&&(l=dr({inputs:{x:s},backend:n,attrs:{perm:c}}));let u=_.getInnerMostAxes(1,s.shape.length)[0];if(u!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${u}`);let d=wr(l.dtype,"int32"),p=w.makeZerosTypedArray(w.sizeFromShape(l.shape),d),h=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=i?(b,y)=>b+f-y-1:(b,y)=>b+y;for(let b=0;b<h.length;b+=f)for(let y=0;y<f;y++){let v=m(b,y);if(y===0)p[v]=o?0:h[v];else{let x=m(b,y-1);p[v]=o?h[x]+p[x]:h[v]+p[x]}}let g=n.makeTensorInfo(l.shape,d,p);if(c!=null){let b=_.getUndoAxesPermutation(c),y=dr({inputs:{x:g},backend:n,attrs:{perm:b}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),y}return g}var mj={kernelName:Xa,backendName:"cpu",kernelFunc:fj};function gj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=gw(c,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(s.shape.length===2){let c=n.bufferSync(s),l=n.bufferSync(a),u=pT(c,l,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var bj={kernelName:Xp,backendName:"cpu",kernelFunc:gj};function yj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r;w.assert(o==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=s.shape[0],c=s.shape[1],l=s.shape[2],u=s.shape[3],d=c*a,p=l*a,h=u/(a*a),f=n.data.get(s.dataId).values,m=new Float32Array(i*d*p*h),g=0;for(let b=0;b<i;++b)for(let y=0;y<d;++y){let v=Math.floor(y/a),x=y%a;for(let k=0;k<p;++k){let C=Math.floor(k/a),N=k%a,F=(x*a+N)*h;for(let R=0;R<h;++R){let D=R+F+u*(C+l*(v+c*b));m[g++]=f[D]}}}return n.makeTensorInfo([i,d,p,h],s.dtype,m)}var vj={kernelName:ic,backendName:"cpu",kernelFunc:yj};function r2(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:l}=r;Ie([s,a],"depthwiseConv2DNative");let u=w.computeStrides(s.shape),d=w.computeStrides(a.shape),p=c;p==null&&(p=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(o,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);let h=_.computeConv2DInfo(s.shape,a.shape,o,p,i,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:b,padInfo:y}=h,v=y.left,x=y.top,k=h.outChannels/h.inChannels,C=new Ut(h.outShape,s.dtype),N=n.data.get(s.dataId).values,F=n.data.get(a.dataId).values,R=C.values;for(let O=0;O<h.batchSize;++O){let D=O*u[0],P=O*C.strides[0];for(let T=0;T<h.outHeight;++T){let L=P+T*C.strides[1],G=T*h.strideHeight-x;for(let j=0;j<f;++j){let q=G+j*g;if(q<0||q>=h.inHeight)continue;let K=j*d[0],ee=D+q*u[1];for(let te=0;te<h.outWidth;++te){let ne=L+te*C.strides[2],ae=te*h.strideWidth-v;for(let se=0;se<m;++se){let re=ae+se*b;if(re<0||re>=h.inWidth)continue;let ue=K+se*d[1],de=ee+re*h.inChannels,me=ne,we=ue;for(let Ce=0;Ce<h.inChannels;++Ce){let _e=N[de+Ce];for(let Me=0;Me<k;++Me)R[me+Me]+=_e*F[we+Me];me+=k,we+=k}}}}}}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var xj={kernelName:Ya,backendName:"cpu",kernelFunc:r2};function wj(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,filterShape:u}=r;Ie([s,a],"depthwiseConv2dNativeBackpropFilter");let d=_.computeConv2DInfo(s.shape,u,o,i,c,l,!0),{strideHeight:p,strideWidth:h,filterHeight:f,filterWidth:m}=d,g=new Ut(d.filterShape,"float32"),b=d.padInfo.left,y=d.padInfo.top,v=d.outChannels/d.inChannels,x=n.data.get(s.dataId).values,k=new Ut(s.shape,s.dtype,x),C=n.data.get(a.dataId).values,N=new Ut(a.shape,a.dtype,C);for(let F=0;F<f;++F){let R=Math.max(0,Math.ceil((y-F)/p)),O=Math.min(d.outHeight,(d.inHeight+y-F)/p);for(let D=0;D<m;++D){let P=Math.max(0,Math.ceil((b-D)/h)),T=Math.min(d.outWidth,(d.inWidth+b-D)/h);for(let L=0;L<d.outChannels;++L){let G=Math.trunc(L/v),j=L%v,q=0;for(let K=0;K<d.batchSize;++K)for(let ee=R;ee<O;++ee){let te=F+ee*p-y;for(let ne=P;ne<T;++ne){let ae=D+ne*h-b;q+=k.get(K,te,ae,G)*N.get(K,ee,ne,L)}}g.set(q,F,D,G,j)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var kj={kernelName:Yp,backendName:"cpu",kernelFunc:wj};function Ij(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,inputShape:u}=r;Ie([s,a],"depthwiseConv2DNativeBackpropInput");let d=w.computeStrides(s.shape),p=w.computeStrides(a.shape),h=_.computeConv2DInfo(u,a.shape,o,i,c,l,!0),f=new Ut(h.inShape,"float32"),m=f.values,[g,b,y]=f.strides,v=n.data.get(s.dataId).values,[x,k,C]=d,N=n.data.get(a.dataId).values,[F,R,O]=p,{batchSize:D,filterHeight:P,filterWidth:T,inChannels:L,inHeight:G,inWidth:j,outChannels:q,outHeight:K,outWidth:ee,strideHeight:te,strideWidth:ne}=h,ae=P-1-h.padInfo.top,se=T-1-h.padInfo.left,re=q/L;for(let ue=0;ue<D;++ue)for(let de=0;de<L;++de)for(let me=0;me<G;++me){let we=me-ae,Ce=Math.max(0,Math.ceil(we/te)),_e=Math.min(K,(P+we)/te);for(let Me=0;Me<j;++Me){let Be=Me-se,Ke=Math.max(0,Math.ceil(Be/ne)),st=Math.min(ee,(T+Be)/ne),et=0;for(let tt=Ce;tt<_e;++tt){let it=tt*te-we;for(let lt=Ke;lt<st;++lt){let xt=lt*ne-Be,Nt=x*ue+k*tt+C*lt,$n=F*(P-1-it)+R*(T-1-xt)+O*de;for(let sn=0;sn<re;++sn){let Dr=de*re+sn,yn=v[Nt+Dr],Hn=N[$n+sn];et+=yn*Hn}}}m[g*ue+b*me+y*Me+de]=et}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var Sj={kernelName:Zp,backendName:"cpu",kernelFunc:Ij};function Cj(e){let{inputs:t,backend:n}=e,{x:r}=t,s=w.sizeFromShape(r.shape),a=n.data.get(r.dataId).values,o=ze([s,s],r.dtype),i=o.values;for(let l=0;l<a.length;l++)i[l*s+l]=a[l];let c=[...r.shape,...r.shape];return n.makeTensorInfo(c,o.dtype,o.values)}var Tj={kernelName:Jp,backendName:"cpu",kernelFunc:Cj},Nj={kernelName:Sl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s}=e,{strides:a,pad:o,dilations:i}=n,c=t,l=c.data.get(r.dataId).values,u=r.shape.length,d=c.data.get(s.dataId).values,p=s.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:b,outWidth:y,padInfo:v,strideHeight:x,strideWidth:k,filterHeight:C,filterWidth:N,dilationHeight:F,dilationWidth:R,outShape:O}=_.computeDilation2DInfo(r.shape,s.shape,a,o,"NHWC",i),D=w.sizeFromShape(O),P=O.length,T=w.getArrayFromDType(r.dtype,D);for(let G=0;G<h;++G)for(let j=0;j<b;++j){let q=j*x-v.top;for(let K=0;K<y;++K){let ee=K*k-v.left;for(let te=0;te<g;++te){let ne=Number.MIN_SAFE_INTEGER;for(let se=0;se<C;++se){let re=q+se*F;if(re>=0&&re<f)for(let ue=0;ue<N;++ue){let de=ee+ue*R;if(de>=0&&de<m){let me=w.locToIndex([G,re,de,te],u,w.computeStrides(r.shape)),we=w.locToIndex([se,ue,te],p,w.computeStrides(s.shape)),Ce=l[me]+d[we];Ce>ne&&(ne=Ce)}}}let ae=w.locToIndex([G,j,K,te],P,w.computeStrides(O));T[ae]=ne}}}return{dataId:c.write(w.toTypedArray(T,r.dtype),O,r.dtype),shape:O,dtype:r.dtype}}},_j={kernelName:eh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s,dy:a}=e,{strides:o,pad:i,dilations:c}=n,l=t,u=w.toNestedArray(r.shape,l.data.get(r.dataId).values),d=w.toNestedArray(s.shape,l.data.get(s.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:y,strideHeight:v,strideWidth:x,filterHeight:k,filterWidth:C,dilationHeight:N,dilationWidth:F,outShape:R}=_.computeDilation2DInfo(r.shape,s.shape,o,i,"NHWC",c);w.assert(a.rank===R.length,()=>`Error in ${eh}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let O=w.toNestedArray(R,l.data.get(a.dataId).values),D=w.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T<p;++T)for(let L=0;L<g;++L){let G=L*v-y.top;for(let j=0;j<b;++j){let q=j*x-y.left;for(let K=0;K<m;++K){let ee=Number.MIN_SAFE_INTEGER,te=0,ne=0;for(let ae=0;ae<k;++ae){let se=G+ae*N;if(se>=0&&se<h)for(let re=0;re<C;++re){let ue=q+re*F;if(ue>=0&&ue<f){let de=u[T][se][ue][K]+d[ae][re][K];de>ee&&(ee=de,te=ae,ne=re)}}}D[te][ne][K]+=O[T][L][j][K]}}}return{dataId:l.write(w.toTypedArray(D,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},Ej={kernelName:Qp,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s,dy:a}=e,{strides:o,pad:i,dilations:c}=n,l=t,u=w.toNestedArray(r.shape,l.data.get(r.dataId).values),d=w.toNestedArray(s.shape,l.data.get(s.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:y,strideHeight:v,strideWidth:x,filterHeight:k,filterWidth:C,dilationHeight:N,dilationWidth:F,outShape:R}=_.computeDilation2DInfo(r.shape,s.shape,o,i,"NHWC",c);w.assert(a.rank===R.length,()=>`Error in ${Qp}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let O=w.toNestedArray(R,l.data.get(a.dataId).values),D=w.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T<p;++T)for(let L=0;L<g;++L){let G=L*v-y.top;for(let j=0;j<b;++j){let q=j*x-y.left;for(let K=0;K<m;++K){let ee=Number.MIN_SAFE_INTEGER,te=G<0?0:G,ne=q<0?0:q;for(let ae=0;ae<k;++ae){let se=G+ae*N;if(se>=0&&se<h)for(let re=0;re<C;++re){let ue=q+re*F;if(ue>=0&&ue<f){let de=u[T][se][ue][K]+d[ae][re][K];de>ee&&(ee=de,te=se,ne=ue)}}}D[T][te][ne][K]+=O[T][L][j][K]}}}return{dataId:l.write(w.toTypedArray(D,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};function Dd(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ie(s,"sum");let i;s.dtype==="bool"?i=ka({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):i=hs({inputs:{x:s},backend:n});let c=i.shape.length,l=w.parseAxisParam(a,i.shape),u=_.getAxesPermutation(l,c),d=l,p=i;u!=null&&(p=dr({inputs:{x:i},backend:n,attrs:{perm:u}}),d=_.getInnerMostAxes(d.length,c)),_.assertAxesAreInnerMostDims("sum",d,p.shape.length);let[h,f]=_.computeOutAndReduceShapes(p.shape,d),m=_.upcastType(p.dtype,"int32"),g=am(n,h,m),b=w.sizeFromShape(f),y=n.data.get(g.dataId).values,v=n.data.get(p.dataId).values;for(let x=0;x<y.length;++x){let k=x*b,C=0;for(let N=0;N<b;++N)C+=v[k+N];y[x]=C}if(o){let x=_.expandShapeToKeepDim(g.shape,l),k=g;g=yt({inputs:{x:g},backend:n,attrs:{shape:x}}),n.disposeIntermediateTensorInfo(k)}return n.disposeIntermediateTensorInfo(i),u!=null&&n.disposeIntermediateTensorInfo(p),g}var Aj={kernelName:Eo,backendName:"cpu",kernelFunc:Dd};function Dj(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=_.decodeEinsumEquation(s,a.length);_.checkEinsumDimSizes(o.length,c,a);let{path:l,steps:u}=_.getEinsumComputePath(i,c),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=dr({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let k=0;k<y.length;++k)x.splice(y[k],0,1);w.arraysEqual(v.shape,x)||(v=yt({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=om({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=Dd({inputs:{x:p},backend:n,attrs:{axis:l[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var Fj={kernelName:th,backendName:"cpu",kernelFunc:Dj};function $j(e){let{inputs:t,backend:n}=e,{dy:r,y:s}=t;Ie([r,s],"eluGrad");let a=new Float32Array(w.sizeFromShape(s.shape)),o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values;for(let c=0;c<o.length;++c){let l=o[c];l>=1?a[c]=i[c]:a[c]=i[c]*(l+1)}return n.makeTensorInfo(s.shape,"float32",a)}var Rj={kernelName:nh,backendName:"cpu",kernelFunc:$j},Pj=_.ERF_P,Oj=_.ERF_A1,Mj=_.ERF_A2,Lj=_.ERF_A3,Bj=_.ERF_A4,zj=_.ERF_A5,Wj=ot(cc,e=>{let t=Math.sign(e),n=Math.abs(e),r=1/(1+Pj*n);return t*(1-((((zj*r+Bj)*r+Lj)*r+Mj)*r+Oj)*r*Math.exp(-n*n))}),Vj={kernelName:cc,backendName:"cpu",kernelFunc:Wj};function cm(e){let{inputs:t,backend:n,attrs:r}=e,{input:s}=t,{dim:a}=r,o=s.shape.length,i=s.shape.slice(),c=a;return a<0&&(w.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+a+1),i.splice(c,0,1),yt({inputs:{x:s},backend:n,attrs:{shape:i}})}var Uj={kernelName:lc,backendName:"cpu",kernelFunc:cm},Gj=zt((e,t)=>e/t),Cw=nn(Za,Gj),Tw={kernelName:Za,backendName:"cpu",kernelFunc:Cw};function s2(e,t,n){let r=e.shape,s=r[0],a=r[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,c=o.complexTensorInfos.imag,l=[s,a],u=w.sizeFromShape(l),d=w.getTypedArrayFromDType("float32",u),p=w.getTypedArrayFromDType("float32",u);for(let g=0;g<s;g++){let b=pi({inputs:{x:i},backend:n,attrs:{begin:[g,0],size:[1,a]}}),y=pi({inputs:{x:c},backend:n,attrs:{begin:[g,0],size:[1,a]}}),v=nr({inputs:{real:b,imag:y},backend:n}),{real:x,imag:k}=Hj(v,t,n),C=_.mergeRealAndImagArrays(x,k);for(let N=0;N<a;N++){let F=_.getComplexWithIndex(C,N);d[g*a+N]=F.real,p[g*a+N]=F.imag}n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(v)}let h=n.makeTensorInfo(l,"float32",d),f=n.makeTensorInfo(l,"float32",p),m=nr({inputs:{real:h,imag:f},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}function Hj(e,t,n){let r=w.sizeFromShape(e.shape),s=n.data.get(e.dataId),a=n.data.get(s.complexTensorInfos.real.dataId).values,o=n.data.get(s.complexTensorInfos.imag.dataId).values;if(jj(r)){let i=Nw(a,o,r,t,n),c=[e.shape[0],e.shape[1]];if(t){let l=n.makeTensorInfo(c,"float32",i.real),u=n.makeTensorInfo(c,"float32",i.imag),d=n.makeTensorInfo([],"float32",w.createScalarValue(r,"float32")),p=hs({inputs:{x:d},backend:n}),h=Tw.kernelFunc({inputs:{a:l,b:d},backend:n}),f=Tw.kernelFunc({inputs:{a:u,b:p},backend:n}),m=n.data.get(h.dataId).values,g=n.data.get(f.dataId).values;return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return i}else{let i=_.mergeRealAndImagArrays(a,o),c=qj(i,r,t);return _.splitRealAndImagArrays(c)}}function jj(e){return(e&e-1)==0}function Nw(e,t,n,r,s){if(n===1)return{real:e,imag:t};let a=_.mergeRealAndImagArrays(e,t),o=n/2,i=_.complexWithEvenIndex(a),c=i.real,l=i.imag,u=[c.length],d=s.makeTensorInfo(u,"float32",c),p=s.makeTensorInfo(u,"float32",l),h=nr({inputs:{real:d,imag:p},backend:s}),f=_.complexWithOddIndex(a),m=f.real,g=f.imag,b=[m.length],y=s.makeTensorInfo(b,"float32",m),v=s.makeTensorInfo(b,"float32",g),x=nr({inputs:{real:y,imag:v},backend:s}),k=Nw(c,l,o,r,s),C=k.real,N=k.imag,F=[C.length],R=s.makeTensorInfo(F,"float32",C),O=s.makeTensorInfo(F,"float32",N),D=nr({inputs:{real:R,imag:O},backend:s}),P=Nw(m,g,o,r,s),T=P.real,L=P.imag,G=[T.length],j=s.makeTensorInfo(G,"float32",T),q=s.makeTensorInfo(G,"float32",L),K=nr({inputs:{real:j,imag:q},backend:s}),ee=_.exponents(n,r),te=[ee.real.length],ne=s.makeTensorInfo(te,"float32",ee.real),ae=s.makeTensorInfo(te,"float32",ee.imag),se=nr({inputs:{real:ne,imag:ae},backend:s}),re=om({inputs:{a:se,b:K},backend:s}),ue=Ed({inputs:{a:D,b:re},backend:s}),de=kw({inputs:{a:D,b:re},backend:s}),me=di({inputs:{input:ue},backend:s}),we=di({inputs:{input:de},backend:s}),Ce=Iu({inputs:{input:ue},backend:s}),_e=Iu({inputs:{input:de},backend:s}),Me=Su({inputs:[me,we],backend:s,attrs:{axis:0}}),Be=Su({inputs:[Ce,_e],backend:s,attrs:{axis:0}}),Ke=s.data.get(Me.dataId).values,st=s.data.get(Be.dataId).values;return s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(y),s.disposeIntermediateTensorInfo(v),s.disposeIntermediateTensorInfo(x),s.disposeIntermediateTensorInfo(R),s.disposeIntermediateTensorInfo(O),s.disposeIntermediateTensorInfo(D),s.disposeIntermediateTensorInfo(j),s.disposeIntermediateTensorInfo(q),s.disposeIntermediateTensorInfo(K),s.disposeIntermediateTensorInfo(ne),s.disposeIntermediateTensorInfo(ae),s.disposeIntermediateTensorInfo(se),s.disposeIntermediateTensorInfo(re),s.disposeIntermediateTensorInfo(ue),s.disposeIntermediateTensorInfo(de),s.disposeIntermediateTensorInfo(me),s.disposeIntermediateTensorInfo(Ce),s.disposeIntermediateTensorInfo(we),s.disposeIntermediateTensorInfo(_e),s.disposeIntermediateTensorInfo(Me),s.disposeIntermediateTensorInfo(Be),{real:Ke,imag:st}}function qj(e,t,n){let r=new Float32Array(t*2);for(let s=0;s<t;s++){let a=0,o=0;for(let i=0;i<t;i++){let c=_.exponent(s*i,t,n),l=_.getComplexWithIndex(e,i);a+=l.real*c.real-l.imag*c.imag,o+=l.real*c.imag+l.imag*c.real}n&&(a/=t,o/=t),_.assignToTypedArray(r,a,o,s)}return r}function Kj(e){let{inputs:t,backend:n}=e,{input:r}=t,s=w.sizeFromShape(r.shape),a=r.shape[r.shape.length-1],o=s/a,i=yt({inputs:{x:r},backend:n,attrs:{shape:[o,a]}}),c=s2(i,!1,n),l=yt({inputs:{x:c},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(c),l}var Xj={kernelName:rh,backendName:"cpu",kernelFunc:Kj};function _w(e){let{backend:t,attrs:n}=e,{shape:r,value:s,dtype:a}=n,o=a||w.inferDtype(s),i=w.getArrayFromDType(o,w.sizeFromShape(r));return Zj(i,s,o),t.makeTensorInfo(r,o,i)}var Yj={kernelName:Cl,backendName:"cpu",kernelFunc:_w};function Zj(e,t,n){e.fill(t)}var Jj={kernelName:pc,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,s=n,a=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(r.shape)),[o,i,c,l]=r.shape,u=s.data.get(r.dataId).values;for(let p=0;p<o;p++){let h=p*c*i*l;for(let f=0;f<i;f++){let m=f*(c*l);for(let g=0;g<c;g++){let b=g*l;for(let y=0;y<l;y++){let v=Math.round(c-g-1),x=h+m+b+y,k=u[x];if(v>=0&&v<c){let C=v*l,N=h+m+C+y;k=u[N]}a[x]=k}}}}return{dataId:s.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},Qj=zt((e,t)=>Math.floor(e/t)),eq=nn(to,Qj,null,"int32"),tq={kernelName:to,backendName:"cpu",kernelFunc:eq};function nq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=n2({inputs:{x:s,filter:a},backend:n,attrs:{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ed({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Iw(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var rq={kernelName:Mo,backendName:"cpu",kernelFunc:nq};function sq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=r2({inputs:{x:s,filter:a},backend:n,attrs:{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=Ed({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Iw(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var aq={kernelName:Lo,backendName:"cpu",kernelFunc:sq};function oq(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=w.sizeFromShape(r.shape),o=s.shape,i=o[o.length-1],[c,l,u,d]=_.prepareAndValidate(r,s);if(l===0)return n.makeTensorInfo(c,r.dtype,[]);let p=n.data.get(s.dataId).values,h=n.bufferSync(r),f=xT(p,h,r.dtype,l,i,u,d,r.shape,a);return n.makeTensorInfo(c,r.dtype,f.values)}var iq={kernelName:fc,backendName:"cpu",kernelFunc:oq};function cq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r;Ie([s,a],"gatherV2");let c=w.parseAxisParam(o,s.shape)[0],l=n.data.get(a.dataId).values,u=s.shape[c];for(let x=0;x<l.length;++x){let k=l[x];w.assert(k<=u-1&&k>=0,()=>`GatherV2: the index value ${k} is not in [0, ${u-1}]`)}let d=i;i==null&&(d=0);let p=w.sizeFromShape(a.shape),h=_.segment_util.collectGatherOpShapeInfo(s,a,c,d),f=yt({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=yt({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],b=n.bufferSync(m),y=n.bufferSync(f),v=wT(y,b,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,v.dtype,v.values)}var uq={kernelName:hc,backendName:"cpu",kernelFunc:cq};function lq(e){let{inputs:t,backend:n}=e,{input:r}=t,s=w.sizeFromShape(r.shape),a=r.shape[r.shape.length-1],o=s/a,i=yt({inputs:{x:r},backend:n,attrs:{shape:[o,a]}}),c=s2(i,!0,n),l=yt({inputs:{x:c},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(c),l}var dq={kernelName:sh,backendName:"cpu",kernelFunc:lq},pq=ot(gc,e=>Number.isFinite(e)?1:0,"bool"),hq={kernelName:gc,backendName:"cpu",kernelFunc:pq},fq=ot(bc,e=>Math.abs(e)===1/0?1:0,"bool"),mq={kernelName:bc,backendName:"cpu",kernelFunc:fq},gq=ot(yc,e=>Number.isNaN(e)?1:0,"bool"),bq={kernelName:yc,backendName:"cpu",kernelFunc:gq};function yq(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=TT(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var vq={kernelName:oh,backendName:"cpu",kernelFunc:yq},xq=ot(wc,e=>Math.log1p(e)),wq={kernelName:wc,backendName:"cpu",kernelFunc:xq},kq=zt((e,t)=>e&&t),Iq=nn(kc,kq,null,"bool"),Sq={kernelName:kc,backendName:"cpu",kernelFunc:Iq},Cq=ot(Tl,e=>e?0:1,"bool"),Tq={kernelName:Tl,backendName:"cpu",kernelFunc:Cq},Nq=zt((e,t)=>e||t),_q=nn(Nl,Nq,null,"bool"),Eq={kernelName:Nl,backendName:"cpu",kernelFunc:_q};function Aq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r;Ie(s,"LRN");let l=s.shape[3],u=l-1,d=n.data.get(s.dataId).values,p=w.sizeFromShape(s.shape),h=new Float32Array(p);function f(m){let g=m%l,b=m-g+Math.max(0,g-a),y=m-g+Math.min(g+a,u),v=0;for(;b<=y;b++){let x=d[b];v+=x*x}return v}for(let m=0;m<p;m++){let g=f(m),b=d[m]*Math.pow(o+i*g,-c);h[m]=b}return n.makeTensorInfo(s.shape,s.dtype,h)}var Dq={kernelName:_l,backendName:"cpu",kernelFunc:Aq};function Fq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:l,beta:u}=r;Ie(o,"LRNGrad");let d=w.sizeFromShape(o.shape),p=o.shape[3],h=n.data.get(o.dataId).values,f=n.data.get(s.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(d),b=d;for(let y=0;y<b;y++){let v=y%p,x=y-v+Math.max(0,v-i),k=y-v+Math.min(p,v+i+1),C=0;for(let N=x;N<k;N++)C+=Math.pow(f[N],2);C=l*C+c;for(let N=x;N<k;N++){let F=-2*l*u*f[N]*m[y]/C;y===N&&(F+=Math.pow(C,-u)),F*=h[y],g[N]+=F}}return n.makeTensorInfo(o.shape,s.dtype,g)}var $q={kernelName:ih,backendName:"cpu",kernelFunc:Fq};function a2(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=n,c=s.shape,l=c.length,u=w.parseAxisParam(a,c),d=u,p=_.getAxesPermutation(d,l),h=i.data.get(s.dataId).values;if(p!=null){let x=new Array(l);for(let k=0;k<x.length;k++)x[k]=c[p[k]];h=vw(h,c,s.dtype,p,x),d=_.getInnerMostAxes(d.length,l),c=x}Ie(s,"max"),_.assertAxesAreInnerMostDims("max",d,l);let[f,m]=_.computeOutAndReduceShapes(c,d),g=w.sizeFromShape(m),b=_T(h,g,f,s.dtype),y=i.write(b,f,s.dtype),v=f;return o&&(v=_.expandShapeToKeepDim(f,u)),{dataId:y,shape:v,dtype:s.dtype}}var Rq={kernelName:io,backendName:"cpu",kernelFunc:a2};function Pq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ie(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c),d;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))d=hs({inputs:{x:s},backend:n});else{let p=n.data.get(s.dataId).values,h=w.computeStrides(s.shape),f=Sw(p,s.shape,s.dtype,h,u,"max");d=n.makeTensorInfo(u.outShape,s.dtype,f.values)}return d}var Oq={kernelName:uo,backendName:"cpu",kernelFunc:Pq};function Mq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r;Ie(s,"maxPool3d");let u=_.computePool3DInfo(s.shape,a,o,1,i,c,l),d=n.data.get(s.dataId).values,p=t2(d,s.shape,s.dtype,w.computeStrides(s.shape),u,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var Lq={kernelName:El,backendName:"cpu",kernelFunc:Mq};function Bq(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:o,strides:i,pad:c,dimRoundingMode:l}=r;Ie([s,a],"maxPool3DGrad");let u=_.computePool3DInfo(a.shape,o,i,1,c,l),d=n.bufferSync(a),p=_5(d,u),h=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,b=u.dilationHeight,y=u.dilationWidth,v=u.effectiveFilterDepth,x=u.effectiveFilterHeight,k=u.effectiveFilterWidth,C=v-1-u.padInfo.front,N=k-1-u.padInfo.left,F=x-1-u.padInfo.top,R=ze(a.shape,"float32"),O=n.bufferSync(s);for(let D=0;D<u.batchSize;++D)for(let P=0;P<u.inChannels;++P)for(let T=0;T<u.inDepth;++T)for(let L=0;L<u.inHeight;++L)for(let G=0;G<u.inWidth;++G){let j=T-C,q=L-F,K=G-N,ee=0;for(let te=0;te<v;te+=g){let ne=(j+te)/h;if(!(ne<0||ne>=u.outDepth||Math.floor(ne)!==ne))for(let ae=0;ae<x;ae+=b){let se=(q+ae)/f;if(!(se<0||se>=u.outHeight||Math.floor(se)!==se))for(let re=0;re<k;re+=y){let ue=(K+re)/m;if(ue<0||ue>=u.outWidth||Math.floor(ue)!==ue)continue;let de=v*x*k-1-p.get(D,ne,se,ue,P),me=te*x*k+ae*k+re,we=de===me?1:0;if(we===0)continue;ee+=O.get(D,ne,se,ue,P)*we}}}R.set(ee,D,T,L,G,P)}return n.makeTensorInfo(R.shape,R.dtype,R.values)}var zq={kernelName:uh,backendName:"cpu",kernelFunc:Bq};function Wq(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Ie([a,o],"maxPoolGrad");let{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,l,1,u,d),h=n.data.get(i.dataId).values,f=ze(p.outShape,i.dtype,e2(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,b=p.dilationHeight,y=p.dilationWidth,v=p.effectiveFilterHeight,x=p.effectiveFilterWidth,k=x-1-p.padInfo.left,C=v-1-p.padInfo.top,N=ze(i.shape,"float32"),F=n.data.get(s.dataId).values,R=ze(s.shape,"float32",F);for(let O=0;O<p.batchSize;++O)for(let D=0;D<p.inChannels;++D)for(let P=0;P<p.inHeight;++P)for(let T=0;T<p.inWidth;++T){let L=P-C,G=T-k,j=0;for(let q=0;q<v;q+=b){let K=(L+q)/m;if(!(K<0||K>=p.outHeight||Math.floor(K)!==K))for(let ee=0;ee<x;ee+=y){let te=(G+ee)/g;if(te<0||te>=p.outWidth||Math.floor(te)!==te)continue;let ne=v*x-1-f.get(O,K,te,D),ae=q*x+ee,se=ne===ae?1:0;if(se===0)continue;j+=R.get(O,K,te,D)*se}}N.set(j,O,P,T,D)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}var Vq={kernelName:ch,backendName:"cpu",kernelFunc:Wq};function Uq(e,t,n,r,s){let a=w.computeStrides(t),o=Sw(e,t,n,a,s,"max"),i=e2(e,t,n,s,!0,r);return[o.values,i.values]}var Gq={kernelName:lh,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;Ie(r,"MaxPoolWithArgmax");let l=c.data.get(r.dataId).values,u=_.computePool2DInfo(r.shape,s,a,[1,1],o),[d,p]=Uq(l,r.shape,r.dtype,i,u),h=c.write(d,u.outShape,r.dtype),f=c.write(p,u.outShape,r.dtype);return[{dataId:h,shape:u.outShape,dtype:r.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function Hq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=w.parseAxisParam(a,s.shape),l=_.computeOutAndReduceShapes(s.shape,i)[1],u=w.sizeFromShape(l),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(p);let h=ka({inputs:{x:s},backend:n,attrs:{dtype:"float32"}});d.push(h);let f=Cw({inputs:{a:h,b:p},backend:n});d.push(f);let m=Dd({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return d.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var jq={kernelName:lo,backendName:"cpu",kernelFunc:Hq};function qq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ie(s,"min");let i=w.parseAxisParam(a,s.shape),c=i,l=_.getAxesPermutation(c,s.shape.length),u=s;l!=null&&(u=dr({inputs:{x:s},backend:n,attrs:{perm:l}}),c=_.getInnerMostAxes(c.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",c,u.shape.length);let[d,p]=_.computeOutAndReduceShapes(u.shape,c),h=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let b=0;b<f.length;++b){let y=b*h,v=m[y];for(let x=0;x<h;++x){let k=m[y+x];(Number.isNaN(k)||k<v)&&(v=k)}f[b]=v}l!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let b=_.expandShapeToKeepDim(d,i),y=yt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var Kq={kernelName:po,backendName:"cpu",kernelFunc:qq};function Xq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,mode:o}=r;Ie(s,"mirrorPad");let i=a.map((v,x)=>v[0]+s.shape[x]+v[1]),c=a.map(v=>v[0]),l=a.map((v,x)=>v[0]+s.shape[x]),u=o==="reflect"?0:1,d=n.data.get(s.dataId).values,p=s.shape.length,h=w.computeStrides(s.shape),f=w.sizeFromShape(i),m=i.length,g=w.computeStrides(i),b=w.getTypedArrayFromDType(s.dtype,f);for(let v=0;v<f;v++){let x=w.indexToLoc(v,m,g);for(let C=0;C<m;C++)x[C]<c[C]?x[C]=c[C]*2-x[C]-u:x[C]>=l[C]&&(x[C]=(l[C]-1)*2-x[C]+u);x=x.map((C,N)=>C-c[N]);let k=w.locToIndex(x,p,h);b[v]=d[k]}return{dataId:n.write(b,i,s.dtype),shape:i,dtype:s.dtype}}var Yq={kernelName:fo,backendName:"cpu",kernelFunc:Xq},Zq=zt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),Jq=nn(Ic,Zq),Qq={kernelName:Ic,backendName:"cpu",kernelFunc:Jq},e8=Oa(t1());function o2(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=s.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let c=w.parseAxisParam([i],s.shape),l=a2({inputs:{x:s},backend:n,attrs:{reductionIndices:c,keepDims:!1}}),u=_.expandShapeToKeepDim(l.shape,c),d=yt({inputs:{x:l},backend:n,attrs:{shape:u}}),p=kw({inputs:{a:s,b:d},backend:n}),h=bT({inputs:{x:p},backend:n}),f=Dd({inputs:{x:h},backend:n,attrs:{axis:c,keepDims:!1}}),m=yt({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Cw({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var t8={kernelName:Ao,backendName:"cpu",kernelFunc:o2};function n8(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r;Ie(s,"multinomial");let c=i?s:o2({inputs:{logits:s},backend:n,attrs:{dim:-1}}),l=c.shape[0],u=c.shape[1],d=n.data.get(c.dataId).values,p=[l,a],h=w.makeZerosTypedArray(w.sizeFromShape(p),"int32");for(let f=0;f<l;++f){let m=f*u,g=new Float32Array(u-1);g[0]=d[m];for(let v=1;v<g.length;++v)g[v]=g[v-1]+d[m+v];let b=e8.alea(o.toString()),y=f*a;for(let v=0;v<a;++v){let x=b();h[y+v]=g.length;for(let k=0;k<g.length;k++)if(x<g[k]){h[y+v]=k;break}}}return i||n.disposeIntermediateTensorInfo(c),n.makeTensorInfo(p,"int32",h)}var r8={kernelName:dh,backendName:"cpu",kernelFunc:n8},s8=is.nonMaxSuppressionV3Impl;function a8(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r;Ie(s,"NonMaxSuppression");let l=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,{selectedIndices:d}=s8(l,u,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var o8={kernelName:Tc,backendName:"cpu",kernelFunc:a8},i8=is.nonMaxSuppressionV4Impl;function c8(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:l}=r;Ie(s,"NonMaxSuppressionPadded");let u=n.data.get(s.dataId).values,d=n.data.get(a.dataId).values,{selectedIndices:p,validOutputs:h}=i8(u,d,o,i,c,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var u8={kernelName:Nc,backendName:"cpu",kernelFunc:c8},l8=is.nonMaxSuppressionV5Impl;function d8(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:l}=r;Ie(s,"NonMaxSuppressionWithScore");let u=n.data.get(s.dataId).values,d=n.data.get(a.dataId).values,p=o,h=i,f=c,m=l,{selectedIndices:g,selectedScores:b}=l8(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var p8={kernelName:_c,backendName:"cpu",kernelFunc:d8};function h8(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r;Ie(s,"oneHot");let c=w.sizeFromShape(s.shape),l=new Float32Array(c*a);l.fill(i);let u=n.data.get(s.dataId).values;for(let d=0;d<c;++d)u[d]>=0&&u[d]<a&&(l[d*a+u[d]]=o);return n.makeTensorInfo([...s.shape,a],"int32",l)}var f8={kernelName:go,backendName:"cpu",kernelFunc:h8};function um(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(r.dtype==="complex64"){let s=di({inputs:{input:r},backend:n}),a=um({inputs:{x:s},backend:n}),o=Iu({inputs:{input:r},backend:n}),i=um({inputs:{x:o},backend:n}),c=nr({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return _w({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}var m8={kernelName:qc,backendName:"cpu",kernelFunc:um};function i2(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(r.dtype==="complex64"){let s=di({inputs:{input:r},backend:n}),a=i2({inputs:{x:s},backend:n}),o=Iu({inputs:{input:r},backend:n}),i=um({inputs:{x:o},backend:n}),c=nr({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return _w({backend:n,attrs:{shape:r.shape,value:1,dtype:r.dtype}})}var g8={kernelName:Ec,backendName:"cpu",kernelFunc:i2};function c2(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return cm({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=cm({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=Su({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),l}var b8={kernelName:Ac,backendName:"cpu",kernelFunc:c2};function y8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;Ie(s,"pad");let i=a.map((y,v)=>y[0]+s.shape[v]+y[1]),c=a.map(y=>y[0]),l=n.data.get(s.dataId).values,u=w.sizeFromShape(s.shape),d=s.shape.length,p=w.computeStrides(s.shape),h=w.sizeFromShape(i),f=i.length,m=w.computeStrides(i),g=w.getTypedArrayFromDType(s.dtype,h);o!==0&&g.fill(o);for(let y=0;y<u;y++){let x=w.indexToLoc(y,d,p).map((C,N)=>C+c[N]),k=w.locToIndex(x,f,m);g[k]=l[y]}return{dataId:n.write(g,i,s.dtype),shape:i,dtype:s.dtype}}var u2={kernelName:bo,backendName:"cpu",kernelFunc:y8},v8=zt((e,t)=>Math.pow(e,t)),x8=nn(yo,v8),w8={kernelName:yo,backendName:"cpu",kernelFunc:x8};function k8(e){let{backend:t,attrs:n}=e,{start:r,stop:s,dtype:a,step:o}=n,i=xw(r,s,o,a);return t.makeTensorInfo([i.length],a,i)}var I8={kernelName:Al,backendName:"cpu",kernelFunc:k8},S8=ot(Fc,e=>1/e),C8={kernelName:Fc,backendName:"cpu",kernelFunc:S8};function T8(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r;Ie(s,"resizeBilinear");let c=w.computeStrides(s.shape),[l,u]=i,[d,p,h,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(w.sizeFromShape([d,l,u,f])),b=[a&&l>1?p-1:p,a&&u>1?h-1:h],y=[a&&l>1?l-1:l,a&&u>1?u-1:u],v=0,x=b[0]/y[0],k=b[1]/y[1];for(let C=0;C<d;C++)for(let N=0;N<l;N++){let F;o?F=x*(N+.5)-.5:F=x*N;let R=Math.max(0,Math.floor(F)),O=F-R,D=Math.min(p-1,Math.ceil(F)),P=C*c[0]+R*c[1],T=C*c[0]+D*c[1];for(let L=0;L<u;L++){let G;o?G=k*(L+.5)-.5:G=k*L;let j=Math.max(0,Math.floor(G)),q=G-j,K=Math.min(h-1,Math.ceil(G)),ee=P+j*c[2],te=T+j*c[2],ne=P+K*c[2],ae=T+K*c[2];for(let se=0;se<f;se++){let re=m[ee+se],ue=m[te+se],de=m[ne+se],me=m[ae+se],we=re+(de-re)*q,Ce=ue+(me-ue)*q,_e=we+(Ce-we)*O;g[v++]=_e}}}return n.makeTensorInfo([d,l,u,f],"float32",g)}var N8={kernelName:wo,backendName:"cpu",kernelFunc:T8};function _8(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r;Ie([a,s],"resizeBilinearGrad");let i=w.computeStrides(s.shape),[c,l,u,d]=s.shape,[,p,h]=a.shape,f=new Float32Array(c*l*u*d),m=[o&&p>1?l-1:l,o&&h>1?u-1:u],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],b=m[0]/g[0],y=m[1]/g[1],v=n.data.get(a.dataId).values,x=0;for(let k=0;k<c;k++){let C=k*i[0];for(let N=0;N<p;N++){let F=N*b,R=Math.floor(F),O=Math.min(Math.ceil(F),l-1),D=C+R*i[1],P=C+O*i[1],T=F-R,L=1-T;for(let G=0;G<h;G++){let j=G*y,q=Math.floor(j),K=Math.min(Math.ceil(j),u-1),ee=j-q,te=1-ee,ne=D+q*i[2],ae=D+K*i[2],se=P+q*i[2],re=P+K*i[2],ue=L*te,de=L*ee,me=T*te,we=T*ee;for(let Ce=0;Ce<d;Ce++){let _e=v[x++];f[ne+Ce]+=_e*ue,f[ae+Ce]+=_e*de,f[se+Ce]+=_e*me,f[re+Ce]+=_e*we}}}}return n.makeTensorInfo([c,u,l,d],"float32",f)}var E8={kernelName:fh,backendName:"cpu",kernelFunc:_8};function A8(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r;Ie(s,"resizeNearestNeighbor");let c=w.computeStrides(s.shape),[l,u]=i,[d,p,h,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(d*l*u*f),b=[a&&l>1?p-1:p,a&&u>1?h-1:h],y=[a&&l>1?l-1:l,a&&u>1?u-1:u],v=b[0]/y[0],x=b[1]/y[1],k=0;for(let C=0;C<d;C++){let N=C*c[0];for(let F=0;F<l;F++){let R=o?v*(F+.5):v*F,O=Math.min(p-1,a?Math.round(R):Math.floor(R));o&&(O=Math.max(0,O));let D=N+O*c[1];for(let P=0;P<u;P++){let T=o?x*(P+.5):x*P,L=Math.min(h-1,a?Math.round(T):Math.floor(T));o&&(L=Math.max(0,L));let G=D+L*c[2];for(let j=0;j<f;j++){let q=m[G+j];g[k++]=q}}}}return n.makeTensorInfo([d,l,u,f],s.dtype,g)}var D8={kernelName:Dl,backendName:"cpu",kernelFunc:A8};function F8(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r;Ie([a,s],"resizeNearestNeighborGrad");let i=w.computeStrides(s.shape),c=w.computeStrides(a.shape),[l,u,d,p]=s.shape,[,h,f]=a.shape,m=new Float32Array(l*u*d*p),g=n.data.get(a.dataId).values,b=[o&&h>1?u-1:u,o&&f>1?d-1:d],y=[o&&h>1?h-1:h,o&&f>1?f-1:f],v=b[0]/y[0],x=b[1]/y[1],k=1/v,C=1/x,N=Math.ceil(k)*2+2,F=Math.ceil(C)*2+2;for(let R=0;R<l;R++){let O=R*i[0];for(let D=0;D<u;D++){let P=O+D*i[1],T=Math.floor(D*k),L=Math.floor(T-N/2);for(let G=0;G<d;G++){let j=P+G*i[2],q=Math.floor(G*C),K=Math.floor(q-F/2);for(let ee=0;ee<p;ee++){let te=0;for(let ne=0;ne<N;ne++){let ae=ne+L;if(ae<0||ae>=h)continue;let se=O+ae*c[1],re=ae*v,ue=Math.min(u-1,o?Math.round(re):Math.floor(re));if(D===ue)for(let de=0;de<F;de++){let me=de+K;if(me<0||me>=f)continue;let we=se+me*c[2],Ce=me*x,_e=Math.min(d-1,o?Math.round(Ce):Math.floor(Ce));G===_e&&(te+=g[we+ee])}}m[j+ee]=te}}}}return n.makeTensorInfo(s.shape,s.dtype,m)}var $8={kernelName:hh,backendName:"cpu",kernelFunc:F8};function R8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r;Ie(s,"reverse");let o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return hs({inputs:{x:s},backend:n});let c=new Ut(s.shape,s.dtype),l=n.bufferSync(s);for(let u=0;u<c.size;u++){let d=c.indexToLoc(u),p=d.slice();i.forEach(h=>p[h]=s.shape[h]-1-p[h]),c.set(l.get(...p),...d)}return n.makeTensorInfo(c.shape,c.dtype,c.values)}var P8={kernelName:Io,backendName:"cpu",kernelFunc:R8},O8={kernelName:Kc,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(r.shape)),[l,u,d,p]=r.shape,[h,f]=_.getImageCenter(o,u,d),m=255,g=Math.sin(s),b=Math.cos(s),y=i.data.get(r.dataId).values;for(let x=0;x<l;x++){let k=x*d*u*p;for(let C=0;C<u;C++){let N=C*(d*p);for(let F=0;F<d;F++){let R=F*p;for(let O=0;O<p;O++){let D=[l,C,F,O],P=D[2],T=D[1],L=(P-h)*b-(T-f)*g,G=(P-h)*g+(T-f)*b;L=Math.round(L+h),G=Math.round(G+f);let j=a;if(typeof a!="number"&&(O===3?j=m:j=a[O]),L>=0&&L<d&&G>=0&&G<u){let K=G*(d*p),ee=L*p,te=k+K+ee+O;j=y[te]}let q=k+N+R+O;c[q]=j}}}}return{dataId:i.write(c,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},M8=ot(So,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}),L8={kernelName:So,backendName:"cpu",kernelFunc:M8};function l2(e,t,n,r,s,a,o,i,c,l){let u=[r/s,s],d=e.values,p=t.values;if(r===0)return ze(n,t.dtype);let h=ze(u,t.dtype);h.values.fill(c);for(let f=0;f<a;f++){let m=[],g=0;for(let b=0;b<o;b++){let y=d[f*o+b];m.push(y),g+=y*i[b]}if(g<0||g>=r/s)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let b=0;b<s;b++)l?h.values[g*s+b]+=p[f*s+b]:h.values[g*s+b]=t.rank===0?p[0]:p[f*s+b]}return h}function B8(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=_.calculateShapes(a,s,o),p=!0,h=n.bufferSync(s),f=n.bufferSync(a),m=l2(h,f,o,d,l,c,i,u,0,p);return n.makeTensorInfo(o,m.dtype,m.values)}var z8={kernelName:Rc,backendName:"cpu",kernelFunc:B8};function W8(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t;Ie([r,s,a],"select");let o=r.shape.length,i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=wr(s.dtype,a.dtype),d=w.makeZerosTypedArray(w.sizeFromShape(s.shape),u),p=0,h=o===0||o>1||s.shape.length===1?1:w.sizeFromShape(s.shape.slice(1));for(let f=0;f<i.length;f++)for(let m=0;m<h;m++)i[f]===1?d[p++]=c[f]:d[p++]=l[f];return n.makeTensorInfo(s.shape,u,d)}var V8={kernelName:Pc,backendName:"cpu",kernelFunc:W8},U8=_.SELU_SCALEALPHA,G8=_.SELU_SCALE,H8=ot(Oc,e=>e>=0?G8*e:U8*(Math.exp(e)-1)),j8={kernelName:Oc,backendName:"cpu",kernelFunc:H8},q8=ot(Bc,e=>e<0?-1:e>0?1:0),K8={kernelName:Bc,backendName:"cpu",kernelFunc:q8},X8=ot(To,e=>Math.sin(e)),Y8={kernelName:To,backendName:"cpu",kernelFunc:X8},Z8=ot(Lc,e=>Math.sinh(e)),J8={kernelName:Lc,backendName:"cpu",kernelFunc:Z8},Q8=11920928955078125e-23,d2=Math.log(Q8)+2,eK=ot(zc,e=>{let t=e>-d2,n=e<d2,r=Math.exp(e),s;return n?s=r:t?s=e:s=Math.log(1+r),s}),tK={kernelName:zc,backendName:"cpu",kernelFunc:eK};function nK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;Ie([s],"spaceToBatchND");let i=w.sizeFromShape(a),c=[[0,0]];c.push(...o);for(let C=1+a.length;C<s.shape.length;++C)c.push([0,0]);let l=u2.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),u=_.getReshaped(l.shape,a,i,!1),d=_.getPermuted(u.length,a.length,!1),p=_.getReshapedPermuted(l.shape,a,i,!1),m=yt({inputs:{x:l},backend:n,attrs:{shape:u}}),y=dr({inputs:{x:m},backend:n,attrs:{perm:d}}),k=yt({inputs:{x:y},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),k}var rK={kernelName:Wc,backendName:"cpu",kernelFunc:nK};function sK(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=n.data.get(o.dataId).values[0],[d,p,h,f,m]=OT(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var aK={kernelName:mh,backendName:"cpu",kernelFunc:sK};function oK(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[l,u,d]=MT(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var iK={kernelName:gh,backendName:"cpu",kernelFunc:oK};function cK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=ww(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var uK={kernelName:bh,backendName:"cpu",kernelFunc:cK};function lK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=ww(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var dK={kernelName:yh,backendName:"cpu",kernelFunc:lK};function pK(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:p}=_.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],b=l2(f,m,i,p,u,l,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var hK={kernelName:vh,backendName:"cpu",kernelFunc:pK};function fK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=pi({inputs:{x:s},backend:n,attrs:{begin:l,size:p}});return l[i]+=d,h})}var mK={kernelName:Vc,backendName:"cpu",kernelFunc:fK},gK={kernelName:Fl,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;Ie(n,"square");let s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){let c=s[i];a[i]=c*c}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},bK=ot(na,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),yK={kernelName:na,backendName:"cpu",kernelFunc:bK};function vK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r;Ie(s,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=kn.sliceInfo(s.shape,a,o,i,c,l,u,d,p),v=yt({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=pi({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=yt({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else{let C=n.bufferSync(v),N=BT(y,C,m,f);x=n.makeTensorInfo(N.shape,N.dtype,N.values)}let k=yt({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var xK={kernelName:Uc,backendName:"cpu",kernelFunc:vK};function wK(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=zT(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var kK={kernelName:xh,backendName:"cpu",kernelFunc:wK};function IK(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[l,u,d]=WT(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var SK={kernelName:wh,backendName:"cpu",kernelFunc:IK};function CK(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=VT(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var TK={kernelName:kh,backendName:"cpu",kernelFunc:CK},NK=ot($o,e=>Math.tan(e)),_K={kernelName:$o,backendName:"cpu",kernelFunc:NK},EK=ot(Ro,e=>Math.tanh(e)),AK={kernelName:Ro,backendName:"cpu",kernelFunc:EK};function DK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;Ie(s,"tile");let o=GT(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var FK={kernelName:ta,backendName:"cpu",kernelFunc:DK};function $K(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;Ie(s,"topk");let i=n.data.get(s.dataId).values,[c,l]=jT(i,s.shape,s.dtype,a,o);return[n.makeTensorInfo(c.shape,c.dtype,c.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}var RK={kernelName:Gc,backendName:"cpu",kernelFunc:$K};function PK(e){let{inputs:t,attrs:n,backend:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:l}=n,[u,d,p,h]=s.shape,[f,m]=l!=null?l:[d,p],g=[u,f,m,h],b=w.computeStrides(s.shape),y=b[0],v=b[1],x=b[2],k=w.getTypedArrayFromDType(s.dtype,w.sizeFromShape(g));k.fill(c);let C=r.data.get(s.dataId).values,N=r.data.get(a.dataId).values;for(let R=0;R<u;++R){let O=a.shape[0]===1?N:N.subarray(R*8,R*8+8);for(let D=0;D<f;++D)for(let P=0;P<m;++P)for(let T=0;T<h;++T){let L,G=O[6]*P+O[7]*D+1;if(G===0)continue;let j=(O[0]*P+O[1]*D+O[2])/G,q=(O[3]*P+O[4]*D+O[5])/G,K=p2(j,p,i),ee=p2(q,d,i);switch(o){case"nearest":L=WK(C,d,p,y,v,x,R,ee,K,T,c);break;case"bilinear":L=VK(C,d,p,y,v,x,R,ee,K,T,c);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${o}`)}let te=R*y+D*v+P*x+T;k[te]=L}return r.makeTensorInfo(g,s.dtype,k)}return{dataId:r.write(k,g,s.dtype),shape:s.shape,dtype:s.dtype}}var OK={kernelName:Hc,backendName:"cpu",kernelFunc:PK};function p2(e,t,n){switch(n){case"reflect":return MK(e,t);case"wrap":return LK(e,t);case"nearest":return zK(e,t);case"constant":default:return BK(e,t)}}function MK(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let r=2*t;n<r&&(n=r*Math.trunc(-n/r)+n),n=n<-t?n+r:-n-1}else if(n>t-1)if(t<=1)n=0;else{let r=2*t;n-=r*Math.trunc(n/r),n>=t&&(n=r-n-1)}return w.clamp(0,n,t-1)}function LK(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let r=t-1;n+=t*(Math.trunc(-n/r)+1)}else if(n>t-1)if(t<=1)n=0;else{let r=t-1;n-=t*Math.trunc(n/r)}return w.clamp(0,n,t-1)}function BK(e,t){return e}function zK(e,t){return w.clamp(0,e,t-1)}function Fd(e,t,n,r,s,a,o,i,c,l,u){let d=o*r+i*s+c*a+l;return 0<=i&&i<t&&0<=c&&c<n?e[d]:u}function WK(e,t,n,r,s,a,o,i,c,l,u){let d=Math.round(i),p=Math.round(c);return Fd(e,t,n,r,s,a,o,d,p,l,u)}function VK(e,t,n,r,s,a,o,i,c,l,u){let d=Math.floor(i),p=Math.floor(c),h=d+1,f=p+1,m=(f-c)*Fd(e,t,n,r,s,a,o,d,p,l,u)+(c-p)*Fd(e,t,n,r,s,a,o,d,f,l,u),g=(f-c)*Fd(e,t,n,r,s,a,o,h,p,l,u)+(c-p)*Fd(e,t,n,r,s,a,o,h,f,l,u);return(h-i)*m+(i-d)*g}function UK(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Ie(a,"unique");let o=r.data.get(a.dataId).values,{outputValues:i,outputShape:c,indices:l}=qT(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}var GK={kernelName:Ih,backendName:"cpu",kernelFunc:UK};function HK(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s.shape.length,i=s.shape[a],c=new Array(o-1),l=0;for(let h=0;h<o;h++)h!==a&&(c[l++]=s.shape[h]);let u=new Array(o).fill(0),d=s.shape.slice();d[a]=1;let p=new Array(i);for(let h=0;h<p.length;h++){u[a]=h;let f=pi({inputs:{x:s},backend:n,attrs:{begin:u,size:d}});p[h]=yt({inputs:{x:f},backend:n,attrs:{shape:c}}),n.disposeIntermediateTensorInfo(f)}return p}var jK={kernelName:jc,backendName:"cpu",kernelFunc:HK};function qK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r;Ie(s,"unsortedSegmentSum");let i=s.shape.length,c=a.shape.length,l=[],u=[],d=i-c,p=a;for(let f=0;f<d;++f){let m=cm({inputs:{input:p},backend:n,attrs:{dim:f+1}});p=m,u.push(m)}for(let f=0;f<o;++f){let m=w.createScalarValue(f,"int32"),g=n.makeTensorInfo([],"int32",m),b=mT({inputs:{a:g,b:p},backend:n}),y=ka({inputs:{x:b},backend:n,attrs:{dtype:"float32"}}),v=om({inputs:{a:y,b:s},backend:n}),x=Dd({inputs:{x:v},backend:n,attrs:{axis:0,keepDims:!1}});l.push(x),u.push(g),u.push(b),u.push(y),u.push(v),u.push(x)}let h=c2({inputs:l,backend:n,attrs:{axis:0}});return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var KK={kernelName:$l,backendName:"cpu",kernelFunc:qK},XK=[n5,XH,s5,o5,t6,c5,l5,p5,f5,g5,y5,x5,k5,C5,N5,A5,F5,R5,O5,e5,L5,z5,V5,G5,QH,r6,j5,YH,K5,Y5,Q5,tj,Z5,aj,ij,rj,uj,dj,hj,mj,bj,vj,xj,kj,Sj,Tj,Nj,Ej,_j,Tw,Fj,q6,Rj,s6,Vj,a6,Uj,i6,Xj,Yj,Jj,u6,tq,rq,aq,iq,uq,d6,h6,ZH,dq,X5,hq,mq,bq,K6,m6,b6,vq,v6,wq,Sq,Tq,Eq,Dq,$q,w6,Oq,Lq,zq,Vq,Gq,Rq,jq,Kq,I6,Yq,Qq,r8,C6,N6,o8,u8,p8,E6,f8,g8,b8,u2,w8,Y6,F6,I8,JH,C8,Z6,J6,Q6,N8,E8,D8,$8,P8,O8,L8,R6,z8,V8,j8,O6,K8,Y8,J8,M6,t8,tK,rK,aK,iK,uK,dK,hK,mK,z6,gK,V6,yK,xK,kK,SK,TK,j6,Aj,_K,AK,FK,RK,A6,OK,GK,jK,KK,m8];for(let e of XK)Pl(e);var h2={};$e(h2,{assertNotComplex:()=>Tu,bindCanvasToFramebuffer:()=>iX,bindColorTextureToFramebuffer:()=>pm,bindTextureToProgramUniformSampler:()=>E2,bindTextureUnit:()=>T2,bindVertexBufferToProgramAttribute:()=>Dw,callAndCheck:()=>xe,canBeRepresented:()=>m2,createFragmentShader:()=>y2,createFramebuffer:()=>C2,createProgram:()=>v2,createStaticIndexBuffer:()=>k2,createStaticVertexBuffer:()=>w2,createTexture:()=>I2,createVertexShader:()=>b2,getBatchDim:()=>fi,getExtensionOrThrow:()=>Pd,getFramebufferErrorMessage:()=>A2,getMaxTexturesInShader:()=>R2,getNumChannels:()=>aX,getProgramUniformLocation:()=>_2,getProgramUniformLocationOrThrow:()=>N2,getRowsCols:()=>mi,getShapeAs3D:()=>hm,getTextureShapeFromLogicalShape:()=>F2,getWebGLDisjointQueryTimerVersion:()=>P2,getWebGLErrorMessage:()=>g2,getWebGLMaxTextureSize:()=>$2,hasExtension:()=>hr,isCapableOfRenderingToFloatTexture:()=>O2,isDownloadFloatTextureEnabled:()=>M2,isReshapeFree:()=>Md,isWebGLFenceEnabled:()=>L2,isWebGLVersionEnabled:()=>$w,linkProgram:()=>x2,resetMaxTextureSize:()=>cX,resetMaxTexturesInShader:()=>uX,unbindColorTextureFromFramebuffer:()=>Fw,unbindTextureUnit:()=>oX,validateFramebuffer:()=>Od,validateProgram:()=>dm,validateTextureSize:()=>S2});var hi={},Ew={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function f2(e,t){hi[e]=t}function fs(e){if(!(e in hi)){let n=ZK(e);if(n!==null)hi[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=hi[e];return t.isContextLost()?(delete hi[e],fs(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),hi[e])}function YK(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 ZK(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=YK(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete hi[e]},!1),e===1?t.getContext("webgl",Ew)||t.getContext("experimental-webgl",Ew):t.getContext("webgl2",Ew)}var $d;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})($d||($d={}));var pr;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(pr||(pr={}));var un;(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"})(un||(un={}));function Rd(e,t){return[t,e]}function JK(e,t){return e*t}function lm(e){let t=w.sizeFromShape(e),n=Math.ceil(t/4);return w.sizeToSquarishShape(n)}function Cu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function QK(e,t){let[n,r]=Cu(e,t);return n*r*4}function Aw(e,t){let n=e,r,s,a,o,i,c,l,u,d,p;return J().getNumber("WEBGL_VERSION")===2?(r=n.R32F,s=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,u=1,d=n.HALF_FLOAT,p=n.FLOAT):(r=e.RGBA,s=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),c=e.RGBA,{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:c,downloadUnpackNumChannels:l,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:p}}function xe(e,t){let n=t();return J().getBool("DEBUG")&&eX(e),n}function eX(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+g2(e,t))}var tX=596e-10,nX=65504;function m2(e){return!!(J().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||tX<Math.abs(e)&&Math.abs(e)<nX)}function g2(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 Pd(e,t){return Ps(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function b2(e,t){let n=Ps(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(xe(e,()=>e.shaderSource(n,t)),xe(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 y2(e,t){let n=Ps(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(xe(e,()=>e.shaderSource(n,t)),xe(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw sX(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var rX=/ERROR: [0-9]+:([0-9]+):/g;function sX(e,t){let n=rX.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let r=+n[1],s=e.split(`
|
|
`),a=s.length.toString().length+2,o=s.map((d,p)=>w.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);let c=o.slice(0,r-1),l=o.slice(r-1,r),u=o.slice(r);console.log(c.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${w.rightPad(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
|
|
`))}function v2(e){return Ps(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function x2(e,t){if(xe(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 dm(e,t){if(xe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function w2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function k2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function aX(){return J().getNumber("WEBGL_VERSION")===2?1:4}function I2(e){return Ps(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function S2(e,t){let n=J().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r=`[${e}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r=`[${e}x${t}]`,s=`[${n}x${n}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function C2(e){return Ps(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Dw(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),xe(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),xe(e,()=>e.enableVertexAttribArray(i)),!0)}function T2(e,t,n){D2(e,n),xe(e,()=>e.activeTexture(e.TEXTURE0+n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function oX(e,t){D2(e,t),xe(e,()=>e.activeTexture(e.TEXTURE0+t)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function N2(e,t,n){return Ps(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function _2(e,t,n){return e.getUniformLocation(t,n)}function E2(e,t,n,r){xe(e,()=>T2(e,t,r)),xe(e,()=>e.uniform1i(n,r))}function iX(e){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),xe(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),xe(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function pm(e,t,n){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Fw(e,t){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Od(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+A2(e,t))}function A2(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 Ps(e,t,n){let r=xe(e,()=>t());if(r==null)throw new Error(n);return r}function D2(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){let s=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${s}.`)}}function fi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function mi(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 hm(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[fi(e),...mi(e)]),t}function F2(e,t=!1){let n=J().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?w.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.sizeFromShape(e);if(e.length<=1&&r<=n)return[1,r];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){let s=fi(e),a=2,o=2;return e.length&&([a,o]=mi(e)),r=s*(a/2)*(o/2),w.sizeToSquarishShape(r).map(i=>i*2)}return w.sizeToSquarishShape(r)}function fm(e){return e%2==0}function Md(e,t){if(e=e.slice(-2),t=t.slice(-2),w.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r||fm(n)&&fm(r)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&fm(e[0])&&fm(t[0])}var mm,gm;function $2(e){if(mm==null){let t=fs(e);mm=t.getParameter(t.MAX_TEXTURE_SIZE)}return mm}function cX(){mm=null}function uX(){gm=null}function R2(e){if(gm==null){let t=fs(e);gm=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,gm)}function P2(e){if(e===0)return 0;let t,n=fs(e);return hr(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:hr(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function hr(e,t){return e.getExtension(t)!=null}function $w(e){try{if(fs(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function O2(e){if(e===0)return!1;let t=fs(e);if(e===1){if(!hr(t,"OES_texture_float"))return!1}else if(!hr(t,"EXT_color_buffer_float"))return!1;return Rw(t)}function M2(e){if(e===0)return!1;let t=fs(e);if(e===1){if(!hr(t,"OES_texture_float")||!hr(t,"WEBGL_color_buffer_float"))return!1}else{if(hr(t,"EXT_color_buffer_float"))return Rw(t);let r="EXT_color_buffer_half_float";if(hr(t,r)){let s=t.getExtension(r);return lX(t,s)}return!1}return Rw(t)}function Rw(e){let t=Aw(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let r=1,s=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,r,s,0,t.textureFormatFloat,t.textureTypeFloat,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),o}function lX(e,t){let n=Aw(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let s=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,s,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(o),i}function L2(e){return e!==2?!1:fs(e).fenceSync!=null}function Tu(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 Ne=J();Ne.registerFlag("HAS_WEBGL",()=>Ne.getNumber("WEBGL_VERSION")>0);Ne.registerFlag("WEBGL_VERSION",()=>$w(2)?2:$w(1)?1:0);Ne.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ne.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ne.get("WEBGL_VERSION")===2);Ne.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ne.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ne.registerFlag("WEBGL_PACK",()=>Ne.getBool("HAS_WEBGL"));Ne.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_CLIP",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_PACK_REDUCE",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_CONV_IM2COL",()=>Ne.getBool("WEBGL_PACK"));Ne.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>$2(Ne.getNumber("WEBGL_VERSION")));Ne.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>R2(Ne.getNumber("WEBGL_VERSION")));Ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Ne.getNumber("WEBGL_VERSION");return e===0?0:P2(e)});Ne.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ne.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Ul.isMobile());Ne.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>O2(Ne.getNumber("WEBGL_VERSION")));Ne.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ne.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ne.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ne.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>M2(Ne.getNumber("WEBGL_VERSION")));Ne.registerFlag("WEBGL_FENCE_API_ENABLED",()=>L2(Ne.getNumber("WEBGL_VERSION")));Ne.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ne.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ne.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}.`)});Ne.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Ul.isMobile()?1:-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});Ne.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Ne.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Ne.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Ne.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Tn(){let e,t,n,r,s,a,o,i,c,l;return J().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",r="in",s="texture",a="outputColor",o="out vec4 outputColor;",i=`
|
|
bool isnan_custom(float val) {
|
|
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)
|
|
`,c="",l=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,c=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,l=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:l}}function gi(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / ${s}`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${s}`:`index -= ${e[a]} * ${s}`;return`${o}; ${i};`}).join("")}function bm(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function dX(e,t){let n=e.length,r=e.map(a=>`${t}[${a}]`),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]=`(${s[a+1]} * ${r[a+1]})`;return s}function pX(e,t,n="index"){let r=e.map((a,o)=>o),s=dX(r,t);return s.map((a,o)=>{let i=`int ${e[o]} = ${n} / ${s[o]}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${s[o]}`:`index -= ${e[o]} * ${s[o]}`;return`${i}; ${c};`}).join("")}function Pw(e){let t=w.computeStrides(e).map(n=>n.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}function Ow(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var B2=`
|
|
const float FLOAT_MAX = 1.70141184e38;
|
|
const float FLOAT_MIN = 1.17549435e-38;
|
|
|
|
lowp vec4 encode_float(highp float v) {
|
|
if (isnan(v)) {
|
|
return vec4(255, 255, 255, 255);
|
|
}
|
|
|
|
highp float av = abs(v);
|
|
|
|
if(av < FLOAT_MIN) {
|
|
return vec4(0.0, 0.0, 0.0, 0.0);
|
|
} else if(v > FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
|
|
} else if(v < -FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
|
|
}
|
|
|
|
highp vec4 c = vec4(0,0,0,0);
|
|
|
|
highp float e = floor(log2(av));
|
|
highp float m = exp2(fract(log2(av))) - 1.0;
|
|
|
|
c[2] = floor(128.0 * m);
|
|
m -= c[2] / 128.0;
|
|
c[1] = floor(32768.0 * m);
|
|
m -= c[1] / 32768.0;
|
|
c[0] = floor(8388608.0 * m);
|
|
|
|
highp float ebias = e + 127.0;
|
|
c[3] = floor(ebias / 2.0);
|
|
ebias -= c[3] * 2.0;
|
|
c[2] += floor(ebias) * 128.0;
|
|
|
|
c[3] += 128.0 * step(0.0, -v);
|
|
|
|
return c / 255.0;
|
|
}
|
|
`,{getBroadcastDims:z2}=_;function hX(e,t,n){let r=[];if(e.forEach(h=>{let f=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=Mw(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:r.push(`uniform int ${h.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}r.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;");break;default:break}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{r.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let s=r.join(`
|
|
`),a=e.map(h=>fX(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
|
|
`),o=t.texShape,i=Tn(),c=bX(i),l,u,d=xX(i);return t.isPacked?(l=mX(t.logicalShape,o,n.enableShapeUniforms),u=vX(i)):(l=gX(t.logicalShape,o,n.enableShapeUniforms),u=yX(i)),n.packedInputs&&(d+=SX),[d,c,u,s,l,a,n.userCode].join(`
|
|
`)}function Nu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return OX(e,t);case 1:return LX(e,t);case 2:return zX(e,t);case 3:return VX(e,t);case 4:return GX(e,t);case 5:return HX(e);case 6:return jX(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function W2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return PX(e);case 1:return MX(e,t);case 2:return BX(e,t);case 3:return WX(e,t);default:return UX(e,t)}}function fX(e,t,n=!1,r){let s="";n?s+=W2(e,r):s+=Nu(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=qX(e,t):s+=KX(e,t)),s}function mX(e,t,n){switch(e.length){case 0:return V2();case 1:return CX(e,t,n);case 2:return $X(e,t,n);case 3:return NX(e,t,n);default:return EX(e,t,n)}}function gX(e,t,n){switch(e.length){case 0:return V2();case 1:return TX(e,t,n);case 2:return RX(e,t,n);case 3:return _X(e,t,n);case 4:return AX(e,t,n);case 5:return DX(e,t);case 6:return FX(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function bX(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function yX(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function vX(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function xX(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);
|
|
}
|
|
|
|
${wX}
|
|
${kX}
|
|
${IX}
|
|
`}var wX=`
|
|
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);
|
|
}
|
|
`,kX=`
|
|
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);
|
|
}
|
|
`,IX=`
|
|
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);
|
|
}
|
|
`,SX=`
|
|
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 V2(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function CX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${r[1]}.0);
|
|
}
|
|
`:r[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${r[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);
|
|
}
|
|
`}function TX(e,t,n){return t[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
return resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
return resTexRC.x * ${t[1]} + resTexRC.y;
|
|
}
|
|
`}function NX(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function _X(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${bm(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let r=gi(["r","c","d"],e);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${r}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function EX(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatchN = texelsInBatch * outShape[1];
|
|
|
|
int b2 = index / texelsInBatchN;
|
|
index -= b2 * texelsInBatchN;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec4(b2, b, r, c);
|
|
}
|
|
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let l=2;l<e.length-1;l++)o*=e[e.length-l-1],i=`
|
|
int b${l} = index / ${o};
|
|
index -= b${l} * ${o};
|
|
`+i,c=`b${l}, `+c;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
|
|
${i}
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec${e.length}(${c});
|
|
}
|
|
`}function AX(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${bm(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let r=gi(["r","c","d","d2"],e);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${r}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function DX(e,t){let n=gi(["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 FX(e,t){let n=gi(["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 $X(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));
|
|
}
|
|
`;let s=Math.ceil(e[1]/2);return n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function RX(e,t,n){return w.arraysEqual(e,t)?n?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`:e[1]===1?n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:e[0]===1?n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
int r = index / outShape[1];
|
|
int c = index - r * outShape[1];
|
|
return ivec2(r, c);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = index / ${e[1]};
|
|
int c = index - r * ${e[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function bi(e){return`offset${e}`}function PX(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Tn();return`
|
|
vec4 ${n}() {
|
|
return ${r.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function OX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return`
|
|
float ${r}() {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let o=bi(n);if(t)return`
|
|
float ${r}() {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let[i,c]=e.shapeInfo.texShape;return`
|
|
float ${r}() {
|
|
vec2 uv = uvFromFlat(${i}, ${c}, ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function MX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=Tn();if(t)return`
|
|
vec4 ${r}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`
|
|
vec4 ${r}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${o[0]}, ${o[1]}, index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`}function LX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int index) {
|
|
${_u(e)}
|
|
}
|
|
`;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return`
|
|
float ${r}(int index) {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let i=bi(n);return o===1?t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:a===1?t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function BX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],c=Tn();if(a!=null&&w.arraysEqual(n,a))return t?`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
|
|
return ${c.texture2D}(${r}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
|
|
|
|
return ${c.texture2D}(${r}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${s}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${c.texture2D}(${r}, uv);
|
|
}
|
|
`;let l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],u=Math.ceil(n[1]/2);return`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${c.texture2D}(${r}, uv);
|
|
}
|
|
`}function zX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&w.arraysEqual(n,a)){if(t)return`
|
|
float ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let p=a[0],h=a[1];return`
|
|
float ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}let{newShape:o,keptDims:i}=w.squeezeShape(n),c=o;if(c.length<n.length){let p=Eu(e,c),h=["row","col"];return`
|
|
${Nu(p,t)}
|
|
float ${s}(int row, int col) {
|
|
return ${s}(${Au(h,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
|
|
${_u(e)}
|
|
}
|
|
`;let l=a[0],u=a[1],d=bi(r);return u===1?t?`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:l===1?t?`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:t?`
|
|
float ${s}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r}Shape[1] + col + ${d};
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n[1]} + col + ${d};
|
|
vec2 uv = uvFromFlat(${l}, ${u}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function WX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(n[0]===1){let p=n.slice(1),h=[1,2],f=Eu(e,p),m=["b","row","col"];return`
|
|
${W2(f,t)}
|
|
vec4 ${s}(int b, int row, int col) {
|
|
return ${s}(${Au(m,h)});
|
|
}
|
|
`}let i=Tn();if(t)return`
|
|
vec4 ${s}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${i.texture2D}(${r}, uv);
|
|
}
|
|
`;let c=o[0],l=o[1],u=Math.ceil(n[2]/2),d=u*Math.ceil(n[1]/2);return`
|
|
vec4 ${s}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${c}, ${l}, ${d}, ${u}, b, row, col);
|
|
return ${i.texture2D}(${r}, uv);
|
|
}
|
|
`}function VX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=w.squeezeShape(n),l=i;if(l.length<n.length){let m=Eu(e,l),g=["row","col","depth"];return`
|
|
${Nu(m,t)}
|
|
float ${s}(int row, int col, int depth) {
|
|
return ${s}(${Au(g,c)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${a}, ${o}, 1)));
|
|
${_u(e)}
|
|
}
|
|
`;let u=e.shapeInfo.texShape,d=u[0],p=u[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
int stride1 = ${r}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${d}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(p===o&&h==null)return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let f=bi(r);return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${r}Shape[1] * ${r}Shape[2];
|
|
int stride1 = ${r}Shape[2];
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${d}, ${p}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function UX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=Tn();if(t)return`
|
|
vec4 ${r}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${n}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int texR = index / packedTexShape[1];
|
|
int texC = index - texR * packedTexShape[1];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);
|
|
}
|
|
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=c[0],u=c[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=a[o-m-1],f=`b${m} * ${p} + `+f;return`
|
|
vec4 ${r}(${h}) {
|
|
int index = ${f};
|
|
int texR = index / ${u};
|
|
int texC = index - texR * ${u};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${l});
|
|
return ${s.texture2D}(${n}, uv);
|
|
}
|
|
`}function GX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:l}=w.squeezeShape(n);if(c.length<n.length){let y=Eu(e,c),v=["row","col","depth","depth2"];return`
|
|
${Nu(y,t)}
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
return ${s}(${Au(v,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, 1)));
|
|
${_u(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&u==null)return t?`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
${f}
|
|
${m}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${o}, ${a}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(h===a&&u==null)return t?`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${n[1]*n[2]}, ${n[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let b=bi(r);return t?`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${f}
|
|
${m}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${b});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} +
|
|
depth * ${a} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index + ${b});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function HX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:l}=w.squeezeShape(t);if(c.length<t.length){let m=Eu(e,c),g=["row","col","depth","depth2","depth3"];return`
|
|
${Nu(m)}
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${r}(${Au(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, ${s})) +
|
|
depth3;
|
|
${_u(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&u==null)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${o}, ${a}, ${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===s&&u==null)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=bi(n);return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} + depth * ${a} +
|
|
depth2 * ${s} + depth3 + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function jX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=w.squeezeShape(t);if(s.length<t.length){let g=Eu(e,s),b=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Nu(g)}
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${r}(${Au(b,a)});
|
|
}
|
|
`}let o=t[5],i=t[4]*o,c=t[3]*i,l=t[2]*c,u=t[1]*l;if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${u}, ${l}, ${c}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${o}, 1)));
|
|
${_u(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===u&&d==null)return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${l}, ${c}, ${i}, ${o})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(f===o&&d==null)return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=bi(n);return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${u} + col * ${l} + depth * ${c} +
|
|
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
|
|
vec2 uv = uvFromFlat(${h}, ${f}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function _u(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 qX(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=z2(e.shapeInfo.logicalShape,t.logicalShape),c=ht(o),l=o-a,u,d=["x","y","z","w","u","v"];a===0?u="":o<2&&i.length>=1?u="coords = 0;":u=i.map(y=>`coords.${d[y+l]} = 0;`).join(`
|
|
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((y,v)=>`coords.${d[v+l]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,b=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!b)o===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${s}() {
|
|
${c} coords = getOutputCoords();
|
|
${u}
|
|
vec4 outputValue = get${r}(${p});
|
|
${h}
|
|
}
|
|
`}function KX(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&w.arraysEqual(o,a))return`
|
|
float ${s}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;let l=ht(c),u=z2(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${h[m+d]} = 0;`).join(`
|
|
`);let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
|
|
float ${s}() {
|
|
${l} coords = getOutputCoords();
|
|
${p}
|
|
return get${r}(${f});
|
|
}
|
|
`}function ht(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 Mw(e,t,n){let{newShape:r,keptDims:s}=w.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!w.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function Eu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Au(e,t){return t.map(n=>e[n]).join(", ")}function XX(e,t,n,r){let s=n.map((v,x)=>{let k={logicalShape:v.shape,texShape:v.isUniform?null:v.texData.texShape,isUniform:v.isUniform,isPacked:v.isUniform?!1:v.texData.isPacked,flatOffset:null};return v.texData!=null&&v.texData.slice!=null&&v.texData.slice.flatOffset>0&&(k.flatOffset=v.texData.slice.flatOffset),{name:t.variableNames[x],shapeInfo:k}}),a=s.map(v=>v.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=hX(s,o,t),c=e.createProgram(i),l=null,u=e.getUniformLocation(c,"NAN",!1);J().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(c,"INFINITY",!1));let d=!1,p={},h={},f={};for(let v=0;v<t.variableNames.length;v++){let x=t.variableNames[v];p[x]=e.getUniformLocation(c,x,d),p[`offset${x}`]=e.getUniformLocation(c,`offset${x}`,d),t.enableShapeUniforms&&(h[`${x}Shape`]=e.getUniformLocation(c,`${x}Shape`,d),f[`${x}TexShape`]=e.getUniformLocation(c,`${x}TexShape`,d))}let m,g,b;t.enableShapeUniforms&&(m=e.getUniformLocation(c,"outShape",d),b=e.getUniformLocation(c,"outShapeStrides",d),g=e.getUniformLocation(c,"outTexShape",d));let y=[];return t.customUniforms&&t.customUniforms.forEach((v,x)=>{y[x]=e.getUniformLocation(c,v.name,d)}),{program:t,source:i,webGLProgram:c,uniformLocations:p,customUniformLocations:y,inShapeInfos:a,outShapeInfo:o,infLoc:l,nanLoc:u,inShapesLocations:h,inTexShapesLocations:f,outShapeLocation:m,outShapeStridesLocation:b,outTexShapeLocation:g}}function U2(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!w.arraysEqual(s,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!w.arraysEqual(i,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${c} must match`)})}function YX(e,t,n,r,s){t.program.enableShapeUniforms||(U2(t.inShapeInfos,n),U2([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),J().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,l)=>{let u=t.program.variableNames[l],d=t.uniformLocations[u],p=t.uniformLocations[`offset${u}`],h=t.inShapesLocations[`${u}Shape`],f=t.inTexShapesLocations[`${u}TexShape`];if(h){let{uniformShape:m}=Mw(t.program.packedInputs,c.shape,c.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,c.texData.texShape[0],c.texData.texShape[1]),d!=null){if(c.isUniform){if(w.sizeFromShape(c.shape)<2)e.gl.uniform1f(d,c.uniformValues[0]);else{let m=c.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}c.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,d,l)}});let i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape));break;default:break}if(t.outShapeStridesLocation){let c=w.computeStrides(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(c));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(c));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(c));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&s&&t.program.customUniforms.forEach((c,l)=>{let u=t.customUniformLocations[l],d=s[l];if(c.type==="float")e.gl.uniform1fv(u,d);else if(c.type==="vec2")e.gl.uniform2fv(u,d);else if(c.type==="vec3")e.gl.uniform3fv(u,d);else if(c.type==="vec4")e.gl.uniform4fv(u,d);else if(c.type==="int")e.gl.uniform1iv(u,d);else if(c.type==="ivec2")e.gl.uniform2iv(u,d);else if(c.type==="ivec3")e.gl.uniform3iv(u,d);else if(c.type==="ivec4")e.gl.uniform4iv(u,d);else throw Error(`uniform type ${c.type} is not supported yet.`)}),e.executeProgram()}function ZX(e,t,n){let r="";t.concat(n).forEach(o=>{let i=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!o.isUniform){let c=o.texData.texShape,{useSqueezeShape:l,uniformShape:u,keptDims:d}=Mw(e.packedInputs,o.shape,c),p="",h="",f="";if(u.length===1&&e.packedInputs){let k=[Math.ceil(c[0]/2),Math.ceil(c[1]/2)];p=`${k[0]>1}_${k[1]>1}`}else if(u.length===2&&!e.packedInputs)h=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!e.packedInputs){let k=w.computeStrides(u);f=`${k[0]===c[1]}_${k[k.length-1]===c[1]}`}let m=o.shape.length,g=u.length===2&&w.arraysEqual(o.shape,c),b=w.sizeFromShape(o.shape)===1,y=_.getBroadcastDims(o.shape,n.shape),v=!e.packedInputs&&m===n.shape.length&&w.arraysEqual(c,n.texData.texShape),x=e.packedInputs||u.length>2?"":`${c[0]>1}_${c[1]>1}`;r+=`${m}_${v}_${l?d:""}_${u.length}_${b}_${y}_${g}_${p}_${h}_${f}_${x}_${i}`}else{let c=o.isUniform?"uniform":o.texData.texShape;r+=`${o.shape}_${c}_${i}`}});let s=e.userCode,a=e.constructor.name;return a+="_"+r+"_"+s+`${J().getNumber("WEBGL_VERSION")}`,a}function fr(e){return J().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var JX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=$d.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?bm(["r","c","d"],e):gi(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getA(rc.x, rc.y, rc.z);
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},QX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=$d.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?bm(["r","c","d"],e):gi(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},e7=class{constructor(e){this.variableNames=["A"],this.outTexUsage=pr.DOWNLOAD;let t=Tn();this.outputShape=e,this.userCode=`
|
|
${B2}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},t7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=pr.DOWNLOAD;let t=Tn();this.outputShape=e,this.userCode=`
|
|
${B2}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},n7=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?Ow():Pw(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${n.texture2D}(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
${n.output} = vec4(${r}, 0., 0., 0.);
|
|
}
|
|
`}},r7=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${o};
|
|
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${a};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
values = ${n.texture2D}(A, uv);
|
|
|
|
if (offset == 0) {
|
|
result[${i}] = values[0];
|
|
} else if (offset == 1) {
|
|
result[${i}] = values[1];
|
|
} else if (offset == 2) {
|
|
result[${i}] = values[2];
|
|
} else {
|
|
result[${i}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${this.enableShapeUniforms?Ow():Pw(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${r}
|
|
|
|
${n.output} = ${s};
|
|
}
|
|
`}},G2={};$e(G2,{bindVertexProgramAttributeStreams:()=>Q2,createBufferFromOutputTexture:()=>nN,createFloat16MatrixTexture:()=>X2,createFloat16PackedMatrixTexture:()=>J2,createFloat32MatrixTexture:()=>K2,createIndexBuffer:()=>q2,createPackedMatrixTexture:()=>Z2,createUnsignedBytesMatrixTexture:()=>Y2,createVertexBuffer:()=>j2,createVertexShader:()=>H2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>sN,downloadFloat32MatrixFromBuffer:()=>rN,downloadMatrixFromPackedOutputTexture:()=>oN,downloadPackedMatrixFromBuffer:()=>aN,getInternalFormatForFloat16MatrixTexture:()=>Bw,getInternalFormatForFloat16PackedMatrixTexture:()=>Vw,getInternalFormatForFloat32MatrixTexture:()=>Lw,getInternalFormatForPackedMatrixTexture:()=>Ww,getInternalFormatForUnsignedBytesMatrixTexture:()=>zw,uploadDenseMatrixToTexture:()=>eN,uploadPixelDataToTexture:()=>tN});function H2(e){let t=Tn(),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 b2(e,n)}function j2(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 w2(e,t)}function q2(e){let t=new Uint16Array([0,1,2,2,1,3]);return k2(e,t)}function Ld(e,t,n,r,s,a){S2(t,n);let o=I2(e),i=e.TEXTURE_2D;return xe(e,()=>e.bindTexture(i,o)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),xe(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Lw(e){return e.internalFormatFloat}function K2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Lw(r),r.textureFormatFloat,e.FLOAT)}function Bw(e){return e.internalFormatHalfFloat}function X2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Bw(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function zw(e){return e.downloadTextureFormat}function Y2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,zw(r),e.RGBA,e.UNSIGNED_BYTE)}function Ww(e){return e.internalFormatPackedFloat}function Z2(e,t,n,r){let[s,a]=Cu(t,n);return Ld(e,s,a,Ww(r),e.RGBA,e.FLOAT)}function Vw(e){return e.internalFormatPackedHalfFloat}function J2(e,t,n,r){let[s,a]=Cu(t,n);return Ld(e,s,a,Vw(r),e.RGBA,r.textureTypeHalfFloat)}function Q2(e,t,n){let r=0,s=3*4,a=3*4+2*4;return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Dw(e,t,"clipSpacePos",n,3,a,r)&&Dw(e,t,"uv",n,2,a,s)}function eN(e,t,n,r,s,a){xe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,c;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,c=a.internalFormatPackedFloat),o.set(s),xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function tN(e,t,n){xe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function nN(e,t,n,r){let s=e.createBuffer();xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return xe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function rN(e,t,n){let r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function sN(e,t,n,r){let[s,a]=Rd(t,n),o=4,i=new Uint8Array(JK(t*n,o));return xe(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function aN(e,t,n,r,s,a,o,i){let c=e,l=new Float32Array(QK(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function oN(e,t,n){let r=new Float32Array(t*n*4);return xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var iN=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=J().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,f2(t,e)):this.gl=fs(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(J().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Pd(this.gl,s),hr(this.gl,a))this.textureHalfFloatExtension=Pd(this.gl,a);else if(J().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),hr(this.gl,r))this.colorBufferHalfFloatExtension=Pd(this.gl,r);else if(J().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",hr(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(hr(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=j2(this.gl),this.indexBuffer=q2(this.gl),this.framebuffer=C2(this.gl),this.textureConfig=Aw(this.gl,this.textureHalfFloatExtension)}get debug(){return J().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;xe(e,()=>e.finish()),xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),xe(e,()=>e.deleteFramebuffer(this.framebuffer)),xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),xe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),xe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),K2(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),X2(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),Y2(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),tN(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),eN(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),J2(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),Z2(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Fw(this.gl,this.framebuffer),this.outputTexture=null),xe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>sN(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,r,s,a){return aN(this.gl,e,t,n,r,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return rN(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let r=nN(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(J().getBool("WEBGL_FENCE_API_ENABLED")){let r=e,s=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let a=r.clientWaitSync(s,0,0);return a===r.ALREADY_SIGNALED||a===r.CONDITION_SATISFIED},t=s}else J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>oN(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=y2(t,e);this.vertexShader==null&&(this.vertexShader=H2(t));let r=v2(t);return xe(t,()=>t.attachShader(r,this.vertexShader)),xe(t,()=>t.attachShader(r,n)),x2(t,r),this.debug&&dm(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=Q2(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&xe(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&dm(this.gl,this.program),xe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?N2(this.gl,e,t):_2(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),xe(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(),E2(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[r,s]=Cu(t,n);this.setOutputMatrixTextureDriver(e,r,s)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&dm(this.gl,this.program),Od(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),xe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),xe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Pd(this.gl,J().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(J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,r=this.getQueryTimerExtensionWebGL2(),s=n.createQuery();return n.beginQuery(r.TIME_ELAPSED_EXT,s),s}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(J().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,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,r=this.getQueryTimerExtensionWebGL2(),s=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),s&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),r=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=s7(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(),pm(this.gl,e,this.framebuffer),this.debug&&Od(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(pm(this.gl,this.outputTexture,this.framebuffer),this.debug&&Od(this.gl)):Fw(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let r=this.gl;pm(r,e,this.framebuffer),this.debug&&Od(r),this.outputTexture=e,xe(r,()=>r.viewport(0,0,t,n)),xe(r,()=>r.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),xe(this.gl,()=>this.gl.scissor(e,t,n,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function s7(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:a7,bincountImpl:cN,bincountReduceImpl:o7,ceilImpl:i7,concatImpl:c7,equalImpl:u7,expImpl:l7,expm1Impl:d7,floorImpl:p7,gatherNdImpl:h7,gatherV2Impl:f7,greaterImpl:m7,greaterEqualImpl:g7,lessImpl:b7,lessEqualImpl:y7,linSpaceImpl:v7,logImpl:x7,maxImpl:w7,maximumImpl:k7,minimumImpl:I7,multiplyImpl:S7,negImpl:C7,notEqualImpl:T7,prodImpl:N7,rangeImpl:_7,rsqrtImpl:E7,sigmoidImpl:A7,simpleAbsImpl:uN,sliceImpl:D7,sparseFillEmptyRowsImpl:F7,sparseReshapeImpl:$7,sparseSegmentReductionImpl:lN,sqrtImpl:R7,stridedSliceImpl:P7,stringNGramsImpl:O7,stringSplitImpl:M7,stringToHashBucketFastImpl:L7,subImpl:B7,tileImpl:z7,topKImpl:W7,transposeImpl:Uw,uniqueImpl:V7}=uT;function dN(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Nn(e,t){return t===1?[e]:dN(e,t)}function U7(e,t){if(e===1)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}var G7=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=Nn("rc",t),r=ht(t),s=j7(t,e,n),a=q7(t,e[e.length-1],e[e.length-2],n),o=K7(e,n);this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${o}));
|
|
}
|
|
}
|
|
`}}};function H7(e,t){let n=[];for(let r=0;r<=1;r++)for(let s=0;s<=1;s++){let a=`${r===0?"r":"rp1"}, ${s===0?"c":"cp1"}`;for(let o=2;o<e;o++)a=`${t[t.length-1-o]},`+a;n.push(a)}return n}function j7(e,t,n){if(e===1)return`rc > ${t[0]}`;let r="";for(let s=e-2;s<e;s++)r+=`${n[s]} >= ${t[s]}`,s<e-1&&(r+="||");return r}function q7(e,t,n,r){if(e===1)return"";let s=r.slice(-2);return`
|
|
int r = ${s[0]};
|
|
int c = ${s[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${t};
|
|
bool rEdge = rp1 >= ${n};
|
|
`}function K7(e,t){let n=e.length,r=H7(n,t);return n===1?`getA(rc),
|
|
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
|
|
0, 0`:`getA(${r[0]}),
|
|
cEdge ? 0. : getA(${r[1]}),
|
|
rEdge ? 0. : getA(${r[2]}),
|
|
rEdge || cEdge ? 0. : getA(${r[3]})`}var pN=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2==1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+=`
|
|
${s}
|
|
${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[${r}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${r>0?"}":""}
|
|
`}this.userCode=`
|
|
${X7(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?Ow():Pw(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
|
|
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function X7(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?pX(["r","c","d"],"inputShape"):gi(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var Y7=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let r=fN(t,n),s=mN(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=hN(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===un.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===un.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===un.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===un.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===un.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=fN(n,r),a=mN(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=hN(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=J().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let c=this.usedTextures[a],l=c.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(l,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 Z7(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function hN(e,t,n,r,s){let a=J7(t,r),o;if(s){let[c,l]=Cu(e[0],e[1]);o=c*l}else{let[c,l]=Rd(e[0],e[1]);o=c*l}let i=Z7(n,a);return o*i}function J7(e,t){switch(e){case un.PACKED_2X2_FLOAT32:return Ww(t);case un.PACKED_2X2_FLOAT16:return Vw(t);case un.UNPACKED_FLOAT32:return Lw(t);case un.UNPACKED_FLOAT16:return Bw(t);case un.PACKED_4X1_UNSIGNED_BYTE:return zw(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function Q7(e){return J().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?un.PACKED_2X2_FLOAT32:un.UNPACKED_FLOAT32:e?un.PACKED_2X2_FLOAT16:un.UNPACKED_FLOAT16}function fN(e,t){if(e===pr.UPLOAD)return un.PACKED_2X2_FLOAT32;if(e===pr.RENDER||e==null)return Q7(t);if(e===pr.DOWNLOAD||e===pr.PIXELS)return un.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function mN(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Sa=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},jr="if (isnan(x)) return x;",e9="return x;",gN="return abs(x);",t9="return (x >= 0.0) ? x : (exp(x) - 1.0);",n9=jr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,r9=jr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,ym="return x;",s9="return 1.0 / (1.0 + exp(-1.0 * x));",a9="return x;",o9=`
|
|
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;
|
|
`,i9=`
|
|
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;
|
|
`,c9=`
|
|
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;
|
|
`,u9="return 1.0 / (1.0 + exp(-1.0 * x));",Du=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},l9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Nn("rc",t),r=ht(t),s=U7(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${s});
|
|
|
|
setOutput(getChannel(packedInput, ${o}));
|
|
}
|
|
`}},d9=is.whereImpl,p9=1e-7,h9=1e-4,vm={};function f9(e){return e in vm||(vm[e]={}),vm[e]}var m9=J().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),g9=600;function b9(){return J().global.screen==null?1024:J().global.screen.height*J().global.screen.width*window.devicePixelRatio*g9/1024/1024}var xm=class extends bl{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!J().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=fs(J().getNumber("WEBGL_VERSION"));this.binaryCache=f9(J().getNumber("WEBGL_VERSION")),this.gpgpu=new iN(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 Y7(this.gpgpu),this.numMBBeforeWarning=b9(),this.texData=new Op(this,Cs())}nextDataId(){return xm.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((J().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||J().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:pr.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,r,s){if(J().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:pr.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:o,isPacked:i}=t;if(a!=null){let d;i?d=new Du(o,ym):d=new Sa(o,ym);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,l;c&&(l=w.now());let u;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);u=_.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=w.now()-l),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Du(r,ym):h=new Sa(r,ym);let f=this.runWebGLProgram(h,[{dataId:e,shape:r,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(!J().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&J().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,l;if(a!=="complex64"&&J().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);let h=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(h.texture,...lm(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=_.mergeRealAndImagArrays(f,m)}else if(c==null)u=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(r);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(l!=null&&this.disposeIntermediateTensorInfo(l),c!=null){let h=this.gpgpu.gl;xe(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Cs().removeDataId(e,this),this.pendingDeletes--),d}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!m2(n))throw J().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:r}=this.texData.get(e),s=w.sizeFromShape(t);if(J().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let d=this.decode(e),p=this.texData.get(d.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(p.texture,...lm(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(d),h}let a=J().getBool("WEBGL_PACK")&&r===!0,o=a?hm(t):t,i=a?new t7(o):new e7(o),c=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(c.dataId),u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture,l.texShape[0],l.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(c),u}timerAvailable(){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){let t=this.activeTimers,n=[],r=!1;this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();let s=w.flatten(this.activeTimers.map(i=>i.query)).filter(i=>i!=null),a=w.flatten(this.activeTimers.map(i=>i.name)).filter(i=>i!=null);this.activeTimers=t,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let i=await Promise.all(s);o.kernelMs=w.sum(i),o.getExtraProfileInfo=()=>i.map((c,l)=>({name:a[l],ms:c})).map(c=>`${c.name}: ${c.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:w.now(),endMs:null}}endTimer(e){return J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=w.now(),e)}async getQueryTime(e){if(J().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:r,usage:s,isPacked:a,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,c=this.dataRefCount.get(i);c>1?this.dataRefCount.set(i,c-1):(this.dataRefCount.delete(i),t!=null&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,s,a)));let l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=m9){return J().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&w.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){_.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return d9(e.shape,t)}packedUnaryOp(e,t,n){let r=new Du(e.shape,t),s=this.compileAndRun(r,[e],n);return Cs().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let r=uN(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,r)}if(J().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,gN,e.dtype);let t=new Sa(e.shape,gN),n=this.compileAndRun(t,[e]);return Cs().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:r}=this.makeTensorInfo(e,t,n);return Cs().makeTensorFromDataId(r,e,t,this)}unpackTensor(e){let t=new l9(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new G7(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[fi(e.shape),...mi(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[fi(t),...mi(t)],a=new pN(s,n),o=!0,i=[n],c=this.runWebGLProgram(a,[r],e.dtype,i,o);return{dataId:c.dataId,shape:t,dtype:c.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:r,dtype:s}=t,a=hm(r),o,i=lm(a);n?o=new QX(a):o=new JX(a);let c=!0,l=[i],u=this.runWebGLProgram(o,[{shape:a,dtype:s,dataId:e}],s,l,c);return{dtype:s,shape:r,dataId:u.dataId}}runWebGLProgram(e,t,n,r,s=!1){let a=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(a.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===$d.DENSE){let m=lm(e.outputShape);o.texShape=m.map(g=>g*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),w.sizeFromShape(a.shape)===0)return o.values=w.getTypedArrayFromDType(a.dtype,0),a;let i=[],c=t.map(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(m.dataId);if(g.texture==null){if(!e.packedInputs&&w.sizeFromShape(m.shape)<=J().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=m.shape)}else if(!!g.isPacked!=!!e.packedInputs)m=g.isPacked?this.unpackTensor(m):this.packTensor(m),i.push(m),g=this.texData.get(m.dataId);else if(g.isPacked&&!Md(g.shape,m.shape)){let b=m,y=m.shape;m.shape=g.shape,m=this.packedReshape(m,y),i.push(m),g=this.texData.get(m.dataId),b.shape=y}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:g,isUniform:!1}});this.uploadToGPU(a.dataId);let l={shape:a.shape,texData:o,isUniform:!1},u=ZX(e,c,l),d=this.getAndSaveBinary(u,()=>XX(this.gpgpu,e,c,l)),p=this.activeTimers!=null,h;p&&(h=this.startTimer()),YX(this.gpgpu,d,c,l,r),i.forEach(m=>this.disposeIntermediateTensorInfo(m)),p&&(h=this.endTimer(h),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)}));let f=J().get("WEBGL_FLUSH_THRESHOLD");if(f>0){let m=w.now();m-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=m)}if(!J().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&s===!1){let m=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),m}return a}compileAndRun(e,t,n,r,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(J().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=M(()=>{if(!J().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=J().getBool("DEBUG");J().set("DEBUG",!1);let t=this.abs(Se(1e-8)).dataSync()[0];if(J().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?p9:h9}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:r,values:s,texture:a,usage:o,isPacked:i}=t;if(a!=null)return;let c=this.activeTimers!=null,l;c&&(l=w.now());let u=t.texShape;if(u==null&&(u=F2(n,i),t.texShape=u),s!=null){let d=hm(n),p,h=u[1],f=u[0],m=s instanceof Uint8Array||s instanceof Uint8ClampedArray;i?([h,f]=Cu(u[0],u[1]),p=new r7(d,m)):p=new n7(d,m);let g=this.makeTensorInfo([f,h],r);m?this.texData.get(g.dataId).usage=pr.PIXELS:this.texData.get(g.dataId).usage=pr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),h,f,s);let b=[[f,h]],y=!0,v=this.runWebGLProgram(p,[g],r,b,y),x=this.texData.get(v.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(v.dataId),t.values=null,c&&(this.uploadWaitMs+=w.now()-l)}else{let d=this.acquireTexture(u,o,r,i);t.texture=d}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:r}=n;return this.releaseGPUData(e),t!=null&&(n.values=y9(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*w.bytesPerElement(t)}};xm.nextDataId=0;function y9(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let r=0;r<n.length;++r)n[r]=Math.round(e[r]);return n}else throw new Error(`Unknown dtype ${t}`)}var v9="3.10.0";function bN(){J().set("WEBGL_FORCE_F16_TEXTURES",!0)}Ul.isBrowser()&&Mh("webgl",()=>new xm,2);var x9={forceHalfFloat:bN},yN=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Fu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},wm=`
|
|
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;
|
|
`,Bd=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=fr(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${ht(s)} coords = getOutputCoords();
|
|
`,s===1)this.enableShapeUniforms?a+=`
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`:a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let i=Nn("coords",s);this.enableShapeUniforms?a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[s-2]} + 1) >= outShape[${s} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[s-1]} + 1) >= outShape[${s} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[s-2]} + 1) >= ${this.outputShape[s-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[s-1]} + 1) >= ${this.outputShape[s-1]};
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
${a}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function rr(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var w9={kernelName:so,backendName:"webgl",kernelFunc:rr};function Ca(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(a.dataId),i=rr({inputs:{x:r},backend:n}),c=rr({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var k9={kernelName:Hp,backendName:"webgl",kernelFunc:Ca},vN="return (a < 0.) ? b * a : a;",xN=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function I9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(xN,s.shape,o.shape):new Fu(vN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),c}var S9={kernelName:ao,backendName:"webgl",kernelFunc:I9},wN="return (a < 0.) ? b * a : a;",kN=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function C9(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(kN,r.shape,s.shape):new Fu(wN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var T9={kernelName:vo,backendName:"webgl",kernelFunc:C9},IN="if (isnan(x)) return x;",N9=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,_9=`
|
|
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 Xe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,c);return i.makeTensorInfo(o.shape,c,p)}let l=J().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return l?u=new Du(o.shape,t):u=new Sa(o.shape,e),i.runWebGLProgram(u,[o],c)}}function ln({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:l}=o,u=i;if(r&&c.dtype==="complex64"){let f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,k]=v,C={dataId:x.dataId,dtype:x.dtype,shape:c.shape},N={dataId:k.dataId,dtype:k.dtype,shape:l.shape},F=new Fu(e,c.shape,l.shape);return u.runWebGLProgram(F,[C,N],wr(x.dtype,k.dtype))}),y=Ca({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),y}let d=a||wr(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&s!=null){let f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?_.fromUint8ToStringArray(f):f,b=c.dtype==="string"?_.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,l.shape,g,b,d),x=u.makeTensorInfo(v,d),k=u.texData.get(x.dataId);return k.values=y,x}let p=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new Bd(t,c.shape,l.shape,n):h=new Fu(e,c.shape,l.shape),u.runWebGLProgram(h,[c,l],d)}}function km(e,t=!1){if(e==="linear")return t?a9:e9;if(e==="relu")return t?i9:n9;if(e==="elu")return t?o9:t9;if(e==="relu6")return t?c9:r9;if(e==="prelu")return t?kN:wN;if(e==="leakyrelu")return t?xN:vN;if(e==="sigmoid")return t?u9:s9;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var SN=class{constructor(e,t,n,r=!1,s=!1,a=!1,o=null,i=!1,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=fr(this.outputShape.length);let l=r?e[1]:e[2],u=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:c?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:m=`vec4 activation(vec4 x) {
|
|
${o}
|
|
}`,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(v=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${m}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${u}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${u}; i++) {
|
|
int batchA = ${y};
|
|
int batchB = ${v};
|
|
vec4 a = getMatrixA(batchA, ${d});
|
|
vec4 b = getMatrixB(batchB, ${p});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${f[0]});
|
|
result += (${h[1]} * ${f[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${b}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},CN={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},TN=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));
|
|
}
|
|
`}},NN="return a * b;";function Gw(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=_.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),l=new TN(CN.REAL,r.shape,s.shape),u=new TN(CN.IMAG,r.shape,s.shape),d=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ca({inputs:{real:p,imag:h},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),[l,u]=S7(r.shape,s.shape,i.values,c.values,a),d=n.makeTensorInfo(u,a),p=n.texData.get(d.dataId);return p.values=l,d}let o;return J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new Bd(NN,r.shape,s.shape):o=new Fu(NN,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var E9={kernelName:mo,backendName:"webgl",kernelFunc:Gw};function A9(e,t,n){let r=[fi(e.shape),...mi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[fi(t),...mi(t)],o=new pN(a,r),i=!0,c=[r],l=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function be(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=w.sizeFromShape(s.shape),c=w.inferFromImplicitShape(a,i),l=w.sizeFromShape(c);w.assert(i===l,()=>`The new shape (${c}) has ${l} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let u=o.texData.get(s.dataId);return u.isPacked&&!Md(s.shape,c)&&!(u.texture!==null&&Md(u.shape,c))?A9(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var D9={kernelName:$c,backendName:"webgl",kernelFunc:be},_N=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let u=1/t;c=`sumValue += dot(values * ${w.isInt(u)?u.toPrecision(2):u}, ones);`}let l="";s%n>0&&(l=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${l}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${o}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${c}
|
|
}
|
|
|
|
int inIdx = inOffset + ${o};
|
|
if (${i===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${c}
|
|
} else if (${i===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${c}
|
|
} else if (${i===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${c}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}},F9=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let l=Math.floor(n/4)*4,u=n%4,d=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,p="vec4";t==="all"?(o="1.0",d=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,p="bvec4"):t==="any"&&(o="0.0",d=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,p="bvec4");let h="";s%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
vec4 minMaxValue = vec4(${o});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${l}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${l};
|
|
if (${u===1}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===2}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===3}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
}
|
|
setOutput(${c});
|
|
}
|
|
`}};function $9(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],r=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function yi(e,t,n,r){let s=$9(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:l}=s[o],u,d;n==="mean"?u=o===0?new _N({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},i):new _N({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l}):u=new F9({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},n),d=a,a=r.runWebGLProgram(u,[a],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return a}var R9=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=ht(this.rank),s=P9(t);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function P9(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let s=0;s<e.length;s++)r[e[s]]=n[s];return r.join()}var O9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let l=0;l<n.length;l++)n[l]=e[t[l]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=ht(this.rank),s=dN("rc",this.rank),a=new Array(this.rank);for(let l=0;l<t.length;l++)a[t[l]]=s[l];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,c=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${c};
|
|
if(${i}) {
|
|
result[1] = ${c};
|
|
}
|
|
--${s[this.rank-1]};
|
|
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${c};
|
|
if(${i}) {
|
|
result[3] = ${c};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Im(e,t,n){let r=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new O9(e.shape,t):new R9(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function M9(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,c=_.getAxesPermutation(i,a),l=c!=null,u=e;l&&(u=Im(e,c,r),i=_.getInnerMostAxes(i.length,a)),_.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=_.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=_.expandShapeToKeepDim(d,o));let f=w.sizeFromShape(p),g=w.sizeFromShape(e.shape)/f,b=be({inputs:{x:u},attrs:{shape:[g,f]},backend:r}),y=Dh(e.dtype),v=yi(b,y,"sum",r),x=be({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),l&&r.disposeIntermediateTensorInfo(u),x}function Sm(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return M9(s,a,o,n)}var L9={kernelName:Eo,backendName:"webgl",kernelFunc:Sm};function _n(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let u=0;u<c.length;u++)c[u]=s.shape[a[u]];let l;if(o.shouldExecuteOnCPU([s])){let d=o.texData.get(s.dataId).values,p=Uw(d,s.shape,s.dtype,a,c);l=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(l.dataId);h.values=p}else l=Im(s,a,o);return l}var B9={kernelName:Po,backendName:"webgl",kernelFunc:_n},EN=1e3;function Cm({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let l=e.shape.length,u=t.shape.length,d=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[u-1]:t.shape[u-2],h=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(m),y=w.sizeFromShape(g),v=b===y||b===1||y===1;w.assert(l>=2&&u>=2&&v,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let k=(b>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);w.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);let C=n?[b,d,h]:[b,h,d],N=r?[y,f,p]:[y,p,f],F=be({inputs:{x:e},backend:s,attrs:{shape:C}}),R=be({inputs:{x:t},backend:s,attrs:{shape:N}}),O=[F,R],D=Math.max(b,y),P=n?F.shape[1]:F.shape[2],T=a!=null,L=o!=null,G=c==="leakyrelu",j=c!=null?km(c,!0):null,q=T||L||G||j!=null,K;if((h===1||f===1)&&P>EN&&q===!1){let te=F,ne=R;n&&(te=_n({inputs:{x:F},backend:s,attrs:{perm:[0,2,1]}}),O.push(te)),r&&(ne=_n({inputs:{x:R},backend:s,attrs:{perm:[0,2,1]}}),O.push(ne));let ae=f!==1,se=f===1,re=te;ae&&(re=be({inputs:{x:te},backend:s,attrs:{shape:[D,P,1]}}),O.push(re));let ue=f===1?2:1,de=ne;se&&(de=be({inputs:{x:ne},backend:s,attrs:{shape:[D,1,P]}}),O.push(de));let me=Gw({inputs:{a:re,b:de},backend:s});K=Sm({inputs:{x:me},backend:s,attrs:{axis:ue,keepDims:!0}}),O.push(me)}else{let te=wr(e.dtype,t.dtype),ne=new SN(C,N,[D,h,f],n,r,T,j,L,G),ae=[F,R];if(a!=null&&ae.push(a),L&&ae.push(o),G){let se=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));ae.push(se),O.push(se)}K=s.runWebGLProgram(ne,ae,te)}let ee=be({inputs:{x:K},backend:s,attrs:{shape:k}});O.push(K);for(let te of O)s.disposeIntermediateTensorInfo(te);return ee}function z9(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r;return Cm({a:s,b:a,transposeA:c,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var W9={kernelName:Oo,backendName:"webgl",kernelFunc:z9},AN="return abs(x);";function V9(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){let a=n.texData.get(r.dataId),o=uN(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Du(r.shape,AN):s=new Sa(r.shape,AN),n.runWebGLProgram(s,[r],r.dtype)}var U9={kernelName:Ki,backendName:"webgl",kernelFunc:V9},G9=jr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,H9=Xe({opSnippet:G9}),j9={kernelName:Xi,backendName:"webgl",kernelFunc:H9},q9=jr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,K9=Xe({opSnippet:q9}),X9={kernelName:Yi,backendName:"webgl",kernelFunc:K9},DN="return a + b;",Y9=ln({opSnippet:DN,packedOpSnippet:DN,supportsComplex:!0,cpuKernelImpl:a7}),Z9={kernelName:Qs,backendName:"webgl",kernelFunc:Y9},J9=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
float result = ${r};
|
|
setOutput(result);
|
|
}
|
|
`}},Q9=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
vec4 result = ${r};
|
|
setOutput(result);
|
|
}
|
|
`}};function Tm(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return rr({inputs:{x:r[0]},backend:n});if(r.length>J().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),l=Tm({inputs:r.slice(0,c),backend:n}),u=Tm({inputs:r.slice(c),backend:n});return Tm({inputs:[l,u],backend:n})}let s=r.map(c=>c.dtype).reduce((c,l)=>wr(c,l)),a=r.map(c=>c.shape),i=J().getBool("WEBGL_PACK")?new Q9(r[0].shape,a):new J9(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var eY={kernelName:Ba,backendName:"webgl",kernelFunc:Tm};function tY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("all",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"all",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var nY={kernelName:Zi,backendName:"webgl",kernelFunc:tY};function rY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("any",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"any",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var sY={kernelName:Ji,backendName:"webgl",kernelFunc:rY},aY=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${r};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${r}; i++) {
|
|
int inIdx = ${i};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${o} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},oY=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=ht(i),l=Nn("coords",i),u,d;if(a===1){d=i+1;let N=ht(d);u=`
|
|
${N} sourceLocR = ${N}(${l.join()}, 0);
|
|
++${l[i-1]};
|
|
${N} sourceLocG = ${N}(${l.join()}, 0);
|
|
++${l[i-2]};
|
|
${N} sourceLocA = ${N}(${l.join()}, 0);
|
|
--${l[i-1]};
|
|
${N} sourceLocB = ${N}(${l.join()}, 0);
|
|
--${l[i-2]};`}else d=i,u=`
|
|
${c} sourceLocR = coords;
|
|
++${l[i-1]};
|
|
${c} sourceLocG = coords;
|
|
++${l[i-2]};
|
|
${c} sourceLocA = coords;
|
|
--${l[i-1]};
|
|
${c} sourceLocB = coords;
|
|
--${l[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(N=>"int "+N),m=Nn("sourceLocR",d-1).concat("inIdx.r"),g=Nn("sourceLocG",d-1).concat("inIdx.g"),b=Nn("sourceLocB",d-1).concat("inIdx.b"),y=Nn("sourceLocA",d-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${y.join()})));`,k=`vec4(
|
|
getAChannel(${m.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,C=r?"":`
|
|
float getBestIndicesAChannel(${f.join()}) {
|
|
return getChannel(getBestIndicesA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${f.join()}) {
|
|
return getChannel(getA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}
|
|
${C}
|
|
void main() {
|
|
${c} coords = getOutputCoords();
|
|
bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};
|
|
bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};
|
|
${u}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${k};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${x}
|
|
vec4 candidate = ${k};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function FN(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);let o=_.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},c=new aY(i,n,r==null),l=[t];r!=null&&l.push(r);let u=e.runWebGLProgram(c,l,"int32");if(u.shape[1]===1)return u;let d=FN(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function $N(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=_.computeOptimalWindowSize(a),i=new oY(s,o,n,r==null),c=r==null?[t]:[t,r],l=e.runWebGLProgram(i,c,"int32");if(l.shape.length===t.shape.length){let u=$N(e,t,n,l);return e.disposeIntermediateTensorInfo(l),u}return l}function RN(e,t,n,r){let s=[n];if(_.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!J().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,c=t;i&&(c=e.unpackTensor(t),a.push(c));let[l,u]=_.computeOutAndReduceShapes(c.shape,s),d=w.sizeFromShape(u),p=be({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=FN(e,p,r);a.push(h);let f=be({inputs:{x:h},backend:e,attrs:{shape:l}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return $N(e,t,r)}function iY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=_n({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let u=RN(n,c,o[0],"max");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var cY={kernelName:za,backendName:"webgl",kernelFunc:iY};function uY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=_n({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let u=RN(n,c,o[0],"min");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var lY={kernelName:xl,backendName:"webgl",kernelFunc:uY},dY=jr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,pY=Xe({opSnippet:dY}),hY={kernelName:Qi,backendName:"webgl",kernelFunc:pY},fY=jr+"return log(x + sqrt(x * x + 1.0));",mY=Xe({opSnippet:fY}),gY={kernelName:ec,backendName:"webgl",kernelFunc:mY},bY=jr+`
|
|
return atan(x);
|
|
`,yY=Xe({opSnippet:bY}),vY={kernelName:tc,backendName:"webgl",kernelFunc:yY},xY=N9+`
|
|
return atan(a, b);
|
|
`,wY=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+_9+`
|
|
return result;
|
|
`,kY=ln({opSnippet:xY,packedOpSnippet:wY}),IY={kernelName:rc,backendName:"webgl",kernelFunc:kY},SY=jr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,CY=Xe({opSnippet:SY}),TY={kernelName:nc,backendName:"webgl",kernelFunc:CY},zd=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(f||(b="-1.0 / 1e-20"),n){let N=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${p}, ${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 += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${l}) {
|
|
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 ${N} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${r?s?m:g:`wR * ${d} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let y="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,k=a%4,C=`
|
|
if (${f}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${y}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${p}, ${h});
|
|
const float initializationValue = ${b};
|
|
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(${b});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${x}; wC += 4) {
|
|
int xC = xCCorner + wC * ${l};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${l}, d),
|
|
getValue(batch, xR, xC + 2 * ${l}, d),
|
|
getValue(batch, xR, xC + 3 * ${l}, d)
|
|
);
|
|
|
|
${C}
|
|
}
|
|
|
|
int xC = xCCorner + ${x};
|
|
if (${k===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
} else if (${k===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${l}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
} else if (${k===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${l}, d),
|
|
getValue(batch, xR, xC + 2 * ${l}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
}
|
|
}
|
|
setOutput(${v});
|
|
}
|
|
`}},Hw=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",v="0.0";if(y||(v="-1.0 / 1e-20"),n){let R=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${c});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${b});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${l}) {
|
|
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 < ${f};
|
|
wC += ${d}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +
|
|
wR * ${f} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let x="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let C=Math.floor(a/4)*4,N=a%4,F=`
|
|
if (${y}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${x}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${c});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${b});
|
|
const float initializationValue = ${v};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${v});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${l}) {
|
|
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 < ${C}; wC += 4) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
|
|
);
|
|
|
|
${F}
|
|
}
|
|
|
|
int xC = xCCorner + ${C};
|
|
if (${N===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
} else if (${N===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
} else if (${N===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${F}
|
|
}
|
|
}
|
|
setOutput(${k});
|
|
}
|
|
}
|
|
`}};function NY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Tu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return rr({inputs:{x:s},backend:n});let d=new zd(u,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var _Y={kernelName:Wa,backendName:"webgl",kernelFunc:NY};function EY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,c,l),p=new Hw(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var AY={kernelName:wl,backendName:"webgl",kernelFunc:EY},DY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=i-1-e.padInfo.top,u=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${l}, ${u});
|
|
const float avgMultiplier = float(${d});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${i};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${c};
|
|
wC+= ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},FY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${f}, ${m});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${u};
|
|
wD += ${i}) {
|
|
float dyD = float(dyDCorner + wD) / ${s}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${c}) {
|
|
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 < ${p};
|
|
wC += ${l}) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function $Y(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new FY(p);return n.runWebGLProgram(h,[s],o.dtype)}var RY={kernelName:Vp,backendName:"webgl",kernelFunc:$Y};function PY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Tu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:l}=r,u=_.computePool2DInfo(o.shape,i,c,1,l),d=new DY(u);return n.runWebGLProgram(d,[s],o.dtype)}var OY={kernelName:Wp,backendName:"webgl",kernelFunc:PY};function MY(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return Cm({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var LY={kernelName:Va,backendName:"webgl",kernelFunc:MY},BY=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${o};
|
|
float scale = ${i};
|
|
float inv = scale * inversesqrt(variance + float(${a}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},zY=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${o};
|
|
vec4 scale = ${i};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},WY=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;w.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let l=[r,s,a],u=null;o!=null&&(u=o.shape,l.push(o));let d=null;i!=null&&(d=i.shape,l.push(i));let p=J().getBool("WEBGL_PACK_NORMALIZATION")?new zY(r.shape,s.shape,a.shape,u,d,c):new BY(r.shape,s.shape,a.shape,u,d,c);return t.runWebGLProgram(p,l,l[0].dtype)},VY={kernelName:no,backendName:"webgl",kernelFunc:WY},UY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=ht(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=GY(this.rank),r,s=e.map((a,o)=>`sourceLoc.${jw[o]} = start[${o}] + coords.${jw[o]};`);r=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${s.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${r}
|
|
setOutput(getSource(${n}));
|
|
}
|
|
`}},jw=["x","y","z","w","u","v"];function GY(e){if(e===1)return"sourceLoc";if(e<=6)return jw.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var HY=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=ht(this.rank),n=Nn("coords",this.rank),r=Nn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
|
|
result.x = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${r[this.rank-1]};
|
|
result.y = ${a};
|
|
--${r[this.rank-1]};
|
|
}
|
|
`,i=this.rank===1?"":`
|
|
--${n[this.rank-1]};
|
|
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${r[this.rank-2]};
|
|
result.z = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${r[this.rank-1]};
|
|
result.w = ${a};
|
|
}
|
|
}
|
|
`,c=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((l,u)=>`start[${u}]`).join()});`:e.map((l,u)=>`${r[u]} = ${n[u]} + start[${u}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${c}
|
|
vec4 result = vec4(0.);
|
|
${o}
|
|
${i}
|
|
setOutput(result);
|
|
}
|
|
`}};function jY(e,t,n,r){let s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),o=r.texData.get(a.dataId);Object.assign(o,s),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=kn.computeFlatOffset(t,w.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function $u(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=kn.parseSliceParams(s,a,o);if(kn.assertParamsValid(s,i,c),w.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let d=n.texData.get(s.dataId),p=D7(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:l}=n.texData.get(s.dataId),u=kn.isSliceContinous(s.shape,i,c);if(l||!u){let d=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new HY(c):new UY(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),jY(s,i,c,n)}var qY={kernelName:Mc,backendName:"webgl",kernelFunc:$u},KY=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=_.getReshaped(s.shape,a,i),l=_.getPermuted(c.length,a.length),u=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(u,o,a.length),h=[],f=be({inputs:{x:s},backend:n,attrs:{shape:c}}),m=_n({inputs:{x:f},backend:n,attrs:{perm:l}}),g=be({inputs:{x:m},backend:n,attrs:{shape:u}}),b=$u({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},XY={kernelName:sc,backendName:"webgl",kernelFunc:KY};function YY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),l=cN(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}var ZY={kernelName:Up,backendName:"webgl",kernelFunc:YY};function JY(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=_.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var QY={kernelName:Gp,backendName:"webgl",kernelFunc:JY},eZ="return float(a != b);",PN=ln({opSnippet:eZ,cpuKernelImpl:T7,dtype:"bool"}),tZ={kernelName:Cc,backendName:"webgl",kernelFunc:PN};function Wd(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return rr({inputs:{x:s.complexTensorInfos.real},backend:n})}var nZ={kernelName:ph,backendName:"webgl",kernelFunc:Wd},rZ="return float(int(x));";function sZ(e,t){let n=new Sa(e.shape,rZ),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function qw(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return rr({inputs:{x:s},backend:n});let o=St(s.shape),i=qw({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=Ca({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=Wd({inputs:{input:s},backend:n}),i=qw({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=rr({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return sZ(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),c=PN({inputs:{a:s,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),c}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}var aZ={kernelName:Ua,backendName:"webgl",kernelFunc:qw},ON="return ceil(x);",oZ=Xe({opSnippet:ON,packedOpSnippet:ON,cpuKernelImpl:i7}),iZ={kernelName:Ga,backendName:"webgl",kernelFunc:oZ},cZ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
|
|
|
|
void main() {
|
|
float value = getAAtOutCoords();
|
|
if (isnan(value)) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, minVal, maxVal));
|
|
}
|
|
`}},uZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 value = getAAtOutCoords();
|
|
|
|
if (any(isnan(value))) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
}
|
|
`}};function lZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;J().getBool("WEBGL_PACK_CLIP")?i=new uZ(s.shape):i=new cZ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var dZ={kernelName:ea,backendName:"webgl",kernelFunc:lZ},pZ=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 MN(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function hZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new pZ(r.shape),o=[MN(r,s.complexTensorInfos.real),MN(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var fZ={kernelName:kl,backendName:"webgl",kernelFunc:hZ},mZ=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},gZ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=ht(r),a=Nn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],l=o.slice(-2),u=o.join(),d=`if (${c} < ${i[0]}) {
|
|
return getChannel(
|
|
getT0(${u}), vec2(${l.join()}));
|
|
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
|
|
if (${c} < ${i[f]} && ${c} >= ${i[f-1]}) {
|
|
return getChannel(
|
|
getT${f}(${Nm(o,c,m)}),
|
|
vec2(${Nm(l,c,m)}));
|
|
}`}let p=i.length,h=i[i.length-1];d+=`
|
|
return getChannel(
|
|
getT${p}(${Nm(o,c,h)}),
|
|
vec2(${Nm(l,c,h)}));`,this.userCode=`
|
|
float getValue(${o.map(f=>"int "+f)}) {
|
|
${d}
|
|
}
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
|
|
|
|
${a[r-1]} = ${a[r-1]} + 1;
|
|
if (${a[r-1]} < ${n[r-1]}) {
|
|
result.g = getValue(${a});
|
|
}
|
|
|
|
${a[r-2]} = ${a[r-2]} + 1;
|
|
if (${a[r-2]} < ${n[r-2]}) {
|
|
result.a = getValue(${a});
|
|
}
|
|
|
|
${a[r-1]} = ${a[r-1]} - 1;
|
|
if (${a[r-2]} < ${n[r-2]} &&
|
|
${a[r-1]} < ${n[r-1]}) {
|
|
result.b = getValue(${a});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Nm(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function _m(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return rr({inputs:{x:s.complexTensorInfos.imag},backend:n})}var bZ={kernelName:ah,backendName:"webgl",kernelFunc:_m};function Ru(e,t,n){let r=e[0].dtype;if(r==="complex64"){let u=e.map(m=>Wd({inputs:{input:m},backend:n})),d=e.map(m=>_m({inputs:{input:m},backend:n})),p=Ru(u,t,n),h=Ru(d,t,n),f=Ca({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let u=e.map(b=>{let y=w.sizeFromShape(b.shape.slice(t));return be({inputs:{x:b},backend:n,attrs:{shape:[-1,y]}})}),d=u.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=_.computeOutShape(u.map(b=>b.shape),1),h=u[0].shape[0]===1,f=c7(d,p,r,h),m=_.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>J().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=Ru(e.slice(0,u),t,n),p=Ru(e.slice(u),t,n),h=Ru([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new gZ(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,r)}let{tensors2D:a,outShape:o}=yZ(e,t,n),i=new mZ(a.map(u=>u.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let l=be({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),l}function yZ(e,t,n){let r=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>be({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function LN(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(l=>l.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(l=>w.sizeFromShape(l.shape)>0);if(i.length===1)return rr({inputs:{x:i[0]},backend:n});let c=i.map(l=>l.shape);return _.assertParamsConsistent(c,a),Ru(i,a,n)}var vZ={kernelName:ac,backendName:"webgl",kernelFunc:LN},BN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,y=m?3:1,v="",x="";n&&(r?v=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?v=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:v=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,x="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${v}
|
|
|
|
const ivec2 strides = ivec2(${i}, ${c});
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${y}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${b}]) * 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 < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${f===1}) {
|
|
|
|
if (${m}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${h}) *
|
|
getW(wR, wC, ${h}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${h}, xR, xC) *
|
|
getW(wR, wC, ${h}, d2);
|
|
}
|
|
|
|
} else if (${f===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${f===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1),
|
|
getX(batch, xR, xC, ${h} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC),
|
|
getX(batch, ${h} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${k}
|
|
${x}
|
|
setOutput(result);
|
|
}
|
|
`}},xZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${s}, ${a}, ${o});
|
|
const ivec3 pads = ivec3(${t}, ${n}, ${r});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${u}; wF++) {
|
|
int xF = xFCorner + wF * ${i};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${c};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${l};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${f===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${f===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${f===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1),
|
|
getX(batch, xF, xR, xC, ${h} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2),
|
|
getW(wF, wR, wC, ${h} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},wZ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let{dataFormat:n}=t,r=Tn(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,c="";for(let l=0;l<=1;l++)for(let u=0;u<=1;u++)c+=`
|
|
blockIndex = rc.y + ${u};
|
|
pos = rc.x + ${l};
|
|
|
|
${i}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${a}] && d0 >= 0) {
|
|
// Use custom imod instead mod. On Intel GPU, mod may generate
|
|
// unexpected value.
|
|
// https://github.com/tensorflow/tfjs/issues/5447
|
|
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
|
|
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
|
|
inChannels);
|
|
|
|
if(d1 < inputShape[${o}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${s}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${l*2+u}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${l*2+u}] = 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;
|
|
|
|
${c}
|
|
|
|
${r.output} = result;
|
|
}
|
|
`}};function zN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,l=r.texData.get(e.dataId),u=n.inChannels,d=c[0]*c[1]*c[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,b=[];if(!((d===1||p===1)&&u>EN)&&l.isPacked&&h&&l.texture!=null&&c[2]%2!=0&&w.arraysEqual(l.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),k={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},C=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,w.assert(Md(l.shape,k.shape),()=>`packed reshape ${l.shape} to ${k.shape} isn't free`);let N=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(N);let F=Cm({a:k,b:N,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),R=r.texData.get(F.dataId);w.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=C,R.shape=n.outShape,g=rr({inputs:{x:F},backend:r}),g.shape=n.outShape,b.push(F)}else{let x=h?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],k=be({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),N=Cm({a:k,b:C,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=be({inputs:{x:N},backend:r,attrs:{shape:n.outShape}}),b.push(k),b.push(C),b.push(N)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function WN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*l*u,g=p*d,b=[m,g],y=!0,v=!1,x=[],k=be({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});x.push(k),x.push(C);let N=new wZ(b,n),F=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],R=r.runWebGLProgram(N,[k],"float32",F),O=be({inputs:{x:R},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(R),x.push(O);let D=s!=null,P=a!=null,T=i==="leakyrelu",L=i?km(i,!0):null,G=new SN(O.shape,C.shape,[1,g,n.outChannels],y,v,D,L,P,T),j=[O,C];if(s&&j.push(s),P&&j.push(a),T){let te=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));j.push(te),x.push(te)}let q=r.runWebGLProgram(G,j,"float32"),K=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],ee=be({inputs:{x:q},backend:r,attrs:{shape:K}});x.push(q);for(let te of x)r.disposeIntermediateTensorInfo(te);return ee}function kZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=zN({x:s,filter:a,convInfo:p,backend:n});else if(J().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=WN({x:s,filter:a,convInfo:p,backend:n});else{let m=new BN(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=be({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var IZ={kernelName:Ha,backendName:"webgl",kernelFunc:kZ},SZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${r};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${a}) {
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
} else {
|
|
float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},CZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,l=a?2:3,u=a?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${u}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${c}], coords[${l}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${a}) {
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
} else {
|
|
float xValue = getDy(batch, d2, idyR, idyC);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},TZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yF = 0; yF < ${e.outDepth}; yF++) {
|
|
int xF = wF + yF * ${t} - ${s};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${n} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${o};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},NZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${i}, ${c}, ${l});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${s}.0;
|
|
|
|
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = ${t} - 1 - wF;
|
|
|
|
for (int wR = 0; wR < ${n}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${n} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function _Z(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,filterShape:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,u,o,1,i,l,!1,d),h=new SZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var EZ={kernelName:jp,backendName:"webgl",kernelFunc:_Z};function AZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(l),p=_.computeConv2DInfo(o,a.shape,i,1,c,u,!1,d),h=new CZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var DZ={kernelName:ja,backendName:"webgl",kernelFunc:AZ};function FZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeConv3DInfo(s.shape,a.shape,o,c,i),u=new xZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var $Z={kernelName:Il,backendName:"webgl",kernelFunc:FZ};function RZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,l=_.computeConv3DInfo(s.shape,c,o,1,i),u=new TZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var PZ={kernelName:qp,backendName:"webgl",kernelFunc:RZ};function OZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,l=_.computeConv3DInfo(c,a.shape,i,1,o),u=new NZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var MZ={kernelName:Kp,backendName:"webgl",kernelFunc:OZ},LZ=IN+`
|
|
return cos(x);
|
|
`,BZ=Xe({opSnippet:LZ}),zZ={kernelName:qa,backendName:"webgl",kernelFunc:BZ},WZ=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,VZ=Xe({opSnippet:WZ}),UZ={kernelName:Ka,backendName:"webgl",kernelFunc:VZ},GZ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[l]=t,[u,d]=n;this.outputShape=[l,u,d,c];let p=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,b]=u>1?[`${(o-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,v,x]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
|
|
const float height_ratio = float(${m});
|
|
const float width_ratio = float(${y});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${v};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${x};
|
|
if( in_x < 0.0 || in_x > ${f} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${p} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},HZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:l}=r,u=new GZ(s.shape,a.shape,i,c,l);return n.runWebGLProgram(u,[s,a,o],"float32")},jZ={kernelName:oc,backendName:"webgl",kernelFunc:HZ},VN=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let r=e.length,s=t?"0.0":`getX(${UN(r,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${ht(r)} coords = getOutputCoords();
|
|
int end = ${GN(r,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${o}) {
|
|
int idx = ${i};
|
|
${GN(r,"coords")} = idx;
|
|
val += getX(${UN(r,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function UN(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 GN(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 qZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,l=_.getAxesPermutation([a],c),u=s;l!=null&&(u=_n({inputs:{x:s},backend:n,attrs:{perm:l}}));let d=_.getInnerMostAxes(1,c)[0];if(d!==c-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let p=u.shape[d],h=rr({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new VN(u.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new VN(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(l!=null){let f=_.getUndoAxesPermutation(l),m=_n({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var KZ={kernelName:Xa,backendName:"webgl",kernelFunc:qZ};function XZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=cN(c,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(s.shape.length===2){let c=n.bufferSync(s),l=n.bufferSync(a),u=o7(c,l,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var YZ={kernelName:Xp,backendName:"webgl",kernelFunc:XZ},ZZ=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 JZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],l=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=l*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new ZZ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var QZ={kernelName:ic,backendName:"webgl",kernelFunc:JZ},HN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=fr(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",l="";n&&(r?c=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?c=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:c=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,l="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${c}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${i};
|
|
int q = d2 - d1 * ${i};
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < ${a}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${o}; wC++) {
|
|
int xC = xCCorner + wC * dilations[1];
|
|
|
|
if (xC < 0 || xC >= inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${u}
|
|
${l}
|
|
setOutput(result);
|
|
}
|
|
`}},jN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=fr(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,d=u,p=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)p+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;p+=`
|
|
for (int r = 0; r < ${l}; r++) {
|
|
`;for(let g=0;g<u;g++)p+=`
|
|
xTexelC${g*2} = vec4(0.0);
|
|
xTexelC${g*2}Ready = 0;
|
|
xTexelC${g*2+1} = vec4(0.0);
|
|
xTexelC${g*2+1}Ready = 0;
|
|
xC${g} = vec4(0.0);`;p+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(d+1)/2;g++){let b=g*2;if(p+=`
|
|
xC = xCCorner + ${b*c};
|
|
`,i===1){if(b<u&&(o%2==1?(p+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
|
|
xTexelC${b} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${b}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b}Ready = 1;
|
|
}
|
|
`,c===1&&b>0?p+=`
|
|
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
|
|
`:p+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
|
|
} else {
|
|
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
|
|
}
|
|
`):p+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
|
|
xTexelC${b} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${b}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b}Ready = 1;
|
|
}
|
|
|
|
xC${b} = xTexelC${b};
|
|
`,b+1<u)){let y=o%2==0?w.nearestLargerEven(c):c;c%2==0&&o%2==1||c%2!=0&&o%2!=1?(p+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${y};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
|
|
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${b+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b+1}Ready = 1;
|
|
}
|
|
`,c>1&&(p+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
|
|
xTexelC${b} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${b}Ready = 1;
|
|
}
|
|
`),p+=`
|
|
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
|
|
`):y===1?p+=`
|
|
xC${b+1} = xTexelC${b};
|
|
`:p+=`
|
|
xCOffset = xC + ${y};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
|
|
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${b+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b+1}Ready = 1;
|
|
}
|
|
|
|
xC${b+1} = xTexelC${b+1};
|
|
`}}else b<u&&(o%2==1?(p+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
|
|
xTexelC${b} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${b}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
|
|
xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${b+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b+1}Ready = 1;
|
|
}
|
|
|
|
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
|
|
`,b+1<u&&(p+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
|
|
`)):(p+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
|
|
xTexelC${b} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${b}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${b}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
|
|
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${b+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${b+1}Ready = 1;
|
|
}
|
|
|
|
xC${b} = vec4(
|
|
xTexelC${b}.xy, xTexelC${b+1}.xy);
|
|
`,b+1<u&&(p+=`
|
|
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
|
|
`)));b<u&&(p+=`
|
|
wTexel = getW(r, ${b}, d1, q);
|
|
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
|
|
`,b+1<u&&(p+=`
|
|
wTexel = getW(r, ${b+1}, d1, q);
|
|
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}p+=`
|
|
}
|
|
`,p+=`
|
|
}
|
|
`;let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:h=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${h}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${a};
|
|
int q = d2 - d1 * ${a};
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${p}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};function eJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:l}=r,u=c;u==null&&(u=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let d=_.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!0),p;J().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new jN(d):p=new HN(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(p,[s,a],"float32",h)}var tJ={kernelName:Ya,backendName:"webgl",kernelFunc:eJ},nJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * ${a} + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${r};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},rJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${i}; dm++) {
|
|
int d2 = d1 * ${i} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function sJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,filterShape:u}=r,d=_.computeConv2DInfo(s.shape,u,o,i,c,l,!0),p=new nJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var aJ={kernelName:Yp,backendName:"webgl",kernelFunc:sJ};function oJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,inputShape:u}=r,d=_.computeConv2DInfo(u,a.shape,o,i,c,l,!0),p=new rJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var iJ={kernelName:Zp,backendName:"webgl",kernelFunc:oJ},cJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
|
|
setOutput(val);
|
|
}
|
|
`}};function uJ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=be({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new cJ(a),c=n.runWebGLProgram(i,[o],o.dtype),l=be({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),l}var lJ={kernelName:Jp,backendName:"webgl",kernelFunc:uJ},dJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:l}=e,{top:u,left:d}=r;this.userCode=`
|
|
const ivec2 strides = ivec2(${s}, ${a});
|
|
const ivec2 pads = ivec2(${u}, ${d});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${o}; h++) {
|
|
int hIn = hBeg + h * ${c};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${i}; w++) {
|
|
int wIn = wBeg + w * ${l};
|
|
|
|
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 pJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),u,d=new dJ(l);u=n.runWebGLProgram(d,[s,a],"float32");let p=be({inputs:{x:u},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(u),p}var hJ={kernelName:Sl,backendName:"webgl",kernelFunc:pJ};function fJ(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=_.decodeEinsumEquation(s,a.length);_.checkEinsumDimSizes(o.length,c,a);let{path:l,steps:u}=_.getEinsumComputePath(i,c),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=_n({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let k=0;k<y.length;++k)x.splice(y[k],0,1);w.arraysEqual(v.shape,x)||(v=be({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=Gw({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=Sm({inputs:{x:p},backend:n,attrs:{axis:l[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var mJ={kernelName:th,backendName:"webgl",kernelFunc:fJ},gJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",bJ=`
|
|
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;
|
|
`,yJ=Xe({opSnippet:gJ,packedOpSnippet:bJ}),vJ={kernelName:Ja,backendName:"webgl",kernelFunc:yJ},xJ="return (b >= 1.0) ? a : a * (b + 1.0);",wJ=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,kJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(wJ,r.shape,s.shape):new Fu(xJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},IJ={kernelName:nh,backendName:"webgl",kernelFunc:kJ},SJ=`
|
|
return vec4(equal(a, b));
|
|
`,CJ="return float(a == b);",TJ=ln({opSnippet:CJ,packedOpSnippet:SJ,dtype:"bool",cpuKernelImpl:u7}),NJ={kernelName:uc,backendName:"webgl",kernelFunc:TJ},_J=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${_.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));
|
|
`,EJ=Xe({opSnippet:_J}),AJ={kernelName:cc,backendName:"webgl",kernelFunc:EJ},qN="return exp(x);",KN=Xe({opSnippet:qN,packedOpSnippet:qN,cpuKernelImpl:l7,dtype:"float32"}),DJ={kernelName:Qa,backendName:"webgl",kernelFunc:KN};function Kw(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(w.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+s+1),i.splice(c,0,1),be({inputs:{x:a},backend:r,attrs:{shape:i}})}var FJ={kernelName:lc,backendName:"webgl",kernelFunc:Kw},XN="return exp(x) - 1.0;",$J=Xe({opSnippet:XN,packedOpSnippet:XN,cpuKernelImpl:d7}),RJ={kernelName:dc,backendName:"webgl",kernelFunc:$J},YN=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${s};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${o}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${r});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${r}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${a};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function ZN(e,t,n){let r=n.texData.get(e.dataId),s=w.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=be({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,l=new YN("real",c,t),u=new YN("imag",c,t),d=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ca({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=be({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function PJ(e){let{inputs:t,backend:n}=e,{input:r}=t;return ZN(r,!1,n)}var OJ={kernelName:rh,backendName:"webgl",kernelFunc:PJ},MJ=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
// Input can be obtained from uniform value.
|
|
setOutput(value);
|
|
}
|
|
`}};function Vd(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new MJ(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var LJ={kernelName:Cl,backendName:"webgl",kernelFunc:Vd},BJ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
|
|
int coordX = ${t} - x - 1;
|
|
float outputValue;
|
|
if(coordX >= 0 && coordX < ${t}) {
|
|
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
|
|
} else {
|
|
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},zJ={kernelName:pc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new BJ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},JN="return floor(x);",WJ=Xe({opSnippet:JN,packedOpSnippet:JN,cpuKernelImpl:p7}),VJ={kernelName:eo,backendName:"webgl",kernelFunc:WJ},UJ=`
|
|
float s = sign(a) * sign(b);
|
|
int ia = round(a);
|
|
int ib = round(b);
|
|
if (ib != 0) {
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
return float(idiv(ia, ib, s));
|
|
} else {
|
|
return NAN;
|
|
}
|
|
`,GJ=`
|
|
ivec4 ia = round(a);
|
|
ivec4 ib = round(b);
|
|
bvec4 cond = notEqual(ib, ivec4(0));
|
|
ivec4 result = ivec4(0);
|
|
vec4 s = sign(a) * sign(b);
|
|
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
if (cond[0]) {
|
|
result[0] = idiv(ia[0], ib[0], s[0]);
|
|
}
|
|
if (cond[1]) {
|
|
result[1] = idiv(ia[1], ib[1], s[1]);
|
|
}
|
|
if (cond[2]) {
|
|
result[2] = idiv(ia[2], ib[2], s[2]);
|
|
}
|
|
if (cond[3]) {
|
|
result[3] = idiv(ia[3], ib[3], s[3]);
|
|
}
|
|
return vec4(result);
|
|
`,HJ=ln({opSnippet:UJ,packedOpSnippet:GJ,dtype:"int32"}),jJ={kernelName:to,backendName:"webgl",kernelFunc:HJ},qJ=class{constructor(e){this.variableNames=["A"];let t=Tn(),[n,r]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);
|
|
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`}},KJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Tn(),[n,r]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}.0, ${n}.0);
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},XJ={kernelName:Sh,backendName:"webgl",kernelFunc:YJ},Pu;function YJ(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,l]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],u=[l,c],d=[l,c,a];(i||o)&&(Pu==null&&(Pu=document.createElement("canvas").getContext("2d")),Pu.canvas.width=c,Pu.canvas.height=l,Pu.drawImage(s,0,0,c,l),s=Pu.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=pr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);let h=J().getBool("WEBGL_PACK")?new KJ(d):new qJ(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function ZJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(s.shape,a.shape,c,d,l,p,!1,m),b,y=[];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"))b=zN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(J().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)b=WN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,k=i!=null,C=h==="leakyrelu",N=h?km(h,!1):null,F=new BN(g,x,N,k,C),R=[s,a];if(o&&R.push(o),i&&R.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(O),y.push(O)}b=n.runWebGLProgram(F,R,"float32")}let v=be({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var JJ={kernelName:Mo,backendName:"webgl",kernelFunc:ZJ};function QJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=u;m==null&&(m=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);let g=_.computeConv2DInfo(s.shape,a.shape,c,m,l,d,!0),b=J().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?km(p,b):null,v=[s,a],x=o!=null,k=i!=null,C=p==="leakyrelu";if(x&&v.push(o),k&&v.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));v.push(O),f.push(O)}let N;b?N=new jN(g,x,y,k,C):N=new HN(g,x,y,k,C);let F=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=n.runWebGLProgram(N,v,"float32",F);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),R}var eQ={kernelName:Lo,backendName:"webgl",kernelFunc:QJ},tQ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=ht(t.length),s=ht(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${r} strides = ${r}(${this.strides});
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${a};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function nQ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[c,l,u,d]=_.prepareAndValidate(r,s),p=be({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),h=be({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/u,u]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=h7(b,y,r.dtype,l,o,u,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new tQ(o,d,[l,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var rQ={kernelName:fc,backendName:"webgl",kernelFunc:nQ},sQ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=ht(this.rank),r=aQ(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function aQ(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("int(getIndices(resRC.x, resRC.z))"):r.push(`${n[s]}`);return r.join()}function QN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=w.parseAxisParam(o,s.shape)[0],l=n.readSync(a.dataId),u=s.shape[c];for(let x=0;x<l.length;++x){let k=l[x];w.assert(k<=u-1&&k>=0,()=>`GatherV2: the index value ${k} is not in [0, ${u-1}]`)}let d=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),p=w.sizeFromShape(a.shape),h=[],f=be({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=be({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);let g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let x=n.bufferSync(m),k=n.bufferSync(f),C=f7(k,x,g);return h.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(d.outputShape,C.dtype,C.values)}let b=new sQ(f.shape,g),y=n.runWebGLProgram(b,[f,m],f.dtype);h.push(y);let v=be({inputs:{x:y},backend:n,attrs:{shape:d.outputShape}});return h.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var oQ={kernelName:hc,backendName:"webgl",kernelFunc:QN},iQ="return float(a > b);",cQ=`
|
|
return vec4(greaterThan(a, b));
|
|
`,uQ=ln({opSnippet:iQ,packedOpSnippet:cQ,cpuKernelImpl:m7,dtype:"bool"}),lQ={kernelName:mc,backendName:"webgl",kernelFunc:uQ},dQ="return float(a >= b);",pQ=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,hQ=ln({opSnippet:dQ,packedOpSnippet:pQ,dtype:"bool",cpuKernelImpl:g7}),fQ={kernelName:ro,backendName:"webgl",kernelFunc:hQ};function mQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return ZN(r,!0,n)}var gQ={kernelName:sh,backendName:"webgl",kernelFunc:mQ},bQ="return float(!isnan(x) && !isinf(x));",yQ=Xe({opSnippet:bQ,dtype:"bool"}),vQ={kernelName:gc,backendName:"webgl",kernelFunc:yQ},xQ="return float(isinf(x));",wQ=Xe({opSnippet:xQ,dtype:"bool"}),kQ={kernelName:bc,backendName:"webgl",kernelFunc:wQ},IQ="return float(isnan(x));",SQ=Xe({opSnippet:IQ,dtype:"bool"}),CQ={kernelName:yc,backendName:"webgl",kernelFunc:SQ},TQ="return float(a < b);",NQ=`
|
|
return vec4(lessThan(a, b));
|
|
`,_Q=ln({opSnippet:TQ,packedOpSnippet:NQ,cpuKernelImpl:b7,dtype:"bool"}),EQ={kernelName:vc,backendName:"webgl",kernelFunc:_Q},AQ="return float(a <= b);",DQ=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,FQ=ln({opSnippet:AQ,packedOpSnippet:DQ,cpuKernelImpl:y7,dtype:"bool"}),$Q={kernelName:xc,backendName:"webgl",kernelFunc:FQ};function RQ(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=v7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var PQ={kernelName:oh,backendName:"webgl",kernelFunc:RQ},OQ=`if (x < 0.0) return NAN;
|
|
return log(x);`,MQ=`
|
|
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;
|
|
`,LQ=Xe({opSnippet:OQ,packedOpSnippet:MQ,cpuKernelImpl:x7}),BQ={kernelName:oo,backendName:"webgl",kernelFunc:LQ},zQ="return log(1.0 + x);",WQ=Xe({opSnippet:zQ}),VQ={kernelName:wc,backendName:"webgl",kernelFunc:WQ},UQ="return float(a >= 1.0 && b >= 1.0);",GQ=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,HQ=ln({opSnippet:UQ,packedOpSnippet:GQ,dtype:"bool"}),jQ={kernelName:kc,backendName:"webgl",kernelFunc:HQ},qQ="return float(!(x >= 1.0));",KQ=Xe({opSnippet:qQ}),XQ={kernelName:Tl,backendName:"webgl",kernelFunc:KQ},YQ="return float(a >= 1.0 || b >= 1.0);",ZQ=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,JQ=ln({opSnippet:YQ,packedOpSnippet:ZQ,dtype:"bool"}),QQ={kernelName:Nl,backendName:"webgl",kernelFunc:JQ},eee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
int d = coords[3];
|
|
float x = getX(b, r, c, d);
|
|
float sum = 0.0;
|
|
for (int j = -${a}; j <= ${a}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${o}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${i};
|
|
setOutput(val);
|
|
}
|
|
`}},tee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords.x;
|
|
int r = coords.y;
|
|
int c = coords.z;
|
|
int d = coords.w;
|
|
|
|
bool hasNextCol = d < ${this.outputShape[3]};
|
|
bool hasNextRow = c < ${this.outputShape[2]};
|
|
|
|
vec4 sum = vec4(0.);
|
|
vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
|
|
|
vec4 xAtOutputCoords = vec4(
|
|
getChannel(xFragAtOutputCoords, vec2(c, d)),
|
|
hasNextCol ?
|
|
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
|
|
hasNextRow ?
|
|
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
|
|
);
|
|
|
|
int firstChannel = d - ${a};
|
|
vec2 cache = vec2(0.);
|
|
if(firstChannel >= 0){
|
|
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
|
|
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
|
|
if(hasNextRow){
|
|
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
|
|
}
|
|
}
|
|
|
|
ivec2 depth = ivec2(d, d + 1);
|
|
for (int j = - ${a}; j <= ${a}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * ${i};
|
|
setOutput(result);
|
|
}
|
|
`}},nee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,l=J().getBool("WEBGL_PACK_NORMALIZATION")?new tee(s.shape,a,o,i,c):new eee(s.shape,a,o,i,c);return n.runWebGLProgram(l,[s],s.dtype)},ree={kernelName:_l,backendName:"webgl",kernelFunc:nee},see=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float result = 0.0;
|
|
for (int d = 0; d < ${this.depth}; ++d) {
|
|
int depthBegin = int(max(0.0, float(d - ${t})));
|
|
int depthEnd = int(min(float(${this.depth}),
|
|
float(d + ${t} + 1)));
|
|
|
|
const int MIN_DEPTH_BEGIN = 0;
|
|
const int MAX_DEPTH_END = ${this.depth};
|
|
|
|
float norm = 0.0;
|
|
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd) {
|
|
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
norm = float(${r}) * norm + float(${n});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${r})
|
|
* float(${s})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${s});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},aee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:l,beta:u}=r,d=new see(s.shape,i,c,l,u);return n.runWebGLProgram(d,[s,a,o],s.dtype)},oee={kernelName:ih,backendName:"webgl",kernelFunc:aee};function iee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=yi(i,e.dtype,"max",r),l=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}function e_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=n.shouldExecuteOnCPU([s]),h=s;if(d){if(p){let v=n.texData.get(h.dataId).values,x=new Array(i);for(let N=0;N<x.length;N++)x[N]=s.shape[u[N]];let k=Uw(v,s.shape,s.dtype,u,x);h=n.makeTensorInfo(x,s.dtype);let C=n.texData.get(h.dataId);C.values=k}else h=Im(s,u,n);l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("max",l,i);let[f,m]=_.computeOutAndReduceShapes(h.shape,l),g=f;o&&(g=_.expandShapeToKeepDim(f,c));let b;if(p){let v=n.texData.get(h.dataId).values,x=w7(v,w.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let k=n.texData.get(b.dataId);k.values=x}else b=iee(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var cee={kernelName:io,backendName:"webgl",kernelFunc:e_},uee=yN+`
|
|
return max(a, b);
|
|
`,lee=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+wm+`
|
|
return result;
|
|
`,dee=ln({opSnippet:uee,packedOpSnippet:lee,cpuKernelImpl:k7}),pee={kernelName:co,backendName:"webgl",kernelFunc:dee};function hee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Tu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return rr({inputs:{x:s},backend:n});let d=new zd(u,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var fee={kernelName:uo,backendName:"webgl",kernelFunc:hee};function mee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,l,c),p=new Hw(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var gee={kernelName:El,backendName:"webgl",kernelFunc:mee},bee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${s};
|
|
wR += ${r}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${a}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * ${a} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},yee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*c*l-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${u}, ${d}, ${p});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${i};
|
|
wD += ${s}) {
|
|
float dyD = float(dyDCorner + wD) / ${t}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC += ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${h} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${c} * ${l} +
|
|
wR * ${l} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function vee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new Hw(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new yee(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var xee={kernelName:uh,backendName:"webgl",kernelFunc:vee};function wee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Tu([a,o],"maxPoolGrad");let{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,l,1,u,d),h=!0,f=new zd(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new bee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var kee={kernelName:ch,backendName:"webgl",kernelFunc:wee};function Iee(e,t,n,r){let s=new zd(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new zd(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var See={kernelName:lh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let l=[1,1];w.assert(_.eitherStridesOrDilationsAreOne(a,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`);let u=_.computePool2DInfo(r.shape,s,a,l,o),[d,p]=Iee(r,i,u,c);return[d,p]}};function Cee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=yi(i,"float32","mean",r),l=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}var Tee={kernelName:lo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=w.parseAxisParam(a,r.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,k=new Array(i);for(let F=0;F<k.length;F++)k[F]=r.shape[u[F]];let C=Uw(x,r.shape,r.dtype,u,k);f=o.makeTensorInfo(k,r.dtype);let N=o.texData.get(f.dataId);N.values=C}else f=Im(r,u,o);h.push(f),l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("sum",l,i);let[m,g]=_.computeOutAndReduceShapes(f.shape,l),b=m;s&&(b=_.expandShapeToKeepDim(m,c));let y=Cee(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function Nee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"min",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var _ee={kernelName:po,backendName:"webgl",kernelFunc:Nee},Eee=yN+`
|
|
return min(a, b);
|
|
`,Aee=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+wm+`
|
|
return result;
|
|
`,Dee=ln({opSnippet:Eee,packedOpSnippet:Aee,cpuKernelImpl:I7}),Fee={kernelName:ho,backendName:"webgl",kernelFunc:Dee},$ee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let r=e.length,s=ht(r),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${c};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${c};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
for (int i = 0; i < ${r}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${c};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${c};
|
|
}
|
|
}
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}},Ree=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=ht(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Nn("rc",r),c=Nn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(r===1){let h=`
|
|
${s} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${d};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${d};
|
|
}
|
|
source -= start;
|
|
`;p=`
|
|
${s} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${c.join()}), ${u});
|
|
${i[r-1]} += 1;
|
|
if(${l}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${c.join()}), ${u});
|
|
}
|
|
`}else{let h=`
|
|
${s} source = rc;
|
|
${s} lt = ${s}(lessThan(source, start));
|
|
${s} gte = ${s}(greaterThanEqual(source, end));
|
|
${s} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${d}) +
|
|
gte * ((end - 1) * 2 - source + ${d});
|
|
source -= start;
|
|
`;p=`
|
|
${s} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${c.join()}), ${u});
|
|
${i[r-1]} += 1;
|
|
if(${l}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${c.join()}), ${u});
|
|
}
|
|
rc = outputLoc;
|
|
${i[r-2]} += 1;
|
|
if(${i[r-2]} < ${this.outputShape[r-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${c.join()}), ${u});
|
|
${i[r-1]} += 1;
|
|
if(${l}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${c.join()}), ${u});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${p}
|
|
setOutput(result);
|
|
}
|
|
`}},Pee=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ree(r.shape,s,a):new $ee(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},Oee={kernelName:fo,backendName:"webgl",kernelFunc:Pee},Mee=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,Lee=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+wm+`
|
|
return result;
|
|
`,Bee=ln({opSnippet:Mee,packedOpSnippet:Lee}),zee={kernelName:Ic,backendName:"webgl",kernelFunc:Bee},Wee=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
|
|
float r = random(seed);
|
|
float cdf = 0.0;
|
|
|
|
for (int i = 0; i < ${t-1}; i++) {
|
|
cdf += getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutput(float(i));
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutput(float(${t-1}));
|
|
}
|
|
`}},Vee=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,Uee=`
|
|
// 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;
|
|
`,t_=ln({opSnippet:Vee,packedOpSnippet:Uee,checkOutOfBounds:!0}),Gee={kernelName:Za,backendName:"webgl",kernelFunc:t_},n_="return a - b;",r_=ln({opSnippet:n_,packedOpSnippet:n_,supportsComplex:!0,cpuKernelImpl:B7}),Hee={kernelName:Fo,backendName:"webgl",kernelFunc:r_};function s_(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=e_({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=_.expandShapeToKeepDim(i.shape,o),l=be({inputs:{x:i},backend:n,attrs:{shape:c}}),u=r_({inputs:{a:s,b:l},backend:n}),d=KN({inputs:{x:u},backend:n}),p=Sm({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=be({inputs:{x:p},backend:n,attrs:{shape:c}}),f=t_({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var jee={kernelName:Ao,backendName:"webgl",kernelFunc:s_};function qee(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:s_({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new Wee(l,u,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var Kee={kernelName:dh,backendName:"webgl",kernelFunc:qee},a_="return -x;";function Xee(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=C7(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Du(r.shape,a_):s=new Sa(r.shape,a_),n.runWebGLProgram(s,[r],r.dtype)}var Yee={kernelName:Sc,backendName:"webgl",kernelFunc:Xee},Zee=is.nonMaxSuppressionV3Impl;function Jee(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r,l=n.readSync(s.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Zee(l,u,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Qee={kernelName:Tc,backendName:"webgl",kernelFunc:Jee},ete=is.nonMaxSuppressionV4Impl;function tte(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=ete(u,d,o,i,c,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var nte={kernelName:Nc,backendName:"webgl",kernelFunc:tte},rte=is.nonMaxSuppressionV5Impl;function ste(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),p=o,h=i,f=c,m=l,{selectedIndices:g,selectedScores:b}=rte(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var ate={kernelName:_c,backendName:"webgl",kernelFunc:ste},ote=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${r}), float(${n}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},ite=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=w.sizeFromShape(s.shape),l=new ote(c,a,o,i),u=be({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(l,[u],s.dtype);n.disposeIntermediateTensorInfo(u);let p=[...s.shape,a],h=be({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},cte={kernelName:go,backendName:"webgl",kernelFunc:ite};function Em(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Wd({inputs:{input:r},backend:n}),a=Em({inputs:{x:s},backend:n}),o=_m({inputs:{input:r},backend:n}),i=Em({inputs:{x:o},backend:n}),c=Ca({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var ute={kernelName:qc,backendName:"webgl",kernelFunc:Em};function o_(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=Wd({inputs:{input:r},backend:n}),a=o_({inputs:{x:s},backend:n}),o=_m({inputs:{input:r},backend:n}),i=Em({inputs:{x:o},backend:n}),c=Ca({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var lte={kernelName:Ec,backendName:"webgl",kernelFunc:o_};function dte(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Kw({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=Kw({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=LN({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),l}var pte={kernelName:Ac,backendName:"webgl",kernelFunc:dte},hte=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,l)=>c[0]+e[l]+c[1]);let r=e.length,s=ht(r),a=t.map(c=>c[0]).join(","),o=t.map((c,l)=>c[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
}
|
|
`}},fte=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=ht(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Nn("rc",r),c=Nn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
|
|
if(${l}) {
|
|
`,r===1?"":`}
|
|
rc = outputLoc;
|
|
${i[r-2]} += 1;
|
|
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
|
|
if(${l}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+=`
|
|
${d[f]}
|
|
if (${p}) {
|
|
result[${f}] = float(value);
|
|
} else {
|
|
${s} source = rc - start;
|
|
result[${f}] = getChannel(getX(${c.join()}), ${u});
|
|
}
|
|
`;h+=r===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},i_=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let l=a.map((u,d)=>u[0]+s.shape[d]+u[1]);return Vd({backend:n,attrs:{shape:l,value:o,dtype:s.dtype}})}let i=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fte(s.shape,a,o):new hte(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},mte={kernelName:bo,backendName:"webgl",kernelFunc:i_},gte=`
|
|
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);
|
|
`,bte=`
|
|
// 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));
|
|
`+wm+`
|
|
return result;
|
|
`,yte=ln({opSnippet:gte,packedOpSnippet:bte}),vte={kernelName:yo,backendName:"webgl",kernelFunc:yte};function xte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],l=w.parseAxisParam(a,s.shape),u=l,d=_.getAxesPermutation(u,i),p=s;d!=null&&(p=_n({inputs:{x:s},backend:n,attrs:{perm:d}}),u=_.getInnerMostAxes(u.length,i),c.push(p)),_.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=N7(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=_.computeOutAndReduceShapes(p.shape,u),g=w.sizeFromShape(m),b=be({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),y=Dh(s.dtype),v=yi(b,y,"prod",n);h=be({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=_.expandShapeToKeepDim(h.shape,l);h=be({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var wte={kernelName:Dc,backendName:"webgl",kernelFunc:xte},c_=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=_7(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},kte={kernelName:Al,backendName:"webgl",kernelFunc:c_},Ite="return 1.0 / x;",Ste=Xe({opSnippet:Ite}),Cte={kernelName:Fc,backendName:"webgl",kernelFunc:Ste},Tte=jr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Nte=`
|
|
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;
|
|
`,_te=Xe({opSnippet:Tte,packedOpSnippet:Nte}),Ete={kernelName:xo,backendName:"webgl",kernelFunc:_te},Ate=jr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Dte=`
|
|
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;
|
|
`,Fte=Xe({opSnippet:Ate,packedOpSnippet:Dte}),$te={kernelName:ko,backendName:"webgl",kernelFunc:Fte},Rte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${l[0]/u[0]},
|
|
${l[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the 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);
|
|
}
|
|
`}},Pte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${l[0]/u[0]},
|
|
${l[1]/u[1]},
|
|
${l[1]/u[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the 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 < ${c-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 Ote(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=J().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Pte(s.shape,c,l,a,o):new Rte(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],"float32")}var Mte={kernelName:wo,backendName:"webgl",kernelFunc:Ote},Lte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${l});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));
|
|
float dxCLerp = dxC - float(leftDxCIndex);
|
|
float inverseDxCLerp = 1.0 - dxCLerp;
|
|
|
|
if (r == topDxRIndex && c == leftDxCIndex) {
|
|
// topLeft
|
|
accumulator +=
|
|
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == topDxRIndex && c == rightDxCIndex) {
|
|
// topRight
|
|
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == leftDxCIndex) {
|
|
// bottomLeft
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == rightDxCIndex) {
|
|
// bottomRight
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function Bte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Lte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var zte={kernelName:fh,backendName:"webgl",kernelFunc:Bte},Wte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${l[0]/u[0]},
|
|
${l[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},Vte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${l[0]/u[0]},
|
|
${l[1]/u[1]},
|
|
${l[1]/u[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${c-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function Ute(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=J().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Vte(s.shape,c,l,a,o):new Wte(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],s.dtype)}var Gte={kernelName:Dl,backendName:"webgl",kernelFunc:Ute},Hte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${l});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${i[0]}) *
|
|
(float(dyR) / float(${c[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${i[1]}) *
|
|
(float(dyC) / float(${c[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${r}) - 1),
|
|
${n} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${s}) - 1),
|
|
${n} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function jte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Hte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var qte={kernelName:hh,backendName:"webgl",kernelFunc:jte},Kte=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,s=e.map((o,i)=>r(i)).join(","),a=ht(n);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}},Xte=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let r=Nn("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=ht(n);n===1?this.userCode=`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(${e[0]} - rc - 1),
|
|
${e[0]} - rc - 1);
|
|
if(${s}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${i(r.slice())};
|
|
if(${s}){
|
|
result.g = ${c(r.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${l(r.slice())};
|
|
if(${s}) {
|
|
result.a = ${u(r.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function l(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((b,y)=>p(y,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Yte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return rr({inputs:{x:s},backend:n});let c=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xte(s.shape,i):new Kte(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var Zte={kernelName:Io,backendName:"webgl",kernelFunc:Yte},Jte=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
|
|
vec3 fill = vec3(${t.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${s}
|
|
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},Qte={kernelName:Kc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new Jte(r.shape,a),[l,u]=_.getImageCenter(o,r.shape[1],r.shape[2]),d=[[l,u,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},ene=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,tne=Xe({opSnippet:ene}),nne={kernelName:So,backendName:"webgl",kernelFunc:tne},rne="return inversesqrt(x);",sne=Xe({opSnippet:rne,cpuKernelImpl:E7}),ane={kernelName:Co,backendName:"webgl",kernelFunc:sne},u_=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=ht(s.length),c=ht(a.length),l="";n===1?l="i":n===2&&(l="i, j");let u=`getIndices(${l})`,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
|
|
${i} strides = ${i}(${s});
|
|
|
|
void main() {
|
|
${c} 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 += ${p};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function one(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=_.calculateShapes(a,s,o),p=[d/l,l];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=be({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=be({inputs:{x:a},backend:n,attrs:{shape:[c,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new u_(c,i,h.shape.length,f.shape.length,u,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=be({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var ine={kernelName:Rc,backendName:"webgl",kernelFunc:one},cne=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let l=0;l<t.length;l++)c.push(`${o[l]}`),l<e&&i.push(`${o[l]}`);r=i.join(),s=c.join()}let a=ht(n);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${r});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function une(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new cne(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],wr(s.dtype,a.dtype))}var lne={kernelName:Pc,backendName:"webgl",kernelFunc:une},dne=`
|
|
// 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);
|
|
`,pne=Xe({opSnippet:dne}),hne={kernelName:Oc,backendName:"webgl",kernelFunc:pne},l_="return 1.0 / (1.0 + exp(-1.0 * x));",fne=Xe({opSnippet:l_,packedOpSnippet:l_,cpuKernelImpl:A7}),mne={kernelName:No,backendName:"webgl",kernelFunc:fne},gne=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,bne=Xe({opSnippet:gne}),yne={kernelName:Bc,backendName:"webgl",kernelFunc:bne},vne=IN+`
|
|
return sin(x);
|
|
`,xne=Xe({opSnippet:vne}),wne={kernelName:To,backendName:"webgl",kernelFunc:xne},kne=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Ine=Xe({opSnippet:kne}),Sne={kernelName:Lc,backendName:"webgl",kernelFunc:Ine},Cne=`
|
|
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;
|
|
`,Tne=Xe({opSnippet:Cne}),Nne={kernelName:zc,backendName:"webgl",kernelFunc:Tne},_ne=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let l=[],u=i_({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=_.getReshaped(u.shape,a,i,!1),p=_.getPermuted(d.length,a.length,!1),h=_.getReshapedPermuted(u.shape,a,i,!1),f=be({inputs:{x:u},backend:n,attrs:{shape:d}}),m=_n({inputs:{x:f},backend:n,attrs:{perm:p}}),g=be({inputs:{x:m},backend:n,attrs:{shape:h}});return l.push(u),l.push(f),l.push(m),l.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},Ene={kernelName:Wc,backendName:"webgl",kernelFunc:_ne};function Ane(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.readSync(r.dataId),c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=F7(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var Dne={kernelName:mh,backendName:"webgl",kernelFunc:Ane};function Fne(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[l,u,d]=$7(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var $ne={kernelName:gh,backendName:"webgl",kernelFunc:Fne};function Rne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=lN(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var Pne={kernelName:bh,backendName:"webgl",kernelFunc:Rne};function One(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=lN(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var Mne={kernelName:yh,backendName:"webgl",kernelFunc:One};function Lne(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,strides:u,outputSize:d}=_.calculateShapes(a,s,i),p=!1,h=new u_(l,c,s.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=be({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var Bne={kernelName:vh,backendName:"webgl",kernelFunc:Lne};function zne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=s.shape.length,u=new Array(l).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=$u({inputs:{x:s},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var Wne={kernelName:Vc,backendName:"webgl",kernelFunc:zne},d_="return sqrt(x);",Vne=Xe({opSnippet:d_,packedOpSnippet:d_,cpuKernelImpl:R7}),Une={kernelName:_o,backendName:"webgl",kernelFunc:Vne},Gne="return x * x;",Hne=Xe({opSnippet:Gne}),jne={kernelName:Fl,backendName:"webgl",kernelFunc:Hne},p_="return (a - b) * (a - b);",qne=ln({opSnippet:p_,packedOpSnippet:p_}),Kne={kernelName:Do,backendName:"webgl",kernelFunc:qne};function Xne({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=jr+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,a=new Sa(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var Yne={kernelName:na,backendName:"webgl",kernelFunc:Xne},Zne=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=ht(n.length),a=ht(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,l)=>(i++,n.length===1?`coords * strides[${l}] + begin[${l}]`:`coords[${i-1}] * strides[${l}] + begin[${l}]`)).join(",")}this.userCode=`
|
|
${s} begin = ${s}(${e});
|
|
${s} strides = ${s}(${t});
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}};function Jne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=kn.sliceInfo(s.shape,a,o,i,c,l,u,d,p),v=be({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=$u({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=be({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else if(n.shouldExecuteOnCPU([v])){let F=n.texData.get(v.dataId).values,R=ze(v.shape,v.dtype,F),O=P7(y,R,m,f);x=n.makeTensorInfo(y,v.dtype,O.values)}else{let N=new Zne(f,m,y);x=n.runWebGLProgram(N,[v],v.dtype)}let k=be({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var Qne={kernelName:Uc,backendName:"webgl",kernelFunc:Jne};function ere(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=O7(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var tre={kernelName:xh,backendName:"webgl",kernelFunc:ere};function nre(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[l,u,d]=M7(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var rre={kernelName:wh,backendName:"webgl",kernelFunc:nre};function sre(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=L7(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var are={kernelName:kh,backendName:"webgl",kernelFunc:sre},ore="return tan(x);",ire=Xe({opSnippet:ore}),cre={kernelName:$o,backendName:"webgl",kernelFunc:ire},ure=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,lre=Xe({opSnippet:ure}),dre={kernelName:Ro,backendName:"webgl",kernelFunc:lre},pre=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=ht(this.rank),s=hre(e);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function hre(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<e.length;s++)r.push(`imod(${n[s]}, ${e[s]})`);return r.join()}function h_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),l=s.dtype==="string"?c.map(p=>w.decodeString(p)):c,u=ze(s.shape,s.dtype,l),d=z7(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new pre(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var fre={kernelName:ta,backendName:"webgl",kernelFunc:h_},mre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// We compare elements pair-wise within a group of size 2 * inc.
|
|
// The comparing rule for each group alternates between ascending
|
|
// and descending. Within each group, we compare each pair at
|
|
// positions i and i+inc. To decide whether an element at position i
|
|
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
|
|
// inc, it is in the first half of the group, we denote it as x0,
|
|
// otherwise we denote it as x1.
|
|
// For example, as shown in the Bitonic top K paper referenced above,
|
|
// Figure5(a) shows that element[1] is in the
|
|
// second half of the group when group size is 2, but it is in the
|
|
// first half of the group when group size is 4.
|
|
|
|
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
|
|
int i = isFirstInPair ? elemIdx : elemIdx - inc;
|
|
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
|
|
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
|
|
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
|
|
|
|
// Denotes which direction indices are in (ascending or descending).
|
|
bool reverse = imod(elemIdx, 2 * dir) >= dir;
|
|
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
|
|
if (reverse == isGreater) { // Elements in opposite order of direction
|
|
int iTemp = i0;
|
|
i0 = i1;
|
|
i1 = iTemp;
|
|
}
|
|
if (isFirstInPair) {
|
|
setOutput(float(i0));
|
|
} else {
|
|
setOutput(float(i1));
|
|
}
|
|
}
|
|
`}},gre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// The output size is half of the previous size.
|
|
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
|
|
// we only need to output the indices at positions |, the indices at
|
|
// positions _ can be thrown away, see Figure5(b) After Phase 2
|
|
// (Merge phase) in the Bitonic Top K paper referenced above.
|
|
// For example, the paper shows we only need to output the orange bars.
|
|
// The output sequence should look like this | | | | | | | |.
|
|
// Because the sequence is halved, to map the output index back
|
|
// to the previous sequence to find the corresponding value,
|
|
// we need to double the index. When we double the index,
|
|
// we basically interpolate a position, so 2i looks like
|
|
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
|
|
// of each 2k positions by - elemIdx % k. E.g. for output at
|
|
// index 4,5,6,7, we want to get the corresponding element at
|
|
// original index 8,9,10,11, for output at index 8,9,10,11,
|
|
// we want to get the corresponding element at original index
|
|
// 16,17,18,19, so on and so forth.
|
|
|
|
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
|
|
|
|
float x0 = getX(batch, i0);
|
|
float x1 = i1 < n ? getX(batch, i1) : x0;
|
|
|
|
setOutput(x0 >= x1 ? float(i0) : float(i1));
|
|
}
|
|
`}};function vi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function f_(e){let t=1;for(;t<e;)t*=2;return t}function bre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=J().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=J().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=s.shape,u=l[l.length-1];if(n.shouldExecuteOnCPU([s])||u<i||a>c){let O=n.readSync(s.dataId),[D,P]=W7(O,l,s.dtype,a,o);return[n.makeTensorInfo(D.shape,D.dtype,D.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(u===1)return[s,Vd({attrs:{shape:l,dtype:"int32",value:0},backend:n})];let d=n.texData.get(s.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(s):s,m=w.sizeFromShape(l)/u,g=be({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&vi(n,h);let b=f_(a),y=f_(u),v=null,x=()=>v===null?[g,g]:[g,v],k=(O,D,P)=>{let T=x(),L=new mre(P),j=[[u],[v===null?1:0],[Number.NEGATIVE_INFINITY],[O],[D]],q=v;v=n.runWebGLProgram(L,T,"int32",j),vi(n,q)};for(let O=1;O<b;O*=2){let D=O*2;for(let P=O;P>=1;P/=2)k(D,P,[m,y])}for(let O=y;O>b;O/=2){let D=x(),P=new gre([m,O/2]),L=[[u],[v===null?1:0],[b]],G=v;v=n.runWebGLProgram(P,D,"int32",L),vi(n,G);let j=b/2,q=j*2;for(let K=j;K>=1;K/=2)k(q,K,v.shape)}let C=v;v=$u({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),vi(n,C);let N=QN({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});vi(n,g);let F=l.slice(0,-1);F.push(a),C=v,v=be({inputs:{x:v},attrs:{shape:F},backend:n}),vi(n,C);let R=N;return N=be({inputs:{x:N},attrs:{shape:F},backend:n}),vi(n,R),[N,v]}var yre={kernelName:Gc,backendName:"webgl",kernelFunc:bre},vre=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${i} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${s});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${s});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${o} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function xre(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:l}=r,[u,d,p,h]=s.shape,[f,m]=l!=null?l:[d,p],g=[u,f,m,h],b=new vre(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var wre={kernelName:Hc,backendName:"webgl",kernelFunc:xre};function kre(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Tu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:l}=V7(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}var Ire={kernelName:Ih,backendName:"webgl",kernelFunc:kre};function Sre(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],l=new Array(i-1),u=0;for(let m=0;m<i;m++)m!==a&&(l[u++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(c);for(let m=0;m<f.length;m++){p[a]=m;let g=$u({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=be({inputs:{x:g},backend:n,attrs:{shape:l}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Cre={kernelName:jc,backendName:"webgl",kernelFunc:Sre},Tre=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",l=Math.floor(n/4)*4,u=n%4,d=`
|
|
sumValue += dot(values, segFilter);
|
|
`,p="";s%n>0&&(p=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`);let h="";s%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${p}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${a})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${a})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${l}; 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
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${l};
|
|
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
|
|
);
|
|
|
|
${d}
|
|
} 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
|
|
);
|
|
|
|
${d}
|
|
} 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
|
|
);
|
|
|
|
${d}
|
|
}
|
|
setOutput(${c});
|
|
}
|
|
`}};function Nre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],l=0,u=_.getAxesPermutation([l],i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),c.push(d),l=_.getInnerMostAxes(1,i)[0]);let p=_.segment_util.computeOutShape(d.shape,l,o),h=w.sizeFromShape([d.shape[l]]),f=be({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Dh(s.dtype),g=(x,k,C,N,F)=>{let R=x.shape[0],O=x.shape[1],D=_.segment_util.segOpComputeOptimalWindowSize(O,F),P={windowSize:D,inSize:O,batchSize:R,numSegments:F},T=new Tre(P,k),L=n.compileAndRun(T,[x,C],N);if(c.push(L),L.shape[1]===F)return L;let G=c_({backend:n,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),j=h_({inputs:{x:G},backend:n,attrs:{reps:[O/D]}});return c.push(G),c.push(j),g(L,k,j,N,F)},b=g(f,"unsortedSegmentSum",a,m,o),y=be({inputs:{x:b},backend:n,attrs:{shape:p}}),v=y;if(u!=null){c.push(y);let x=_.getUndoAxesPermutation(u);v=_n({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var _re={kernelName:$l,backendName:"webgl",kernelFunc:Nre},Ere=[ree,oee,W9,U9,j9,X9,Z9,eY,nY,sY,cY,lY,hY,gY,IY,vY,TY,AY,_Y,RY,OY,LY,VY,XY,ZY,QY,aZ,iZ,dZ,fZ,k9,vZ,EZ,DZ,IZ,PZ,MZ,$Z,zZ,UZ,jZ,KZ,YZ,QZ,aJ,iJ,tJ,lJ,hJ,mJ,vJ,IJ,NJ,AJ,DJ,FJ,RJ,OJ,LJ,zJ,VJ,jJ,XJ,JJ,eQ,rQ,oQ,lQ,fQ,w9,gQ,bZ,vQ,kQ,CQ,S9,EQ,$Q,PQ,VQ,BQ,jQ,XQ,QQ,cee,gee,fee,xee,kee,See,pee,Tee,_ee,Fee,Oee,zee,Kee,E9,Yee,Qee,nte,ate,tZ,cte,lte,pte,mte,vte,T9,wte,kte,nZ,Gee,Cte,$te,Ete,D9,Mte,zte,Gte,qte,Zte,Qte,nne,ane,ine,lne,hne,mne,yne,wne,Sne,qY,jee,Nne,Ene,Dne,$ne,Pne,Mne,Bne,Wne,Une,jne,Kne,Yne,Qne,tre,rre,are,Hee,L9,cre,dre,fre,yre,wre,B9,Ire,Cre,_re,ute];for(let e of Ere)Pl(e);var Wt;(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"})(Wt||(Wt={}));var Ud;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Ud||(Ud={}));var m_;function Are(e){m_=e.wasm.cwrap(Oo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Dre(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r,p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let F=n.dataIdMap.get(o.dataId);if(F.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${F.shape.length}.`);f=F.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=Ud[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let b=c?s.shape[2]:s.shape[1],y=l?a.shape[1]:a.shape[2],v=s.shape[0],x=n.makeOutput([v,b,y],s.dtype),k=n.dataIdMap.get(x.dataId).id,C=new Uint8Array(new Int32Array(s.shape).buffer),N=new Uint8Array(new Int32Array(a.shape).buffer);return m_(p,C,s.shape.length,h,N,a.shape.length,c,l,g,f,m,d||0,k),x}var Fre={kernelName:Oo,backendName:"wasm",setupFunc:Are,kernelFunc:Dre};function dn(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,c=o.dataIdMap.get(i.dataId).id,l=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(l.dataId).id;return w.sizeFromShape(l.shape)===0||n(c,Wt[i.dtype],u),l}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var $re=dn(Ki);function En(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:l,b:u}=c,d=i.dataIdMap.get(l.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:l.dtype,f=_.assertAndGetBroadcastShape(l.shape,u.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(l.shape).buffer),b=new Uint8Array(new Int32Array(u.shape).buffer),y=i.dataIdMap.get(m.dataId).id,v=()=>r(d,g,l.shape.length,p,b,u.shape.length,Wt[l.dtype],y);if(t&&l.dtype==="float32")return v(),m;let x=_.getBroadcastDims(l.shape,f),k=_.getBroadcastDims(u.shape,f),C=x.every((F,R)=>F===R),N=k.every((F,R)=>F===R);if(C&&N)return v(),m;throw new Error(`Broadcasting along outer dims is not yet supported for ${l.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:a}}var Rre=!0,Pre=En(Qs,Rre),g_;function Ore(e){g_=e.wasm.cwrap(Ba,null,["array","number","number","number"])}function Mre(e){let{inputs:t,backend:n}=e,r=n.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(r.shape)===0)return r;let s=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(s).buffer),o=n.dataIdMap.get(r.dataId).id;return g_(a,s.length,Wt[r.dtype],o),r}var Lre={kernelName:Ba,backendName:"wasm",setupFunc:Ore,kernelFunc:Mre};function Am(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(s),r}var Bre={kernelName:so,backendName:"wasm",kernelFunc:Am},b_;function zre(e){b_=e.wasm.cwrap(Po,null,["number","array","number","number","number","array","number"])}function Ou(e){let{inputs:t,backend:n,attrs:r}=e,[s,a]=Vre(t.x.shape,r.perm),o=!0;for(let f=0;f<a.length;f++)a[f]!==f&&(o=!1);let i=Wre(t.x.shape,r.perm),c={dataId:t.x.dataId,shape:s,dtype:t.x.dtype};if(o){let f=Am({inputs:t,backend:n});return f.shape=i,f}let l=n.makeOutput(i,c.dtype),u=n.dataIdMap.get(c.dataId).id,d=n.dataIdMap.get(l.dataId).id,p=new Uint8Array(new Int32Array(a).buffer),h=new Uint8Array(new Int32Array(c.shape).buffer);return b_(u,h,c.shape.length,Wt[c.dtype],d,p,a.length),l}function Wre(e,t){let n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];return n}function Vre(e,t){let n=[],r=[];for(let s=0;s<e.length;++s)e[s]!==1&&n.push(e[s]),e[t[s]]!==1&&r.push(t[s]);for(let s=0;s<r.length;++s){let a=-1;for(let o=0;o<r.length;++o)r[o]>=s&&(a===-1||r[a]>r[o])&&(a=o);r[a]=s}return[n,r]}var Ure={kernelName:Po,backendName:"wasm",kernelFunc:Ou,setupFunc:zre};function Ta(e,t,n){let r=e.shape,s=e.shape.length,a=w.parseAxisParam(t,r),o=a,i=_.getAxesPermutation(o,s),c=null,l=!1;if(i!=null){let u=new Array(s);for(let h=0;h<u.length;h++)u[h]=r[i[h]];o=_.getInnerMostAxes(o.length,s),c=Ou({inputs:{x:e},attrs:{perm:i},backend:n});let d=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(c.dataId).id!==d&&(l=!0)}return{transposed:c,originalAxes:a,axes:o,inputWasTransposed:l}}var y_;function Gre(e){y_=e.wasm.cwrap(Zi,null,["number, number, number"])}function Hre(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,c=t.dataIdMap.get(o.dataId).id,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t);if(h){let v=t.dataIdMap.get(u.dataId).id;l=u,c=v}let f=l.shape.length;_.assertAxesAreInnerMostDims("all",d,f);let[m,g]=_.computeOutAndReduceShapes(l.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(m,o.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;y_(c,b,v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var jre={kernelName:Zi,backendName:"wasm",setupFunc:Gre,kernelFunc:Hre},v_;function qre(e){v_=e.wasm.cwrap(Ji,null,["number, number, number"])}function Kre(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,c=t.dataIdMap.get(o.dataId).id,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t);if(h){let v=t.dataIdMap.get(u.dataId).id;l=u,c=v}let f=l.shape.length;_.assertAxesAreInnerMostDims("any",d,f);let[m,g]=_.computeOutAndReduceShapes(l.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(m,o.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;v_(c,b,v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var Xre={kernelName:Ji,backendName:"wasm",setupFunc:qre,kernelFunc:Kre},x_;function Yre(e){x_=e.wasm.cwrap(za,null,["number","number","number","number","number"])}function Zre(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=o,c=a,{transposed:l,axes:u,inputWasTransposed:d}=Ta(a,s,t);if(d){let b=t.dataIdMap.get(l.dataId).id;b!==o&&(c=l,i=b)}let p=c.shape.slice(0,-1),h=t.makeOutput(p,"int32"),f=t.dataIdMap.get(h.dataId).id,m=w.sizeFromShape(h.shape),g=c.shape[u[0]];return x_(i,Wt[c.dtype],m,g,f),d&&t.disposeData(l.dataId),h}var Jre={kernelName:za,backendName:"wasm",kernelFunc:Zre,setupFunc:Yre},w_;function Qre(e){w_=e.wasm.cwrap(Wa,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ese(e){let{inputs:t,attrs:n,backend:r}=e,s=t.x,a=r.dataIdMap.get(s.dataId).id,{filterSize:o,strides:i,pad:c,dimRoundingMode:l}=n,u=_.computePool2DInfo(s.shape,o,i,1,c,l),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,b=u.strideHeight,y=u.strideWidth,v=u.inChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);if(u.dilationWidth!==1||u.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${u.dilationHeight}, ${u.dilationWidth}].`);let x=r.makeOutput(u.outShape,"float32"),k=r.dataIdMap.get(x.dataId).id;return w_(a,s.shape[0],s.shape[1],s.shape[2],d,p,h,f,m,g,b,y,v,k),x}var tse={kernelName:Wa,backendName:"wasm",setupFunc:Qre,kernelFunc:ese};function Vn(e){let{inputs:t,attrs:n}=e,{x:r}=t,{shape:s}=n,a=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,a);return w.assert(a===w.sizeFromShape(o),()=>`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}var nse={kernelName:$c,backendName:"wasm",kernelFunc:Vn},k_;function rse(e){k_=e.wasm.cwrap(Va,null,["number","array","number","number","array","number","number","number","number"])}function sse(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let c=s.shape.length,l=a.shape.length,u=o?s.shape[c-2]:s.shape[c-1],d=i?a.shape[l-1]:a.shape[l-2],p=o?s.shape[c-1]:s.shape[c-2],h=i?a.shape[l-2]:a.shape[l-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=w.sizeFromShape(f),b=w.sizeFromShape(m),y=g===b||g===1||b===1;w.assert(c>=2&&l>=2&&y,()=>`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 (${m}).`);let x=(g>b?s.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);w.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let k=o?[g,u,p]:[g,p,u],C=i?[b,h,d]:[b,d,h],N=Vn({inputs:{x:s},backend:n,attrs:{shape:k}}),F=Vn({inputs:{x:a},backend:n,attrs:{shape:C}}),R=n.dataIdMap.get(N.dataId).id,O=n.dataIdMap.get(F.dataId).id,D=o?N.shape[2]:N.shape[1],P=i?F.shape[1]:F.shape[2],T=Math.max(g,b),L=n.makeOutput([T,D,P],N.dtype),G=n.dataIdMap.get(L.dataId).id,j=new Uint8Array(new Int32Array(N.shape).buffer),q=new Uint8Array(new Int32Array(F.shape).buffer);return k_(R,j,N.shape.length,O,q,F.shape.length,o,i,G),n.disposeData(N.dataId),n.disposeData(F.dataId),L.shape=x,L}var ase={kernelName:Va,backendName:"wasm",setupFunc:rse,kernelFunc:sse};function Gd(e){let{inputs:{x:t},attrs:{begin:n,size:r},backend:s}=e,[a,o]=kn.parseSliceParams(t,n,r),i=kn.isSliceContinous(t.shape,a,o),c=s.readSync(t.dataId),l=s.makeOutput(o,t.dtype),u=w.computeStrides(t.shape),d=s.dataIdMap.get(l.dataId);if(i){let f=kn.computeFlatOffset(a,u);return t.dtype==="string"?d.stringBytes=c.slice(f,f+w.sizeFromShape(o)):s.typedArrayFromHeap(l).set(c.subarray(f,f+w.sizeFromShape(o))),l}if(t.dtype==="string"){let f=im(c,a,o,t.shape,t.dtype);return d.stringBytes=f,l}let p=s.typedArrayFromHeap(l),h=t.shape.length;if(h===2)ose(c,u[0],p,a,o);else if(h===3)ise(c,u[0],u[1],p,a,o);else if(h===4)cse(c,u[0],u[1],u[2],p,a,o);else{let f=im(c,a,o,t.shape,t.dtype);p.set(f)}return l}function ose(e,t,n,r,s){let a=0,o=r[0],i=r[1],c=o+s[0];for(let l=o;l<c;l++){let u=l*t+i;n.set(e.subarray(u,u+s[1]),a),a+=s[1]}}function ise(e,t,n,r,s,a){let o=0,i=s[0],c=s[1],l=s[2],u=i+a[0],d=c+a[1];for(let p=i;p<u;p++)for(let h=c;h<d;h++){let f=p*t+h*n+l;r.set(e.subarray(f,f+a[2]),o),o+=a[2]}}function cse(e,t,n,r,s,a,o){let i=0,c=a[0],l=a[1],u=a[2],d=c+o[0],p=l+o[1],h=u+o[2],f=a[3];for(let m=c;m<d;m++)for(let g=l;g<p;g++)for(let b=u;b<h;b++){let y=m*t+g*n+b*r+f;s.set(e.subarray(y,y+o[3]),i),i+=o[3]}}var use={kernelName:Mc,backendName:"wasm",kernelFunc:Gd};function lse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r,i=a.reduce((b,y)=>b*y),c=_.getReshaped(s.shape,a,i),l=_.getPermuted(c.length,a.length),u=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(u,o,a.length),h=Vn({inputs:{x:s},backend:n,attrs:{shape:c}}),f=Ou({inputs:{x:h},backend:n,attrs:{perm:l}}),m=Vn({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Gd({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var dse={kernelName:sc,backendName:"wasm",kernelFunc:lse};function Hd(e){let{inputs:{x:t},attrs:{dtype:n},backend:r}=e,s=r.makeOutput(t.shape,n),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(s).set(a),s}var pse={kernelName:Ua,backendName:"wasm",kernelFunc:Hd},hse=dn(Ga),I_;function fse(e){I_=e.wasm.cwrap(ea,null,["number","number","number","number"])}function mse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i=n.dataIdMap.get(s.dataId).id,c=n.makeOutput(s.shape,s.dtype),l=n.dataIdMap.get(c.dataId).id;return I_(i,a,o,l),c}var gse={kernelName:ea,backendName:"wasm",setupFunc:fse,kernelFunc:mse};function S_(e){let{inputs:t,backend:n}=e,r=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],s=_.computeOutShape(t.map(h=>h.shape),r),a=t.filter(h=>w.sizeFromShape(h.shape)>0);if(a.length===1)return Am({inputs:{x:a[0]},backend:n});let o=n.makeOutput(s,t[0].dtype);if(w.sizeFromShape(s)===0)return o;let i=a.map(h=>h.shape);if(_.assertParamsConsistent(i,r),a[0].dtype==="string"){let h=a.map(v=>{let x=w.sizeFromShape(v.shape.slice(r));return Vn({inputs:{x:v},backend:n,attrs:{shape:[-1,x]}})}),f=h.map(v=>({vals:n.readSync(v.dataId),shape:v.shape}));s=_.computeOutShape(h.map(v=>v.shape),1);let m=h[0].shape[0]===1,g=bw(f,s,t[0].dtype,m),b=_.computeOutShape(a.map(v=>v.shape),r);o.shape=b;let y=n.dataIdMap.get(o.dataId);return y.stringBytes=_.fromStringArrayToUint8(g),h.forEach(v=>n.disposeData(v.dataId)),o}let c=w.sizeFromShape(a[0].shape.slice(0,r)),l=0,u=a.map(h=>{let f=w.sizeFromShape(h.shape.slice(r));return l+=f,f}),d=a.map(h=>n.typedArrayFromHeap(h)),p=n.typedArrayFromHeap(o);for(let h=0;h<c;h++){let f=h*l;for(let m=0;m<d.length;m++){let g=u[m],b=h*g,y=d[m].subarray(b,b+g);p.set(y,f),f+=g}}return o}var bse={kernelName:ac,backendName:"wasm",kernelFunc:S_},C_;function yse(e){C_=e.wasm.cwrap(Ha,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function vse(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a}=t,o=r.dataIdMap.get(s.dataId).id,i=r.dataIdMap.get(a.dataId).id,{strides:c,dilations:l,pad:u,dimRoundingMode:d,dataFormat:p}=n,h=_.convertConv2DDataFormat(p),f=_.computeConv2DInfo(s.shape,a.shape,c,l,u,d,!1,h),m=f.filterHeight,g=f.filterWidth,b=f.padInfo.top,y=f.padInfo.right,v=f.padInfo.bottom,x=f.padInfo.left,k=f.dilationHeight,C=f.dilationWidth,N=f.strideHeight,F=f.strideWidth,R=f.inChannels,O=f.outChannels,D=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let P=r.makeOutput(f.outShape,"float32"),T=r.dataIdMap.get(P.dataId).id;return C_(o,s.shape[0],s.shape[1],s.shape[2],i,m,g,b,y,v,x,D,k,C,N,F,R,O,T),P}var xse={kernelName:Ha,backendName:"wasm",setupFunc:yse,kernelFunc:vse},T_;function wse(e){T_=e.wasm.cwrap(ja,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 kse(e){let{backend:t,inputs:n,attrs:r}=e,{dy:s,filter:a}=n,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,inputShape:u}=r,d=1,p=_.convertConv2DDataFormat(c),h=_.computeConv2DInfo(u,a.shape,o,d,i,l,!1,p),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:b,inHeight:y,inWidth:v,outChannels:x,outHeight:k,outWidth:C,strideHeight:N,strideWidth:F}=h,R=m-1-h.padInfo.top,O=g-1-h.padInfo.left,D=h.dataFormat==="channelsLast",P=w.computeStrides(h.inShape),T=w.computeStrides(s.shape),[L,G,j]=w.computeStrides(a.shape),q=P[0],K=D?P[1]:P[2],ee=D?P[2]:1,te=D?1:P[1],ne=T[0],ae=D?T[1]:T[2],se=D?T[2]:1,re=D?1:T[1],ue=t.makeOutput(h.inShape,"float32"),de=t.dataIdMap.get(ue.dataId).id,me=t.dataIdMap.get(s.dataId).id,we=t.dataIdMap.get(a.dataId).id;return T_(me,we,f,m,g,y,v,b,k,C,x,N,F,R,O,L,G,j,q,K,ee,te,ne,ae,se,re,de),ue}var Ise={kernelName:ja,backendName:"wasm",setupFunc:wse,kernelFunc:kse},Sse=dn(qa),Cse=dn(Ka),Xw;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(Xw||(Xw={}));var N_;function Tse(e){N_=e.wasm.cwrap(oc,null,["number","number","number","number","array","number","number","number","number","number"])}function Nse(e){let{backend:t,inputs:n,attrs:r}=e,{method:s,extrapolationValue:a,cropSize:o}=r,{image:i,boxes:c,boxInd:l}=n,u=c.shape[0],[d,p]=o,h=[u,d,p,i.shape[3]],f=t.dataIdMap.get(i.dataId),m;i.dtype!=="float32"&&(m=Hd({backend:t,inputs:{x:i},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,b=t.dataIdMap.get(c.dataId).id,y=t.dataIdMap.get(l.dataId).id,v=t.makeOutput(h,"float32"),x=t.dataIdMap.get(v.dataId).id,k=new Uint8Array(new Int32Array(i.shape).buffer);return N_(g,b,y,u,k,d,p,Xw[s],a,x),m!=null&&t.disposeData(m.dataId),v}var _se={kernelName:oc,backendName:"wasm",setupFunc:Tse,kernelFunc:Nse},__;function Ese(e){__=e.wasm.cwrap(Xa,null,["number","number","number","number","number","number"])}function Ase(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length;w.assert(s.dtype==="float32"||s.dtype==="int32",()=>`cumsum does not support ${s.dtype} tensors in the WASM backend`);let l=_.getAxesPermutation([a],c),u=s;l!==null&&(u=Ou({inputs:{x:s},attrs:{perm:l},backend:n}));let d=_.getInnerMostAxes(1,c)[0];_.assertAxesAreInnerMostDims("cumsum",[d],c);let p=n.makeOutput(u.shape,u.dtype),h=u.shape[d],f=n.dataIdMap.get(u.dataId).id,m=n.dataIdMap.get(p.dataId).id;__(f,o?1:0,i?1:0,h,m,Wt[s.dtype]);let g=p;if(l!==null){let b=_.getUndoAxesPermutation(l);g=Ou({inputs:{x:p},attrs:{perm:b},backend:n}),n.disposeData(u.dataId),n.disposeData(p.dataId)}return g}var Dse={kernelName:Xa,backendName:"wasm",setupFunc:Ese,kernelFunc:Ase},E_;function Fse(e){E_=e.wasm.cwrap(ic,null,["number","number","number","array","number","array","array","number","number"])}function $se(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{blockSize:a,dataFormat:o}=r,i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],l=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=l*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=t.makeOutput(f,"float32"),b=t.dataIdMap.get(s.dataId).id,y=new Uint8Array(new Int32Array(w.computeStrides(s.shape)).buffer),v=new Uint8Array(new Int32Array(f).buffer),x=new Uint8Array(new Int32Array(w.computeStrides(f)).buffer),k=t.dataIdMap.get(m.dataId).id;return E_(b,a,o==="NHWC"?1:0,y,s.shape.length-1,v,x,f.length,k),m}var Rse={kernelName:ic,backendName:"wasm",setupFunc:Fse,kernelFunc:$se},A_;function Pse(e){A_=e.wasm.cwrap(Ya,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Ose(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a}=t,o=r.dataIdMap.get(s.dataId).id,i=r.dataIdMap.get(a.dataId).id,{strides:c,dilations:l,pad:u,dimRoundingMode:d}=n,p=l==null?[1,1]:l,h=_.computeConv2DInfo(s.shape,a.shape,c,p,u,d,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,b=h.padInfo.right,y=h.padInfo.bottom,v=h.padInfo.left,x=h.dilationHeight,k=h.dilationWidth,C=h.strideHeight,N=h.strideWidth,F=h.inChannels,R=h.outChannels,O=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let D=r.makeOutput(h.outShape,"float32"),P=r.dataIdMap.get(D.dataId).id;return A_(o,s.shape[0],s.shape[1],s.shape[2],i,f,m,g,b,y,v,O,x,k,C,N,F,R,P),D}var Mse={kernelName:Ya,backendName:"wasm",setupFunc:Pse,kernelFunc:Ose},Lse=dn(Ja),Bse=!1,zse=En(uc,Bse,"bool"),Wse=dn(Qa,"float32");function Yw(e){let{inputs:t,attrs:n,backend:r}=e,{input:s}=t,{dim:a}=n,o=s.shape.length,i=s.shape.slice(),c=a;return a<0&&(w.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+a+1),i.splice(c,0,1),Vn({inputs:{x:s},backend:r,attrs:{shape:i}})}var Vse={kernelName:lc,backendName:"wasm",kernelFunc:Yw};function D_(e){let{attrs:{shape:t,value:n,dtype:r},backend:s}=e,a=s.makeOutput(t,r);return s.typedArrayFromHeap(a).fill(n),a}var Use={kernelName:Cl,backendName:"wasm",kernelFunc:D_},F_;function Gse(e){F_=e.wasm.cwrap(pc,null,["number","number","number","number","number","number"])}function Hse(e){let{inputs:t,backend:n}=e,{image:r}=t,s=n.makeOutput(r.shape,r.dtype),a=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,[i,c,l,u]=r.shape;return F_(a,i,c,l,u,o),s}var jse={kernelName:pc,backendName:"wasm",kernelFunc:Hse,setupFunc:Gse},qse=dn(eo),Kse=!1,Xse=En(to,Kse),$_;function Yse(e){$_=e.wasm.cwrap(no,null,["number","number","number","number","number","number","number"])}function Zse(e){let{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:s}=r,{x:a,mean:o,variance:i,offset:c,scale:l}=n,u=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=c!=null?t.dataIdMap.get(c.dataId).id:0,f=l!=null?t.dataIdMap.get(l.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(w.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return $_(u,d,p,h,f,s,g),m}var Jse={kernelName:no,backendName:"wasm",setupFunc:Yse,kernelFunc:Zse},R_;function Qse(e){R_=e.wasm.cwrap(Mo,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 eae(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=_.computeConv2DInfo(s.shape,a.shape,c,u,l,p),g=Ud[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let b=r.dataIdMap.get(s.dataId).id,y=r.dataIdMap.get(a.dataId).id,v=m.outChannels,x=0;if(o!=null){let se=r.dataIdMap.get(o.dataId);if(se.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${se.shape.length}.`);if(se.shape[0]!==v)throw new Error(`FusedConv2D bias shape (${se.shape}) does not match the number of output channels (${v})`);x=se.id}let k=m.filterHeight,C=m.filterWidth,N=m.padInfo.top,F=m.padInfo.right,R=m.padInfo.bottom,O=m.padInfo.left,D=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,L=m.strideWidth,G=m.inChannels,j=m.padInfo.type==="SAME"?1:0,q=m.batchSize,K=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let te=r.makeOutput(m.outShape,"float32"),ne=r.dataIdMap.get(te.dataId).id,ae=i==null?0:r.dataIdMap.get(i.dataId).id;return R_(b,q,K,ee,y,k,C,x,N,F,R,O,j,D,P,T,L,G,v,g,ae,f||0,ne),te}var tae={kernelName:Mo,backendName:"wasm",setupFunc:Qse,kernelFunc:eae},P_;function nae(e){P_=e.wasm.cwrap(Lo,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 rae(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=_.computeConv2DInfo(s.shape,a.shape,c,u,l,p,!0),g=Ud[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let b=r.dataIdMap.get(s.dataId).id,y=r.dataIdMap.get(a.dataId).id,v=m.outChannels,x=0;if(o!=null){let se=r.dataIdMap.get(o.dataId);if(se.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${se.shape.length}.`);if(se.shape[0]!==v)throw new Error(`FusedDepthwiseConv2D bias shape (${se.shape}) does not match the number of output channels (${v})`);x=se.id}let k=m.filterHeight,C=m.filterWidth,N=m.padInfo.top,F=m.padInfo.right,R=m.padInfo.bottom,O=m.padInfo.left,D=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,L=m.strideWidth,G=m.inChannels,j=m.padInfo.type==="SAME"?1:0,q=m.batchSize,K=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let te=r.makeOutput(m.outShape,"float32"),ne=r.dataIdMap.get(te.dataId).id,ae=i==null?0:r.dataIdMap.get(i.dataId).id;return P_(b,q,K,ee,y,k,C,x,N,F,R,O,j,D,P,T,L,G,v,g,ae,f||0,ne),te}var sae={kernelName:Lo,backendName:"wasm",setupFunc:nae,kernelFunc:rae},O_;function aae(e){O_=e.wasm.cwrap(fc,null,["number","number","number","number","number","number","array","number"])}function oae(e){let{backend:t,inputs:n}=e,{params:r,indices:s}=n,[a,o,i,c]=ly.prepareAndValidate(r,s),l=t.makeOutput(a,r.dtype);if(o===0)return l;let u=s.shape,d=u[u.length-1],h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,g=new Uint8Array(new Int32Array(c).buffer),b=t.dataIdMap.get(l.dataId).id;return O_(h,Wt[r.dtype],m,o,d,i,g,b),l}var iae={kernelName:fc,backendName:"wasm",setupFunc:aae,kernelFunc:oae},M_;function cae(e){M_=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function uae(e){let{backend:t,inputs:n,attrs:r}=e,{x:s,indices:a}=n,{axis:o,batchDims:i}=r,c=w.parseAxisParam(o,s.shape)[0],l=t.readSync(a.dataId),u=s.shape[c];for(let R=0;R<l.length;++R){let O=l[R];w.assert(O<=u-1&&O>=0,()=>`GatherV2: the index value ${O} is not in [0, ${u-1}]`)}let d=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),p=Vn({inputs:{x:s},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=w.sizeFromShape(a.shape),f=Vn({inputs:{x:a},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),m=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(m,s.dtype);if(w.sizeFromShape(s.shape)===0)return g;let b=p.shape.length-1,v=t.dataIdMap.get(p.dataId).id,k=t.dataIdMap.get(f.dataId).id,C=t.dataIdMap.get(g.dataId).id,N=new Uint8Array(new Int32Array(w.computeStrides(p.shape)).buffer),F=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer);return M_(v,Wt[s.dtype],N,b,k,d.batchSize,F,C),t.disposeData(p.dataId),t.disposeData(f.dataId),g.shape=d.outputShape,g}var lae={kernelName:hc,backendName:"wasm",setupFunc:cae,kernelFunc:uae},dae=!1,pae=En(mc,dae,"bool"),hae=!1,fae=En(ro,hae,"bool"),L_;function mae(e){L_=e.wasm.cwrap(ao,null,["number","number","number","number"])}function gae(e){let{inputs:{x:t},attrs:{alpha:n},backend:r}=e,s=r.dataIdMap.get(t.dataId).id,a=r.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let o=r.dataIdMap.get(a.dataId).id;L_(s,Wt[t.dtype],n,o)}return a}var bae={kernelName:ao,backendName:"wasm",setupFunc:mae,kernelFunc:gae},yae=!1,vae=En(vc,yae,"bool"),xae=!1,wae=En(xc,xae,"bool"),kae=dn(oo),Iae=!1,Sae=En(kc,Iae,"bool"),B_;function Cae(e){B_=e.wasm.cwrap(io,null,["number","number","number","number"])}function Tae(e){let{backend:t,inputs:n,attrs:r}=e,{reductionIndices:s,keepDims:a}=r,{x:o}=n,c=t.dataIdMap.get(o.dataId).id,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t);if(h){let v=t.dataIdMap.get(u.dataId).id;l=u,c=v}let f=l.shape.length;_.assertAxesAreInnerMostDims("max",d,f);let[m,g]=_.computeOutAndReduceShapes(l.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(m,o.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;B_(c,Wt[o.dtype],b,v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var Nae={kernelName:io,backendName:"wasm",setupFunc:Cae,kernelFunc:Tae},_ae=!1,Eae=En(co,_ae),z_;function Aae(e){z_=e.wasm.cwrap(uo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Dae(e){let{inputs:t,attrs:n,backend:r}=e,s=t.x,a=r.dataIdMap.get(s.dataId).id;w.assert(s.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${s.dtype}.`);let{filterSize:o,strides:i,pad:c,dimRoundingMode:l}=n,u=_.computePool2DInfo(s.shape,o,i,1,c,l),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,b=u.dilationHeight,y=u.dilationWidth,v=u.strideHeight,x=u.strideWidth,k=u.inChannels,C=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let N=r.makeOutput(u.outShape,"float32"),F=r.dataIdMap.get(N.dataId).id;return z_(a,s.shape[0],s.shape[1],s.shape[2],d,p,h,f,m,g,b,y,v,x,k,C,F),N}var Fae={kernelName:uo,backendName:"wasm",setupFunc:Aae,kernelFunc:Dae},W_;function $ae(e){W_=e.wasm.cwrap(lo,null,["number, number, number"])}function Rae(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,c=i,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(l=u,c=x,f=_.getInnerMostAxes(f.length,l.shape.length))}_.assertAxesAreInnerMostDims("mean",f,l.shape.length);let[m,g]=_.computeOutAndReduceShapes(l.shape,f),b=w.sizeFromShape(g),y=l;l.dtype!=="float32"&&(y=Hd({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),c=t.dataIdMap.get(y.dataId).id);let v=t.makeOutput(m,"float32");if(w.sizeFromShape(l.shape)!==0){let x=t.dataIdMap.get(v.dataId).id;W_(c,b,x)}if(h&&t.disposeData(u.dataId),a){let x=_.expandShapeToKeepDim(v.shape,p);v.shape=x}return l.dtype!=="float32"&&t.disposeData(y.dataId),v}var Pae={kernelName:lo,backendName:"wasm",setupFunc:$ae,kernelFunc:Rae},V_;function Oae(e){V_=e.wasm.cwrap(po,null,["number","number","number","number"])}function Mae(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,c=i,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t);if(h){let v=t.dataIdMap.get(u.dataId).id;v!==i&&(l=u,c=v)}let f=l.shape.length;_.assertAxesAreInnerMostDims("min",d,f);let[m,g]=_.computeOutAndReduceShapes(l.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(m,l.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;V_(c,Wt[o.dtype],b,v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var Lae={kernelName:po,backendName:"wasm",setupFunc:Oae,kernelFunc:Mae},Bae=!1,zae=En(ho,Bae),Zw;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(Zw||(Zw={}));var U_;function Wae(e){U_=e.wasm.cwrap(fo,null,["number","array","number","number","array","array","number","number"])}function Vae(e){let{inputs:{x:t},backend:n,attrs:{paddings:r,mode:s}}=e,a=r.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),c=n.dataIdMap.get(i.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),u=r.map(f=>f[0]),d=r.map(f=>f[1]),p=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(d).buffer);return U_(o,l,t.shape.length,Wt[t.dtype],p,h,Zw[s],c),i}var Uae={kernelName:fo,backendName:"wasm",kernelFunc:Vae,setupFunc:Wae},Gae=!0,Hae=En(mo,Gae),jae=dn(Sc);function Jw(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],s=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:s,pSelectedScores:a,pValidOutputs:o}}var G_;function qae(e){G_=e.wasm.cwrap(Tc,"number",["number","number","number","number","number"])}function Kae(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o}=r,{boxes:i,scores:c}=n,l=t.dataIdMap.get(i.dataId).id,u=t.dataIdMap.get(c.dataId).id,d=G_(l,u,a,s,o),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=Jw(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}var Xae={kernelName:Tc,backendName:"wasm",setupFunc:qae,kernelFunc:Kae},H_;function Yae(e){H_=e.wasm.cwrap(Nc,"number",["number","number","number","number","number","bool"])}function Zae(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=r,{boxes:c,scores:l}=n,u=t.dataIdMap.get(c.dataId).id,d=t.dataIdMap.get(l.dataId).id,p=H_(u,d,a,s,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Jw(t,p);t.wasm._free(m);let b=t.makeOutput([f],"int32",h),y=t.makeOutput([],"int32",g);return[b,y]}var Jae={kernelName:Nc,backendName:"wasm",setupFunc:Yae,kernelFunc:Zae},j_;function Qae(e){j_=e.wasm.cwrap(_c,"number",["number","number","number","number","number","number"])}function eoe(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=r,{boxes:c,scores:l}=n,u=t.dataIdMap.get(c.dataId).id,d=t.dataIdMap.get(l.dataId).id,p=j_(u,d,a,s,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Jw(t,p);t.wasm._free(g);let b=t.makeOutput([f],"int32",h),y=t.makeOutput([f],"float32",m);return[b,y]}var toe={kernelName:_c,backendName:"wasm",setupFunc:Qae,kernelFunc:eoe},noe=!1,roe=En(Cc,noe,"bool"),q_;function soe(e){q_=e.wasm.cwrap(go,null,["number","number","number","number","number"])}function aoe(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=n.makeOutput([...s.shape,a],"int32"),l=n.dataIdMap.get(c.dataId).id,d=n.dataIdMap.get(s.dataId).id;return q_(d,a,o,i,l),c}var ooe={kernelName:go,backendName:"wasm",setupFunc:soe,kernelFunc:aoe};function ioe(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}var coe={kernelName:Ec,backendName:"wasm",kernelFunc:ioe};function uoe(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Yw({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=Yw({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=S_({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeData(u.dataId)),l}var loe={kernelName:Ac,backendName:"wasm",kernelFunc:uoe},K_;function doe(e){K_=e.wasm.cwrap(bo,null,["number","array","number","number","array","array","number","number"])}function poe(e){let{inputs:{x:t},backend:n,attrs:{paddings:r,constantValue:s}}=e,a=r.map((m,g)=>m[0]+t.shape[g]+m[1]);if(w.sizeFromShape(t.shape)===0)return D_({backend:n,attrs:{shape:a,value:s,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=r.map(m=>m[0]),p=r.map(m=>m[1]),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return K_(o,u,t.shape.length,Wt[t.dtype],h,f,s,l),i}var X_={kernelName:bo,backendName:"wasm",kernelFunc:poe,setupFunc:doe},hoe=!1,foe=En(yo,hoe),Y_;function moe(e){Y_=e.wasm.cwrap(vo,null,["number","number","number"])}function goe(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,i=a,c=r,l=c;c.dtype!=="float32"&&(l=Hd({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(l.dataId).id);let u=n.makeOutput(r.shape,"float32"),d=n.dataIdMap.get(u.dataId).id;return Y_(i,o,d),c.dtype!=="float32"&&n.disposeData(l.dataId),u}var boe={kernelName:vo,backendName:"wasm",setupFunc:moe,kernelFunc:goe},Z_;function yoe(e){Z_=e.wasm.cwrap(Dc,null,["number","number","number","number"])}function voe(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,c=i,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t),f=d;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==i&&(l=u,c=v,f=_.getInnerMostAxes(f.length,l.shape.length))}_.assertAxesAreInnerMostDims("prod",f,l.shape.length);let[m,g]=_.computeOutAndReduceShapes(l.shape,f),b=w.sizeFromShape(g),y=t.makeOutput(m,l.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;Z_(c,b,Wt[y.dtype],v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var xoe={kernelName:Dc,backendName:"wasm",setupFunc:yoe,kernelFunc:voe},woe=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=xw(r,s,a,o),c=t.makeOutput([i.length],o);return t.typedArrayFromHeap(c).set(i),c},koe={kernelName:Al,backendName:"wasm",kernelFunc:woe},Ioe=!0,Soe=En(Za,Ioe),Coe=dn(xo),Toe=dn(ko),J_;function Noe(e){J_=e.wasm.cwrap(wo,null,["number","number","number","number","number","number","number","number","number","number"])}function _oe(e){let{backend:t,inputs:n,attrs:r}=e,{images:s}=n,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,[u,d,p,h]=s.shape,f=[u,c,l,h],m=t.dataIdMap.get(s.dataId),g;m.dtype!=="float32"&&(g=Hd({backend:t,inputs:{x:s},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let b=m.id,y=t.makeOutput(f,"float32");if(w.sizeFromShape(s.shape)===0)return y;let v=t.dataIdMap.get(y.dataId).id;return J_(b,u,d,p,h,c,l,a?1:0,o?1:0,v),g!=null&&t.disposeData(g.dataId),y}var Eoe={kernelName:wo,backendName:"wasm",setupFunc:Noe,kernelFunc:_oe},Q_;function Aoe(e){Q_=e.wasm.cwrap(Io,null,["number","array","number","array","number","number"])}function Doe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=w.parseAxisParam(a,s.shape);if(s.shape.length===0)return Am({inputs:{x:s},backend:n});let i=n.makeOutput(s.shape,s.dtype),c=n.dataIdMap.get(s.dataId).id,l=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(s.shape).buffer);Q_(c,u,o.length,d,s.shape.length,l);let p=Vn({inputs:{x:i},attrs:{shape:s.shape},backend:n});return n.disposeData(i.dataId),p}var Foe={kernelName:Io,backendName:"wasm",kernelFunc:Doe,setupFunc:Aoe},eE;function $oe(e){eE=e.wasm.cwrap(Kc,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Roe(e){let{inputs:t,backend:n,attrs:r}=e,{image:s}=t,{radians:a,fillValue:o,center:i}=r,c=n.makeOutput(s.shape,s.dtype),l=n.dataIdMap.get(s.dataId).id,u=n.dataIdMap.get(c.dataId).id,[d,p,h,f]=s.shape,[m,g]=_.getImageCenter(i,p,h),b=o===0,y=255,v=typeof o=="number"?[o,o,o,b?0:y]:[...o,y],x=new Uint8Array(new Int32Array(v).buffer);return eE(l,d,p,h,f,a,m,g,x,v.length,u),c}var Poe={kernelName:Kc,backendName:"wasm",kernelFunc:Roe,setupFunc:$oe},Ooe=dn(So),Moe=dn(Co),tE;function Loe(e){tE=e.wasm.cwrap(Rc,null,["number","number","number","number","number","number","array","number","number"])}function Boe(e){let{backend:t,inputs:n,attrs:r}=e,{indices:s,updates:a}=n,{shape:o}=r,i=t.makeOutput(o,a.dtype);if(w.sizeFromShape(o)===0)return i;let{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:p}=dy.calculateShapes(a,s,o),f=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(a.dataId).id,b=new Uint8Array(new Int32Array(d).buffer),y=t.dataIdMap.get(i.dataId).id;return tE(f,g,Wt[a.dtype],c,l,u,b,p,y),i}var zoe={kernelName:Rc,backendName:"wasm",setupFunc:Loe,kernelFunc:Boe},nE;function Woe(e){nE=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Voe(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(s.dataId).id,c=n.dataIdMap.get(a.dataId).id,l=n.makeOutput(s.shape,s.dtype),u=n.dataIdMap.get(l.dataId).id,d=r.shape.length,p=s.shape.length,h=d===0||d>1||p===1?1:w.sizeFromShape(s.shape.slice(1));return nE(o,i,c,h,u),l}var Uoe={kernelName:Pc,backendName:"wasm",kernelFunc:Voe,setupFunc:Woe},rE;function Goe(e){rE=e.wasm.cwrap(No,null,["number","number"])}function Hoe(e){let{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(s.dataId).id;return w.sizeFromShape(s.shape)===0||rE(r,a),s}var joe={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Goe,kernelFunc:Hoe},qoe=dn(To),sE;function Koe(e){sE=e.wasm.cwrap(Ao,null,["number","number","number","number"])}function Xoe(e){let{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,s=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[r],c=w.sizeFromShape(n.shape)/i;return w.sizeFromShape(a.shape)===0||sE(s,o,i,c),a}var Yoe={kernelName:Ao,backendName:"wasm",setupFunc:Koe,kernelFunc:Xoe};function Zoe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r,i=w.sizeFromShape(a),c=[[0,0]];c.push(...o);for(let C=1+a.length;C<s.shape.length;++C)c.push([0,0]);let l=X_.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),u=_.getReshaped(l.shape,a,i,!1),d=_.getPermuted(u.length,a.length,!1),p=_.getReshapedPermuted(l.shape,a,i,!1),m=Vn({inputs:{x:l},backend:n,attrs:{shape:u}}),y=Ou({inputs:{x:m},backend:n,attrs:{perm:d}}),k=Vn({inputs:{x:y},backend:n,attrs:{shape:p}});return n.disposeData(l.dataId),n.disposeData(m.dataId),n.disposeData(y.dataId),k}var Joe={kernelName:Wc,backendName:"wasm",kernelFunc:Zoe};function Qoe(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=n,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=Gd({inputs:{x:s},attrs:{begin:l,size:p},backend:r});return l[i]+=d,h})}var eie={kernelName:Vc,backendName:"wasm",kernelFunc:Qoe},tie=dn(_o),nie=dn(Fl),rie=!0,sie=En(Do,rie),aE;function aie(e){aE=e.wasm.cwrap(na,null,["number","number","number","number"])}function oie(e){let{backend:t,inputs:n,attrs:r}=e,{alpha:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),c=t.dataIdMap.get(i.dataId).id;return aE(o,s,Wt[a.dtype],c),i}var iie={kernelName:na,backendName:"wasm",setupFunc:aie,kernelFunc:oie},oE;function cie(e){oE=e.wasm.cwrap(Uc,null,["number","array","number","array","array","array","array","array","number","number"])}function uie(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:o,strides:i}=r;i==null&&(i=new Array(a.length));let{beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,h=_.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=s.shape.length-a.length,m=_.slice_util.maskToAxes(d),g=s.shape.slice();m.forEach(D=>{a[D]=0,o[D]=1,g.splice(D,0,1)});let b=Vn({inputs:{x:s},attrs:{shape:g},backend:t}),{begin:y,end:v,strides:x}=_.slice_util.getNormalizedAxes(b.shape,h,f,a,o,i,c,l,u);a=y,o=v,i=x;let k=_.slice_util.maskToAxes(p);k.forEach(D=>{o[D]=a[D]+1,i[D]=1});let C=_.slice_util.computeOutShape(a,o,i),N=C.filter((D,P)=>k.indexOf(P)===-1);if(i.every(D=>D===1)){let D=Gd({inputs:{x:b},attrs:{begin:a,size:C},backend:t});t.disposeData(b.dataId);let P=Vn({inputs:{x:D},attrs:{shape:N},backend:t});return t.disposeData(D.dataId),P}let R=t.makeOutput(N,"float32");if(!N.some(D=>D===0)){let D=t.dataIdMap.get(b.dataId).id,P=new Uint8Array(new Int32Array(w.computeStrides(b.shape)).buffer),T=new Uint8Array(new Int32Array(a).buffer),L=new Uint8Array(new Int32Array(o).buffer),G=new Uint8Array(new Int32Array(i).buffer),j=new Uint8Array(new Int32Array(N).buffer),q=new Uint8Array(new Int32Array(w.computeStrides(N)).buffer),K=t.dataIdMap.get(R.dataId).id;oE(D,P,b.shape.length,T,L,G,j,q,N.length,K)}t.disposeData(b.dataId);let O=Vn({inputs:{x:R},attrs:{shape:N},backend:t});return t.disposeData(R.dataId),O}var lie={kernelName:Uc,backendName:"wasm",setupFunc:cie,kernelFunc:uie},die=!0,pie=En(Fo,die),iE;function hie(e){iE=e.wasm.cwrap(Eo,null,["number","number","number","number"])}function fie(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,c=i,l=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ta(o,s,t),f=d;if(h){let v=t.dataIdMap.get(u.dataId).id;v!==i&&(l=u,c=v,f=_.getInnerMostAxes(f.length,l.shape.length))}_.assertAxesAreInnerMostDims("sum",f,l.shape.length);let[m,g]=_.computeOutAndReduceShapes(l.shape,f),b=w.sizeFromShape(g),y=t.makeOutput(m,l.dtype);if(w.sizeFromShape(l.shape)!==0){let v=t.dataIdMap.get(y.dataId).id;iE(c,b,Wt[y.dtype],v)}if(h&&t.disposeData(u.dataId),a){let v=_.expandShapeToKeepDim(y.shape,p);y.shape=v}return y}var mie={kernelName:Eo,backendName:"wasm",setupFunc:hie,kernelFunc:fie},gie=dn($o),bie=dn(Ro),cE;function yie(e){cE=e.wasm.cwrap(ta,null,["number","array","number","array","number","number"])}function vie(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,a=n.dataIdMap.get(s.dataId).id,{reps:o}=r,i=new Array(s.shape.length);for(let p=0;p<i.length;p++)i[p]=s.shape[p]*o[p];let c=new Uint8Array(new Int32Array(s.shape).buffer),l=new Uint8Array(new Int32Array(i).buffer),u=n.makeOutput(i,s.dtype),d=n.dataIdMap.get(u.dataId).id;return cE(a,c,s.shape.length,l,i.length,Wt[u.dtype],d),u}var xie={kernelName:ta,backendName:"wasm",setupFunc:yie,kernelFunc:vie},uE;function wie(e){uE=e.wasm.cwrap(Gc,null,["number","array","number","number","number","bool","number","number"])}var kie=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{k:s,sorted:a}=n,o=t.dataIdMap.get(r.dataId).id,i=new Uint8Array(new Int32Array(r.shape).buffer),c=r.shape.slice();c[c.length-1]=s;let l=t.makeOutput(c,r.dtype),u=t.dataIdMap.get(l.dataId).id,d=t.makeOutput(c,"int32"),p=t.dataIdMap.get(d.dataId).id;return uE(o,i,r.shape.length,Wt[r.dtype],s,a,u,p),[l,d]},Iie={kernelName:Gc,backendName:"wasm",setupFunc:wie,kernelFunc:kie},lE;function Sie(e){lE=e.wasm.cwrap(Hc,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function Cie(e){let{backend:t,inputs:n,attrs:r}=e,{image:s,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:c,outputShape:l}=r,[u,d,p,h]=s.shape,[f,m]=l!=null?l:[d,p],g=[u,f,m,h],b=new Uint8Array(new Int32Array(w.computeStrides(s.shape)).buffer),y=t.makeOutput(g,s.dtype),v=t.dataIdMap.get(y.dataId).id,k=t.dataIdMap.get(s.dataId).id,N=t.dataIdMap.get(a.dataId).id,F=o==="nearest"?1:2,R;switch(i){case"constant":R=1;break;case"reflect":R=2;break;case"wrap":R=3;break;case"nearest":R=4;break;default:R=1;break}return lE(k,N,a.shape[0]>1,u,f,m,h,p,d,b,s.shape.length-1,F,R,c,v),y}var Tie={kernelName:Hc,backendName:"wasm",setupFunc:Sie,kernelFunc:Cie};function Nie(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s.shape[a],i=s.shape.length,c=new Array(i-1),l=0;for(let h=0;h<i;h++)h!==a&&(c[l++]=s.shape[h]);let u=new Array(o),d=new Array(i).fill(0),p=s.shape.slice();p[a]=1;for(let h=0;h<u.length;h++)d[a]=h,u[h]=Gd({inputs:{x:s},attrs:{begin:d,size:p},backend:n});return u.map(({dataId:h,dtype:f})=>({dataId:h,dtype:f,shape:c}))}var _ie={kernelName:jc,backendName:"wasm",kernelFunc:Nie};function Eie(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}var Aie={kernelName:qc,backendName:"wasm",kernelFunc:Eie},Die=[$re,Pre,Lre,jre,Xre,Jre,tse,ase,dse,pse,hse,gse,bse,xse,Ise,Sse,Cse,_se,Dse,Rse,Mse,Lse,zse,Wse,Vse,Use,jse,qse,Xse,Fre,Jse,tae,sae,iae,lae,pae,fae,Bre,bae,vae,wae,kae,Sae,Nae,Eae,Fae,Pae,Lae,zae,Uae,Hae,jae,Xae,Jae,toe,roe,ooe,coe,loe,X_,foe,boe,xoe,koe,Soe,Coe,Toe,nse,Eoe,Foe,Poe,Moe,Ooe,zoe,Uoe,joe,qoe,use,Yoe,Joe,eie,tie,nie,sie,iie,lie,pie,mie,gie,bie,xie,Iie,Tie,Ure,_ie,Aie];for(let e of Die)Pl(e);var Qw=J();Qw.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])));Qw.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Qw.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 dE=Oa(SD()),Fie='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()}}}}',$ie=Oa(CD()),pE=class extends bl{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(fE),t0=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Op(this,Cs())}write(e,t,n){let r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,r,s){let a=this.dataIdNextNumber++;if(r==="string"){let l=t;this.dataIdMap.set(e,{id:a,stringBytes:l,shape:n,dtype:r,memoryOffset:null,refCount:s});return}let o=w.sizeFromShape(n),i=o*w.bytesPerElement(r),c=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:c,shape:n,dtype:r,refCount:s}),this.wasm.tfjs.registerTensor(a,o,c),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),c)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:r,stringBytes:s}=this.dataIdMap.get(e);if(n==="string")return s;let a=this.wasm.HEAPU8.slice(t,t+w.sizeFromShape(r)*w.bytesPerElement(n));return Oie(a.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let r;if(n==null)r=this.write(null,e,t);else{let s=this.dataIdNextNumber++;r={id:s},this.dataIdMap.set(r,{id:s,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,a,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let r=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(n),a=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(r,s,a);case"int32":return new Int32Array(r,s,a);case"bool":return new Uint8Array(r,s,a);default:throw new Error(`Unknown dtype ${t}`)}}};function Rie(e){return(t,n)=>(w.fetch(e,{credentials:"same-origin"}).then(r=>{r.ok||t.env.a(`failed to load wasm binary file at '${e}'`),r.arrayBuffer().then(s=>{WebAssembly.instantiate(s,t).then(a=>{n(a.instance,a.module)})})}),{})}function hE(e,t,n){if(Dm!=null)return Dm;let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),qd!=null&&qd[r]!=null?qd[r]:n+r}async function Pie(){let[e,t]=await Promise.all([J().getAsync("WASM_HAS_SIMD_SUPPORT"),J().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,r)=>{let s={};s.locateFile=(i,c)=>{if(i.endsWith(".worker.js")){let l=Fie,u=new Blob([l],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?hE(e,t,jd!=null?jd:c):c+i},e0&&(s.instantiateWasm=Rie(hE(e,t,jd!=null?jd:"")));let a=!1;s.onAbort=()=>{if(a||Kd)return;Kd=!0,r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&Dm==null?(s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+dE.default.toString()],{type:"text/javascript"}),o=(0,dE.default)(s)):o=(0,$ie.default)(s),o.then(i=>{a=!0,Kd=!1;let c=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",c,["number"]),dispose:i.cwrap("dispose",c,[])},n({wasm:i})})})}function Oie(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 Mie=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Dm=null,jd=null,qd={},Kd=!1,e0=!1;function Lie(e,t=!1){if(by("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Kd)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Dm=e,e0=t}function Bie(e,t=!1){if(Kd)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")jd=e;else{qd=e;let n=Mie.filter(r=>qd[r]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}e0=t}var fE=-1,t0=-1;function zie(e){fE=e}function Wie(){if(t0===-1)throw new Error("WASM backend not initialized.");return t0}var Vie="3.10.0",Uie=2;Mh("wasm",async()=>{let{wasm:e}=await Pie();return new pE(e)},Uie);var Gie="3.10.0",Hie="3.10.0",jie="3.10.0",qie="3.10.0",Kie="3.10.0",Xie="3.10.0",Yie="3.10.0",Zie="3.10.0",Jie={tfjs:Gie,"tfjs-core":Hie,"tfjs-data":jie,"tfjs-layers":qie,"tfjs-converter":Kie,"tfjs-backend-cpu":Xie,"tfjs-backend-webgl":Yie,"tfjs-backend-wasm":Zie};var _0={};Rp(_0,{AnchorPosition:()=>bs,DrawBox:()=>Pm,DrawBoxOptions:()=>b0,DrawFaceLandmarks:()=>N0,DrawFaceLandmarksOptions:()=>T0,DrawTextField:()=>_a,DrawTextFieldOptions:()=>Jd,drawContour:()=>Os,drawDetections:()=>ice,drawFaceExpressions:()=>pce,drawFaceLandmarks:()=>fce});function Os(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:r,y:s},a)=>{let o=t[a];e.moveTo(o.x,o.y),e.lineTo(r,s)}),n){let r=t[t.length-1],s=t[0];if(!r||!s)return;e.moveTo(r.x,r.y),e.lineTo(s.x,s.y)}e.stroke()}var o0={};Rp(o0,{computeReshapedDimensions:()=>a0,getCenterPoint:()=>ki,isDimensions:()=>$m,isEven:()=>Fm,isFloat:()=>s0,isTensor:()=>xi,isTensor1D:()=>Qie,isTensor2D:()=>r0,isTensor3D:()=>Ms,isTensor4D:()=>mr,isValidNumber:()=>qr,isValidProbablitiy:()=>Mu,range:()=>ms,round:()=>wi});var An=class{constructor(t,n){if(!qr(t)||!qr(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 An(1/this.width,1/this.height)}};function xi(e,t){return e instanceof Ee&&e.shape.length===t}function Qie(e){return xi(e,1)}function r0(e){return xi(e,2)}function Ms(e){return xi(e,3)}function mr(e){return xi(e,4)}function s0(e){return e%1!=0}function Fm(e){return e%2==0}function wi(e,t=2){let n=10**t;return Math.floor(e*n)/n}function $m(e){return e&&e.width&&e.height}function a0({width:e,height:t},n){let r=n/Math.max(t,e);return new An(Math.round(e*r),Math.round(t*r))}function ki(e){return e.reduce((t,n)=>t.add(n),new Pe(0,0)).div(new Pe(e.length,e.length))}function ms(e,t,n){return Array(e).fill(0).map((r,s)=>t+s*n)}function qr(e){return!!e&&e!==1/0&&e!==-1/0&&!Number.isNaN(e)||e===0}function Mu(e){return qr(e)&&e>=0&&e<=1}var Pe=class{constructor(t,n){this._x=t,this._y=n}get x(){return this._x}get y(){return this._y}add(t){return new Pe(this.x+t.x,this.y+t.y)}sub(t){return new Pe(this.x-t.x,this.y-t.y)}mul(t){return new Pe(this.x*t.x,this.y*t.y)}div(t){return new Pe(this.x/t.x,this.y/t.y)}abs(){return new Pe(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new Pe(Math.floor(this.x),Math.floor(this.y))}};var ut=class{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(qr)}static assertIsValidBox(t,n,r=!1){if(!ut.isRect(t))throw new Error(`${n} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!r&&(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 r=t||{},s=[r.left,r.top,r.right,r.bottom].every(qr),a=[r.x,r.y,r.width,r.height].every(qr);if(!a&&!s)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(r)}`);let[o,i,c,l]=a?[r.x,r.y,r.width,r.height]:[r.left,r.top,r.right-r.left,r.bottom-r.top];ut.assertIsValidBox({x:o,y:i,width:c,height:l},"Box.constructor",n),this._x=o,this._y=i,this._width=c,this._height=l}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 Pe(this.left,this.top)}get topRight(){return new Pe(this.right,this.top)}get bottomLeft(){return new Pe(this.left,this.bottom)}get bottomRight(){return new Pe(this.right,this.bottom)}round(){let[t,n,r,s]=[this.x,this.y,this.width,this.height].map(a=>Math.round(a));return new ut({x:t,y:n,width:r,height:s})}floor(){let[t,n,r,s]=[this.x,this.y,this.width,this.height].map(a=>Math.floor(a));return new ut({x:t,y:n,width:r,height:s})}toSquare(){let{x:t,y:n,width:r,height:s}=this,a=Math.abs(r-s);return r<s&&(t-=a/2,r+=a),s<r&&(n-=a/2,s+=a),new ut({x:t,y:n,width:r,height:s})}rescale(t){let n=$m(t)?t.width:t,r=$m(t)?t.height:t;return new ut({x:this.x*n,y:this.y*r,width:this.width*n,height:this.height*r})}pad(t,n){let[r,s,a,o]=[this.x-t/2,this.y-n/2,this.width+t,this.height+n];return new ut({x:r,y:s,width:a,height:o})}clipAtImageBorders(t,n){let{x:r,y:s,right:a,bottom:o}=this,i=Math.max(r,0),c=Math.max(s,0),l=a-i,u=o-c,d=Math.min(l,t-i),p=Math.min(u,n-c);return new ut({x:i,y:c,width:d,height:p}).floor()}shift(t,n){let{width:r,height:s}=this,a=this.x+t,o=this.y+n;return new ut({x:a,y:o,width:r,height:s})}padAtBorders(t,n){let r=this.width+1,s=this.height+1,a=1,o=1,i=r,c=s,l=this.left,u=this.top,d=this.right,p=this.bottom;return d>n&&(i=-d+n+r,d=n),p>t&&(c=-p+t+s,p=t),l<1&&(c=2-l,l=1),u<1&&(c=2-u,u=1),{dy:o,edy:c,dx:a,edx:i,y:u,ey:p,x:l,ex:d,w:r,h:s}}calibrate(t){return new ut({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()}};var Lu=class extends ut{constructor(t,n,r,s,a=!1){super({left:t,top:n,right:r,bottom:s},a)}};var Na=class{constructor(t,n,r,s,a){this._imageDims=new An(a.width,a.height),this._score=t,this._classScore=n,this._className=r,this._box=new ut(s).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new ut(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new Na(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var vt=class extends Na{constructor(t,n,r){super(t,t,"",n,r)}forSize(t,n){let{score:r,relativeBox:s,imageDims:a}=super.forSize(t,n);return new vt(r,s,a)}};function i0(e,t,n=!0){let r=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),s=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),a=r*s;return n?a/(e.area+t.area-a):a/Math.min(e.area,t.area)}function c0(e){let t=e.map(i=>i.x),n=e.map(i=>i.y),r=t.reduce((i,c)=>c<i?c:i,1/0),s=n.reduce((i,c)=>c<i?c:i,1/0),a=t.reduce((i,c)=>i<c?c:i,0),o=n.reduce((i,c)=>i<c?c:i,0);return new Lu(r,s,a,o)}function u0(e,t,n,r=!0){let s=t.map((o,i)=>({score:o,boxIndex:i})).sort((o,i)=>o.score-i.score).map(o=>o.boxIndex),a=[];for(;s.length>0;){let o=s.pop();a.push(o);let i=s,c=[];for(let l=0;l<i.length;l++){let u=i[l],d=e[o],p=e[u];c.push(i0(d,p,r))}s=s.filter((l,u)=>c[u]<=n)}return a}function Kr(e,t){return M(()=>{let[n,r,s]=t,a=In([...e.shape.slice(0,3),1],n,"float32"),o=In([...e.shape.slice(0,3),1],r,"float32"),i=In([...e.shape.slice(0,3),1],s,"float32"),c=Ze([a,o,i],3);return fe(e,c)})}function l0(e,t=!1){return M(()=>{let[n,r]=e.shape.slice(1);if(n===r)return e;let s=Math.abs(n-r),a=Math.round(s*(t?.5:1)),o=n>r?2:1,i=p=>{let h=e.shape.slice();return h[o]=p,In(h,0,"float32")},c=i(a),l=s-c.shape[o],d=[t&&l?i(l):null,e,c].filter(p=>!!p).map(p=>ce(p,"float32"));return Ze(d,o)})}function ece(e){let t=e.slice();for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),s=t[n];t[n]=t[r],t[r]=s}return t}function Xd(e){return 1/(1+Math.exp(-e))}function tce(e){return Math.log(e/(1-e))}var Bu=class extends ut{constructor(t,n,r,s,a=!1){super({x:t,y:n,width:r,height:s},a)}};var nce=.5,rce=.43,sce=.45,gr=class{constructor(t,n,r=new Pe(0,0)){let{width:s,height:a}=n;this._imgDims=new An(s,a),this._shift=r,this._positions=t.map(o=>o.mul(new Pe(s,a)).add(r))}get shift(){return new Pe(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 Pe(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 Pe(t,n))}shiftByPoint(t){return this.shiftBy(t.x,t.y)}align(t,n={}){if(t){let a=t instanceof vt?t.box.floor():new ut(t);return this.shiftBy(a.x,a.y).align(null,n)}let{useDlibAlignment:r,minBoxPadding:s}={useDlibAlignment:!1,minBoxPadding:.2,...n};return r?this.alignDlib():this.alignMinBbox(s)}alignDlib(){let t=this.getRefPointsForAlignment(),[n,r,s]=t,a=d=>s.sub(d).magnitude(),o=(a(n)+a(r))/2,i=Math.floor(o/sce),c=ki(t),l=Math.floor(Math.max(0,c.x-nce*i)),u=Math.floor(Math.max(0,c.y-rce*i));return new Bu(l,u,Math.min(i,this.imageWidth+l),Math.min(i,this.imageHeight+u))}alignMinBbox(t){let n=c0(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var mE=class extends gr{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],ki([t[3],t[4]])]}};var zu=class extends gr{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(ki)}};var Yd=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?` (${wi(this.distance)})`:""}`}};var Zd=class extends ut{static assertIsValidLabeledBox(t,n){if(ut.assertIsValidBox(t,n),!qr(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 Ls=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(r=>!(r 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(r=>new Float32Array(r));return new Ls(t.label,n)}};var gE=class extends Zd{static assertIsValidPredictedBox(t,n){if(Zd.assertIsValidLabeledBox(t,n),!Mu(t.score)||!Mu(t.classScore))throw new Error(`${n} - expected properties score (${t.score}) and (${t.classScore}) to be a number between [0, 1]`)}constructor(t,n,r,s){super(t,n);this._score=r,this._classScore=s}get score(){return this._score}get classScore(){return this._classScore}};function gs(e){return e.detection instanceof vt}function Ii(e,t){return{...e,...{detection:t}}}function d0(){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"),createVideoElement:()=>document.createElement("video"),fetch:e,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function Rm(e){let t="";if(!e)try{e=Qr("fs")}catch(r){t=r.toString()}return{readFile:e?r=>new Promise((s,a)=>{e.readFile(r,(o,i)=>o?a(o):s(i))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function p0(){let e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=global.Video||global.HTMLVideoElement,r=()=>{if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},s=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},a=()=>{if(n)return new n;throw new Error("createVideoElement - missing Video implementation for nodejs environment")},o=global.fetch,i=Rm();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:r,createImageElement:s,createVideoElement:a,fetch:o,...i}}function h0(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}function f0(){return typeof global=="object"&&typeof Qr=="function"&&typeof module!="undefined"&&typeof process!="undefined"&&!!process.version}var rn;function ace(){if(!rn)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return rn}function m0(e){rn=e}function g0(){return h0()?m0(d0()):f0()?m0(p0()):null}function oce(e){if(rn||g0(),!rn)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=rn.Canvas,Image:n=rn.Image}=e;rn.Canvas=t,rn.Image=n,rn.createCanvasElement=e.createCanvasElement||(()=>new t),rn.createImageElement=e.createImageElement||(()=>new n),rn.ImageData=e.ImageData||rn.ImageData,rn.Video=e.Video||rn.Video,rn.fetch=e.fetch||rn.fetch,rn.readFile=e.readFile||rn.readFile}var Je={getEnv:ace,setEnv:m0,initialize:g0,createBrowserEnv:d0,createFileSystem:Rm,createNodejsEnv:p0,monkeyPatch:oce,isBrowser:h0,isNodejs:f0};g0();function Si(e){return!Je.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Un(e){let{Canvas:t,CanvasRenderingContext2D:n}=Je.getEnv();if(e instanceof n)return e;let r=Si(e);if(!(r instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let s=r.getContext("2d");if(!s)throw new Error("resolveContext2d - canvas 2d context is null");return s}var bs;(function(s){s.TOP_LEFT="TOP_LEFT",s.TOP_RIGHT="TOP_RIGHT",s.BOTTOM_LEFT="BOTTOM_LEFT",s.BOTTOM_RIGHT="BOTTOM_RIGHT"})(bs||(bs={}));var Jd=class{constructor(t={}){let{anchorPosition:n,backgroundColor:r,fontColor:s,fontSize:a,fontStyle:o,padding:i}=t;this.anchorPosition=n||bs.TOP_LEFT,this.backgroundColor=r||"rgba(0, 0, 0, 0.5)",this.fontColor=s||"rgba(255, 255, 255, 1)",this.fontSize=a||14,this.fontStyle=o||"Georgia",this.padding=i||4}},_a=class{constructor(t,n,r={}){this.text=typeof t=="string"?[t]:t instanceof _a?t.text:t,this.anchor=n,this.options=new Jd(r)}measureWidth(t){let{padding:n}=this.options;return this.text.map(r=>t.measureText(r).width).reduce((r,s)=>r<s?s:r,0)+2*n}measureHeight(){let{fontSize:t,padding:n}=this.options;return this.text.length*t+2*n}getUpperLeft(t,n){let{anchorPosition:r}=this.options,s=r===bs.BOTTOM_RIGHT||r===bs.TOP_RIGHT,a=r===bs.BOTTOM_LEFT||r===bs.BOTTOM_RIGHT,o=this.measureWidth(t),i=this.measureHeight(),c=s?this.anchor.x-o:this.anchor.x,l=a?this.anchor.y-i:this.anchor.y;if(n){let{width:u,height:d}=n,p=Math.max(Math.min(c,u-o),0),h=Math.max(Math.min(l,d-i),0);return{x:p,y:h}}return{x:c,y:l}}draw(t){let n=Si(t),r=Un(n),{backgroundColor:s,fontColor:a,fontSize:o,fontStyle:i,padding:c}=this.options;r.font=`${o}px ${i}`;let l=this.measureWidth(r),u=this.measureHeight();r.fillStyle=s;let d=this.getUpperLeft(r,n);r.fillRect(d.x,d.y,l,u),r.fillStyle=a,this.text.forEach((p,h)=>{let f=c+d.x,m=c+d.y+(h+1)*o;r.fillText(p,f,m)})}};var b0=class{constructor(t={}){let{boxColor:n,lineWidth:r,label:s,drawLabelOptions:a}=t;this.boxColor=n||"rgba(0, 0, 255, 1)",this.lineWidth=r||2,this.label=s;let o={anchorPosition:bs.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Jd({...o,...a})}},Pm=class{constructor(t,n={}){this.box=new ut(t),this.options=new b0(n)}draw(t){let n=Un(t),{boxColor:r,lineWidth:s}=this.options,{x:a,y:o,width:i,height:c}=this.box;n.strokeStyle=r,n.lineWidth=s,n.strokeRect(a,o,i,c);let{label:l}=this.options;l&&new _a([l],{x:a-s/2,y:o},this.options.drawLabelOptions).draw(t)}};function ice(e,t){(Array.isArray(t)?t:[t]).forEach(r=>{let s=r instanceof vt?r.score:gs(r)?r.detection.score:void 0,a=r instanceof vt?r.box:gs(r)?r.detection.box:new ut(r),o=s?`${wi(s)}`:void 0;new Pm(a,{label:o}).draw(e)})}function Qd(e){let{Image:t,Video:n}=Je.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function y0(e){return new Promise((t,n)=>{if(e instanceof Je.getEnv().Canvas||Qd(e))return t(null);function r(a){!a.currentTarget||(a.currentTarget.removeEventListener("load",s),a.currentTarget.removeEventListener("error",r),n(a))}function s(a){!a.currentTarget||(a.currentTarget.removeEventListener("load",s),a.currentTarget.removeEventListener("error",r),t(a))}e.addEventListener("load",s),e.addEventListener("error",r)})}function v0(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToImage - expected buf to be of type: Blob"));let r=new FileReader;r.onload=()=>{typeof r.result!="string"&&n(new Error("bufferToImage - expected reader.result to be a string, in onload"));let s=Je.getEnv().createImageElement();s.onload=()=>t(s),s.onerror=n,s.src=r.result},r.onerror=n,r.readAsDataURL(e)})}function Ci(e){let{Image:t,Video:n}=Je.getEnv();return e instanceof t?new An(e.naturalWidth,e.naturalHeight):e instanceof n?new An(e.videoWidth,e.videoHeight):new An(e.width,e.height)}function Ti({width:e,height:t}){let{createCanvasElement:n}=Je.getEnv(),r=n();return r.width=e,r.height=t,r}function ep(e,t){let{ImageData:n}=Je.getEnv();if(!(e instanceof n)&&!Qd(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:r,height:s}=t||Ci(e),a=Ti({width:r,height:s});return e instanceof n?Un(a).putImageData(e,0,0):Un(a).drawImage(e,0,0,r,s),a}async function x0(e,t){let n=t||Je.getEnv().createCanvasElement(),[r,s,a]=e.shape.slice(mr(e)?1:0),o=M(()=>e.as3D(r,s,a).toInt());return await Go.toPixels(o,n),o.dispose(),n}function Om(e){let{Image:t,Canvas:n,Video:r}=Je.getEnv();return e instanceof t||e instanceof n||e instanceof r}function w0(e,t,n=!1){let{Image:r,Canvas:s}=Je.getEnv();if(!(e instanceof r||e instanceof s))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return Ti({width:1,height:1});let a=Ci(e),o=t/Math.max(a.height,a.width),i=o*a.width,c=o*a.height,l=Ti({width:t,height:t}),u=e instanceof s?e:ep(e),d=Math.abs(i-c)/2,p=n&&i<c?d:0,h=n&&c<i?d:0;return u.width>0&&u.height>0&&Un(l).drawImage(u,p,h,i,c),l}var Bs=class{constructor(t,n=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];this._inputSize=0;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((r,s)=>{if(Ms(r)){this._imageTensors[s]=r,this._inputDimensions[s]=r.shape;return}if(mr(r)){let o=r.shape[0];if(o!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${o} passed, but not supported in input array`);this._imageTensors[s]=r,this._inputDimensions[s]=r.shape.slice(1);return}let a=r instanceof Je.getEnv().Canvas?r:ep(r);this._canvases[s]=a,this._inputDimensions[s]=[a.height,a.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 ms(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),r=this.getInputHeight(t);return a0({width:n,height:r},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,M(()=>{let r=ms(this.batchSize,0,1).map(a=>{let o=this.getInput(a);if(o instanceof Ee){let i=mr(o)?o:bn(o);return i=l0(i,n),(i.shape[1]!==t||i.shape[2]!==t)&&(i=Qn.resizeBilinear(i,[t,t],!1,!1)),i.as3D(t,t,3)}if(o instanceof Je.getEnv().Canvas)return Go.fromPixels(w0(o,t,n));throw new Error(`toBatchTensor - at batchIdx ${a}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${o}`)});return Ot(r.map(a=>ce(a,"float32"))).as4D(this.batchSize,t,t,3)})}};async function mt(e){if(e instanceof Bs)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");let n=s=>Array.isArray(e)?` at input index ${s}:`:"",r=t.map(Si);return r.forEach((s,a)=>{if(!Om(s)&&!Ms(s)&&!mr(s))throw typeof t[a]=="string"?new Error(`toNetInput -${n(a)} string passed, but could not resolve HTMLElement for element id ${t[a]}`):new Error(`toNetInput -${n(a)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(mr(s)){let o=s.shape[0];if(o!==1)throw new Error(`toNetInput -${n(a)} tf.Tensor4D with batchSize ${o} passed, but not supported in input array`)}}),await Promise.all(r.map(s=>Om(s)&&y0(s))),new Bs(r,Array.isArray(e))}async function Wu(e,t){let{Canvas:n}=Je.getEnv(),r=e;if(!(e instanceof n)){let o=await mt(e);if(o.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let i=o.getInput(0);r=i instanceof n?i:await x0(i)}let s=Un(r);return t.map(o=>o instanceof vt?o.forSize(r.width,r.height).box.floor():o).map(o=>o.clipAtImageBorders(r.width,r.height)).map(({x:o,y:i,width:c,height:l})=>{let u=Ti({width:c,height:l});return c>0&&l>0&&Un(u).putImageData(s.getImageData(o,i,c,l),0,0),u})}async function Vu(e,t){if(!Ms(e)&&!mr(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(mr(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return M(()=>{let[n,r,s]=e.shape.slice(mr(e)?1:0);return t.map(i=>i instanceof vt?i.forSize(r,n).box:i).map(i=>i.clipAtImageBorders(r,n)).map(({x:i,y:c,width:l,height:u})=>uu(e.as3D(n,r,s),[c,i,0],[u,l,s]))})}async function zs(e,t){let{fetch:n}=Je.getEnv(),r=await n(e,t);if(!(r.status<400))throw new Error(`failed to fetch: (${r.status}) ${r.statusText}, from url: ${r.url}`);return r}async function cce(e){let t=await zs(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 v0(n)}async function k0(e){return(await zs(e)).json()}async function uce(e){return new Float32Array(await(await zs(e)).arrayBuffer())}function bE(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToVideo - expected buf to be of type: Blob"));let r=Je.getEnv().createVideoElement();r.oncanplay=()=>t(r),r.onerror=n,r.playsInline=!0,r.muted=!0,r.src=URL.createObjectURL(e),r.play()})}async function lce(e){let t=await zs(e),n=await t.blob();if(!n.type.startsWith("video/"))throw new Error(`fetchVideo - expected blob type to be of type video/*, instead have: ${n.type}, for url: ${t.url}`);return bE(n)}function Mm(e,t){let n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};let r=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(r,"");let s=e.split("/").filter(i=>i),a=e.endsWith(".json")?s[s.length-1]:n,o=r+(e.endsWith(".json")?s.slice(0,s.length-1):s).join("/");return o=e.startsWith("/")?`/${o}`:o,{modelBaseUri:o,manifestUri:o==="/"?`/${a}`:`${o}/${a}`}}async function I0(e,t){let{manifestUri:n,modelBaseUri:r}=Mm(e,t),s=await k0(n);return Zt.loadWeights(s,r)}function dce(e,t,n=!1){let{width:r,height:s}=n?Ci(t):t;return e.width=r,e.height=s,{width:r,height:s}}var pn=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:r}=this.traversePropertyPath(t);return n[r]}reassignParamFromPath(t,n){let{obj:r,objProp:s}=this.traversePropertyPath(t);r[s].dispose(),r[s]=n}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof sa)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof sa))}variable(){this.getFrozenParams().forEach(({path:t,tensor:n})=>{this.reassignParamFromPath(t,n.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:n})=>{let r=qn(n.dataSync());n.dispose(),this.reassignParamFromPath(t,r)})}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 I0(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}=Je.getEnv(),{manifestUri:r,modelBaseUri:s}=Mm(t,this.getDefaultModelName()),a=l=>Promise.all(l.map(u=>n(u).then(d=>d.buffer))),o=Zt.weightsLoaderFactory(a),i=JSON.parse((await n(r)).toString()),c=await o(i,s);this.loadFromWeightMap(c)}loadFromWeightMap(t){let{paramMappings:n,params:r}=this.extractParamsFromWeightMap(t);this._paramMappings=n,this._params=r}extractWeights(t){let{paramMappings:n,params:r}=this.extractParams(t);this._paramMappings=n,this._params=r}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let n=t.split("/").reduce((a,o)=>{if(!a.nextObj.hasOwnProperty(o))throw new Error(`traversePropertyPath - object does not have property ${o}, for path ${t}`);return{obj:a.nextObj,objProp:o,nextObj:a.nextObj[o]}},{nextObj:this.params}),{obj:r,objProp:s}=n;if(!r||!s||!(r[s]instanceof Ee))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:r,objProp:s}}};function Gn(e,t,n){return M(()=>{let r=Qo(e,t.depthwise_filter,t.pointwise_filter,n,"same");return r=Y(r,t.bias),r})}function Lm(e,t,n=!1){return M(()=>{let r=je(n?Y(Rt(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Gn(e,t.conv0,[2,2])),s=Gn(r,t.conv1,[1,1]),a=je(Y(r,s)),o=Gn(a,t.conv2,[1,1]);return je(Y(r,Y(s,o)))})}function tp(e,t,n=!1,r=!0){return M(()=>{let s=je(n?Y(Rt(e,t.conv0.filters,r?[2,2]:[1,1],"same"),t.conv0.bias):Gn(e,t.conv0,r?[2,2]:[1,1])),a=Gn(s,t.conv1,[1,1]),o=je(Y(s,a)),i=Gn(o,t.conv2,[1,1]),c=je(Y(s,Y(a,i))),l=Gn(c,t.conv3,[1,1]);return je(Y(s,Y(a,Y(i,l))))})}function Ni(e,t,n="same",r=!1){return M(()=>{let s=Y(Rt(e,t.filters,[1,1],n),t.bias);return r?je(s):s})}function Dn(e,t){Object.keys(e).forEach(n=>{t.some(r=>r.originalPath===n)||e[n].dispose()})}function Uu(e,t){return(n,r,s,a)=>{let o=Mr(e(n*r*s*s),[s,s,n,r]),i=Ge(e(r));return t.push({paramPath:`${a}/filters`},{paramPath:`${a}/bias`}),{filters:o,bias:i}}}function Bm(e,t){return(n,r,s)=>{let a=Or(e(n*r),[n,r]),o=Ge(e(r));return t.push({paramPath:`${s}/weights`},{paramPath:`${s}/bias`}),{weights:a,bias:o}}}var zm=class{constructor(t,n,r){this.depthwise_filter=t;this.pointwise_filter=n;this.bias=r}};function Gu(e,t){return(n,r,s)=>{let a=Mr(e(3*3*n),[3,3,n,1]),o=Mr(e(n*r),[1,1,n,r]),i=Ge(e(r));return t.push({paramPath:`${s}/depthwise_filter`},{paramPath:`${s}/pointwise_filter`},{paramPath:`${s}/bias`}),new zm(a,o,i)}}function Hu(e){return t=>{let n=e(`${t}/depthwise_filter`,4),r=e(`${t}/pointwise_filter`,4),s=e(`${t}/bias`,1);return new zm(n,r,s)}}function sr(e,t){return(n,r,s)=>{let a=e[n];if(!xi(a,r))throw new Error(`expected weightMap[${n}] to be a Tensor${r}D, instead have ${a}`);return t.push({originalPath:n,paramPath:s||n}),a}}function Fn(e){let t=e;function n(s){let a=t.slice(0,s);return t=t.slice(s),a}function r(){return t}return{extractWeights:n,getRemainingWeights:r}}function Wm(e,t){let n=Uu(e,t),r=Gu(e,t);function s(o,i,c,l=!1){let u=l?n(o,i,3,`${c}/conv0`):r(o,i,`${c}/conv0`),d=r(i,i,`${c}/conv1`),p=r(i,i,`${c}/conv2`);return{conv0:u,conv1:d,conv2:p}}function a(o,i,c,l=!1){let{conv0:u,conv1:d,conv2:p}=s(o,i,c,l),h=r(i,i,`${c}/conv3`);return{conv0:u,conv1:d,conv2:p,conv3:h}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:a}}function yE(e){let t=[],{extractWeights:n,getRemainingWeights:r}=Fn(e),{extractDenseBlock4Params:s}=Wm(n,t),a=s(3,32,"dense0",!0),o=s(32,64,"dense1"),i=s(64,128,"dense2"),c=s(128,256,"dense3");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:a,dense1:o,dense2:i,dense3:c}}}function Vm(e){return t=>{let n=e(`${t}/filters`,4),r=e(`${t}/bias`,1);return{filters:n,bias:r}}}function Um(e,t){let n=sr(e,t),r=Vm(n),s=Hu(n);function a(i,c=!1){let l=c?r(`${i}/conv0`):s(`${i}/conv0`),u=s(`${i}/conv1`),d=s(`${i}/conv2`);return{conv0:l,conv1:u,conv2:d}}function o(i,c=!1){let l=c?r(`${i}/conv0`):s(`${i}/conv0`),u=s(`${i}/conv1`),d=s(`${i}/conv2`),p=s(`${i}/conv3`);return{conv0:l,conv1:u,conv2:d,conv3:p}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:o}}function vE(e){let t=[],{extractDenseBlock4Params:n}=Um(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return Dn(e,t),{params:r,paramMappings:t}}var np=class extends pn{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return M(()=>{let r=ce(t.toBatchTensor(112,!0),"float32"),a=Kr(r,[122.782,117.001,104.298]).div(255),o=tp(a,n.dense0,!0);return o=tp(o,n.dense1),o=tp(o,n.dense2),o=tp(o,n.dense3),o=ir(o,[7,7],[2,2],"valid"),o})}async forward(t){return this.forwardInput(await mt(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return vE(t)}extractParams(t){return yE(t)}};function rp(e,t){return M(()=>Y(Ae(e,t.weights),t.bias))}function xE(e,t,n){let r=[],{extractWeights:s,getRemainingWeights:a}=Fn(e),i=Bm(s,r)(t,n,"fc");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:r,params:{fc:i}}}function wE(e){let t=[],n=sr(e,t);function r(a){let o=n(`${a}/weights`,2),i=n(`${a}/bias`,1);return{weights:o,bias:i}}let s={fc:r("fc")};return Dn(e,t),{params:s,paramMappings:t}}function Gm(e){let t={},n={};return Object.keys(e).forEach(r=>{let s=r.startsWith("fc")?n:t;s[r]=e[r]}),{featureExtractorMap:t,classifierMap:n}}var sp=class extends pn{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 M(()=>{let r=t instanceof Bs?this.faceFeatureExtractor.forwardInput(t):t;return rp(r.as2D(r.shape[0],-1),n.fc)})}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:r}=this.extractClassifierParams(t);this._params=n,this._paramMappings=r}extractClassifierParams(t){return xE(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:r}=Gm(t);return this.faceFeatureExtractor.loadFromWeightMap(n),wE(r)}extractParams(t){let n=this.getClassifierChannelsIn(),r=this.getClassifierChannelsOut(),s=r*n+r,a=t.slice(0,t.length-s),o=t.slice(t.length-s);return this.faceFeatureExtractor.extractWeights(a),this.extractClassifierParams(o)}};var S0=["neutral","happy","sad","angry","fearful","disgusted","surprised"],Ea=class{constructor(t){this.neutral=0;this.happy=0;this.sad=0;this.angry=0;this.fearful=0;this.disgusted=0;this.surprised=0;if(t.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${t.length}`);S0.forEach((n,r)=>{this[n]=t[r]})}asSortedArray(){return S0.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var Hm=class extends sp{constructor(t=new np){super("FaceExpressionNet",t)}forwardInput(t){return M(()=>Pr(this.runNet(t)))}async forward(t){return this.forwardInput(await mt(t))}async predictExpressions(t){let n=await mt(t),r=await this.forwardInput(n),s=await Promise.all(dt(r).map(async o=>{let i=o.dataSync();return o.dispose(),i}));r.dispose();let a=s.map(o=>new Ea(o));return n.isBatchInput?a:a[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function C0(e){return e.expressions instanceof Ea}function jm(e,t){return{...e,...{expressions:t}}}function pce(e,t,n=.1,r){(Array.isArray(t)?t:[t]).forEach(a=>{let o=a instanceof Ea?a:C0(a)?a.expressions:void 0;if(!o)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let c=o.asSortedArray().filter(d=>d.probability>n),l=gs(a)?a.detection.box.bottomLeft:r||new Pe(0,0);new _a(c.map(d=>`${d.expression} (${wi(d.probability)})`),l).draw(e)})}function _i(e){return gs(e)&&e.landmarks instanceof gr&&e.unshiftedLandmarks instanceof gr&&e.alignedRect instanceof vt}function hce(e){let t=(i,c,l,u)=>Math.atan2(u-c,l-i)%Math.PI,n=i=>i*180/Math.PI,r={roll:void 0,pitch:void 0,yaw:void 0};if(!e||!e._positions||e._positions.length!==68)return r;let s=e._positions;r.roll=-t(s[36]._x,s[36]._y,s[45]._x,s[45]._y),r.pitch=t(0,Math.abs(s[0]._x-s[30]._x)/s[30]._x,Math.PI,Math.abs(s[16]._x-s[30]._x)/s[30]._x);let a=s.reduce((i,c)=>i<c._y?i:c._y,1/0),o=s.reduce((i,c)=>i>c._y?i:c._y,-1/0);return r.yaw=Math.PI*(e._imgDims._height/(o-a)/1.4-1),r}function ju(e,t){let{box:n}=e.detection,r=t.shiftBy(n.x,n.y),s=r.align(),{imageDims:a}=e.detection,o=new vt(e.detection.score,s.rescale(a.reverse()),a),i=hce(t);return{...e,...{landmarks:r,unshiftedLandmarks:t,alignedRect:o,angle:i}}}var T0=class{constructor(t={}){let{drawLines:n=!0,drawPoints:r=!0,lineWidth:s,lineColor:a,pointSize:o,pointColor:i}=t;this.drawLines=n,this.drawPoints=r,this.lineWidth=s||1,this.pointSize=o||2,this.lineColor=a||"rgba(0, 255, 255, 1)",this.pointColor=i||"rgba(255, 0, 255, 1)"}},N0=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new T0(n)}draw(t){let n=Un(t),{drawLines:r,drawPoints:s,lineWidth:a,lineColor:o,pointSize:i,pointColor:c}=this.options;if(r&&this.faceLandmarks instanceof zu&&(n.strokeStyle=o,n.lineWidth=a,Os(n,this.faceLandmarks.getJawOutline()),Os(n,this.faceLandmarks.getLeftEyeBrow()),Os(n,this.faceLandmarks.getRightEyeBrow()),Os(n,this.faceLandmarks.getNose()),Os(n,this.faceLandmarks.getLeftEye(),!0),Os(n,this.faceLandmarks.getRightEye(),!0),Os(n,this.faceLandmarks.getMouth(),!0)),s){n.strokeStyle=c,n.fillStyle=c;let l=u=>{n.beginPath(),n.arc(u.x,u.y,i,0,2*Math.PI),n.fill()};this.faceLandmarks.positions.forEach(l)}}};function fce(e,t){(Array.isArray(t)?t:[t]).forEach(r=>{let s=r instanceof gr?r:_i(r)?r.landmarks:void 0;if(!s)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new N0(s).draw(e)})}var kE="1.5.6";function gce(e,t){let n=Uu(e,t),r=Gu(e,t);function s(o,i,c){let l=r(o,i,`${c}/separable_conv0`),u=r(i,i,`${c}/separable_conv1`),d=n(o,i,1,`${c}/expansion_conv`);return{separable_conv0:l,separable_conv1:u,expansion_conv:d}}function a(o,i){let c=r(o,o,`${i}/separable_conv0`),l=r(o,o,`${i}/separable_conv1`),u=r(o,o,`${i}/separable_conv2`);return{separable_conv0:c,separable_conv1:l,separable_conv2:u}}return{extractConvParams:n,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:a}}function IE(e,t){let n=[],{extractWeights:r,getRemainingWeights:s}=Fn(e),{extractConvParams:a,extractSeparableConvParams:o,extractReductionBlockParams:i,extractMainBlockParams:c}=gce(r,n),l=a(3,32,3,"entry_flow/conv_in"),u=i(32,64,"entry_flow/reduction_block_0"),d=i(64,128,"entry_flow/reduction_block_1"),p={conv_in:l,reduction_block_0:u,reduction_block_1:d},h={};ms(t,0,1).forEach(b=>{h[`main_block_${b}`]=c(128,`middle_flow/main_block_${b}`)});let f=i(128,256,"exit_flow/reduction_block"),m=o(256,512,"exit_flow/separable_conv"),g={reduction_block:f,separable_conv:m};if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:n,params:{entry_flow:p,middle_flow:h,exit_flow:g}}}function bce(e,t){let n=sr(e,t),r=Vm(n),s=Hu(n);function a(i){let c=s(`${i}/separable_conv0`),l=s(`${i}/separable_conv1`),u=r(`${i}/expansion_conv`);return{separable_conv0:c,separable_conv1:l,expansion_conv:u}}function o(i){let c=s(`${i}/separable_conv0`),l=s(`${i}/separable_conv1`),u=s(`${i}/separable_conv2`);return{separable_conv0:c,separable_conv1:l,separable_conv2:u}}return{extractConvParams:r,extractSeparableConvParams:s,extractReductionBlockParams:a,extractMainBlockParams:o}}function SE(e,t){let n=[],{extractConvParams:r,extractSeparableConvParams:s,extractReductionBlockParams:a,extractMainBlockParams:o}=bce(e,n),i=r("entry_flow/conv_in"),c=a("entry_flow/reduction_block_0"),l=a("entry_flow/reduction_block_1"),u={conv_in:i,reduction_block_0:c,reduction_block_1:l},d={};ms(t,0,1).forEach(m=>{d[`main_block_${m}`]=o(`middle_flow/main_block_${m}`)});let p=a("exit_flow/reduction_block"),h=s("exit_flow/separable_conv"),f={reduction_block:p,separable_conv:h};return Dn(e,n),{params:{entry_flow:u,middle_flow:d,exit_flow:f},paramMappings:n}}function CE(e,t,n){return Y(Rt(e,t.filters,n,"same"),t.bias)}function E0(e,t,n=!0){let r=n?je(e):e;return r=Gn(r,t.separable_conv0,[1,1]),r=Gn(je(r),t.separable_conv1,[1,1]),r=Pt(r,[3,3],[2,2],"same"),r=Y(r,CE(e,t.expansion_conv,[2,2])),r}function yce(e,t){let n=Gn(je(e),t.separable_conv0,[1,1]);return n=Gn(je(n),t.separable_conv1,[1,1]),n=Gn(je(n),t.separable_conv2,[1,1]),n=Y(n,e),n}var A0=class extends pn{constructor(t){super("TinyXception");this._numMainBlocks=t}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyXception - load model before inference");return M(()=>{let r=ce(t.toBatchTensor(112,!0),"float32"),a=Kr(r,[122.782,117.001,104.298]).div(255),o=je(CE(a,n.entry_flow.conv_in,[2,2]));return o=E0(o,n.entry_flow.reduction_block_0,!1),o=E0(o,n.entry_flow.reduction_block_1),ms(this._numMainBlocks,0,1).forEach(i=>{o=yce(o,n.middle_flow[`main_block_${i}`])}),o=E0(o,n.exit_flow.reduction_block),o=je(Gn(o,n.exit_flow.separable_conv,[1,1])),o})}async forward(t){return this.forwardInput(await mt(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return SE(t,this._numMainBlocks)}extractParams(t){return IE(t,this._numMainBlocks)}};function TE(e){let t=[],{extractWeights:n,getRemainingWeights:r}=Fn(e),s=Bm(n,t),a=s(512,1,"fc/age"),o=s(512,2,"fc/gender");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{fc:{age:a,gender:o}}}}function NE(e){let t=[],n=sr(e,t);function r(a){let o=n(`${a}/weights`,2),i=n(`${a}/bias`,1);return{weights:o,bias:i}}let s={fc:{age:r("fc/age"),gender:r("fc/gender")}};return Dn(e,t),{params:s,paramMappings:t}}var Ws;(function(n){n.FEMALE="female",n.MALE="male"})(Ws||(Ws={}));var qm=class extends pn{constructor(t=new A0(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 M(()=>{let r=t instanceof Bs?this.faceFeatureExtractor.forwardInput(t):t,s=ir(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1),a=rp(s,n.fc.age).as1D(),o=rp(s,n.fc.gender);return{age:a,gender:o}})}forwardInput(t){return M(()=>{let{age:n,gender:r}=this.runNet(t);return{age:n,gender:Pr(r)}})}async forward(t){return this.forwardInput(await mt(t))}async predictAgeAndGender(t){let n=await mt(t),r=await this.forwardInput(n),s=dt(r.age),a=dt(r.gender),o=s.map((c,l)=>({ageTensor:c,genderTensor:a[l]})),i=await Promise.all(o.map(async({ageTensor:c,genderTensor:l})=>{let u=c.dataSync()[0],d=l.dataSync()[0],p=d>.5,h=p?Ws.MALE:Ws.FEMALE,f=p?d:1-d;return c.dispose(),l.dispose(),{age:u,gender:h,genderProbability:f}}));return r.age.dispose(),r.gender.dispose(),n.isBatchInput?i:i[0]}getDefaultModelName(){return"age_gender_model"}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:r}=this.extractClassifierParams(t);this._params=n,this._paramMappings=r}extractClassifierParams(t){return TE(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:r}=Gm(t);return this.faceFeatureExtractor.loadFromWeightMap(n),NE(r)}extractParams(t){let n=512*1+1+(512*2+2),r=t.slice(0,t.length-n),s=t.slice(t.length-n);return this.faceFeatureExtractor.extractWeights(r),this.extractClassifierParams(s)}};var ap=class extends sp{postProcess(t,n,r){let s=r.map(({width:o,height:i})=>{let c=n/Math.max(i,o);return{width:o*c,height:i*c}}),a=s.length;return M(()=>{let o=(d,p)=>Ot([In([68],d,"float32"),In([68],p,"float32")],1).as2D(1,136).as1D(),i=(d,p)=>{let{width:h,height:f}=s[d];return p(h,f)?Math.abs(h-f)/2:0},c=d=>i(d,(p,h)=>p<h),l=d=>i(d,(p,h)=>h<p);return t.mul(In([a,136],n,"float32")).sub(Ot(Array.from(Array(a),(d,p)=>o(c(p),l(p))))).div(Ot(Array.from(Array(a),(d,p)=>o(s[p].width,s[p].height))))})}forwardInput(t){return M(()=>{let n=this.runNet(t);return this.postProcess(n,t.inputSize,t.inputDimensions.map(([r,s])=>({height:r,width:s})))})}async forward(t){return this.forwardInput(await mt(t))}async detectLandmarks(t){let n=await mt(t),r=M(()=>dt(this.forwardInput(n))),s=await Promise.all(r.map(async(a,o)=>{let i=Array.from(a.dataSync()),c=i.filter((u,d)=>Fm(d)),l=i.filter((u,d)=>!Fm(d));return new zu(Array(68).fill(0).map((u,d)=>new Pe(c[d],l[d])),{height:n.getInputHeight(o),width:n.getInputWidth(o)})}));return r.forEach(a=>a.dispose()),n.isBatchInput?s:s[0]}getClassifierChannelsOut(){return 136}};var qu=class extends ap{constructor(t=new np){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function _E(e){let t=[],{extractDenseBlock3Params:n}=Um(e,t),r={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return Dn(e,t),{params:r,paramMappings:t}}function EE(e){let t=[],{extractWeights:n,getRemainingWeights:r}=Fn(e),{extractDenseBlock3Params:s}=Wm(n,t),a=s(3,32,"dense0",!0),o=s(32,64,"dense1"),i=s(64,128,"dense2");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:t,params:{dense0:a,dense1:o,dense2:i}}}var D0=class extends pn{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return M(()=>{let r=ce(t.toBatchTensor(112,!0),"float32"),a=Kr(r,[122.782,117.001,104.298]).div(255),o=Lm(a,n.dense0,!0);return o=Lm(o,n.dense1),o=Lm(o,n.dense2),o=ir(o,[14,14],[2,2],"valid"),o})}async forward(t){return this.forwardInput(await mt(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return _E(t)}extractParams(t){return EE(t)}};var Km=class extends ap{constructor(t=new D0){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var AE=class extends qu{};function DE(e,t){return Y(V(e,t.weights),t.biases)}function F0(e,t,n,r,s="same"){let{filters:a,bias:o}=t.conv,i=Rt(e,a,n,s);return i=Y(i,o),i=DE(i,t.scale),r?je(i):i}function FE(e,t){return F0(e,t,[1,1],!0)}function $0(e,t){return F0(e,t,[1,1],!1)}function Xm(e,t){return F0(e,t,[2,2],!0,"valid")}function vce(e,t){function n(i,c,l){let u=e(i),d=u.length/(c*l*l);if(s0(d))throw new Error(`depth has to be an integer: ${d}, weights.length: ${u.length}, numFilters: ${c}, filterSize: ${l}`);return M(()=>Re(Mr(u,[c,d,l,l]),[2,3,1,0]))}function r(i,c,l,u){let d=n(i,c,l),p=Ge(e(c));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/bias`}),{filters:d,bias:p}}function s(i,c){let l=Ge(e(i)),u=Ge(e(i));return t.push({paramPath:`${c}/weights`},{paramPath:`${c}/biases`}),{weights:l,biases:u}}function a(i,c,l,u){let d=r(i,c,l,`${u}/conv`),p=s(c,`${u}/scale`);return{conv:d,scale:p}}function o(i,c,l,u,d=!1){let p=a((d?.5:1)*i,c,l,`${u}/conv1`),h=a(i,c,l,`${u}/conv2`);return{conv1:p,conv2:h}}return{extractConvLayerParams:a,extractResidualLayerParams:o}}function $E(e){let{extractWeights:t,getRemainingWeights:n}=Fn(e),r=[],{extractConvLayerParams:s,extractResidualLayerParams:a}=vce(t,r),o=s(4704,32,7,"conv32_down"),i=a(9216,32,3,"conv32_1"),c=a(9216,32,3,"conv32_2"),l=a(9216,32,3,"conv32_3"),u=a(36864,64,3,"conv64_down",!0),d=a(36864,64,3,"conv64_1"),p=a(36864,64,3,"conv64_2"),h=a(36864,64,3,"conv64_3"),f=a(147456,128,3,"conv128_down",!0),m=a(147456,128,3,"conv128_1"),g=a(147456,128,3,"conv128_2"),b=a(589824,256,3,"conv256_down",!0),y=a(589824,256,3,"conv256_1"),v=a(589824,256,3,"conv256_2"),x=a(589824,256,3,"conv256_down_out"),k=M(()=>Re(Or(t(256*128),[128,256]),[1,0]));if(r.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{conv32_down:o,conv32_1:i,conv32_2:c,conv32_3:l,conv64_down:u,conv64_1:d,conv64_2:p,conv64_3:h,conv128_down:f,conv128_1:m,conv128_2:g,conv256_down:b,conv256_1:y,conv256_2:v,conv256_down_out:x,fc:k},paramMappings:r}}function xce(e,t){let n=sr(e,t);function r(o){let i=n(`${o}/scale/weights`,1),c=n(`${o}/scale/biases`,1);return{weights:i,biases:c}}function s(o){let i=n(`${o}/conv/filters`,4),c=n(`${o}/conv/bias`,1),l=r(o);return{conv:{filters:i,bias:c},scale:l}}function a(o){return{conv1:s(`${o}/conv1`),conv2:s(`${o}/conv2`)}}return{extractConvLayerParams:s,extractResidualLayerParams:a}}function RE(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:r}=xce(e,t),s=n("conv32_down"),a=r("conv32_1"),o=r("conv32_2"),i=r("conv32_3"),c=r("conv64_down"),l=r("conv64_1"),u=r("conv64_2"),d=r("conv64_3"),p=r("conv128_down"),h=r("conv128_1"),f=r("conv128_2"),m=r("conv256_down"),g=r("conv256_1"),b=r("conv256_2"),y=r("conv256_down_out"),{fc:v}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!r0(v))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${v}`);let x={conv32_down:s,conv32_1:a,conv32_2:o,conv32_3:i,conv64_down:c,conv64_1:l,conv64_2:u,conv64_3:d,conv128_down:p,conv128_1:h,conv128_2:f,conv256_down:m,conv256_1:g,conv256_2:b,conv256_down_out:y,fc:v};return Dn(e,t),{params:x,paramMappings:t}}function Xr(e,t){let n=FE(e,t.conv1);return n=$0(n,t.conv2),n=Y(n,e),n=je(n),n}function op(e,t){let n=Xm(e,t.conv1);n=$0(n,t.conv2);let r=ir(e,2,2,"valid"),s=St(r.shape),a=r.shape[3]!==n.shape[3];if(r.shape[1]!==n.shape[1]||r.shape[2]!==n.shape[2]){let i=[...n.shape];i[1]=1;let c=St(i);n=Ze([n,c],1);let l=[...n.shape];l[2]=1;let u=St(l);n=Ze([n,u],2)}return r=a?Ze([r,s],3):r,n=Y(r,n),n=je(n),n}var Ku=class extends pn{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return M(()=>{let r=ce(t.toBatchTensor(150,!0),"float32"),a=Kr(r,[122.782,117.001,104.298]).div(255),o=Xm(a,n.conv32_down);o=Pt(o,3,2,"valid"),o=Xr(o,n.conv32_1),o=Xr(o,n.conv32_2),o=Xr(o,n.conv32_3),o=op(o,n.conv64_down),o=Xr(o,n.conv64_1),o=Xr(o,n.conv64_2),o=Xr(o,n.conv64_3),o=op(o,n.conv128_down),o=Xr(o,n.conv128_1),o=Xr(o,n.conv128_2),o=op(o,n.conv256_down),o=Xr(o,n.conv256_1),o=Xr(o,n.conv256_2),o=op(o,n.conv256_down_out);let i=o.mean([1,2]);return Ae(i,n.fc)})}async forward(t){return this.forwardInput(await mt(t))}async computeFaceDescriptor(t){var a;if((a=t==null?void 0:t.shape)==null?void 0:a.some(o=>o<=0))return new Float32Array(128);let n=await mt(t),r=M(()=>dt(this.forwardInput(n))),s=await Promise.all(r.map(o=>o.data()));return r.forEach(o=>o.dispose()),n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(t){return RE(t)}extractParams(t){return $E(t)}};function wce(e){let t=new Ku;return t.extractWeights(e),t}function Ym(e,t){return{...e,...{descriptor:t}}}function kce(e){return typeof e.age=="number"}function Zm(e,t){return{...e,...{age:t}}}function Ice(e){return(e.gender===Ws.MALE||e.gender===Ws.FEMALE)&&Mu(e.genderProbability)}function Jm(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function Sce(e,t){function n(c,l){let u=Mr(e(3*3*c),[3,3,c,1]),d=Ge(e(c)),p=Ge(e(c)),h=Ge(e(c)),f=Ge(e(c));return t.push({paramPath:`${l}/filters`},{paramPath:`${l}/batch_norm_scale`},{paramPath:`${l}/batch_norm_offset`},{paramPath:`${l}/batch_norm_mean`},{paramPath:`${l}/batch_norm_variance`}),{filters:u,batch_norm_scale:d,batch_norm_offset:p,batch_norm_mean:h,batch_norm_variance:f}}function r(c,l,u,d,p){let h=Mr(e(c*l*u*u),[u,u,c,l]),f=Ge(e(l));return t.push({paramPath:`${d}/filters`},{paramPath:`${d}/${p?"batch_norm_offset":"bias"}`}),{filters:h,bias:f}}function s(c,l,u,d){let{filters:p,bias:h}=r(c,l,u,d,!0);return{filters:p,batch_norm_offset:h}}function a(c,l,u){let d=n(c,`${u}/depthwise_conv`),p=s(c,l,1,`${u}/pointwise_conv`);return{depthwise_conv:d,pointwise_conv:p}}function o(){let c=s(3,32,3,"mobilenetv1/conv_0"),l=a(32,64,"mobilenetv1/conv_1"),u=a(64,128,"mobilenetv1/conv_2"),d=a(128,128,"mobilenetv1/conv_3"),p=a(128,256,"mobilenetv1/conv_4"),h=a(256,256,"mobilenetv1/conv_5"),f=a(256,512,"mobilenetv1/conv_6"),m=a(512,512,"mobilenetv1/conv_7"),g=a(512,512,"mobilenetv1/conv_8"),b=a(512,512,"mobilenetv1/conv_9"),y=a(512,512,"mobilenetv1/conv_10"),v=a(512,512,"mobilenetv1/conv_11"),x=a(512,1024,"mobilenetv1/conv_12"),k=a(1024,1024,"mobilenetv1/conv_13");return{conv_0:c,conv_1:l,conv_2:u,conv_3:d,conv_4:p,conv_5:h,conv_6:f,conv_7:m,conv_8:g,conv_9:b,conv_10:y,conv_11:v,conv_12:x,conv_13:k}}function i(){let c=s(1024,256,1,"prediction_layer/conv_0"),l=s(256,512,3,"prediction_layer/conv_1"),u=s(512,128,1,"prediction_layer/conv_2"),d=s(128,256,3,"prediction_layer/conv_3"),p=s(256,128,1,"prediction_layer/conv_4"),h=s(128,256,3,"prediction_layer/conv_5"),f=s(256,64,1,"prediction_layer/conv_6"),m=s(64,128,3,"prediction_layer/conv_7"),g=r(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),b=r(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),y=r(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),v=r(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),x=r(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),k=r(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),C=r(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),N=r(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),F=r(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),R=r(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),O=r(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),D=r(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:c,conv_1:l,conv_2:u,conv_3:d,conv_4:p,conv_5:h,conv_6:f,conv_7:m,box_predictor_0:{box_encoding_predictor:g,class_predictor:b},box_predictor_1:{box_encoding_predictor:y,class_predictor:v},box_predictor_2:{box_encoding_predictor:x,class_predictor:k},box_predictor_3:{box_encoding_predictor:C,class_predictor:N},box_predictor_4:{box_encoding_predictor:F,class_predictor:R},box_predictor_5:{box_encoding_predictor:O,class_predictor:D}}}return{extractMobilenetV1Params:o,extractPredictionLayerParams:i}}function PE(e){let t=[],{extractWeights:n,getRemainingWeights:r}=Fn(e),{extractMobilenetV1Params:s,extractPredictionLayerParams:a}=Sce(n,t),o=s(),i=a(),l={extra_dim:Rh(n(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:{mobilenetv1:o,prediction_layer:i,output_layer:l},paramMappings:t}}function Cce(e,t){let n=sr(e,t);function r(l,u,d){let p=n(`${l}/Conv2d_${u}_pointwise/weights`,4,`${d}/filters`),h=n(`${l}/Conv2d_${u}_pointwise/convolution_bn_offset`,1,`${d}/batch_norm_offset`);return{filters:p,batch_norm_offset:h}}function s(l){let u=`mobilenetv1/conv_${l}`,d=`MobilenetV1/Conv2d_${l}_depthwise`,p=`${u}/depthwise_conv`,h=`${u}/pointwise_conv`,f=n(`${d}/depthwise_weights`,4,`${p}/filters`),m=n(`${d}/BatchNorm/gamma`,1,`${p}/batch_norm_scale`),g=n(`${d}/BatchNorm/beta`,1,`${p}/batch_norm_offset`),b=n(`${d}/BatchNorm/moving_mean`,1,`${p}/batch_norm_mean`),y=n(`${d}/BatchNorm/moving_variance`,1,`${p}/batch_norm_variance`);return{depthwise_conv:{filters:f,batch_norm_scale:m,batch_norm_offset:g,batch_norm_mean:b,batch_norm_variance:y},pointwise_conv:r("MobilenetV1",l,h)}}function a(){return{conv_0:r("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:s(1),conv_2:s(2),conv_3:s(3),conv_4:s(4),conv_5:s(5),conv_6:s(6),conv_7:s(7),conv_8:s(8),conv_9:s(9),conv_10:s(10),conv_11:s(11),conv_12:s(12),conv_13:s(13)}}function o(l,u){let d=n(`${l}/weights`,4,`${u}/filters`),p=n(`${l}/biases`,1,`${u}/bias`);return{filters:d,bias:p}}function i(l){let u=o(`Prediction/BoxPredictor_${l}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${l}/box_encoding_predictor`),d=o(`Prediction/BoxPredictor_${l}/ClassPredictor`,`prediction_layer/box_predictor_${l}/class_predictor`);return{box_encoding_predictor:u,class_predictor:d}}function c(){return{conv_0:r("Prediction",0,"prediction_layer/conv_0"),conv_1:r("Prediction",1,"prediction_layer/conv_1"),conv_2:r("Prediction",2,"prediction_layer/conv_2"),conv_3:r("Prediction",3,"prediction_layer/conv_3"),conv_4:r("Prediction",4,"prediction_layer/conv_4"),conv_5:r("Prediction",5,"prediction_layer/conv_5"),conv_6:r("Prediction",6,"prediction_layer/conv_6"),conv_7:r("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:i(0),box_predictor_1:i(1),box_predictor_2:i(2),box_predictor_3:i(3),box_predictor_4:i(4),box_predictor_5:i(5)}}return{extractMobilenetV1Params:a,extractPredictionLayerParams:c}}function OE(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:r}=Cce(e,t),s=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Ms(s))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${s}`);let a={mobilenetv1:n(),prediction_layer:r(),output_layer:{extra_dim:s}};return Dn(e,t),{params:a,paramMappings:t}}function _r(e,t,n){return M(()=>{let r=Rt(e,t.filters,n,"same");return r=Y(r,t.batch_norm_offset),Qt(r,0,6)})}var Tce=.0010000000474974513;function Nce(e,t,n){return M(()=>{let r=la(e,t.filters,n,"same");return r=Ts(r,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Tce),Qt(r,0,6)})}function _ce(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function ME(e,t){return M(()=>{let n,r=_r(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((a,o)=>{let i=o+1,c=_ce(i);r=Nce(r,a.depthwise_conv,c),r=_r(r,a.pointwise_conv,[1,1]),i===11&&(n=r)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:r,conv11:n}})}function Ece(e,t,n){let r=e.arraySync(),s=Math.min(r[t][0],r[t][2]),a=Math.min(r[t][1],r[t][3]),o=Math.max(r[t][0],r[t][2]),i=Math.max(r[t][1],r[t][3]),c=Math.min(r[n][0],r[n][2]),l=Math.min(r[n][1],r[n][3]),u=Math.max(r[n][0],r[n][2]),d=Math.max(r[n][1],r[n][3]),p=(o-s)*(i-a),h=(u-c)*(d-l);if(p<=0||h<=0)return 0;let f=Math.max(s,c),m=Math.max(a,l),g=Math.min(o,u),b=Math.min(i,d),y=Math.max(g-f,0)*Math.max(b-m,0);return y/(p+h-y)}function LE(e,t,n,r,s){let a=e.shape[0],o=Math.min(n,a),i=t.map((u,d)=>({score:u,boxIndex:d})).filter(u=>u.score>s).sort((u,d)=>d.score-u.score),c=u=>u<=r?1:0,l=[];return i.forEach(u=>{if(l.length>=o)return;let d=u.score;for(let p=l.length-1;p>=0;--p){let h=Ece(e,u.boxIndex,l[p]);if(h!==0&&(u.score*=c(h),u.score<=s))break}d===u.score&&l.push(u.boxIndex)}),l}function Ace(e){let t=dt(Re(e,[1,0])),n=[fe(t[2],t[0]),fe(t[3],t[1])],r=[Y(t[0],ge(n[0],2)),Y(t[1],ge(n[1],2))];return{sizes:n,centers:r}}function Dce(e,t){let{sizes:n,centers:r}=Ace(e),s=dt(Re(t,[1,0])),a=ge(V(gn(ge(s[2],5)),n[0]),2),o=Y(V(ge(s[0],10),n[0]),r[0]),i=ge(V(gn(ge(s[3],5)),n[1]),2),c=Y(V(ge(s[1],10),n[1]),r[1]);return Re(Ot([fe(o,a),fe(c,i),Y(o,a),Y(c,i)]),[1,0])}function BE(e,t,n){return M(()=>{let r=e.shape[0],s=Dce(U(On(n.extra_dim,[r,1,1]),[-1,4]),U(e,[-1,4]));s=U(s,[r,s.shape[0]/r,4]);let a=cr(We(t,[0,0,1],[-1,-1,-1])),o=We(a,[0,0,0],[-1,-1,1]);o=U(o,[r,o.shape[1]]);let i=dt(s),c=dt(o);return{boxes:i,scores:c}})}function Ei(e,t){return M(()=>{let n=e.shape[0],r=U(Ni(e,t.box_encoding_predictor),[n,-1,1,4]),s=U(Ni(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:r,classPrediction:s}})}function zE(e,t,n){return M(()=>{let r=_r(e,n.conv_0,[1,1]),s=_r(r,n.conv_1,[2,2]),a=_r(s,n.conv_2,[1,1]),o=_r(a,n.conv_3,[2,2]),i=_r(o,n.conv_4,[1,1]),c=_r(i,n.conv_5,[2,2]),l=_r(c,n.conv_6,[1,1]),u=_r(l,n.conv_7,[2,2]),d=Ei(t,n.box_predictor_0),p=Ei(e,n.box_predictor_1),h=Ei(s,n.box_predictor_2),f=Ei(o,n.box_predictor_3),m=Ei(c,n.box_predictor_4),g=Ei(u,n.box_predictor_5),b=Ze([d.boxPredictionEncoding,p.boxPredictionEncoding,h.boxPredictionEncoding,f.boxPredictionEncoding,m.boxPredictionEncoding,g.boxPredictionEncoding],1),y=Ze([d.classPrediction,p.classPrediction,h.classPrediction,f.classPrediction,m.classPrediction,g.classPrediction],1);return{boxPredictions:b,classPredictions:y}})}var Er=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 Ai=class extends pn{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return M(()=>{let r=ce(t.toBatchTensor(512,!1),"float32"),s=fe(ge(r,127.5),1),a=ME(s,n.mobilenetv1),{boxPredictions:o,classPredictions:i}=zE(a.out,a.conv11,n.prediction_layer);return BE(o,i,n.output_layer)})}async forward(t){return this.forwardInput(await mt(t))}async locateFaces(t,n={}){let{maxResults:r,minConfidence:s}=new Er(n),a=await mt(t),{boxes:o,scores:i}=this.forwardInput(a),c=o[0],l=i[0];for(let v=1;v<o.length;v++)o[v].dispose(),i[v].dispose();let u=Array.from(l.dataSync()),p=LE(c,u,r,.5,s),h=a.getReshapedInputDimensions(0),f=a.inputSize,m=f/h.width,g=f/h.height,b=c.arraySync(),y=p.map(v=>{let[x,k]=[Math.max(0,b[v][0]),Math.min(1,b[v][2])].map(F=>F*g),[C,N]=[Math.max(0,b[v][1]),Math.min(1,b[v][3])].map(F=>F*m);return new vt(u[v],new Bu(C,x,N-C,k-x),{height:a.getInputHeight(0),width:a.getInputWidth(0)})});return c.dispose(),l.dispose(),y}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return OE(t)}extractParams(t){return PE(t)}};function WE(e){let t=new Ai;return t.extractWeights(e),t}function Fce(e){return WE(e)}var VE=class extends Ai{};var UE=.4,GE=[new Pe(.738768,.874946),new Pe(2.42204,2.65704),new Pe(4.30971,7.04493),new Pe(10.246,4.59428),new Pe(12.6868,11.8741)],HE=[new Pe(1.603231,2.094468),new Pe(6.041143,7.080126),new Pe(2.882459,3.518061),new Pe(4.266906,5.178857),new Pe(9.041765,10.66308)],jE=[117.001,114.697,97.404],qE="tiny_yolov2_model",KE="tiny_yolov2_separable_conv_model";var Qm=e=>typeof e=="number";function R0(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(!Qm(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=>Qm(t.x)&&Qm(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(Qm)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Xu(e){return M(()=>{let t=V(e,Se(.10000000149011612));return Y(je(fe(e,t)),t)})}function Vs(e,t){return M(()=>{let n=ur(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Rt(n,t.conv.filters,[1,1],"valid"),n=fe(n,t.bn.sub),n=V(n,t.bn.truediv),n=Y(n,t.conv.bias),Xu(n)})}function Us(e,t){return M(()=>{let n=ur(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Qo(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=Y(n,t.bias),Xu(n)})}function $ce(e,t){let n=Uu(e,t);function r(o,i){let c=Ge(e(o)),l=Ge(e(o));return t.push({paramPath:`${i}/sub`},{paramPath:`${i}/truediv`}),{sub:c,truediv:l}}function s(o,i,c){let l=n(o,i,3,`${c}/conv`),u=r(i,`${c}/bn`);return{conv:l,bn:u}}let a=Gu(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:s,extractSeparableConvParams:a}}function XE(e,t,n,r){let{extractWeights:s,getRemainingWeights:a}=Fn(e),o=[],{extractConvParams:i,extractConvWithBatchNormParams:c,extractSeparableConvParams:l}=$ce(s,o),u;if(t.withSeparableConvs){let[d,p,h,f,m,g,b,y,v]=r,x=t.isFirstLayerConv2d?i(d,p,3,"conv0"):l(d,p,"conv0"),k=l(p,h,"conv1"),C=l(h,f,"conv2"),N=l(f,m,"conv3"),F=l(m,g,"conv4"),R=l(g,b,"conv5"),O=y?l(b,y,"conv6"):void 0,D=v?l(y,v,"conv7"):void 0,P=i(v||y||b,5*n,1,"conv8");u={conv0:x,conv1:k,conv2:C,conv3:N,conv4:F,conv5:R,conv6:O,conv7:D,conv8:P}}else{let[d,p,h,f,m,g,b,y,v]=r,x=c(d,p,"conv0"),k=c(p,h,"conv1"),C=c(h,f,"conv2"),N=c(f,m,"conv3"),F=c(m,g,"conv4"),R=c(g,b,"conv5"),O=c(b,y,"conv6"),D=c(y,v,"conv7"),P=i(v,5*n,1,"conv8");u={conv0:x,conv1:k,conv2:C,conv3:N,conv4:F,conv5:R,conv6:O,conv7:D,conv8:P}}if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{params:u,paramMappings:o}}function Rce(e,t){let n=sr(e,t);function r(i){let c=n(`${i}/sub`,1),l=n(`${i}/truediv`,1);return{sub:c,truediv:l}}function s(i){let c=n(`${i}/filters`,4),l=n(`${i}/bias`,1);return{filters:c,bias:l}}function a(i){let c=s(`${i}/conv`),l=r(`${i}/bn`);return{conv:c,bn:l}}let o=Hu(n);return{extractConvParams:s,extractConvWithBatchNormParams:a,extractSeparableConvParams:o}}function YE(e,t){let n=[],{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:a}=Rce(e,n),o;if(t.withSeparableConvs){let i=t.filterSizes&&t.filterSizes.length||9;o={conv0:t.isFirstLayerConv2d?r("conv0"):a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:i>7?a("conv6"):void 0,conv7:i>8?a("conv7"):void 0,conv8:r("conv8")}}else o={conv0:s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:s("conv6"),conv7:s("conv7"),conv8:r("conv8")};return Dn(e,n),{params:o,paramMappings:n}}var ys=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 P0=class extends pn{constructor(t){super("TinyYolov2");R0(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 r=Vs(t,n.conv0);return r=Pt(r,[2,2],[2,2],"same"),r=Vs(r,n.conv1),r=Pt(r,[2,2],[2,2],"same"),r=Vs(r,n.conv2),r=Pt(r,[2,2],[2,2],"same"),r=Vs(r,n.conv3),r=Pt(r,[2,2],[2,2],"same"),r=Vs(r,n.conv4),r=Pt(r,[2,2],[2,2],"same"),r=Vs(r,n.conv5),r=Pt(r,[2,2],[1,1],"same"),r=Vs(r,n.conv6),r=Vs(r,n.conv7),Ni(r,n.conv8,"valid",!1)}runMobilenet(t,n){let r=this.config.isFirstLayerConv2d?Xu(Ni(t,n.conv0,"valid",!1)):Us(t,n.conv0);return r=Pt(r,[2,2],[2,2],"same"),r=Us(r,n.conv1),r=Pt(r,[2,2],[2,2],"same"),r=Us(r,n.conv2),r=Pt(r,[2,2],[2,2],"same"),r=Us(r,n.conv3),r=Pt(r,[2,2],[2,2],"same"),r=Us(r,n.conv4),r=Pt(r,[2,2],[2,2],"same"),r=Us(r,n.conv5),r=Pt(r,[2,2],[1,1],"same"),r=n.conv6?Us(r,n.conv6):r,r=n.conv7?Us(r,n.conv7):r,Ni(r,n.conv8,"valid",!1)}forwardInput(t,n){let{params:r}=this;if(!r)throw new Error("TinyYolov2 - load model before inference");return M(()=>{let s=ce(t.toBatchTensor(n,!1),"float32");return s=this.config.meanRgb?Kr(s,this.config.meanRgb):s,s=s.div(255),this.config.withSeparableConvs?this.runMobilenet(s,r):this.runTinyYolov2(s,r)})}async forward(t,n){return this.forwardInput(await mt(t),n)}async detect(t,n={}){let{inputSize:r,scoreThreshold:s}=new ys(n),a=await mt(t),o=await this.forwardInput(a,r),i=M(()=>dt(o)[0].expandDims()),c={width:a.getInputWidth(0),height:a.getInputHeight(0)},l=await this.extractBoxes(i,a.getReshapedInputDimensions(0),s);o.dispose(),i.dispose();let u=l.map(g=>g.box),d=l.map(g=>g.score),p=l.map(g=>g.classScore),h=l.map(g=>this.config.classes[g.label]);return u0(u.map(g=>g.rescale(r)),d,this.config.iouThreshold,!0).map(g=>new Na(d[g],p[g],h[g],u[g],c))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return YE(t,this.config)}extractParams(t){let n=this.config.filterSizes||P0.DEFAULT_FILTER_SIZES,r=n?n.length:void 0;if(r!==7&&r!==8&&r!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${r} filterSizes in config`);return XE(t,this.config,this.boxEncodingSize,n)}async extractBoxes(t,n,r){let{width:s,height:a}=n,o=Math.max(s,a),i=o/s,c=o/a,l=t.shape[1],u=this.config.anchors.length,[d,p,h]=M(()=>{let b=t.reshape([l,l,u,this.boxEncodingSize]),y=b.slice([0,0,0,0],[l,l,u,4]),v=b.slice([0,0,0,4],[l,l,u,1]),x=this.withClassScores?Pr(b.slice([0,0,0,5],[l,l,u,this.config.classes.length]),3):Se(0);return[y,v,x]}),f=[],m=await p.array(),g=await d.array();for(let b=0;b<l;b++)for(let y=0;y<l;y++)for(let v=0;v<u;v++){let x=Xd(m[b][y][v][0]);if(!r||x>r){let k=(y+Xd(g[b][y][v][0]))/l*i,C=(b+Xd(g[b][y][v][1]))/l*c,N=Math.exp(g[b][y][v][2])*this.config.anchors[v].x/l*i,F=Math.exp(g[b][y][v][3])*this.config.anchors[v].y/l*c,R=k-N/2,O=C-F/2,D={row:b,col:y,anchor:v},{classScore:P,label:T}=this.withClassScores?await this.extractPredictedClass(h,D):{classScore:1,label:0};f.push({box:new Lu(R,O,R+N,O+F),score:x,classScore:x*P,label:T,...D})}}return d.dispose(),p.dispose(),h.dispose(),f}async extractPredictedClass(t,n){let{row:r,col:s,anchor:a}=n,o=await t.array();return Array(this.config.classes.length).fill(0).map((i,c)=>o[r][s][a][c]).map((i,c)=>({classScore:i,label:c})).reduce((i,c)=>i.classScore>c.classScore?i:c)}},Yu=P0;Yu.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var Zu=class extends Yu{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:UE,classes:["face"],...t?{anchors:HE,meanRgb:jE}:{anchors:GE,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(s=>new vt(s.score,s.relativeBox,{width:s.imageWidth,height:s.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?KE:qE}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function Pce(e,t=!0){let n=new Zu(t);return n.extractWeights(e),n}var eg=class extends ys{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var Ar=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function Di(e,t,n,r,s=({alignedRect:a})=>a){let a=e.map(c=>_i(c)?s(c):c.detection),o=r||(t instanceof Ee?await Vu(t,a):await Wu(t,a)),i=await n(o);return o.forEach(c=>c instanceof Ee&&c.dispose()),i}async function Ju(e,t,n,r,s){return Di([e],t,async a=>n(a[0]),r,s)}var ZE=.4,JE=[new Pe(1.603231,2.094468),new Pe(6.041143,7.080126),new Pe(2.882459,3.518061),new Pe(4.266906,5.178857),new Pe(9.041765,10.66308)],QE=[117.001,114.697,97.404];var Qu=class extends Yu{constructor(){let t={withSeparableConvs:!0,iouThreshold:ZE,classes:["face"],anchors:JE,meanRgb:QE,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(s=>new vt(s.score,s.relativeBox,{width:s.imageWidth,height:s.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var Qe={ssdMobilenetv1:new Ai,tinyFaceDetector:new Qu,tinyYolov2:new Zu,faceLandmark68Net:new qu,faceLandmark68TinyNet:new Km,faceRecognitionNet:new Ku,faceExpressionNet:new Hm,ageGenderNet:new qm},eA=(e,t)=>Qe.ssdMobilenetv1.locateFaces(e,t),Oce=(e,t)=>Qe.tinyFaceDetector.locateFaces(e,t),Mce=(e,t)=>Qe.tinyYolov2.locateFaces(e,t),tA=e=>Qe.faceLandmark68Net.detectLandmarks(e),Lce=e=>Qe.faceLandmark68TinyNet.detectLandmarks(e),Bce=e=>Qe.faceRecognitionNet.computeFaceDescriptor(e),zce=e=>Qe.faceExpressionNet.predictExpressions(e),Wce=e=>Qe.ageGenderNet.predictAgeAndGender(e),nA=e=>Qe.ssdMobilenetv1.load(e),Vce=e=>Qe.tinyFaceDetector.load(e),Uce=e=>Qe.tinyYolov2.load(e),Gce=e=>Qe.faceLandmark68Net.load(e),Hce=e=>Qe.faceLandmark68TinyNet.load(e),jce=e=>Qe.faceRecognitionNet.load(e),qce=e=>Qe.faceExpressionNet.load(e),Kce=e=>Qe.ageGenderNet.load(e),Xce=nA,Yce=eA,Zce=tA;var O0=class extends Ar{constructor(t,n,r){super();this.parentTask=t;this.input=n;this.extractedFaces=r}},el=class extends O0{async run(){let t=await this.parentTask,n=await Di(t,this.input,async r=>Promise.all(r.map(s=>Qe.faceExpressionNet.predictExpressions(s))),this.extractedFaces);return t.map((r,s)=>jm(r,n[s]))}withAgeAndGender(){return new nl(this,this.input)}},tl=class extends O0{async run(){let t=await this.parentTask;if(!t)return;let n=await Ju(t,this.input,r=>Qe.faceExpressionNet.predictExpressions(r),this.extractedFaces);return jm(t,n)}withAgeAndGender(){return new rl(this,this.input)}},Fi=class extends el{withAgeAndGender(){return new Ri(this,this.input)}withFaceDescriptors(){return new Aa(this,this.input)}},$i=class extends tl{withAgeAndGender(){return new Pi(this,this.input)}withFaceDescriptor(){return new Da(this,this.input)}};var M0=class extends Ar{constructor(t,n,r){super();this.parentTask=t;this.input=n;this.extractedFaces=r}},nl=class extends M0{async run(){let t=await this.parentTask,n=await Di(t,this.input,async r=>Promise.all(r.map(s=>Qe.ageGenderNet.predictAgeAndGender(s))),this.extractedFaces);return t.map((r,s)=>{let{age:a,gender:o,genderProbability:i}=n[s];return Zm(Jm(r,o,i),a)})}withFaceExpressions(){return new el(this,this.input)}},rl=class extends M0{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:r,genderProbability:s}=await Ju(t,this.input,a=>Qe.ageGenderNet.predictAgeAndGender(a),this.extractedFaces);return Zm(Jm(t,r,s),n)}withFaceExpressions(){return new tl(this,this.input)}},Ri=class extends nl{withFaceExpressions(){return new Fi(this,this.input)}withFaceDescriptors(){return new Aa(this,this.input)}},Pi=class extends rl{withFaceExpressions(){return new $i(this,this.input)}withFaceDescriptor(){return new Da(this,this.input)}};var tg=class extends Ar{constructor(t,n){super();this.parentTask=t;this.input=n}},Aa=class extends tg{async run(){let t=await this.parentTask;return(await Di(t,this.input,r=>Promise.all(r.map(s=>Qe.faceRecognitionNet.computeFaceDescriptor(s))),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}))).map((r,s)=>Ym(t[s],r))}withFaceExpressions(){return new Fi(this,this.input)}withAgeAndGender(){return new Ri(this,this.input)}},Da=class extends tg{async run(){let t=await this.parentTask;if(!t)return;let n=await Ju(t,this.input,r=>Qe.faceRecognitionNet.computeFaceDescriptor(r),null,r=>r.landmarks.align(null,{useDlibAlignment:!0}));return Ym(t,n)}withFaceExpressions(){return new $i(this,this.input)}withAgeAndGender(){return new Pi(this,this.input)}};var ng=class extends Ar{constructor(t,n,r){super();this.parentTask=t;this.input=n;this.useTinyLandmarkNet=r}get landmarkNet(){return this.useTinyLandmarkNet?Qe.faceLandmark68TinyNet:Qe.faceLandmark68Net}},rg=class extends ng{async run(){let t=await this.parentTask,n=t.map(a=>a.detection),r=this.input instanceof Ee?await Vu(this.input,n):await Wu(this.input,n),s=await Promise.all(r.map(a=>this.landmarkNet.detectLandmarks(a)));return r.forEach(a=>a instanceof Ee&&a.dispose()),t.map((a,o)=>ju(a,s[o]))}withFaceExpressions(){return new Fi(this,this.input)}withAgeAndGender(){return new Ri(this,this.input)}withFaceDescriptors(){return new Aa(this,this.input)}},sg=class extends ng{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,r=this.input instanceof Ee?await Vu(this.input,[n]):await Wu(this.input,[n]),s=await this.landmarkNet.detectLandmarks(r[0]);return r.forEach(a=>a instanceof Ee&&a.dispose()),ju(t,s)}withFaceExpressions(){return new $i(this,this.input)}withAgeAndGender(){return new Pi(this,this.input)}withFaceDescriptor(){return new Da(this,this.input)}};var ag=class extends Ar{constructor(t,n=new Er){super();this.input=t;this.options=n}},ip=class extends ag{async run(){let{input:t,options:n}=this,r;if(n instanceof eg)r=Qe.tinyFaceDetector.locateFaces(t,n);else if(n instanceof Er)r=Qe.ssdMobilenetv1.locateFaces(t,n);else if(n instanceof ys)r=Qe.tinyYolov2.locateFaces(t,n);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return r}runAndExtendWithFaceDetections(){return new Promise((t,n)=>{this.run().then(r=>t(r.map(s=>Ii({},s)))).catch(r=>n(r))})}withFaceLandmarks(t=!1){return new rg(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new el(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new nl(this.runAndExtendWithFaceDetections(),this.input)}},og=class extends ag{async run(){let t=await new ip(this.input,this.options),n=t[0];return t.forEach(r=>{r.score>n.score&&(n=r)}),n}runAndExtendWithFaceDetection(){return new Promise(async t=>{let n=await this.run();t(n?Ii({},n):void 0)})}withFaceLandmarks(t=!1){return new sg(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new tl(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new rl(this.runAndExtendWithFaceDetection(),this.input)}};function Jce(e,t=new Er){return new og(e,t)}function ig(e,t=new Er){return new ip(e,t)}async function rA(e,t){return ig(e,new Er(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function Qce(e,t={}){return ig(e,new ys(t)).withFaceLandmarks().withFaceDescriptors()}var eue=rA;function L0(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");let n=Array.from(e),r=Array.from(t);return Math.sqrt(n.map((s,a)=>s-r[a]).reduce((s,a)=>s+a**2,0))}var cg=class{constructor(t,n=.6){this._distanceThreshold=n;let r=Array.isArray(t)?t:[t];if(!r.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let s=1,a=()=>`person ${s++}`;this._labeledDescriptors=r.map(o=>{if(o instanceof Ls)return o;if(o instanceof Float32Array)return new Ls(a(),[o]);if(o.descriptor&&o.descriptor instanceof Float32Array)return new Ls(a(),[o.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(r=>L0(r,t)).reduce((r,s)=>r+s,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:r})=>new Yd(r,this.computeMeanDistance(t,n))).reduce((n,r)=>n.distance<r.distance?n:r)}findBestMatch(t){let n=this.matchDescriptor(t);return n.distance<this._distanceThreshold?n:new Yd("unknown",n.distance)}toJSON(){return{distanceThreshold:this._distanceThreshold,labeledDescriptors:this._labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(r=>Ls.fromJSON(r));return new cg(n,t.distanceThreshold)}};function tue(e){let t=new Qu;return t.extractWeights(e),t}function sA(e,t){let{width:n,height:r}=new An(t.width,t.height);if(n<=0||r<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:r})}`);if(Array.isArray(e))return e.map(s=>sA(s,{width:n,height:r}));if(_i(e)){let s=e.detection.forSize(n,r),a=e.unshiftedLandmarks.forSize(s.box.width,s.box.height);return ju(Ii(e,s),a)}return gs(e)?Ii(e,e.detection.forSize(n,r)):e instanceof gr||e instanceof vt?e.forSize(n,r):e}var nue=typeof process!="undefined",aA=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",rue={faceapi:kE,node:nue,browser:aA};aA&&(qi.set("CHECK_COMPUTATION_FOR_ERRORS",!1),qi.set("WEBGL_CPU_FORWARD",!0),qi.set("WEBGL_USE_SHAPES_UNIFORMS",!0));return sue;})();
|
|
/**
|
|
* @license
|
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google Inc. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the License);
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an AS IS BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/** @license See the LICENSE file. */
|