5011 lines
1.3 MiB
5011 lines
1.3 MiB
/*
|
|
Face-API
|
|
homepage: <https://github.com/vladmandic/face-api>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var yR=Object.defineProperty;var xR=(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 Error('Dynamic require of "'+e+'" is not supported')});var nx=(e,t)=>{for(var n in t)yR(e,n,{get:t[n],enumerable:!0})};var Pe={};nx(Pe,{Abs:()=>Yl,Acos:()=>Ni,Acosh:()=>Ti,AdadeltaOptimizer:()=>Vw,AdagradOptimizer:()=>Uw,AdamOptimizer:()=>Gw,AdamaxOptimizer:()=>Hw,Add:()=>xs,AddN:()=>Ci,All:()=>Zl,Any:()=>Jl,ArgMax:()=>Ql,ArgMin:()=>eu,Asin:()=>Ei,Asinh:()=>_i,Atan:()=>Ai,Atan2:()=>$i,Atanh:()=>Fi,AvgPool:()=>Di,AvgPool3D:()=>tu,AvgPool3DGrad:()=>Rc,AvgPoolGrad:()=>Dc,BackendWasm:()=>O$,BatchMatMul:()=>Ri,BatchToSpaceND:()=>nu,Bincount:()=>au,BitwiseAnd:()=>ru,BroadcastArgs:()=>Mc,BroadcastTo:()=>HS,Callback:()=>MC,CallbackList:()=>A2,Cast:()=>Mi,Ceil:()=>Oi,ClipByValue:()=>vs,Complex:()=>wm,ComplexAbs:()=>Oc,Concat:()=>su,Conv2D:()=>Pi,Conv2DBackpropFilter:()=>km,Conv2DBackpropInput:()=>Li,Conv3D:()=>zi,Conv3DBackpropFilterV2:()=>iu,Conv3DBackpropInputV2:()=>ou,Cos:()=>Wi,Cosh:()=>Bi,CropAndResize:()=>uu,Cumprod:()=>lu,Cumsum:()=>Vi,CustomCallback:()=>$2,DataStorage:()=>ym,DenseBincount:()=>Pc,DepthToSpace:()=>pu,DepthwiseConv2dNative:()=>Ui,DepthwiseConv2dNativeBackpropFilter:()=>Im,DepthwiseConv2dNativeBackpropInput:()=>Sm,Diag:()=>Lc,Dilation2D:()=>Gi,Dilation2DBackpropFilter:()=>Rl,Dilation2DBackpropInput:()=>Dl,Draw:()=>Nm,ENV:()=>Nv,EarlyStopping:()=>OC,Einsum:()=>Tm,Elu:()=>qi,EluGrad:()=>cu,Environment:()=>US,Equal:()=>du,Erf:()=>ji,Exp:()=>Ki,ExpandDims:()=>hu,Expm1:()=>Xi,FFT:()=>Cm,Fill:()=>zc,FlipLeftRight:()=>mu,Floor:()=>Yi,FloorDiv:()=>Zi,FromPixels:()=>Hh,FusedBatchNorm:()=>Ji,FusedConv2D:()=>ii,FusedDepthwiseConv2D:()=>oi,GPGPUContext:()=>Wh,GatherNd:()=>gu,GatherV2:()=>fu,GraphModel:()=>F1,Greater:()=>bu,GreaterEqual:()=>Qi,History:()=>F2,IFFT:()=>Em,Identity:()=>eo,Imag:()=>_m,InputSpec:()=>zt,IsFinite:()=>to,IsInf:()=>no,IsNan:()=>ao,KernelBackend:()=>Fc,LRN:()=>oo,LRNGrad:()=>Su,LayerVariable:()=>k2,LayersModel:()=>Cr,LeakyRelu:()=>ro,Less:()=>yu,LessEqual:()=>xu,LinSpace:()=>vu,Log:()=>so,Log1p:()=>io,LogSoftmax:()=>jS,LogicalAnd:()=>wu,LogicalNot:()=>ku,LogicalOr:()=>Iu,LogicalXor:()=>qS,LowerBound:()=>pM,MathBackendCPU:()=>R1,MathBackendWebGL:()=>lk,MatrixBandPart:()=>cM,Max:()=>lo,MaxPool:()=>po,MaxPool3D:()=>Nu,MaxPool3DGrad:()=>Bc,MaxPoolGrad:()=>Wc,MaxPoolWithArgmax:()=>Vc,Maximum:()=>uo,Mean:()=>co,Min:()=>ho,Minimum:()=>mo,MirrorPad:()=>fo,Mod:()=>go,MomentumOptimizer:()=>qw,Multinomial:()=>Tu,Multiply:()=>bo,Neg:()=>Cu,NonMaxSuppressionV3:()=>_u,NonMaxSuppressionV4:()=>Au,NonMaxSuppressionV5:()=>Fu,NotEqual:()=>Eu,OP_SCOPE_SUFFIX:()=>Av,OneHot:()=>yo,OnesLike:()=>$u,Optimizer:()=>Rr,OptimizerConstructors:()=>t2,Pack:()=>Du,PadV2:()=>xo,Pool:()=>dM,Pow:()=>vo,Prelu:()=>wo,Prod:()=>ko,RMSPropOptimizer:()=>jw,RNN:()=>Mr,RaggedGather:()=>Am,RaggedRange:()=>Fm,RaggedTensorToTensor:()=>$m,Range:()=>Uc,Rank:()=>wx,Real:()=>Dm,RealDiv:()=>Hi,Reciprocal:()=>Io,Reduction:()=>wn,Relu:()=>So,Relu6:()=>Co,Reshape:()=>Ru,ResizeBilinear:()=>To,ResizeBilinearGrad:()=>Ou,ResizeNearestNeighbor:()=>No,ResizeNearestNeighborGrad:()=>Mu,Reverse:()=>Eo,RotateWithOffset:()=>Zu,Round:()=>_o,Rsqrt:()=>Ao,SGDOptimizer:()=>mf,ScatterNd:()=>Pu,SearchSorted:()=>zu,Select:()=>Wu,Selu:()=>Fo,Sequential:()=>Cf,Sigmoid:()=>Mo,Sign:()=>Ro,Sin:()=>$o,Sinh:()=>Do,Slice:()=>Bu,Softmax:()=>zo,Softplus:()=>Oo,SpaceToBatchND:()=>Vu,SparseFillEmptyRows:()=>Gc,SparseReshape:()=>Gu,SparseSegmentMean:()=>Hc,SparseSegmentSum:()=>qc,SparseToDense:()=>Hu,SplitV:()=>Uu,Sqrt:()=>Po,Square:()=>jc,SquaredDifference:()=>Wo,StaticRegexReplace:()=>Kc,Step:()=>ks,StridedSlice:()=>qu,StringNGrams:()=>Xc,StringSplit:()=>Yc,StringToHashBucketFast:()=>Zc,Sub:()=>Bo,Sum:()=>Lo,SymbolicTensor:()=>Ha,Tan:()=>Vo,Tanh:()=>Uo,Tensor:()=>Ce,TensorBuffer:()=>Wt,TensorScatterUpdate:()=>Lu,Tile:()=>ws,TopK:()=>ju,Transform:()=>Ku,Transpose:()=>Tr,Unique:()=>Jc,Unpack:()=>Xu,UnsortedSegmentSum:()=>Qc,UpperBound:()=>hM,Variable:()=>os,ZerosLike:()=>Yu,_FusedMatMul:()=>si,abs:()=>Lt,acos:()=>Ov,acosh:()=>Pv,add:()=>X,addN:()=>vN,all:()=>Lm,any:()=>yc,argMax:()=>ci,argMin:()=>Lv,asin:()=>zv,asinh:()=>Wv,atan:()=>Bv,atan2:()=>Vv,atanh:()=>Uv,avgPool:()=>ya,avgPool3d:()=>Hv,backend:()=>$v,backend_util:()=>T,basicLSTMCell:()=>SN,batchNorm:()=>Ss,batchNorm2d:()=>qv,batchNorm3d:()=>jv,batchNorm4d:()=>Kv,batchToSpaceND:()=>id,bincount:()=>Xv,bitwiseAnd:()=>NN,booleanMaskAsync:()=>mT,broadcastArgs:()=>TN,broadcastTo:()=>ni,broadcast_util:()=>Ju,browser:()=>jo,buffer:()=>Oe,callbacks:()=>lj,cast:()=>re,ceil:()=>Yv,clipByValue:()=>an,clone:()=>sr,complex:()=>Er,concat:()=>et,concat1d:()=>Zv,concat2d:()=>Jv,concat3d:()=>Qv,concat4d:()=>ew,constraints:()=>T2,conv1d:()=>zm,conv2d:()=>$t,conv2dTranspose:()=>Wm,conv3d:()=>nw,conv3dTranspose:()=>aw,copyRegisteredKernels:()=>bM,cos:()=>od,cosh:()=>Bm,cosineWindow:()=>uf,cumprod:()=>wc,cumsum:()=>Vm,customGrad:()=>ur,data:()=>iE,denseBincount:()=>Xh,deprecationWarn:()=>Fv,depthToSpace:()=>rw,depthwiseConv2d:()=>Ns,deregisterOp:()=>cj,device_util:()=>ad,diag:()=>EN,dilation2d:()=>sw,disableDeprecationWarnings:()=>XM,dispose:()=>Ee,disposeVariables:()=>YM,div:()=>he,divNoNan:()=>iw,dot:()=>ow,dropout:()=>Pw,einsum:()=>Ys,elu:()=>Qu,enableDebugMode:()=>KM,enableProdMode:()=>jM,enclosingPowerOfTwo:()=>Lw,engine:()=>Ta,ensureShape:()=>AN,env:()=>G,equal:()=>Jn,erf:()=>lw,euclideanNorm:()=>cw,exp:()=>dn,expandDims:()=>Gt,expm1:()=>dw,eye:()=>Um,fft:()=>bd,fill:()=>yn,findBackend:()=>nO,findBackendFactory:()=>aO,floor:()=>tp,floorDiv:()=>Pm,forceHalfFloat:()=>AA,fused:()=>Vl,gather:()=>np,gatherND:()=>yT,gather_util:()=>Yw,getBackend:()=>oN,getGradient:()=>xx,getKernel:()=>fc,getKernelsForBackend:()=>qh,getThreadsCount:()=>Nfe,gpgpu_util:()=>oA,grad:()=>M3,grads:()=>O3,greater:()=>Tn,greaterEqual:()=>$r,ifft:()=>Bl,imag:()=>ld,image:()=>Zn,inTopKAsync:()=>xT,initializers:()=>C2,input:()=>q2,io:()=>qt,irfft:()=>nf,isFinite:()=>hw,isInf:()=>mw,isNaN:()=>fw,keep:()=>Ht,kernel_impls:()=>hr,layers:()=>E2,leakyRelu:()=>ud,less:()=>Pl,lessEqual:()=>Ts,linalg:()=>Bw,linspace:()=>MN,loadGraphModel:()=>b5,loadGraphModelSync:()=>y5,loadLayersModel:()=>r6,localResponseNormalization:()=>gw,log:()=>Qn,log1p:()=>pd,logSigmoid:()=>bw,logSoftmax:()=>Hm,logSumExp:()=>cd,logicalAnd:()=>_a,logicalNot:()=>dd,logicalOr:()=>qm,logicalXor:()=>yw,losses:()=>FT,lowerBound:()=>PN,matMul:()=>$e,math:()=>VT,max:()=>ma,maxPool:()=>Dt,maxPool3d:()=>xw,maxPoolWithArgmax:()=>LN,maximum:()=>dr,mean:()=>Ct,memory:()=>Kh,meshgrid:()=>zN,metrics:()=>$C,min:()=>Ol,minimum:()=>cs,mirrorPad:()=>vw,mod:()=>ww,model:()=>o6,models:()=>DC,moments:()=>hd,movingAverage:()=>fT,mul:()=>z,multiRNNCell:()=>WN,multinomial:()=>BN,neg:()=>yt,nextFrame:()=>Zw,norm:()=>ep,notEqual:()=>fi,oneHot:()=>Ll,ones:()=>On,onesLike:()=>ea,op:()=>L,outerProduct:()=>VN,pad:()=>xa,pad1d:()=>UN,pad2d:()=>GN,pad3d:()=>HN,pad4d:()=>qN,pool:()=>kw,pow:()=>_r,prelu:()=>fd,print:()=>Mv,prod:()=>Iw,profile:()=>ZM,raggedGather:()=>jN,raggedRange:()=>KN,raggedTensorToTensor:()=>XN,rand:()=>YN,randomGamma:()=>eT,randomNormal:()=>Km,randomStandardNormal:()=>tT,randomUniform:()=>Cs,randomUniformInt:()=>nT,range:()=>gi,ready:()=>eO,real:()=>zl,reciprocal:()=>Ew,registerBackend:()=>Om,registerCallbackConstructor:()=>u6,registerGradient:()=>KS,registerKernel:()=>ed,registerOp:()=>pj,regularizers:()=>RC,relu:()=>Ke,relu6:()=>Xm,removeBackend:()=>tO,reshape:()=>W,reverse:()=>ba,reverse1d:()=>aT,reverse2d:()=>rT,reverse3d:()=>sT,reverse4d:()=>iT,rfft:()=>yd,round:()=>Ym,rsqrt:()=>Zm,scalar:()=>ve,scatterND:()=>gT,scatter_util:()=>rf,searchSorted:()=>jm,selu:()=>Jm,separableConv2d:()=>Es,sequential:()=>l6,serialization:()=>ne,setBackend:()=>QM,setPlatform:()=>rO,setThreadsCount:()=>Sfe,setWasmPath:()=>kfe,setWasmPaths:()=>Ife,setWebGLContext:()=>F_,setdiff1dAsync:()=>oT,shared:()=>M1,sigmoid:()=>ha,sign:()=>_w,signal:()=>AT,sin:()=>Qm,sinh:()=>ef,slice:()=>Ve,slice1d:()=>gd,slice2d:()=>tf,slice3d:()=>Ho,slice4d:()=>Wl,slice_util:()=>Kt,softmax:()=>ja,softplus:()=>Go,spaceToBatchND:()=>md,sparse:()=>$T,sparseToDense:()=>bT,spectral:()=>_T,split:()=>Pn,sqrt:()=>cn,square:()=>pt,squaredDifference:()=>af,squeeze:()=>_s,stack:()=>At,step:()=>qo,stridedSlice:()=>Aw,string:()=>DT,sub:()=>pe,sum:()=>fe,sumOutType:()=>Mm,tan:()=>Fw,tanh:()=>hi,tensor:()=>bn,tensor1d:()=>qe,tensor2d:()=>Ea,tensor3d:()=>xd,tensor4d:()=>Fa,tensor5d:()=>lT,tensor6d:()=>uT,tensorScatterUpdate:()=>cT,tensor_util:()=>Wa,test_util:()=>ZN,tidy:()=>O,tile:()=>Mn,time:()=>JM,topk:()=>Dw,train:()=>Ks,transpose:()=>De,truncatedNormal:()=>of,unique:()=>Rw,unregisterGradient:()=>gM,unregisterKernel:()=>fM,unsortedSegmentSum:()=>lf,unstack:()=>dt,upcastType:()=>fa,upperBound:()=>dT,util:()=>w,valueAndGrad:()=>P3,valueAndGrads:()=>L3,variable:()=>Mw,variableGrads:()=>ON,version:()=>$fe,version_converter:()=>v5,version_core:()=>l4,version_cpu:()=>w8,version_layers:()=>v0,version_wasm:()=>Tfe,version_webgl:()=>pee,webgl:()=>cee,webgl_util:()=>A_,where:()=>nn,whereAsync:()=>Ow,zeros:()=>It,zerosLike:()=>je});var vR=Object.create,wv=Object.defineProperty,wR=Object.getOwnPropertyDescriptor,kR=Object.getOwnPropertyNames,IR=Object.getPrototypeOf,SR=Object.prototype.hasOwnProperty,Vt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_e=(e,t)=>{for(var n in t)wv(e,n,{get:t[n],enumerable:!0})},NR=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of kR(t))!SR.call(e,r)&&r!==n&&wv(e,r,{get:()=>t[r],enumerable:!(a=wR(t,r))||a.enumerable});return e},ys=(e,t,n)=>(n=e!=null?vR(IR(e)):{},NR(t||!e||!e.__esModule?wv(n,"default",{value:e,enumerable:!0}):n,e)),TR=Vt((e,t)=>{t.exports=a;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(S){}function a(S,M,B){this.low=S|0,this.high=M|0,this.unsigned=!!B}a.prototype.__isLong__,Object.defineProperty(a.prototype,"__isLong__",{value:!0});function r(S){return(S&&S.__isLong__)===!0}a.isLong=r;var s={},i={};function o(S,M){var B,U,H;return M?(S>>>=0,(H=0<=S&&S<256)&&(U=i[S],U)?U:(B=u(S,(S|0)<0?-1:0,!0),H&&(i[S]=B),B)):(S|=0,(H=-128<=S&&S<128)&&(U=s[S],U)?U:(B=u(S,S<0?-1:0,!1),H&&(s[S]=B),B))}a.fromInt=o;function l(S,M){if(isNaN(S))return M?v:x;if(M){if(S<0)return v;if(S>=g)return F}else{if(S<=-b)return D;if(S+1>=b)return _}return S<0?l(-S,M).neg():u(S%f|0,S/f|0,M)}a.fromNumber=l;function u(S,M,B){return new a(S,M,B)}a.fromBits=u;var p=Math.pow;function d(S,M,B){if(S.length===0)throw Error("empty string");if(S==="NaN"||S==="Infinity"||S==="+Infinity"||S==="-Infinity")return x;if(typeof M=="number"?(B=M,M=!1):M=!!M,B=B||10,B<2||36<B)throw RangeError("radix");var U;if((U=S.indexOf("-"))>0)throw Error("interior hyphen");if(U===0)return d(S.substring(1),M,B).neg();for(var H=l(p(B,8)),j=x,K=0;K<S.length;K+=8){var Z=Math.min(8,S.length-K),J=parseInt(S.substring(K,K+Z),B);if(Z<8){var ee=l(p(B,Z));j=j.mul(ee).add(l(J))}else j=j.mul(H),j=j.add(l(J))}return j.unsigned=M,j}a.fromString=d;function c(S,M){return typeof S=="number"?l(S,M):typeof S=="string"?d(S,M):u(S.low,S.high,typeof M=="boolean"?M:S.unsigned)}a.fromValue=c;var h=65536,m=1<<24,f=h*h,g=f*f,b=g/2,y=o(m),x=o(0);a.ZERO=x;var v=o(0,!0);a.UZERO=v;var I=o(1);a.ONE=I;var N=o(1,!0);a.UONE=N;var C=o(-1);a.NEG_ONE=C;var _=u(-1,2147483647,!1);a.MAX_VALUE=_;var F=u(-1,-1,!0);a.MAX_UNSIGNED_VALUE=F;var D=u(0,-2147483648,!1);a.MIN_VALUE=D;var $=a.prototype;$.toInt=function(){return this.unsigned?this.low>>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},$.toString=function(S){if(S=S||10,S<2||36<S)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(D)){var M=l(S),B=this.div(M),U=B.mul(M).sub(this);return B.toString(S)+U.toInt().toString(S)}else return"-"+this.neg().toString(S);for(var H=l(p(S,6),this.unsigned),j=this,K="";;){var Z=j.div(H),J=j.sub(Z.mul(H)).toInt()>>>0,ee=J.toString(S);if(j=Z,j.isZero())return ee+K;for(;ee.length<6;)ee="0"+ee;K=""+ee+K}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(D)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,M=31;M>0&&!(S&1<<M);M--);return this.high!=0?M+33:M+1},$.isZero=function(){return this.high===0&&this.low===0},$.eqz=$.isZero,$.isNegative=function(){return!this.unsigned&&this.high<0},$.isPositive=function(){return this.unsigned||this.high>=0},$.isOdd=function(){return(this.low&1)===1},$.isEven=function(){return(this.low&1)===0},$.equals=function(S){return r(S)||(S=c(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},$.eq=$.equals,$.notEquals=function(S){return!this.eq(S)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(S){return this.comp(S)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(S){return this.comp(S)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(S){return this.comp(S)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(S){return this.comp(S)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(S){if(r(S)||(S=c(S)),this.eq(S))return 0;var M=this.isNegative(),B=S.isNegative();return M&&!B?-1:!M&&B?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(D)?D:this.not().add(I)},$.neg=$.negate,$.add=function(S){r(S)||(S=c(S));var M=this.high>>>16,B=this.high&65535,U=this.low>>>16,H=this.low&65535,j=S.high>>>16,K=S.high&65535,Z=S.low>>>16,J=S.low&65535,ee=0,ae=0,te=0,se=0;return se+=H+J,te+=se>>>16,se&=65535,te+=U+Z,ae+=te>>>16,te&=65535,ae+=B+K,ee+=ae>>>16,ae&=65535,ee+=M+j,ee&=65535,u(te<<16|se,ee<<16|ae,this.unsigned)},$.subtract=function(S){return r(S)||(S=c(S)),this.add(S.neg())},$.sub=$.subtract,$.multiply=function(S){if(this.isZero())return x;if(r(S)||(S=c(S)),n){var M=n.mul(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}if(S.isZero())return x;if(this.eq(D))return S.isOdd()?D:x;if(S.eq(D))return this.isOdd()?D:x;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(y)&&S.lt(y))return l(this.toNumber()*S.toNumber(),this.unsigned);var B=this.high>>>16,U=this.high&65535,H=this.low>>>16,j=this.low&65535,K=S.high>>>16,Z=S.high&65535,J=S.low>>>16,ee=S.low&65535,ae=0,te=0,se=0,ie=0;return ie+=j*ee,se+=ie>>>16,ie&=65535,se+=H*ee,te+=se>>>16,se&=65535,se+=j*J,te+=se>>>16,se&=65535,te+=U*ee,ae+=te>>>16,te&=65535,te+=H*J,ae+=te>>>16,te&=65535,te+=j*Z,ae+=te>>>16,te&=65535,ae+=B*ee+U*J+H*Z+j*K,ae&=65535,u(se<<16|ie,ae<<16|te,this.unsigned)},$.mul=$.multiply,$.divide=function(S){if(r(S)||(S=c(S)),S.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?v:x;var B,U,H;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return v;if(S.gt(this.shru(1)))return N;H=v}else{if(this.eq(D)){if(S.eq(I)||S.eq(C))return D;if(S.eq(D))return I;var j=this.shr(1);return B=j.div(S).shl(1),B.eq(x)?S.isNegative()?I:C:(U=this.sub(S.mul(B)),H=B.add(U.div(S)),H)}else if(S.eq(D))return this.unsigned?v:x;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();H=x}for(U=this;U.gte(S);){B=Math.max(1,Math.floor(U.toNumber()/S.toNumber()));for(var K=Math.ceil(Math.log(B)/Math.LN2),Z=K<=48?1:p(2,K-48),J=l(B),ee=J.mul(S);ee.isNegative()||ee.gt(U);)B-=Z,J=l(B,this.unsigned),ee=J.mul(S);J.isZero()&&(J=I),H=H.add(J),U=U.sub(ee)}return H},$.div=$.divide,$.modulo=function(S){if(r(S)||(S=c(S)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,S.low,S.high);return u(M,n.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return u(~this.low,~this.high,this.unsigned)},$.and=function(S){return r(S)||(S=c(S)),u(this.low&S.low,this.high&S.high,this.unsigned)},$.or=function(S){return r(S)||(S=c(S)),u(this.low|S.low,this.high|S.high,this.unsigned)},$.xor=function(S){return r(S)||(S=c(S)),u(this.low^S.low,this.high^S.high,this.unsigned)},$.shiftLeft=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low<<S,this.high<<S|this.low>>>32-S,this.unsigned):u(0,this.low<<S-32,this.unsigned)},$.shl=$.shiftLeft,$.shiftRight=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low>>>S|this.high<<32-S,this.high>>S,this.unsigned):u(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(S){if(r(S)&&(S=S.toInt()),S&=63,S===0)return this;var M=this.high;if(S<32){var B=this.low;return u(B>>>S|M<<32-S,M>>>S,this.unsigned)}else return S===32?u(M,0,this.unsigned):u(M>>>S-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},$.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var S=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},$.toBytesBE=function(){var S=this.high,M=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},a.fromBytes=function(S,M,B){return B?a.fromBytesLE(S,M):a.fromBytesBE(S,M)},a.fromBytesLE=function(S,M){return new a(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,M)},a.fromBytesBE=function(S,M){return new a(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],M)}}),CR=Vt(()=>{}),ER=Vt(()=>{}),_R=Vt((e,t)=>{(function(n,a,r){function s(u){var p=this,d=l();p.next=function(){var c=2091639*p.s0+p.c*23283064365386963e-26;return p.s0=p.s1,p.s1=p.s2,p.s2=c-(p.c=c|0)},p.c=1,p.s0=d(" "),p.s1=d(" "),p.s2=d(" "),p.s0-=d(u),p.s0<0&&(p.s0+=1),p.s1-=d(u),p.s1<0&&(p.s1+=1),p.s2-=d(u),p.s2<0&&(p.s2+=1),d=null}function i(u,p){return p.c=u.c,p.s0=u.s0,p.s1=u.s1,p.s2=u.s2,p}function o(u,p){var d=new s(u),c=p&&p.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,c&&(typeof c=="object"&&i(c,d),h.state=function(){return i(d,{})}),h}function l(){var u=4022871197,p=function(d){d=String(d);for(var c=0;c<d.length;c++){u+=d.charCodeAt(c);var h=.02519603282416938*u;u=h>>>0,h-=u,h*=u,u=h>>>0,h-=u,u+=h*4294967296}return(u>>>0)*23283064365386963e-26};return p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),AR=Vt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var c=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^c^c>>>8},l===(l|0)?u.x=l:p+=l;for(var d=0;d<p.length+64;d++)u.x^=p.charCodeAt(d)|0,u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),FR=Vt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.next=function(){var c=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(c^c<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:p+=l;for(var d=0;d<p.length+64;d++)u.x^=p.charCodeAt(d)|0,d==p.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),$R=Vt((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var d=u.x,c=u.i,h,m,f;return h=d[c],h^=h>>>7,m=h^h<<24,h=d[c+1&7],m^=h^h>>>10,h=d[c+3&7],m^=h^h>>>3,h=d[c+4&7],m^=h^h<<7,h=d[c+7&7],h=h^h<<13,m^=h^h<<9,d[c]=m,u.i=c+1&7,m};function p(d,c){var h,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,h=0;h<c.length;++h)f[h&7]=f[h&7]<<15^c.charCodeAt(h)+f[h+1&7]<<13;for(;f.length<8;)f.push(0);for(h=0;h<8&&f[h]===0;++h);for(h==8?m=f[7]=-1:m=f[h],d.x=f,d.i=0,h=256;h>0;--h)d.next()}p(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(d.x&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),DR=Vt((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var d=u.w,c=u.X,h=u.i,m,f;return u.w=d=d+1640531527|0,f=c[h+34&127],m=c[h=h+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[h]=f^m,u.i=h,f+(d^d>>>16)|0};function p(d,c){var h,m,f,g,b,y=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,g=-32;g<x;++g)c&&(m^=c.charCodeAt((g+32)%c.length)),g===0&&(b=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,g>=0&&(b=b+1640531527|0,h=y[g&127]^=m+b,f=h==0?f+1:0);for(f>=128&&(y[(c&&c.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=y[f+34&127],h=y[f=f+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,y[f]=m^h;d.w=b,d.X=y,d.i=f}p(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(d.X&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),RR=Vt((e,t)=>{(function(n,a,r){function s(l){var u=this,p="";u.next=function(){var c=u.b,h=u.c,m=u.d,f=u.a;return c=c<<25^c>>>7^h,h=h-m|0,m=m<<24^m>>>8^f,f=f-c|0,u.b=c=c<<20^c>>>12^h,u.c=h=h-m|0,u.d=m<<16^h>>>16^f,u.a=f-c|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):p+=l;for(var d=0;d<p.length+20;d++)u.b^=p.charCodeAt(d)|0,u.next()}function i(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function o(l,u){var p=new s(l),d=u&&u.state,c=function(){return(p.next()>>>0)/4294967296};return c.double=function(){do var h=p.next()>>>11,m=(p.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},c.int32=p.next,c.quick=c,d&&(typeof d=="object"&&i(d,p),c.state=function(){return i(p,{})}),c}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),MR=Vt(()=>{}),OR=Vt((e,t)=>{(function(n,a,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),p=r.pow(2,o),d=p*2,c=s-1,h;function m(I,N,C){var _=[];N=N==!0?{entropy:!0}:N||{};var F=y(b(N.entropy?[I,v(a)]:I==null?x():I,3),_),D=new f(_),$=function(){for(var S=D.g(i),M=u,B=0;S<p;)S=(S+B)*s,M*=s,B=D.g(1);for(;S>=d;)S/=2,M/=2,B>>>=1;return(S+B)/M};return $.int32=function(){return D.g(4)|0},$.quick=function(){return D.g(4)/4294967296},$.double=$,y(v(D.S),a),(N.pass||C||function(S,M,B,U){return U&&(U.S&&g(U,D),S.state=function(){return g(D,{})}),B?(r[l]=S,M):S})($,F,"global"in N?N.global:this==r,N.state)}function f(I){var N,C=I.length,_=this,F=0,D=_.i=_.j=0,$=_.S=[];for(C||(I=[C++]);F<s;)$[F]=F++;for(F=0;F<s;F++)$[F]=$[D=c&D+I[F%C]+(N=$[F])],$[D]=N;(_.g=function(S){for(var M,B=0,U=_.i,H=_.j,j=_.S;S--;)M=j[U=c&U+1],B=B*s+j[c&(j[U]=j[H=c&H+M])+(j[H]=M)];return _.i=U,_.j=H,B})(s)}function g(I,N){return N.i=I.i,N.j=I.j,N.S=I.S.slice(),N}function b(I,N){var C=[],_=typeof I,F;if(N&&_=="object")for(F in I)try{C.push(b(I[F],N-1))}catch(D){}return C.length?C:_=="string"?I:I+"\0"}function y(I,N){for(var C=I+"",_,F=0;F<C.length;)N[c&F]=c&(_^=N[c&F]*19)+C.charCodeAt(F++);return v(N)}function x(){try{var I;return h&&(I=h.randomBytes)?I=I(s):(I=new Uint8Array(s),(n.crypto||n.msCrypto).getRandomValues(I)),v(I)}catch(_){var N=n.navigator,C=N&&N.plugins;return[+new Date,n,C,n.screen,v(a)]}}function v(I){return String.fromCharCode.apply(0,I)}if(y(r.random(),a),typeof t=="object"&&t.exports){t.exports=m;try{h=MR()}catch(I){}}else typeof define=="function"&&define.amd?define(function(){return m}):r["seed"+l]=m})(typeof self!="undefined"?self:e,[],Math)}),bm=Vt((e,t)=>{var n=_R(),a=AR(),r=FR(),s=$R(),i=DR(),o=RR(),l=OR();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),FS=Vt(()=>{}),kv=Vt(()=>{}),$S=Vt(()=>{}),PR=Vt(()=>{}),LR=Vt(()=>{}),zR=Vt(()=>{}),WR=Vt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};function s(){return ue.buffer!=Re&&ut(ue.buffer),gt}function i(){return ue.buffer!=Re&&ut(ue.buffer),Gn}function o(){return ue.buffer!=Re&&ut(ue.buffer),Ot}function l(){return ue.buffer!=Re&&ut(ue.buffer),ln}function u(){return ue.buffer!=Re&&ut(ue.buffer),An}function p(){return ue.buffer!=Re&&ut(ue.buffer),oa}function d(){return ue.buffer!=Re&&ut(ue.buffer),Fn}var c=typeof r!="undefined"?r:{},h,m;c.ready=new Promise(function(R,q){h=R,m=q});var f;typeof process!="undefined"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},c),b=[],y="./this.program",x=(R,q)=>{throw q},v=typeof window=="object",I=typeof importScripts=="function",N=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=c.ENVIRONMENT_IS_PTHREAD||!1,_="";function F(R){return c.locateFile?c.locateFile(R,_):_+R}var D,$,S,M;function B(R){R instanceof Us||J("exiting due to exception: "+R)}if(N){var U=kv(),H=$S();I?_=H.dirname(_)+"/":_=__dirname+"/",D=(q,le)=>(q=gl(q)?new URL(q):H.normalize(q),U.readFileSync(q,le?void 0:"utf8")),S=q=>{var le=D(q,!0);return le.buffer||(le=new Uint8Array(le)),le},$=(q,le,Ne)=>{q=gl(q)?new URL(q):H.normalize(q),U.readFile(q,function(Me,Fe){Me?Ne(Me):le(Fe.buffer)})},process.argv.length>1&&(y=process.argv[1].replace(/\\/g,"/")),b=process.argv.slice(2),process.on("uncaughtException",function(q){if(!(q instanceof Us))throw q}),process.on("unhandledRejection",function(q){throw q}),x=(q,le)=>{if(Ia())throw process.exitCode=q,le;B(le),process.exit(q)},c.inspect=function(){return"[Emscripten Module object]"};let R;try{R=PR()}catch(q){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),q}global.Worker=R.Worker}else(v||I)&&(I?_=self.location.href:typeof document!="undefined"&&document.currentScript&&(_=document.currentScript.src),typeof a!="undefined"&&a&&(_=a),_.indexOf("blob:")!==0?_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):_="",N||(D=R=>{var q=new XMLHttpRequest;return q.open("GET",R,!1),q.send(null),q.responseText},I&&(S=R=>{var q=new XMLHttpRequest;return q.open("GET",R,!1),q.responseType="arraybuffer",q.send(null),new Uint8Array(q.response)}),$=(R,q,le)=>{var Ne=new XMLHttpRequest;Ne.open("GET",R,!0),Ne.responseType="arraybuffer",Ne.onload=()=>{if(Ne.status==200||Ne.status==0&&Ne.response){q(Ne.response);return}le()},Ne.onerror=le,Ne.send(null)}),M=R=>document.title=R);N&&typeof performance=="undefined"&&(global.performance=LR().performance);var j=console.log.bind(console),K=console.warn.bind(console);N&&(j=R=>U.writeSync(1,R+`
|
|
`),K=R=>U.writeSync(2,R+`
|
|
`));var Z=c.print||j,J=c.printErr||K;Object.assign(c,g),g=null,c.arguments&&(b=c.arguments),c.thisProgram&&(y=c.thisProgram),c.quit&&(x=c.quit);var ee=4,ae=Atomics.load,te=Atomics.store,se=Atomics.compareExchange,ie;c.wasmBinary&&(ie=c.wasmBinary);var xe=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Vs("no native wasm support detected");var ue,ye,ke=!1,Se;function Le(R,q){R||Vs(q)}var Ue=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function mt(R,q,le){q>>>=0;for(var Ne=q+le,Me=q;R[Me]&&!(Me>=Ne);)++Me;if(Me-q>16&&R.buffer&&Ue)return Ue.decode(R.buffer instanceof SharedArrayBuffer?R.slice(q,Me):R.subarray(q,Me));for(var Fe="";q<Me;){var me=R[q++];if(!(me&128)){Fe+=String.fromCharCode(me);continue}var we=R[q++]&63;if((me&224)==192){Fe+=String.fromCharCode((me&31)<<6|we);continue}var Tt=R[q++]&63;if((me&240)==224?me=(me&15)<<12|we<<6|Tt:me=(me&7)<<18|we<<12|Tt<<6|R[q++]&63,me<65536)Fe+=String.fromCharCode(me);else{var ua=me-65536;Fe+=String.fromCharCode(55296|ua>>10,56320|ua&1023)}}return Fe}function st(R,q){return R>>>=0,R?mt(i(),R,q):""}function tt(R,q,le,Ne){if(le>>>=0,!(Ne>0))return 0;for(var Me=le,Fe=le+Ne-1,me=0;me<R.length;++me){var we=R.charCodeAt(me);if(we>=55296&&we<=57343){var Tt=R.charCodeAt(++me);we=65536+((we&1023)<<10)|Tt&1023}if(we<=127){if(le>=Fe)break;q[le++>>>0]=we}else if(we<=2047){if(le+1>=Fe)break;q[le++>>>0]=192|we>>6,q[le++>>>0]=128|we&63}else if(we<=65535){if(le+2>=Fe)break;q[le++>>>0]=224|we>>12,q[le++>>>0]=128|we>>6&63,q[le++>>>0]=128|we&63}else{if(le+3>=Fe)break;q[le++>>>0]=240|we>>18,q[le++>>>0]=128|we>>12&63,q[le++>>>0]=128|we>>6&63,q[le++>>>0]=128|we&63}}return q[le>>>0]=0,le-Me}function nt(R,q,le){return tt(R,i(),q,le)}var Re,gt,Gn,Ot,ia,ln,An,oa,Fn;C&&(Re=c.buffer);function ut(R){Re=R,c.HEAP8=gt=new Int8Array(R),c.HEAP16=Ot=new Int16Array(R),c.HEAP32=ln=new Int32Array(R),c.HEAPU8=Gn=new Uint8Array(R),c.HEAPU16=ia=new Uint16Array(R),c.HEAPU32=An=new Uint32Array(R),c.HEAPF32=oa=new Float32Array(R),c.HEAPF64=Fn=new Float64Array(R)}var $n=c.INITIAL_MEMORY||16777216;if(C)ue=c.wasmMemory,Re=c.buffer;else if(c.wasmMemory)ue=c.wasmMemory;else if(ue=new WebAssembly.Memory({initial:$n/65536,maximum:65536,shared:!0}),!(ue.buffer instanceof SharedArrayBuffer))throw J("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),N&&J("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");ue&&(Re=ue.buffer),$n=Re.byteLength,ut(Re);var Hn,yr=[],ml=[],Za=[],Wp=!1;function Ia(){return xe}function Ur(){if(c.preRun)for(typeof c.preRun=="function"&&(c.preRun=[c.preRun]);c.preRun.length;)Ig(c.preRun.shift());Vp(yr)}function Jt(){Wp=!0,!C&&Vp(ml)}function Hd(){if(!C){if(c.postRun)for(typeof c.postRun=="function"&&(c.postRun=[c.postRun]);c.postRun.length;)Rk(c.postRun.shift());Vp(Za)}}function Ig(R){yr.unshift(R)}function Sg(R){ml.unshift(R)}function Rk(R){Za.unshift(R)}var Gr=0,fl=null,xr=null;function Ng(R){Gr++,c.monitorRunDependencies&&c.monitorRunDependencies(Gr)}function qd(R){if(Gr--,c.monitorRunDependencies&&c.monitorRunDependencies(Gr),Gr==0&&(fl!==null&&(clearInterval(fl),fl=null),xr)){var q=xr;xr=null,q()}}function Vs(R){c.onAbort&&c.onAbort(R),R="Aborted("+R+")",J(R),ke=!0,Se=1,R+=". Build with -sASSERTIONS for more info.";var q=new WebAssembly.RuntimeError(R);throw m(q),q}var Tg="data:application/octet-stream;base64,";function jd(R){return R.startsWith(Tg)}function gl(R){return R.startsWith("file://")}var gn;gn="tfjs-backend-wasm-threaded-simd.wasm",jd(gn)||(gn=F(gn));function Kd(R){try{if(R==gn&&ie)return new Uint8Array(ie);if(S)return S(R);throw"both async and sync fetching of the wasm failed"}catch(q){Vs(q)}}function Cg(){if(!ie&&(v||I)){if(typeof fetch=="function"&&!gl(gn))return fetch(gn,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+gn+"'";return R.arrayBuffer()}).catch(function(){return Kd(gn)});if($)return new Promise(function(R,q){$(gn,function(le){R(new Uint8Array(le))},q)})}return Promise.resolve().then(function(){return Kd(gn)})}function Eg(){var R={env:oh,wasi_snapshot_preview1:oh};function q(me,we){var Tt=me.exports;if(c.asm=Tt,Pg(c.asm._emscripten_tls_init),Hn=c.asm.__indirect_function_table,Sg(c.asm.__wasm_call_ctors),ye=we,!C){var ua=Ae.unusedWorkers.length;Ae.unusedWorkers.forEach(function(wr){Ae.loadWasmModuleToWorker(wr,function(){--ua||qd("wasm-instantiate")})})}}C||Ng("wasm-instantiate");function le(me){q(me.instance,me.module)}function Ne(me){return Cg().then(function(we){return WebAssembly.instantiate(we,R)}).then(function(we){return we}).then(me,function(we){J("failed to asynchronously prepare wasm: "+we),Vs(we)})}function Me(){return!ie&&typeof WebAssembly.instantiateStreaming=="function"&&!jd(gn)&&!gl(gn)&&!N&&typeof fetch=="function"?fetch(gn,{credentials:"same-origin"}).then(function(me){var we=WebAssembly.instantiateStreaming(me,R);return we.then(le,function(Tt){return J("wasm streaming compile failed: "+Tt),J("falling back to ArrayBuffer instantiation"),Ne(le)})}):Ne(le)}if(c.instantiateWasm)try{var Fe=c.instantiateWasm(R,q);return Fe}catch(me){J("Module.instantiateWasm callback failed with error: "+me),m(me)}return Me().catch(m),{}}var Mk,Ok,Xd={};function Us(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function _g(R){var q=Ae.pthreads[R];delete Ae.pthreads[R],q.terminate(),Qy(R),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(q),1),q.pthread_ptr=0}function Ag(R){var q=Ae.pthreads[R];q.postMessage({cmd:"cancel"})}function Bp(R){var q=Ae.pthreads[R];Le(q),Ae.returnWorkerToPool(q)}function Fg(R){var q=Ae.getNewWorker();if(!q)return 6;Ae.runningWorkers.push(q),Ae.pthreads[R.pthread_ptr]=q,q.pthread_ptr=R.pthread_ptr;var le={cmd:"run",start_routine:R.startRoutine,arg:R.arg,pthread_ptr:R.pthread_ptr};return q.runPthread=()=>{N&&q.ref(),q.postMessage(le,R.transferList),delete q.runPthread},q.loaded&&q.runPthread(),0}var Yd={varargs:void 0,get:function(){Yd.varargs+=4;var R=l()[Yd.varargs-4>>>2];return R},getStr:function(R){var q=st(R);return q}};function Zd(R){if(C)return Hr(1,1,R);Se=R,Ia()||(Ae.terminateAllThreads(),c.onExit&&c.onExit(R),ke=!0),x(R,new Us(R))}function $g(R,q){if(Se=R,!q&&C)throw Qd(R),"unwind";Zd(R)}var Jd=$g;function Dg(R){if(R instanceof Us||R=="unwind")return Se;x(1,R)}var Ae={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?Ae.initWorker():Ae.initMainThread()},initMainThread:function(){for(var R=8;R--;)Ae.allocateUnusedWorker()},initWorker:function(){xe=!1},setExitStatus:function(R){Se=R},terminateAllThreads:function(){for(var R of Object.values(Ae.pthreads))Ae.returnWorkerToPool(R);for(var R of Ae.unusedWorkers)R.terminate();Ae.unusedWorkers=[]},returnWorkerToPool:function(R){var q=R.pthread_ptr;delete Ae.pthreads[q],Ae.unusedWorkers.push(R),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(R),1),R.pthread_ptr=0,N&&R.unref(),Qy(q)},receiveObjectTransfer:function(R){},threadInitTLS:function(){Ae.tlsInitFunctions.forEach(R=>R())},loadWasmModuleToWorker:function(R,q){R.onmessage=Fe=>{var me=Fe.data,we=me.cmd;if(R.pthread_ptr&&(Ae.currentProxiedOperationCallerThread=R.pthread_ptr),me.targetThread&&me.targetThread!=hh()){var Tt=Ae.pthreads[me.targetThread];Tt?Tt.postMessage(me,me.transferList):J('Internal error! Worker sent a message "'+we+'" to target pthread '+me.targetThread+", but that thread no longer exists!"),Ae.currentProxiedOperationCallerThread=void 0;return}we==="processProxyingQueue"?Up(me.queue):we==="spawnThread"?Fg(me):we==="cleanupThread"?Bp(me.thread):we==="killThread"?_g(me.thread):we==="cancelThread"?Ag(me.thread):we==="loaded"?(R.loaded=!0,N&&R.unref(),q&&q(R),R.runPthread&&R.runPthread()):we==="print"?Z("Thread "+me.threadId+": "+me.text):we==="printErr"?J("Thread "+me.threadId+": "+me.text):we==="alert"?alert("Thread "+me.threadId+": "+me.text):me.target==="setimmediate"?R.postMessage(me):we==="callHandler"?c[me.handler](...me.args):we&&J("worker sent an unknown command "+we),Ae.currentProxiedOperationCallerThread=void 0},R.onerror=Fe=>{var me="worker sent an error!";throw J(me+" "+Fe.filename+":"+Fe.lineno+": "+Fe.message),Fe},N&&(R.on("message",function(Fe){R.onmessage({data:Fe})}),R.on("error",function(Fe){R.onerror(Fe)}),R.on("detachedExit",function(){}));var le=[],Ne=["onExit","onAbort","print","printErr"];for(var Me of Ne)c.hasOwnProperty(Me)&&le.push(Me);R.postMessage({cmd:"load",handlers:le,urlOrBlob:c.mainScriptUrlOrBlob||a,wasmMemory:ue,wasmModule:ye})},allocateUnusedWorker:function(){var R,q=F("tfjs-backend-wasm-threaded-simd.worker.js");R=new Worker(q),Ae.unusedWorkers.push(R)},getNewWorker:function(){return Ae.unusedWorkers.length==0&&(Ae.allocateUnusedWorker(),Ae.loadWasmModuleToWorker(Ae.unusedWorkers[0])),Ae.unusedWorkers.pop()}};c.PThread=Ae;function Vp(R){for(;R.length>0;)R.shift()(c)}function Rg(){var R=hh(),q=l()[R+52>>>2],le=l()[R+56>>>2],Ne=q-le;Vk(q,Ne),mh(q)}c.establishStackSpace=Rg;function Qd(R){if(C)return Hr(2,0,R);try{Jd(R)}catch(q){Dg(q)}}var bl=[];function Mg(R){var q=bl[R];return q||(R>=bl.length&&(bl.length=R+1),bl[R]=q=Hn.get(R)),q}function Og(R,q){var le=Mg(R)(q);Ia()?Ae.setExitStatus(le):Bk(le)}c.invokeEntryPoint=Og;function Pg(R){Ae.tlsInitFunctions.push(R)}function Lg(R){Lk(R,!I,1,!v),Ae.threadInitTLS()}function zg(R){C?postMessage({cmd:"cleanupThread",thread:R}):Bp(R)}function eh(R,q,le,Ne){return C?Hr(3,1,R,q,le,Ne):th(R,q,le,Ne)}function th(R,q,le,Ne){if(typeof SharedArrayBuffer=="undefined")return J("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Me=[],Fe=0;if(C&&(Me.length===0||Fe))return eh(R,q,le,Ne);if(Fe)return Fe;var me={startRoutine:le,pthread_ptr:R,arg:Ne,transferList:Me};return C?(me.cmd="spawnThread",postMessage(me,Me),0):Fg(me)}function Wg(){return 65536}var Bg=!0;function Vg(){return Bg}function Up(R){Atomics.store(l(),R>>2,1),hh()&&Wk(R),Atomics.compareExchange(l(),R>>2,1,0)}c.executeNotifiedProxyingQueue=Up;function Ug(R,q,le,Ne){if(R==q)setTimeout(()=>Up(Ne));else if(C)postMessage({targetThread:R,cmd:"processProxyingQueue",queue:Ne});else{var Me=Ae.pthreads[R];if(!Me)return;Me.postMessage({cmd:"processProxyingQueue",queue:Ne})}return 1}function Gg(R,q,le){return-1}function Hg(){Vs("")}function Gs(R){Gs.shown||(Gs.shown={}),Gs.shown[R]||(Gs.shown[R]=1,N&&(R="warning: "+R),J(R))}function qg(){N||I||Gs("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function jg(){return Date.now()}function nh(){return 4294901760}function Kg(){return nh()}var Gp;N?Gp=()=>{var R=process.hrtime();return R[0]*1e3+R[1]/1e6}:Gp=()=>performance.timeOrigin+performance.now();function Xg(R,q,le){i().copyWithin(R>>>0,q>>>0,q+le>>>0)}function Yg(){return N?zR().cpus().length:navigator.hardwareConcurrency}function Zg(R){var q=ex(),le=R();return mh(q),le}function Hr(R,q){var le=arguments.length-2,Ne=arguments;return Zg(()=>{for(var Me=le,Fe=fh(Me*8),me=Fe>>3,we=0;we<le;we++){var Tt=Ne[2+we];d()[me+we>>>0]=Tt}return zk(R,Me,Fe,q)})}var Hp=[];function Jg(R,q,le){Hp.length=q;for(var Ne=le>>3,Me=0;Me<q;Me++)Hp[Me]=d()[Ne+Me>>>0];var Fe=R<0,me=Fe?Xd[-R-1]:ob[R];return me.apply(null,Hp)}function Qg(R){try{return ue.grow(R-Re.byteLength+65535>>>16),ut(ue.buffer),1}catch(q){}}function eb(R){var q=i().length;if(R=R>>>0,R<=q)return!1;var le=nh();if(R>le)return!1;let Ne=(Tt,ua)=>Tt+(ua-Tt%ua)%ua;for(var Me=1;Me<=4;Me*=2){var Fe=q*(1+.2/Me);Fe=Math.min(Fe,R+100663296);var me=Math.min(le,Ne(Math.max(R,Fe),65536)),we=Qg(me);if(we)return!0}return!1}function tb(){throw"unwind"}function ah(R){return C?Hr(4,1,R):52}function rh(R,q,le,Ne,Me){return C?Hr(5,1,R,q,le,Ne,Me):70}var nb=[null,[],[]];function ab(R,q){var le=nb[R];q===0||q===10?((R===1?Z:J)(mt(le,0)),le.length=0):le.push(q)}function sh(R,q,le,Ne){if(C)return Hr(6,1,R,q,le,Ne);for(var Me=0,Fe=0;Fe<le;Fe++){var me=u()[q>>>2],we=u()[q+4>>>2];q+=8;for(var Tt=0;Tt<we;Tt++)ab(R,i()[me+Tt>>>0]);Me+=we}return u()[Ne>>>2]=Me,0}function ih(R){var q=c["_"+R];return q}function rb(R,q){s().set(R,q>>>0)}function sb(R,q,le,Ne,Me){var Fe={string:pa=>{var wl=0;if(pa!=null&&pa!==0){var Hk=(pa.length<<2)+1;wl=fh(Hk),nt(pa,wl,Hk)}return wl},array:pa=>{var wl=fh(pa.length);return rb(pa,wl),wl}};function me(pa){return q==="string"?st(pa):q==="boolean"?!!pa:pa}var we=ih(R),Tt=[],ua=0;if(Ne)for(var wr=0;wr<Ne.length;wr++){var Gk=Fe[le[wr]];Gk?(ua===0&&(ua=ex()),Tt[wr]=Gk(Ne[wr])):Tt[wr]=Ne[wr]}var tx=we.apply(null,Tt);function bR(pa){return ua!==0&&mh(ua),me(pa)}return tx=bR(tx),tx}function ib(R,q,le,Ne){le=le||[];var Me=le.every(me=>me==="number"||me==="boolean"),Fe=q!=="string";return Fe&&Me&&!Ne?ih(R):function(){return sb(R,q,le,arguments,Ne)}}Ae.init();var ob=[null,Zd,Qd,eh,ah,rh,sh],oh={__emscripten_init_main_thread_js:Lg,__emscripten_thread_cleanup:zg,__pthread_create_js:th,_emscripten_default_pthread_stack_size:Wg,_emscripten_get_now_is_monotonic:Vg,_emscripten_notify_task_queue:Ug,_emscripten_set_offscreencanvas_size:Gg,abort:Hg,emscripten_check_blocking_allowed:qg,emscripten_date_now:jg,emscripten_get_heap_max:Kg,emscripten_get_now:Gp,emscripten_memcpy_big:Xg,emscripten_num_logical_cores:Yg,emscripten_receive_on_main_thread_js:Jg,emscripten_resize_heap:eb,emscripten_unwind_to_js_event_loop:tb,exit:Jd,fd_close:ah,fd_seek:rh,fd_write:sh,memory:ue||c.wasmMemory},Pk=Eg(),lb=c.___wasm_call_ctors=function(){return(lb=c.___wasm_call_ctors=c.asm.__wasm_call_ctors).apply(null,arguments)},ub=c._init=function(){return(ub=c._init=c.asm.init).apply(null,arguments)},pb=c._init_with_threads_count=function(){return(pb=c._init_with_threads_count=c.asm.init_with_threads_count).apply(null,arguments)},cb=c._get_threads_count=function(){return(cb=c._get_threads_count=c.asm.get_threads_count).apply(null,arguments)},db=c._register_tensor=function(){return(db=c._register_tensor=c.asm.register_tensor).apply(null,arguments)},hb=c._dispose_data=function(){return(hb=c._dispose_data=c.asm.dispose_data).apply(null,arguments)},mb=c._dispose=function(){return(mb=c._dispose=c.asm.dispose).apply(null,arguments)},fb=c._Abs=function(){return(fb=c._Abs=c.asm.Abs).apply(null,arguments)},gb=c._Acos=function(){return(gb=c._Acos=c.asm.Acos).apply(null,arguments)},bb=c._Acosh=function(){return(bb=c._Acosh=c.asm.Acosh).apply(null,arguments)},yb=c._Add=function(){return(yb=c._Add=c.asm.Add).apply(null,arguments)},xb=c._AddN=function(){return(xb=c._AddN=c.asm.AddN).apply(null,arguments)},vb=c._All=function(){return(vb=c._All=c.asm.All).apply(null,arguments)},wb=c._Any=function(){return(wb=c._Any=c.asm.Any).apply(null,arguments)},kb=c._ArgMax=function(){return(kb=c._ArgMax=c.asm.ArgMax).apply(null,arguments)},Ib=c._ArgMin=function(){return(Ib=c._ArgMin=c.asm.ArgMin).apply(null,arguments)},Sb=c._Asin=function(){return(Sb=c._Asin=c.asm.Asin).apply(null,arguments)},Nb=c._Asinh=function(){return(Nb=c._Asinh=c.asm.Asinh).apply(null,arguments)},Tb=c._Atan=function(){return(Tb=c._Atan=c.asm.Atan).apply(null,arguments)},Cb=c._Atan2=function(){return(Cb=c._Atan2=c.asm.Atan2).apply(null,arguments)},Eb=c._Atanh=function(){return(Eb=c._Atanh=c.asm.Atanh).apply(null,arguments)},_b=c._AvgPool=function(){return(_b=c._AvgPool=c.asm.AvgPool).apply(null,arguments)},Ab=c._AvgPool3D=function(){return(Ab=c._AvgPool3D=c.asm.AvgPool3D).apply(null,arguments)},Fb=c._AvgPool3DGrad=function(){return(Fb=c._AvgPool3DGrad=c.asm.AvgPool3DGrad).apply(null,arguments)},$b=c._AvgPoolGrad=function(){return($b=c._AvgPoolGrad=c.asm.AvgPoolGrad).apply(null,arguments)},Db=c._BatchMatMul=function(){return(Db=c._BatchMatMul=c.asm.BatchMatMul).apply(null,arguments)},Rb=c._Bincount=function(){return(Rb=c._Bincount=c.asm.Bincount).apply(null,arguments)},Mb=c._BitwiseAnd=function(){return(Mb=c._BitwiseAnd=c.asm.BitwiseAnd).apply(null,arguments)},Ob=c._Ceil=function(){return(Ob=c._Ceil=c.asm.Ceil).apply(null,arguments)},Pb=c._ClipByValue=function(){return(Pb=c._ClipByValue=c.asm.ClipByValue).apply(null,arguments)},Lb=c._Conv2D=function(){return(Lb=c._Conv2D=c.asm.Conv2D).apply(null,arguments)},zb=c._Conv2DBackpropInput=function(){return(zb=c._Conv2DBackpropInput=c.asm.Conv2DBackpropInput).apply(null,arguments)},Wb=c._Conv3D=function(){return(Wb=c._Conv3D=c.asm.Conv3D).apply(null,arguments)},Bb=c._Conv3DBackpropFilterV2=function(){return(Bb=c._Conv3DBackpropFilterV2=c.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Vb=c._Conv3DBackpropInputV2=function(){return(Vb=c._Conv3DBackpropInputV2=c.asm.Conv3DBackpropInputV2).apply(null,arguments)},Ub=c._Cos=function(){return(Ub=c._Cos=c.asm.Cos).apply(null,arguments)},Gb=c._Cosh=function(){return(Gb=c._Cosh=c.asm.Cosh).apply(null,arguments)},Hb=c._CropAndResize=function(){return(Hb=c._CropAndResize=c.asm.CropAndResize).apply(null,arguments)},qb=c._Cumprod=function(){return(qb=c._Cumprod=c.asm.Cumprod).apply(null,arguments)},jb=c._Cumsum=function(){return(jb=c._Cumsum=c.asm.Cumsum).apply(null,arguments)},Kb=c._DenseBincount=function(){return(Kb=c._DenseBincount=c.asm.DenseBincount).apply(null,arguments)},Xb=c._DepthToSpace=function(){return(Xb=c._DepthToSpace=c.asm.DepthToSpace).apply(null,arguments)},Yb=c._DepthwiseConv2dNative=function(){return(Yb=c._DepthwiseConv2dNative=c.asm.DepthwiseConv2dNative).apply(null,arguments)},Zb=c._Diag=function(){return(Zb=c._Diag=c.asm.Diag).apply(null,arguments)},Jb=c._Dilation2D=function(){return(Jb=c._Dilation2D=c.asm.Dilation2D).apply(null,arguments)},Qb=c._Dilation2DBackpropFilter=function(){return(Qb=c._Dilation2DBackpropFilter=c.asm.Dilation2DBackpropFilter).apply(null,arguments)},ey=c._Dilation2DBackpropInput=function(){return(ey=c._Dilation2DBackpropInput=c.asm.Dilation2DBackpropInput).apply(null,arguments)},ty=c._Elu=function(){return(ty=c._Elu=c.asm.Elu).apply(null,arguments)},ny=c._EluGrad=function(){return(ny=c._EluGrad=c.asm.EluGrad).apply(null,arguments)},ay=c._Equal=function(){return(ay=c._Equal=c.asm.Equal).apply(null,arguments)},ry=c._Erf=function(){return(ry=c._Erf=c.asm.Erf).apply(null,arguments)},sy=c._Exp=function(){return(sy=c._Exp=c.asm.Exp).apply(null,arguments)},iy=c._Expm1=function(){return(iy=c._Expm1=c.asm.Expm1).apply(null,arguments)},oy=c._FlipLeftRight=function(){return(oy=c._FlipLeftRight=c.asm.FlipLeftRight).apply(null,arguments)},ly=c._Floor=function(){return(ly=c._Floor=c.asm.Floor).apply(null,arguments)},uy=c._FloorDiv=function(){return(uy=c._FloorDiv=c.asm.FloorDiv).apply(null,arguments)},py=c._FusedBatchNorm=function(){return(py=c._FusedBatchNorm=c.asm.FusedBatchNorm).apply(null,arguments)},cy=c._FusedConv2D=function(){return(cy=c._FusedConv2D=c.asm.FusedConv2D).apply(null,arguments)},dy=c._FusedDepthwiseConv2D=function(){return(dy=c._FusedDepthwiseConv2D=c.asm.FusedDepthwiseConv2D).apply(null,arguments)},hy=c._Gather=function(){return(hy=c._Gather=c.asm.Gather).apply(null,arguments)},my=c._GatherNd=function(){return(my=c._GatherNd=c.asm.GatherNd).apply(null,arguments)},fy=c._Greater=function(){return(fy=c._Greater=c.asm.Greater).apply(null,arguments)},gy=c._GreaterEqual=function(){return(gy=c._GreaterEqual=c.asm.GreaterEqual).apply(null,arguments)},by=c._IsFinite=function(){return(by=c._IsFinite=c.asm.IsFinite).apply(null,arguments)},yy=c._IsInf=function(){return(yy=c._IsInf=c.asm.IsInf).apply(null,arguments)},xy=c._IsNan=function(){return(xy=c._IsNan=c.asm.IsNan).apply(null,arguments)},vy=c._LRN=function(){return(vy=c._LRN=c.asm.LRN).apply(null,arguments)},wy=c._LRNGrad=function(){return(wy=c._LRNGrad=c.asm.LRNGrad).apply(null,arguments)},ky=c._LeakyRelu=function(){return(ky=c._LeakyRelu=c.asm.LeakyRelu).apply(null,arguments)},Iy=c._Less=function(){return(Iy=c._Less=c.asm.Less).apply(null,arguments)},Sy=c._LessEqual=function(){return(Sy=c._LessEqual=c.asm.LessEqual).apply(null,arguments)},Ny=c._LinSpace=function(){return(Ny=c._LinSpace=c.asm.LinSpace).apply(null,arguments)},Ty=c._Log=function(){return(Ty=c._Log=c.asm.Log).apply(null,arguments)},Cy=c._Log1p=function(){return(Cy=c._Log1p=c.asm.Log1p).apply(null,arguments)},Ey=c._LogicalAnd=function(){return(Ey=c._LogicalAnd=c.asm.LogicalAnd).apply(null,arguments)},_y=c._LogicalNot=function(){return(_y=c._LogicalNot=c.asm.LogicalNot).apply(null,arguments)},Ay=c._LogicalOr=function(){return(Ay=c._LogicalOr=c.asm.LogicalOr).apply(null,arguments)},Fy=c._LogicalXor=function(){return(Fy=c._LogicalXor=c.asm.LogicalXor).apply(null,arguments)},$y=c._Max=function(){return($y=c._Max=c.asm.Max).apply(null,arguments)},Dy=c._MaxPool=function(){return(Dy=c._MaxPool=c.asm.MaxPool).apply(null,arguments)},Ry=c._MaxPool3D=function(){return(Ry=c._MaxPool3D=c.asm.MaxPool3D).apply(null,arguments)},My=c._MaxPool3DGrad=function(){return(My=c._MaxPool3DGrad=c.asm.MaxPool3DGrad).apply(null,arguments)},Oy=c._MaxPoolGrad=function(){return(Oy=c._MaxPoolGrad=c.asm.MaxPoolGrad).apply(null,arguments)},Py=c._MaxPoolWithArgmax=function(){return(Py=c._MaxPoolWithArgmax=c.asm.MaxPoolWithArgmax).apply(null,arguments)},Ly=c._Maximum=function(){return(Ly=c._Maximum=c.asm.Maximum).apply(null,arguments)},zy=c._Mean=function(){return(zy=c._Mean=c.asm.Mean).apply(null,arguments)},Wy=c._Min=function(){return(Wy=c._Min=c.asm.Min).apply(null,arguments)},By=c._Minimum=function(){return(By=c._Minimum=c.asm.Minimum).apply(null,arguments)},Vy=c._MirrorPad=function(){return(Vy=c._MirrorPad=c.asm.MirrorPad).apply(null,arguments)},Uy=c._Mod=function(){return(Uy=c._Mod=c.asm.Mod).apply(null,arguments)},Gy=c._Multinomial=function(){return(Gy=c._Multinomial=c.asm.Multinomial).apply(null,arguments)},Hy=c._Multiply=function(){return(Hy=c._Multiply=c.asm.Multiply).apply(null,arguments)},qy=c._Neg=function(){return(qy=c._Neg=c.asm.Neg).apply(null,arguments)},jy=c._NonMaxSuppressionV3=function(){return(jy=c._NonMaxSuppressionV3=c.asm.NonMaxSuppressionV3).apply(null,arguments)},Ky=c._NonMaxSuppressionV4=function(){return(Ky=c._NonMaxSuppressionV4=c.asm.NonMaxSuppressionV4).apply(null,arguments)},lh=c._NonMaxSuppressionV5=function(){return(lh=c._NonMaxSuppressionV5=c.asm.NonMaxSuppressionV5).apply(null,arguments)},uh=c._NotEqual=function(){return(uh=c._NotEqual=c.asm.NotEqual).apply(null,arguments)},qp=c._OneHot=function(){return(qp=c._OneHot=c.asm.OneHot).apply(null,arguments)},Xy=c._PadV2=function(){return(Xy=c._PadV2=c.asm.PadV2).apply(null,arguments)},Yy=c._Pow=function(){return(Yy=c._Pow=c.asm.Pow).apply(null,arguments)},yl=c._Prelu=function(){return(yl=c._Prelu=c.asm.Prelu).apply(null,arguments)},ph=c._Prod=function(){return(ph=c._Prod=c.asm.Prod).apply(null,arguments)},xl=c._RealDiv=function(){return(xl=c._RealDiv=c.asm.RealDiv).apply(null,arguments)},vl=c._Reciprocal=function(){return(vl=c._Reciprocal=c.asm.Reciprocal).apply(null,arguments)},Zy=c._Relu=function(){return(Zy=c._Relu=c.asm.Relu).apply(null,arguments)},Y=c._Relu6=function(){return(Y=c._Relu6=c.asm.Relu6).apply(null,arguments)},oe=c._ResizeBilinear=function(){return(oe=c._ResizeBilinear=c.asm.ResizeBilinear).apply(null,arguments)},Ie=c._ResizeBilinearGrad=function(){return(Ie=c._ResizeBilinearGrad=c.asm.ResizeBilinearGrad).apply(null,arguments)},Ye=c._ResizeNearestNeighbor=function(){return(Ye=c._ResizeNearestNeighbor=c.asm.ResizeNearestNeighbor).apply(null,arguments)},wt=c._ResizeNearestNeighborGrad=function(){return(wt=c._ResizeNearestNeighborGrad=c.asm.ResizeNearestNeighborGrad).apply(null,arguments)},kt=c._Reverse=function(){return(kt=c._Reverse=c.asm.Reverse).apply(null,arguments)},Ge=c._RotateWithOffset=function(){return(Ge=c._RotateWithOffset=c.asm.RotateWithOffset).apply(null,arguments)},Be=c._Round=function(){return(Be=c._Round=c.asm.Round).apply(null,arguments)},Pt=c._Rsqrt=function(){return(Pt=c._Rsqrt=c.asm.Rsqrt).apply(null,arguments)},la=c._ScatterNd=function(){return(la=c._ScatterNd=c.asm.ScatterNd).apply(null,arguments)},vr=c._SearchSorted=function(){return(vr=c._SearchSorted=c.asm.SearchSorted).apply(null,arguments)},ch=c._SelectV2=function(){return(ch=c._SelectV2=c.asm.SelectV2).apply(null,arguments)},jp=c._Selu=function(){return(jp=c._Selu=c.asm.Selu).apply(null,arguments)},Jy=c._Sigmoid=function(){return(Jy=c._Sigmoid=c.asm.Sigmoid).apply(null,arguments)},Dn=c._Sign=function(){return(Dn=c._Sign=c.asm.Sign).apply(null,arguments)},qr=c._Sin=function(){return(qr=c._Sin=c.asm.Sin).apply(null,arguments)},dh=c._Sinh=function(){return(dh=c._Sinh=c.asm.Sinh).apply(null,arguments)},zD=c._Softmax=function(){return(zD=c._Softmax=c.asm.Softmax).apply(null,arguments)},WD=c._Softplus=function(){return(WD=c._Softplus=c.asm.Softplus).apply(null,arguments)},BD=c._SparseFillEmptyRows=function(){return(BD=c._SparseFillEmptyRows=c.asm.SparseFillEmptyRows).apply(null,arguments)},VD=c._SparseReshape=function(){return(VD=c._SparseReshape=c.asm.SparseReshape).apply(null,arguments)},UD=c._SparseSegmentReduction=function(){return(UD=c._SparseSegmentReduction=c.asm.SparseSegmentReduction).apply(null,arguments)},GD=c._SparseToDense=function(){return(GD=c._SparseToDense=c.asm.SparseToDense).apply(null,arguments)},HD=c._Sqrt=function(){return(HD=c._Sqrt=c.asm.Sqrt).apply(null,arguments)},qD=c._Square=function(){return(qD=c._Square=c.asm.Square).apply(null,arguments)},jD=c._SquaredDifference=function(){return(jD=c._SquaredDifference=c.asm.SquaredDifference).apply(null,arguments)},KD=c._Step=function(){return(KD=c._Step=c.asm.Step).apply(null,arguments)},XD=c._StridedSlice=function(){return(XD=c._StridedSlice=c.asm.StridedSlice).apply(null,arguments)},YD=c._Sub=function(){return(YD=c._Sub=c.asm.Sub).apply(null,arguments)},ZD=c._Sum=function(){return(ZD=c._Sum=c.asm.Sum).apply(null,arguments)},JD=c._Tan=function(){return(JD=c._Tan=c.asm.Tan).apply(null,arguments)},QD=c._Tanh=function(){return(QD=c._Tanh=c.asm.Tanh).apply(null,arguments)},eR=c._TensorScatterUpdate=function(){return(eR=c._TensorScatterUpdate=c.asm.TensorScatterUpdate).apply(null,arguments)},tR=c._Tile=function(){return(tR=c._Tile=c.asm.Tile).apply(null,arguments)},nR=c._TopK=function(){return(nR=c._TopK=c.asm.TopK).apply(null,arguments)},aR=c._Transform=function(){return(aR=c._Transform=c.asm.Transform).apply(null,arguments)},rR=c._Transpose=function(){return(rR=c._Transpose=c.asm.Transpose).apply(null,arguments)},sR=c.__FusedMatMul=function(){return(sR=c.__FusedMatMul=c.asm._FusedMatMul).apply(null,arguments)},iR=c._malloc=function(){return(iR=c._malloc=c.asm.malloc).apply(null,arguments)},oR=c._free=function(){return(oR=c._free=c.asm.free).apply(null,arguments)},lR=c.__emscripten_tls_init=function(){return(lR=c.__emscripten_tls_init=c.asm._emscripten_tls_init).apply(null,arguments)},hh=c._pthread_self=function(){return(hh=c._pthread_self=c.asm.pthread_self).apply(null,arguments)},uR=c.___errno_location=function(){return(uR=c.___errno_location=c.asm.__errno_location).apply(null,arguments)},Lk=c.__emscripten_thread_init=function(){return(Lk=c.__emscripten_thread_init=c.asm._emscripten_thread_init).apply(null,arguments)},pR=c.__emscripten_thread_crashed=function(){return(pR=c.__emscripten_thread_crashed=c.asm._emscripten_thread_crashed).apply(null,arguments)},cR=c._emscripten_main_thread_process_queued_calls=function(){return(cR=c._emscripten_main_thread_process_queued_calls=c.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},dR=c._emscripten_main_browser_thread_id=function(){return(dR=c._emscripten_main_browser_thread_id=c.asm.emscripten_main_browser_thread_id).apply(null,arguments)},zk=c._emscripten_run_in_main_runtime_thread_js=function(){return(zk=c._emscripten_run_in_main_runtime_thread_js=c.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},hR=c._emscripten_dispatch_to_thread_=function(){return(hR=c._emscripten_dispatch_to_thread_=c.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},Wk=c.__emscripten_proxy_execute_task_queue=function(){return(Wk=c.__emscripten_proxy_execute_task_queue=c.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},Qy=c.__emscripten_thread_free_data=function(){return(Qy=c.__emscripten_thread_free_data=c.asm._emscripten_thread_free_data).apply(null,arguments)},Bk=c.__emscripten_thread_exit=function(){return(Bk=c.__emscripten_thread_exit=c.asm._emscripten_thread_exit).apply(null,arguments)},Vk=c._emscripten_stack_set_limits=function(){return(Vk=c._emscripten_stack_set_limits=c.asm.emscripten_stack_set_limits).apply(null,arguments)},ex=c.stackSave=function(){return(ex=c.stackSave=c.asm.stackSave).apply(null,arguments)},mh=c.stackRestore=function(){return(mh=c.stackRestore=c.asm.stackRestore).apply(null,arguments)},fh=c.stackAlloc=function(){return(fh=c.stackAlloc=c.asm.stackAlloc).apply(null,arguments)},mR=c.dynCall_iijjiiii=function(){return(mR=c.dynCall_iijjiiii=c.asm.dynCall_iijjiiii).apply(null,arguments)},fR=c.dynCall_jiji=function(){return(fR=c.dynCall_jiji=c.asm.dynCall_jiji).apply(null,arguments)};c.keepRuntimeAlive=Ia,c.wasmMemory=ue,c.cwrap=ib,c.ExitStatus=Us,c.PThread=Ae;var gh;xr=function R(){gh||Uk(),gh||(xr=R)};function Uk(R){if(R=R||b,Gr>0)return;if(C){h(c),Jt(),startWorker(c);return}if(Ur(),Gr>0)return;function q(){gh||(gh=!0,c.calledRun=!0,!ke&&(Jt(),h(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),Hd()))}c.setStatus?(c.setStatus("Running..."),setTimeout(function(){setTimeout(function(){c.setStatus("")},1),q()},1)):q()}if(c.preInit)for(typeof c.preInit=="function"&&(c.preInit=[c.preInit]);c.preInit.length>0;)c.preInit.pop()();Uk();var bh;f&&(bh={uncaughtException:process.listeners("uncaughtException").filter(function(R){return!f.uncaughtException.indexOf(R)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(R){return!f.unhandledRejection.indexOf(R)>-1})});var yh;if(typeof WasmBackendModule!="undefined")yh=WasmBackendModule;else if(typeof r!="undefined")yh=r;else throw new Error("Could not find wasm module in post.js");if(bh){var gR=yh._dispose;yh._dispose=function(){gR(),bh.uncaughtException.forEach(function(R){process.removeListener("uncaughtException",R)}),bh.unhandledRejection.forEach(function(R){process.removeListener("unhandledRejection",R)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}),BR=Vt((e,t)=>{t.exports.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
|
|
");return}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;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}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)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`}),VR=Vt((e,t)=>{var n=(()=>{var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};var s=typeof r!="undefined"?r:{},i,o;s.ready=new Promise(function(Y,oe){i=Y,o=oe});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),p=[],d="./this.program",c=(Y,oe)=>{throw oe},h=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function b(Y){return s.locateFile?s.locateFile(Y,g):g+Y}var y,x,v,I;function N(Y){Y instanceof fl||D("exiting due to exception: "+Y)}if(f){var C=kv(),_=$S();m?g=_.dirname(g)+"/":g=__dirname+"/",y=(Y,oe)=>(Y=Ur(Y)?new URL(Y):_.normalize(Y),C.readFileSync(Y,oe?void 0:"utf8")),v=Y=>{var oe=y(Y,!0);return oe.buffer||(oe=new Uint8Array(oe)),oe},x=(Y,oe,Ie)=>{Y=Ur(Y)?new URL(Y):_.normalize(Y),C.readFile(Y,function(Ye,wt){Ye?Ie(Ye):oe(wt.buffer)})},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(Y){if(!(Y instanceof fl))throw Y}),process.on("unhandledRejection",function(Y){throw Y}),c=(Y,oe)=>{if(Gn())throw process.exitCode=Y,oe;N(oe),process.exit(Y)},s.inspect=function(){return"[Emscripten Module object]"}}else(h||m)&&(m?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),a&&(g=a),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",y=Y=>{var oe=new XMLHttpRequest;return oe.open("GET",Y,!1),oe.send(null),oe.responseText},m&&(v=Y=>{var oe=new XMLHttpRequest;return oe.open("GET",Y,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),x=(Y,oe,Ie)=>{var Ye=new XMLHttpRequest;Ye.open("GET",Y,!0),Ye.responseType="arraybuffer",Ye.onload=()=>{if(Ye.status==200||Ye.status==0&&Ye.response){oe(Ye.response);return}Ie()},Ye.onerror=Ie,Ye.send(null)},I=Y=>document.title=Y);var F=s.print||console.log.bind(console),D=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(p=s.arguments),s.thisProgram&&(d=s.thisProgram),s.quit&&(c=s.quit);var $=4,S;s.wasmBinary&&(S=s.wasmBinary);var M=s.noExitRuntime||!0;typeof WebAssembly!="object"&&Za("no native wasm support detected");var B,U=!1,H;function j(Y,oe){Y||Za(oe)}var K=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Z(Y,oe,Ie){oe>>>=0;for(var Ye=oe+Ie,wt=oe;Y[wt]&&!(wt>=Ye);)++wt;if(wt-oe>16&&Y.buffer&&K)return K.decode(Y.subarray(oe,wt));for(var kt="";oe<wt;){var Ge=Y[oe++];if(!(Ge&128)){kt+=String.fromCharCode(Ge);continue}var Be=Y[oe++]&63;if((Ge&224)==192){kt+=String.fromCharCode((Ge&31)<<6|Be);continue}var Pt=Y[oe++]&63;if((Ge&240)==224?Ge=(Ge&15)<<12|Be<<6|Pt:Ge=(Ge&7)<<18|Be<<12|Pt<<6|Y[oe++]&63,Ge<65536)kt+=String.fromCharCode(Ge);else{var la=Ge-65536;kt+=String.fromCharCode(55296|la>>10,56320|la&1023)}}return kt}function J(Y,oe){return Y>>>=0,Y?Z(ie,Y,oe):""}function ee(Y,oe,Ie,Ye){if(Ie>>>=0,!(Ye>0))return 0;for(var wt=Ie,kt=Ie+Ye-1,Ge=0;Ge<Y.length;++Ge){var Be=Y.charCodeAt(Ge);if(Be>=55296&&Be<=57343){var Pt=Y.charCodeAt(++Ge);Be=65536+((Be&1023)<<10)|Pt&1023}if(Be<=127){if(Ie>=kt)break;oe[Ie++>>>0]=Be}else if(Be<=2047){if(Ie+1>=kt)break;oe[Ie++>>>0]=192|Be>>6,oe[Ie++>>>0]=128|Be&63}else if(Be<=65535){if(Ie+2>=kt)break;oe[Ie++>>>0]=224|Be>>12,oe[Ie++>>>0]=128|Be>>6&63,oe[Ie++>>>0]=128|Be&63}else{if(Ie+3>=kt)break;oe[Ie++>>>0]=240|Be>>18,oe[Ie++>>>0]=128|Be>>12&63,oe[Ie++>>>0]=128|Be>>6&63,oe[Ie++>>>0]=128|Be&63}}return oe[Ie>>>0]=0,Ie-wt}function ae(Y,oe,Ie){return ee(Y,ie,oe,Ie)}var te,se,ie,xe,ue,ye,ke,Se,Le;function Ue(Y){te=Y,s.HEAP8=se=new Int8Array(Y),s.HEAP16=xe=new Int16Array(Y),s.HEAP32=ye=new Int32Array(Y),s.HEAPU8=ie=new Uint8Array(Y),s.HEAPU16=ue=new Uint16Array(Y),s.HEAPU32=ke=new Uint32Array(Y),s.HEAPF32=Se=new Float32Array(Y),s.HEAPF64=Le=new Float64Array(Y)}var mt=s.INITIAL_MEMORY||16777216,st,tt=[],nt=[],Re=[],gt=!1;function Gn(){return M}function Ot(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)An(s.preRun.shift());xr(tt)}function ia(){gt=!0,xr(nt)}function ln(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Fn(s.postRun.shift());xr(Re)}function An(Y){tt.unshift(Y)}function oa(Y){nt.unshift(Y)}function Fn(Y){Re.unshift(Y)}var ut=0,$n=null,Hn=null;function yr(Y){ut++,s.monitorRunDependencies&&s.monitorRunDependencies(ut)}function ml(Y){if(ut--,s.monitorRunDependencies&&s.monitorRunDependencies(ut),ut==0&&($n!==null&&(clearInterval($n),$n=null),Hn)){var oe=Hn;Hn=null,oe()}}function Za(Y){s.onAbort&&s.onAbort(Y),Y="Aborted("+Y+")",D(Y),U=!0,H=1,Y+=". Build with -sASSERTIONS for more info.";var oe=new WebAssembly.RuntimeError(Y);throw o(oe),oe}var Wp="data:application/octet-stream;base64,";function Ia(Y){return Y.startsWith(Wp)}function Ur(Y){return Y.startsWith("file://")}var Jt;Jt="tfjs-backend-wasm.wasm",Ia(Jt)||(Jt=b(Jt));function Hd(Y){try{if(Y==Jt&&S)return new Uint8Array(S);if(v)return v(Y);throw"both async and sync fetching of the wasm failed"}catch(oe){Za(oe)}}function Ig(){if(!S&&(h||m)){if(typeof fetch=="function"&&!Ur(Jt))return fetch(Jt,{credentials:"same-origin"}).then(function(Y){if(!Y.ok)throw"failed to load wasm binary file at '"+Jt+"'";return Y.arrayBuffer()}).catch(function(){return Hd(Jt)});if(x)return new Promise(function(Y,oe){x(Jt,function(Ie){Y(new Uint8Array(Ie))},oe)})}return Promise.resolve().then(function(){return Hd(Jt)})}function Sg(){var Y={env:Bp,wasi_snapshot_preview1:Bp};function oe(Ge,Be){var Pt=Ge.exports;s.asm=Pt,B=s.asm.memory,Ue(B.buffer),st=s.asm.__indirect_function_table,oa(s.asm.__wasm_call_ctors),ml("wasm-instantiate")}yr("wasm-instantiate");function Ie(Ge){oe(Ge.instance)}function Ye(Ge){return Ig().then(function(Be){return WebAssembly.instantiate(Be,Y)}).then(function(Be){return Be}).then(Ge,function(Be){D("failed to asynchronously prepare wasm: "+Be),Za(Be)})}function wt(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!Ia(Jt)&&!Ur(Jt)&&!f&&typeof fetch=="function"?fetch(Jt,{credentials:"same-origin"}).then(function(Ge){var Be=WebAssembly.instantiateStreaming(Ge,Y);return Be.then(Ie,function(Pt){return D("wasm streaming compile failed: "+Pt),D("falling back to ArrayBuffer instantiation"),Ye(Ie)})}):Ye(Ie)}if(s.instantiateWasm)try{var kt=s.instantiateWasm(Y,oe);return kt}catch(Ge){D("Module.instantiateWasm callback failed with error: "+Ge),o(Ge)}return wt().catch(o),{}}var Rk,Gr;function fl(Y){this.name="ExitStatus",this.message="Program terminated with exit("+Y+")",this.status=Y}function xr(Y){for(;Y.length>0;)Y.shift()(s)}function Ng(){Za("")}function qd(){return 4294901760}function Vs(){return qd()}function Tg(Y,oe,Ie){ie.copyWithin(Y>>>0,oe>>>0,oe+Ie>>>0)}function jd(Y){try{return B.grow(Y-te.byteLength+65535>>>16),Ue(B.buffer),1}catch(oe){}}function gl(Y){var oe=ie.length;Y=Y>>>0;var Ie=qd();if(Y>Ie)return!1;let Ye=(Pt,la)=>Pt+(la-Pt%la)%la;for(var wt=1;wt<=4;wt*=2){var kt=oe*(1+.2/wt);kt=Math.min(kt,Y+100663296);var Ge=Math.min(Ie,Ye(Math.max(Y,kt),65536)),Be=jd(Ge);if(Be)return!0}return!1}var gn={varargs:void 0,get:function(){gn.varargs+=4;var Y=ye[gn.varargs-4>>>2];return Y},getStr:function(Y){var oe=J(Y);return oe}};function Kd(Y){return 52}function Cg(Y,oe,Ie,Ye,wt){return 70}var Eg=[null,[],[]];function Mk(Y,oe){var Ie=Eg[Y];oe===0||oe===10?((Y===1?F:D)(Z(Ie,0)),Ie.length=0):Ie.push(oe)}function Ok(Y,oe,Ie,Ye){for(var wt=0,kt=0;kt<Ie;kt++){var Ge=ke[oe>>>2],Be=ke[oe+4>>>2];oe+=8;for(var Pt=0;Pt<Be;Pt++)Mk(Y,ie[Ge+Pt>>>0]);wt+=Be}return ke[Ye>>>2]=wt,0}function Xd(Y){var oe=s["_"+Y];return oe}function Us(Y,oe){se.set(Y,oe>>>0)}function _g(Y,oe,Ie,Ye,wt){var kt={string:Dn=>{var qr=0;if(Dn!=null&&Dn!==0){var dh=(Dn.length<<2)+1;qr=qp(dh),ae(Dn,qr,dh)}return qr},array:Dn=>{var qr=qp(Dn.length);return Us(Dn,qr),qr}};function Ge(Dn){return oe==="string"?J(Dn):oe==="boolean"?!!Dn:Dn}var Be=Xd(Y),Pt=[],la=0;if(Ye)for(var vr=0;vr<Ye.length;vr++){var ch=kt[Ie[vr]];ch?(la===0&&(la=lh()),Pt[vr]=ch(Ye[vr])):Pt[vr]=Ye[vr]}var jp=Be.apply(null,Pt);function Jy(Dn){return la!==0&&uh(la),Ge(Dn)}return jp=Jy(jp),jp}function Ag(Y,oe,Ie,Ye){Ie=Ie||[];var wt=Ie.every(Ge=>Ge==="number"||Ge==="boolean"),kt=oe!=="string";return kt&&wt&&!Ye?Xd(Y):function(){return _g(Y,oe,Ie,arguments,Ye)}}var Bp={abort:Ng,emscripten_get_heap_max:Vs,emscripten_memcpy_big:Tg,emscripten_resize_heap:gl,fd_close:Kd,fd_seek:Cg,fd_write:Ok},Fg=Sg(),Yd=s.___wasm_call_ctors=function(){return(Yd=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},Zd=s._init=function(){return(Zd=s._init=s.asm.init).apply(null,arguments)},$g=s._init_with_threads_count=function(){return($g=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},Jd=s._get_threads_count=function(){return(Jd=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},Dg=s._register_tensor=function(){return(Dg=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},Ae=s._dispose_data=function(){return(Ae=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},Vp=s._dispose=function(){return(Vp=s._dispose=s.asm.dispose).apply(null,arguments)},Rg=s._Abs=function(){return(Rg=s._Abs=s.asm.Abs).apply(null,arguments)},Qd=s._Acos=function(){return(Qd=s._Acos=s.asm.Acos).apply(null,arguments)},bl=s._Acosh=function(){return(bl=s._Acosh=s.asm.Acosh).apply(null,arguments)},Mg=s._Add=function(){return(Mg=s._Add=s.asm.Add).apply(null,arguments)},Og=s._AddN=function(){return(Og=s._AddN=s.asm.AddN).apply(null,arguments)},Pg=s._All=function(){return(Pg=s._All=s.asm.All).apply(null,arguments)},Lg=s._Any=function(){return(Lg=s._Any=s.asm.Any).apply(null,arguments)},zg=s._ArgMax=function(){return(zg=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},eh=s._ArgMin=function(){return(eh=s._ArgMin=s.asm.ArgMin).apply(null,arguments)},th=s._Asin=function(){return(th=s._Asin=s.asm.Asin).apply(null,arguments)},Wg=s._Asinh=function(){return(Wg=s._Asinh=s.asm.Asinh).apply(null,arguments)},Bg=s._Atan=function(){return(Bg=s._Atan=s.asm.Atan).apply(null,arguments)},Vg=s._Atan2=function(){return(Vg=s._Atan2=s.asm.Atan2).apply(null,arguments)},Up=s._Atanh=function(){return(Up=s._Atanh=s.asm.Atanh).apply(null,arguments)},Ug=s._AvgPool=function(){return(Ug=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},Gg=s._AvgPool3D=function(){return(Gg=s._AvgPool3D=s.asm.AvgPool3D).apply(null,arguments)},Hg=s._AvgPool3DGrad=function(){return(Hg=s._AvgPool3DGrad=s.asm.AvgPool3DGrad).apply(null,arguments)},Gs=s._AvgPoolGrad=function(){return(Gs=s._AvgPoolGrad=s.asm.AvgPoolGrad).apply(null,arguments)},qg=s._BatchMatMul=function(){return(qg=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},jg=s._Bincount=function(){return(jg=s._Bincount=s.asm.Bincount).apply(null,arguments)},nh=s._BitwiseAnd=function(){return(nh=s._BitwiseAnd=s.asm.BitwiseAnd).apply(null,arguments)},Kg=s._Ceil=function(){return(Kg=s._Ceil=s.asm.Ceil).apply(null,arguments)},Gp=s._ClipByValue=function(){return(Gp=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Xg=s._Conv2D=function(){return(Xg=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},Yg=s._Conv2DBackpropInput=function(){return(Yg=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},Zg=s._Conv3D=function(){return(Zg=s._Conv3D=s.asm.Conv3D).apply(null,arguments)},Hr=s._Conv3DBackpropFilterV2=function(){return(Hr=s._Conv3DBackpropFilterV2=s.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Hp=s._Conv3DBackpropInputV2=function(){return(Hp=s._Conv3DBackpropInputV2=s.asm.Conv3DBackpropInputV2).apply(null,arguments)},Jg=s._Cos=function(){return(Jg=s._Cos=s.asm.Cos).apply(null,arguments)},Qg=s._Cosh=function(){return(Qg=s._Cosh=s.asm.Cosh).apply(null,arguments)},eb=s._CropAndResize=function(){return(eb=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},tb=s._Cumprod=function(){return(tb=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},ah=s._Cumsum=function(){return(ah=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},rh=s._DenseBincount=function(){return(rh=s._DenseBincount=s.asm.DenseBincount).apply(null,arguments)},nb=s._DepthToSpace=function(){return(nb=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},ab=s._DepthwiseConv2dNative=function(){return(ab=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},sh=s._Diag=function(){return(sh=s._Diag=s.asm.Diag).apply(null,arguments)},ih=s._Dilation2D=function(){return(ih=s._Dilation2D=s.asm.Dilation2D).apply(null,arguments)},rb=s._Dilation2DBackpropFilter=function(){return(rb=s._Dilation2DBackpropFilter=s.asm.Dilation2DBackpropFilter).apply(null,arguments)},sb=s._Dilation2DBackpropInput=function(){return(sb=s._Dilation2DBackpropInput=s.asm.Dilation2DBackpropInput).apply(null,arguments)},ib=s._Elu=function(){return(ib=s._Elu=s.asm.Elu).apply(null,arguments)},ob=s._EluGrad=function(){return(ob=s._EluGrad=s.asm.EluGrad).apply(null,arguments)},oh=s._Equal=function(){return(oh=s._Equal=s.asm.Equal).apply(null,arguments)},Pk=s._Erf=function(){return(Pk=s._Erf=s.asm.Erf).apply(null,arguments)},lb=s._Exp=function(){return(lb=s._Exp=s.asm.Exp).apply(null,arguments)},ub=s._Expm1=function(){return(ub=s._Expm1=s.asm.Expm1).apply(null,arguments)},pb=s._FlipLeftRight=function(){return(pb=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},cb=s._Floor=function(){return(cb=s._Floor=s.asm.Floor).apply(null,arguments)},db=s._FloorDiv=function(){return(db=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},hb=s._FusedBatchNorm=function(){return(hb=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},mb=s._FusedConv2D=function(){return(mb=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},fb=s._FusedDepthwiseConv2D=function(){return(fb=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},gb=s._Gather=function(){return(gb=s._Gather=s.asm.Gather).apply(null,arguments)},bb=s._GatherNd=function(){return(bb=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},yb=s._Greater=function(){return(yb=s._Greater=s.asm.Greater).apply(null,arguments)},xb=s._GreaterEqual=function(){return(xb=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},vb=s._IsFinite=function(){return(vb=s._IsFinite=s.asm.IsFinite).apply(null,arguments)},wb=s._IsInf=function(){return(wb=s._IsInf=s.asm.IsInf).apply(null,arguments)},kb=s._IsNan=function(){return(kb=s._IsNan=s.asm.IsNan).apply(null,arguments)},Ib=s._LRN=function(){return(Ib=s._LRN=s.asm.LRN).apply(null,arguments)},Sb=s._LRNGrad=function(){return(Sb=s._LRNGrad=s.asm.LRNGrad).apply(null,arguments)},Nb=s._LeakyRelu=function(){return(Nb=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},Tb=s._Less=function(){return(Tb=s._Less=s.asm.Less).apply(null,arguments)},Cb=s._LessEqual=function(){return(Cb=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},Eb=s._LinSpace=function(){return(Eb=s._LinSpace=s.asm.LinSpace).apply(null,arguments)},_b=s._Log=function(){return(_b=s._Log=s.asm.Log).apply(null,arguments)},Ab=s._Log1p=function(){return(Ab=s._Log1p=s.asm.Log1p).apply(null,arguments)},Fb=s._LogicalAnd=function(){return(Fb=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},$b=s._LogicalNot=function(){return($b=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},Db=s._LogicalOr=function(){return(Db=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},Rb=s._LogicalXor=function(){return(Rb=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},Mb=s._Max=function(){return(Mb=s._Max=s.asm.Max).apply(null,arguments)},Ob=s._MaxPool=function(){return(Ob=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Pb=s._MaxPool3D=function(){return(Pb=s._MaxPool3D=s.asm.MaxPool3D).apply(null,arguments)},Lb=s._MaxPool3DGrad=function(){return(Lb=s._MaxPool3DGrad=s.asm.MaxPool3DGrad).apply(null,arguments)},zb=s._MaxPoolGrad=function(){return(zb=s._MaxPoolGrad=s.asm.MaxPoolGrad).apply(null,arguments)},Wb=s._MaxPoolWithArgmax=function(){return(Wb=s._MaxPoolWithArgmax=s.asm.MaxPoolWithArgmax).apply(null,arguments)},Bb=s._Maximum=function(){return(Bb=s._Maximum=s.asm.Maximum).apply(null,arguments)},Vb=s._Mean=function(){return(Vb=s._Mean=s.asm.Mean).apply(null,arguments)},Ub=s._Min=function(){return(Ub=s._Min=s.asm.Min).apply(null,arguments)},Gb=s._Minimum=function(){return(Gb=s._Minimum=s.asm.Minimum).apply(null,arguments)},Hb=s._MirrorPad=function(){return(Hb=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},qb=s._Mod=function(){return(qb=s._Mod=s.asm.Mod).apply(null,arguments)},jb=s._Multinomial=function(){return(jb=s._Multinomial=s.asm.Multinomial).apply(null,arguments)},Kb=s._Multiply=function(){return(Kb=s._Multiply=s.asm.Multiply).apply(null,arguments)},Xb=s._Neg=function(){return(Xb=s._Neg=s.asm.Neg).apply(null,arguments)},Yb=s._NonMaxSuppressionV3=function(){return(Yb=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},Zb=s._NonMaxSuppressionV4=function(){return(Zb=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},Jb=s._NonMaxSuppressionV5=function(){return(Jb=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Qb=s._NotEqual=function(){return(Qb=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},ey=s._OneHot=function(){return(ey=s._OneHot=s.asm.OneHot).apply(null,arguments)},ty=s._PadV2=function(){return(ty=s._PadV2=s.asm.PadV2).apply(null,arguments)},ny=s._Pow=function(){return(ny=s._Pow=s.asm.Pow).apply(null,arguments)},ay=s._Prelu=function(){return(ay=s._Prelu=s.asm.Prelu).apply(null,arguments)},ry=s._Prod=function(){return(ry=s._Prod=s.asm.Prod).apply(null,arguments)},sy=s._RealDiv=function(){return(sy=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},iy=s._Reciprocal=function(){return(iy=s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},oy=s._Relu=function(){return(oy=s._Relu=s.asm.Relu).apply(null,arguments)},ly=s._Relu6=function(){return(ly=s._Relu6=s.asm.Relu6).apply(null,arguments)},uy=s._ResizeBilinear=function(){return(uy=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},py=s._ResizeBilinearGrad=function(){return(py=s._ResizeBilinearGrad=s.asm.ResizeBilinearGrad).apply(null,arguments)},cy=s._ResizeNearestNeighbor=function(){return(cy=s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},dy=s._ResizeNearestNeighborGrad=function(){return(dy=s._ResizeNearestNeighborGrad=s.asm.ResizeNearestNeighborGrad).apply(null,arguments)},hy=s._Reverse=function(){return(hy=s._Reverse=s.asm.Reverse).apply(null,arguments)},my=s._RotateWithOffset=function(){return(my=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},fy=s._Round=function(){return(fy=s._Round=s.asm.Round).apply(null,arguments)},gy=s._Rsqrt=function(){return(gy=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},by=s._ScatterNd=function(){return(by=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},yy=s._SearchSorted=function(){return(yy=s._SearchSorted=s.asm.SearchSorted).apply(null,arguments)},xy=s._SelectV2=function(){return(xy=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},vy=s._Selu=function(){return(vy=s._Selu=s.asm.Selu).apply(null,arguments)},wy=s._Sigmoid=function(){return(wy=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},ky=s._Sign=function(){return(ky=s._Sign=s.asm.Sign).apply(null,arguments)},Iy=s._Sin=function(){return(Iy=s._Sin=s.asm.Sin).apply(null,arguments)},Sy=s._Sinh=function(){return(Sy=s._Sinh=s.asm.Sinh).apply(null,arguments)},Ny=s._Softmax=function(){return(Ny=s._Softmax=s.asm.Softmax).apply(null,arguments)},Ty=s._Softplus=function(){return(Ty=s._Softplus=s.asm.Softplus).apply(null,arguments)},Cy=s._SparseFillEmptyRows=function(){return(Cy=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},Ey=s._SparseReshape=function(){return(Ey=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},_y=s._SparseSegmentReduction=function(){return(_y=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},Ay=s._SparseToDense=function(){return(Ay=s._SparseToDense=s.asm.SparseToDense).apply(null,arguments)},Fy=s._Sqrt=function(){return(Fy=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},$y=s._Square=function(){return($y=s._Square=s.asm.Square).apply(null,arguments)},Dy=s._SquaredDifference=function(){return(Dy=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},Ry=s._Step=function(){return(Ry=s._Step=s.asm.Step).apply(null,arguments)},My=s._StridedSlice=function(){return(My=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},Oy=s._Sub=function(){return(Oy=s._Sub=s.asm.Sub).apply(null,arguments)},Py=s._Sum=function(){return(Py=s._Sum=s.asm.Sum).apply(null,arguments)},Ly=s._Tan=function(){return(Ly=s._Tan=s.asm.Tan).apply(null,arguments)},zy=s._Tanh=function(){return(zy=s._Tanh=s.asm.Tanh).apply(null,arguments)},Wy=s._TensorScatterUpdate=function(){return(Wy=s._TensorScatterUpdate=s.asm.TensorScatterUpdate).apply(null,arguments)},By=s._Tile=function(){return(By=s._Tile=s.asm.Tile).apply(null,arguments)},Vy=s._TopK=function(){return(Vy=s._TopK=s.asm.TopK).apply(null,arguments)},Uy=s._Transform=function(){return(Uy=s._Transform=s.asm.Transform).apply(null,arguments)},Gy=s._Transpose=function(){return(Gy=s._Transpose=s.asm.Transpose).apply(null,arguments)},Hy=s.__FusedMatMul=function(){return(Hy=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},qy=s._malloc=function(){return(qy=s._malloc=s.asm.malloc).apply(null,arguments)},jy=s._free=function(){return(jy=s._free=s.asm.free).apply(null,arguments)},Ky=s.___errno_location=function(){return(Ky=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},lh=s.stackSave=function(){return(lh=s.stackSave=s.asm.stackSave).apply(null,arguments)},uh=s.stackRestore=function(){return(uh=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},qp=s.stackAlloc=function(){return(qp=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},Xy=s.dynCall_iijjiiii=function(){return(Xy=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},Yy=s.dynCall_jiji=function(){return(Yy=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=Ag;var yl;Hn=function Y(){yl||ph(),yl||(Hn=Y)};function ph(Y){if(Y=Y||p,ut>0||(Ot(),ut>0))return;function oe(){yl||(yl=!0,s.calledRun=!0,!U&&(ia(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),ln()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),oe()},1)):oe()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();ph();var xl;l&&(xl={uncaughtException:process.listeners("uncaughtException").filter(function(Y){return!l.uncaughtException.indexOf(Y)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(Y){return!l.unhandledRejection.indexOf(Y)>-1})});var vl;if(typeof r!="undefined")vl=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")vl=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(xl){var Zy=vl._dispose;vl._dispose=function(){Zy(),xl.uncaughtException.forEach(function(Y){process.removeListener("uncaughtException",Y)}),xl.unhandledRejection.forEach(function(Y){process.removeListener("unhandledRejection",Y)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}),ym=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}},Fc=class{refCount(e){return qn("refCount")}incRef(e){return qn("incRef")}timerAvailable(){return!0}time(e){return qn("time")}read(e){return qn("read")}readSync(e){return qn("readSync")}readToGPU(e,t){return qn("readToGPU")}numDataIds(){return qn("numDataIds")}disposeData(e,t){return qn("disposeData")}write(e,t,n){return qn("write")}move(e,t,n,a,r){return qn("move")}createTensorFromGPUData(e,t,n){return qn("createTensorFromGPUData")}memory(){return qn("memory")}floatPrecision(){return qn("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return qn("dispose")}};function qn(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 DS(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Vh(e,t,n)}function UR(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,a=0;for(;n>0;)a=Math.random()*n|0,n--,Vh(e,n,a),Vh(t,n,a)}function hc(e,t,n){return Math.max(e,Math.min(t,n))}function GR(e){return e%2===0?e:e+1}function Vh(e,t,n){let a=e[t];e[t]=e[n],e[n]=a}function HR(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function qR(e,t){let n=Math.random();return t*n+(1-n)*e}function jR(e,t){let n=0;for(let a=0;a<e.length;a++){let r=Number(e[a])-Number(t[a]);n+=r*r}return n}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Sn(e,t,n=""){A(Ar(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Si(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ot(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 KR(e){return e.length===0}function RS(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]!==null&&t[n]!==null&&e[n]!==t[n])return!1;return!0}function Ar(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 $l(e){return e%1===0}function XR(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 YR(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ZR(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return DS(t),t}function uc(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function JR(e,t=r=>0,n,a){return new Promise((r,s)=>{let i=0,o=()=>{if(e()){r();return}i++;let l=t(i);if(n!=null&&i>=n){s();return}a!=null?a(o,l):setTimeout(o,l)};o()})}function QR(e,t){let n=1,a=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)n*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let r=e.slice();return r[a]=t/n,r}function Aa(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),A(e.every(a=>a>=-n&&a<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(a=>$l(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function MS(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:Aa(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(n.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(n.push(e[o]),a.push(o))}return{newShape:n,keptDims:a}}function OS(e,t){return Iv(e,t)}function Iv(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 PS(e,t){for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))throw Error(`A tensor of type ${t} being uploaded contains ${a}.`)}}function LS(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function eM(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function Uh(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 zS(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Jr(e){return typeof e=="string"||e instanceof String}function WS(e){return typeof e=="boolean"}function BS(e){return typeof e=="number"}function $c(e){return Array.isArray(e)?$c(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":BS(e)?"float32":Jr(e)?"string":WS(e)?"bool":"float32"}function ss(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Gh(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Xl(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let a=t-3;a>=0;--a)n[a]=n[a+1]*e[a+1];return n}function VS(e,t,n,a=!1){let r=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;i<s;i++)r[i]=n[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,u)=>l*u)*(a?2:1);for(let l=0;l<s;l++)r[l]=VS(e+l*o,i,n,a)}return r}function El(e,t,n=!1){if(e.length===0)return t[0];let a=e.reduce((r,s)=>r*s)*(n?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return VS(0,e,t,n)}function tM(e,t){if(Array.isArray(e))return e;if(t==="float32")return e instanceof Float32Array?e:new Float32Array(e);if(t==="int32")return e instanceof Int32Array?e:new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Sv(e,t){let n=xm(e,t);for(let a=0;a<n.length;a++)n[a]=1;return n}function xm(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 nM(e,t){let n=e.reduce((a,r)=>a*r,1);if(t==null||t==="float32")return El(e,new Float32Array(n));if(t==="int32")return El(e,new Int32Array(n));if(t==="bool")return El(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function na(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function aM(e,t,n){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let r=0;r<e.length-1;++r)a+=n[r]*e[r];return a}function rM(e,t,n){if(t===0)return[];if(t===1)return[e];let a=new Array(t);for(let r=0;r<a.length-1;++r)a[r]=Math.floor(e/n[r]),e-=a[r]*n[r];return a[a.length-1]=e,a}function vm(e){return e&&e.then&&typeof e.then=="function"}var qk="tfjsflags",US=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=sM,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let a=this.urlFlags[e];G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${a}.`),this.set(e,a)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(vm(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)}getString(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);qk in e&&e[qk].split(",").forEach(t=>{let[n,a]=t.split(":");this.urlFlags[n]=oM(n,a)})}};function sM(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(iM(t,a[0],a[1]),a.join("="))),t}function iM(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function oM(e,t){let n=t.toLowerCase();return n==="true"||n==="false"?n==="true":`${+n}`===n?+n:t}function G(){return Nv}var Nv=null;function lM(e){Nv=e}var ax;function GS(){if(ax==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");ax=e}return ax}function uM(){let e=GS();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Tv(e,t){let n=uM();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var Yl="Abs",Ni="Acos",Ti="Acosh",xs="Add",Ci="AddN",Zl="All",Jl="Any",Ql="ArgMax",eu="ArgMin",Ei="Asin",_i="Asinh",Ai="Atan",Fi="Atanh",$i="Atan2",Di="AvgPool",Dc="AvgPoolGrad",tu="AvgPool3D",Rc="AvgPool3DGrad",Ri="BatchMatMul",nu="BatchToSpaceND",au="Bincount",ru="BitwiseAnd",HS="BroadcastTo",Mc="BroadcastArgs",Mi="Cast",Oi="Ceil",vs="ClipByValue",wm="Complex",Oc="ComplexAbs",su="Concat",Pi="Conv2D",km="Conv2DBackpropFilter",Li="Conv2DBackpropInput",zi="Conv3D",iu="Conv3DBackpropFilterV2",ou="Conv3DBackpropInputV2",Wi="Cos",Bi="Cosh",lu="Cumprod",Vi="Cumsum",uu="CropAndResize",Pc="DenseBincount",pu="DepthToSpace",Ui="DepthwiseConv2dNative",Im="DepthwiseConv2dNativeBackpropFilter",Sm="DepthwiseConv2dNativeBackpropInput",Lc="Diag",Gi="Dilation2D",Dl="Dilation2DBackpropInput",Rl="Dilation2DBackpropFilter",Nm="Draw",Hi="RealDiv",Tm="Einsum",qi="Elu",cu="EluGrad",ji="Erf",du="Equal",Ki="Exp",hu="ExpandDims",Xi="Expm1",Cm="FFT",zc="Fill",mu="FlipLeftRight",Yi="Floor",Zi="FloorDiv",Ji="FusedBatchNorm",fu="GatherV2",gu="GatherNd",bu="Greater",Qi="GreaterEqual",eo="Identity",Em="IFFT",_m="Imag",to="IsFinite",no="IsInf",ao="IsNan",ro="LeakyRelu",yu="Less",xu="LessEqual",vu="LinSpace",so="Log",io="Log1p",wu="LogicalAnd",ku="LogicalNot",Iu="LogicalOr",qS="LogicalXor",jS="LogSoftmax",pM="LowerBound",oo="LRN",Su="LRNGrad",cM="MatrixBandPart",lo="Max",uo="Maximum",po="MaxPool",Wc="MaxPoolGrad",Nu="MaxPool3D",Bc="MaxPool3DGrad",Vc="MaxPoolWithArgmax",co="Mean",ho="Min",mo="Minimum",fo="MirrorPad",go="Mod",Tu="Multinomial",bo="Multiply",Cu="Neg",Eu="NotEqual",_u="NonMaxSuppressionV3",Au="NonMaxSuppressionV4",Fu="NonMaxSuppressionV5",$u="OnesLike",yo="OneHot",Du="Pack",xo="PadV2",dM="Pool",vo="Pow",wo="Prelu",ko="Prod",Am="RaggedGather",Fm="RaggedRange",$m="RaggedTensorToTensor",Uc="Range",Dm="Real",Io="Reciprocal",So="Relu",Ru="Reshape",No="ResizeNearestNeighbor",Mu="ResizeNearestNeighborGrad",To="ResizeBilinear",Ou="ResizeBilinearGrad",Co="Relu6",Eo="Reverse",_o="Round",Ao="Rsqrt",Pu="ScatterNd",Lu="TensorScatterUpdate",zu="SearchSorted",Wu="Select",Fo="Selu",Bu="Slice",$o="Sin",Do="Sinh",Ro="Sign",Mo="Sigmoid",Oo="Softplus",Po="Sqrt",Lo="Sum",Vu="SpaceToBatchND",Uu="SplitV",zo="Softmax",Gc="SparseFillEmptyRows",Gu="SparseReshape",Hc="SparseSegmentMean",qc="SparseSegmentSum",Hu="SparseToDense",Wo="SquaredDifference",jc="Square",Kc="StaticRegexReplace",qu="StridedSlice",Xc="StringNGrams",Yc="StringSplit",Zc="StringToHashBucketFast",Bo="Sub",Vo="Tan",Uo="Tanh",ws="Tile",ju="TopK",Ku="Transform",Tr="Transpose",Jc="Unique",Xu="Unpack",Qc="UnsortedSegmentSum",hM="UpperBound",Yu="ZerosLike",ks="Step",Hh="FromPixels",Zu="RotateWithOffset",si="_FusedMatMul",ii="FusedConv2D",oi="FusedDepthwiseConv2D";function Zr(...e){G().getBool("IS_TEST")||G().getBool("PROD")||console.warn(...e)}function mM(...e){G().getBool("IS_TEST")||G().getBool("PROD")||console.log(...e)}var Ml=Tv("kernelRegistry",()=>new Map),mc=Tv("gradRegistry",()=>new Map);function fc(e,t){let n=Cv(e,t);return Ml.get(n)}function xx(e){return mc.get(e)}function qh(e){let t=Ml.entries(),n=[];for(;;){let{done:a,value:r}=t.next();if(a)break;let[s,i]=r,[o]=s.split("_");o===e&&n.push(i)}return n}function ed(e){let{kernelName:t,backendName:n}=e,a=Cv(t,n);Ml.has(a)&&Zr(`The kernel '${t}' for backend '${n}' is already registered`),Ml.set(a,e)}function KS(e){let{kernelName:t}=e;mc.has(t)&&G().getBool("DEBUG")&&Zr(`Overriding the gradient for '${t}'`),mc.set(t,e)}function fM(e,t){let n=Cv(e,t);if(!Ml.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ml.delete(n)}function gM(e){if(!mc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);mc.delete(e)}function bM(e,t){qh(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});ed(a)})}function Cv(e,t){return`${t}_${e}`}var w={};_e(w,{arraysEqual:()=>Ar,arraysEqualWithNull:()=>RS,assert:()=>A,assertNonNegativeIntegerDimensions:()=>na,assertNonNull:()=>Si,assertShapesMatch:()=>Sn,bytesFromStringArray:()=>zS,bytesPerElement:()=>Uh,checkConversionForErrors:()=>PS,clamp:()=>hc,computeStrides:()=>Xl,convertBackendValuesAndArrayBuffer:()=>tM,createScalarValue:()=>IM,createShuffledIndices:()=>ZR,decodeString:()=>jh,distSquared:()=>jR,encodeString:()=>nd,fetch:()=>NM,fingerPrint64:()=>kM,flatten:()=>is,getArrayFromDType:()=>Iv,getTypedArrayFromDType:()=>OS,hasEncodingLoss:()=>eM,hexToLong:()=>td,indexToLoc:()=>rM,inferDtype:()=>$c,inferFromImplicitShape:()=>QR,isBoolean:()=>WS,isFunction:()=>ss,isInt:()=>$l,isNumber:()=>BS,isPromise:()=>vm,isScalarShape:()=>KR,isString:()=>Jr,isTypedArray:()=>en,isValidDtype:()=>LS,locToIndex:()=>aM,makeOnesTypedArray:()=>Sv,makeZerosNestedTypedArray:()=>nM,makeZerosTypedArray:()=>xm,nearestDivisor:()=>Gh,nearestLargerEven:()=>GR,now:()=>gc,parseAxisParam:()=>Aa,randUniform:()=>qR,repeatedTry:()=>JR,rightPad:()=>uc,shuffle:()=>DS,shuffleCombo:()=>UR,sizeFromShape:()=>ot,sizeToSquarishShape:()=>YR,squeezeShape:()=>MS,sum:()=>HR,swap:()=>Vh,tanh:()=>XR,toNestedArray:()=>El,toTypedArray:()=>Rm});function XS(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var jk=ys(TR()),Xs=jk.default||jk;function td(e){return Xs.fromString(e,!0,16)}var YS=td("c3a5c85c97cb3127"),js=td("b492b66fbe98f273"),vn=td("9ae16a3b2f90404f");function vx(e){return e.xor(e.shru(47))}function ZS(e,t,n){let a=e.slice(t,t+n);return Xs.fromBytes(Array.from(a),!0,!0)}function bt(e,t){return ZS(e,t,8)}function Kk(e,t){return ZS(e,t,4)}function Qt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function ns(e,t,n=td("9ddfea08eb382d69")){let a=e.xor(t).mul(n);a=a.xor(a.shru(47));let r=t.xor(a).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function yM(e,t,n,a,r,s){r=r.add(e),s=Qt(s.add(r).add(a),21);let i=r;return r=r.add(t),r=r.add(n),s=s.add(Qt(r,44)),[r.add(a),s.add(i)]}function xh(e,t,n,a){return yM(bt(e,t),bt(e,t+8),bt(e,t+16),bt(e,t+24),n,a)}function xM(e,t=e.length){if(t>=8){let n=vn.add(t*2),a=bt(e,0).add(vn),r=bt(e,t-8),s=Qt(r,37).mul(n).add(a),i=Qt(a,25).add(r).mul(n);return ns(s,i,n)}if(t>=4){let n=vn.add(t*2),a=Kk(e,0);return ns(a.shl(3).add(t),Kk(e,t-4),n)}if(t>0){let n=e[0],a=e[t>>1],r=e[t-1],s=n+(a<<8),i=t+(r<<2);return vx(vn.mul(s).xor(YS.mul(i))).mul(vn)}return vn}function vM(e,t=e.length){let n=vn.add(t*2),a=bt(e,0).mul(js),r=bt(e,8),s=bt(e,t-8).mul(n),i=bt(e,t-16).mul(vn);return ns(Qt(a.add(r),43).add(Qt(s,30)).add(i),a.add(Qt(r.add(vn),18)).add(s),n)}function wM(e,t=e.length){let n=vn.add(t*2),a=bt(e,0).mul(vn),r=bt(e,8),s=bt(e,t-8).mul(n),i=bt(e,t-16).mul(vn),o=Qt(a.add(r),43).add(Qt(s,30)).add(i),l=ns(o,a.add(Qt(r.add(vn),18)).add(s),n),u=bt(e,16).mul(n),p=bt(e,24),d=o.add(bt(e,t-32)).mul(n),c=l.add(bt(e,t-24)).mul(n);return ns(Qt(u.add(p),43).add(Qt(d,30)).add(c),u.add(Qt(p.add(a),18)).add(d),n)}function kM(e,t=e.length){let n=Xs.fromNumber(81,!0);if(t<=32)return t<=16?xM(e,t):vM(e,t);if(t<=64)return wM(e,t);let a=n,r=n.mul(js).add(113),s=vx(r.mul(vn).add(113)).mul(vn),i=[Xs.UZERO,Xs.UZERO],o=[Xs.UZERO,Xs.UZERO];a=a.mul(vn).add(bt(e,0));let l=0,u=(t-1>>6)*64,p=u+(t-1&63)-63;do a=Qt(a.add(r).add(i[0]).add(bt(e,l+8)),37).mul(js),r=Qt(r.add(i[1]).add(bt(e,l+48)),42).mul(js),a=a.xor(o[1]),r=r.add(i[0]).add(bt(e,l+40)),s=Qt(s.add(o[0]),33).mul(js),i=xh(e,l,i[1].mul(js),a.add(o[0])),o=xh(e,l+32,s.add(o[1]),r.add(bt(e,l+16))),[s,a]=[a,s],l+=64;while(l!==u);let d=js.add(s.and(255).shl(1));return l=p,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=Qt(a.add(r).add(i[0]).add(bt(e,l+8)),37).mul(d),r=Qt(r.add(i[1]).add(bt(e,l+48)),42).mul(d),a=a.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(bt(e,l+40))),s=Qt(s.add(o[0]),33).mul(d),i=xh(e,l,i[1].mul(d),a.add(o[0])),o=xh(e,l+32,s.add(o[1]),r.add(bt(e,l+16))),[s,a]=[a,s],ns(ns(i[0],o[0],d).add(vx(r).mul(YS)).add(s),ns(i[1],o[1],d).add(a),d)}function IM(e,t){return t==="string"?nd(e):Rm([e],t)}function SM(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Rm(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=is(e)),G().getBool("DEBUG")&&PS(e,t),SM(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let a=0;a<n.length;++a)Math.round(e[a])!==0&&(n[a]=1);return n}else throw new Error(`Unknown data type ${t}`)}function gc(){return G().platform.now()}function NM(e,t){return G().platform.fetch(e,t)}function nd(e,t="utf-8"){return t=t||"utf-8",G().platform.encode(e,t)}function jh(e,t="utf-8"){return t=t||"utf-8",G().platform.decode(e,t)}function en(e){return G().platform.isTypedArray!=null?G().platform.isTypedArray(e):XS(e)}function is(e,t=[],n=!1){if(t==null&&(t=[]),typeof e=="boolean"||typeof e=="number"||typeof e=="string"||vm(e)||e==null||en(e)&&n)t.push(e);else if(Array.isArray(e)||en(e))for(let a=0;a<e.length;++a)is(e[a],t,n);else{let a=-1;for(let r of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(r)&&(a=Math.max(a,Number(r)));for(let r=0;r<=a;r++)is(e[r],t,n)}return t}var TM=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new EM)}profileKernel(e,t,n){let a,r=()=>{a=n()},s,i=gc();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:gc()-i})}if(G().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<a.length;o++){let l=a[o];l.data().then(u=>{CM(u,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function CM(e,t,n){if(t!=="float32")return!1;for(let a=0;a<e.length;a++){let r=e[a];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}var EM=class{logKernelProfile(e,t,n,a,r,s){let i=typeof a=="number"?uc(`${a}ms`,9):a.error,o=uc(e,25),l=t.rank,u=t.size,p=uc(t.shape.toString(),14),d="";for(let c in r){let h=r[c];if(h!=null){let m=h.shape||t.shape,f=m.length;d+=`${c}: ${f}D ${f>0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${p} %c${u} %c${d} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function _M(e,t,n){let a={},r={};for(let l=0;l<t.length;l++)a[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],p=u.inputs;for(let d in p){let c=p[d],h=!1;for(let m=0;m<t.length;m++)if(a[c.id]){u.outputs.forEach(f=>a[f.id]=!0),h=!0,r[u.id]=!0;break}if(h)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],p=u.inputs;for(let d=0;d<u.outputs.length;d++)if(s[u.outputs[d].id]){for(let c in p)s[p[c].id]=!0,i[u.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let u=e[l];if(r[u.id]&&i[u.id]){let p={};for(let c in u.inputs){let h=u.inputs[c];a[h.id]&&(p[c]=h)}let d=Object.assign({},u);d.inputs=p,d.outputs=u.outputs,o.push(d)}}return o}function AM(e,t,n,a){for(let r=t.length-1;r>=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=n(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!Ar(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=u;else{let d=e[p.id];e[p.id]=a(d,u),d.dispose()}}}}var Xk=20,Kp=3,rx=7;function FM(e,t,n,a){let r=Xl(t),s=$M(e,t,n,r),i=t.length,o=Dh(e,t,n,r,s),l=["Tensor"];return a&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function $M(e,t,n,a){let r=ot(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?ec(e):e;if(o>1)for(let u=0;u<r/s;u++){let p=u*s;for(let d=0;d<s;d++)i[d]=Math.max(i[d],Qp(l[p+d],0,n).length)}return i}function Qp(e,t,n){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(rx))} + ${parseFloat(e[1].toFixed(rx))}j`:Jr(e)?a=`'${e}'`:n==="bool"?a=JS(e):a=parseFloat(e.toFixed(rx)).toString(),uc(a,t)}function JS(e){return e===0?"false":"true"}function Dh(e,t,n,a,r,s=!0){let i=n==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(n==="complex64"){let f=ec(e);return[Qp(f[0],0,n)]}return n==="bool"?[JS(e[0])]:[e[0].toString()]}if(l===1){if(o>Xk){let f=Kp*i,g=Array.from(e.slice(0,f)),b=Array.from(e.slice((o-Kp)*i,o*i));return n==="complex64"&&(g=ec(g),b=ec(b)),["["+g.map((y,x)=>Qp(y,r[x],n)).join(", ")+", ..., "+b.map((y,x)=>Qp(y,r[o-Kp+x],n)).join(", ")+"]"]}return["["+(n==="complex64"?ec(e):Array.from(e)).map((f,g)=>Qp(f,r[g],n)).join(", ")+"]"]}let u=t.slice(1),p=a.slice(1),d=a[0]*i,c=[];if(o>Xk){for(let f=0;f<Kp;f++){let g=f*d,b=g+d;c.push(...Dh(e.slice(g,b),u,n,p,r,!1))}c.push("...");for(let f=o-Kp;f<o;f++){let g=f*d,b=g+d;c.push(...Dh(e.slice(g,b),u,n,p,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*d,b=g+d;c.push(...Dh(e.slice(g,b),u,n,p,r,f===o-1))}let h=l===2?",":"";c[0]="["+(o>0?c[0]+h:"");for(let f=1;f<c.length-1;f++)c[f]=" "+c[f]+h;let m=`,
|
|
`;for(let f=2;f<l;f++)m+=`
|
|
`;return c[c.length-1]=" "+c[c.length-1]+"]"+(s?"":m),c}function ec(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Wt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=ot(e),n!=null){let a=n.length;A(a===this.size,()=>`Length of values '${a}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||Iv(t,this.size),this.strides=Xl(e)}set(e,...t){t.length===0&&(t=[0]),A(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return za().makeTensor(this.values,this.shape,this.dtype)}},za=null,Sl=null,DM=null;function RM(e){za=e}function MM(e){Sl=e}function OM(e){DM=e}var Ce=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ot(e),this.strides=Xl(e),this.dataId=n,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Sl.buffer(this.shape,this.dtype,e)}bufferSync(){return Sl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return El(this.shape,e,this.dtype==="complex64")}arraySync(){return El(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=za().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>jh(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}dataToGPU(e){return this.throwIfDisposed(),za().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=za().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>jh(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 za().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),za().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Sl.print(this,e)}clone(){return this.throwIfDisposed(),Sl.clone(this)}toString(e=!1){let t=this.dataSync();return FM(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Sl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),za().makeVariable(this,e,t,n)}};Object.defineProperty(Ce,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Q(){return Tv("Tensor",()=>Ce)}Q();var os=class extends Ce{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Ar(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);za().disposeTensor(this),this.dataId=e.dataId,za().incRef(this,null)}dispose(){za().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(os,Symbol.hasInstance,{value:e=>e instanceof Ce&&e.assign!=null&&e.assign instanceof Function});var Wa={};_e(Wa,{assertTypesMatch:()=>tN,getTensorsInContainer:()=>Ev,isTensorInList:()=>LM,makeTypesMatch:()=>_t});var wx;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(wx||(wx={}));var kx;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(kx||(kx={}));var Ix;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Ix||(Ix={}));var Sx;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Sx||(Sx={}));var Nx;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Nx||(Nx={}));var PM={float32:Sx,int32:kx,bool:Ix,complex64:Nx};function fa(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return PM[e][t]}function Mm(e){return fa(e,"int32")}function QS(e){return e!=null&&typeof e=="object"&&"texture"in e&&e.texture instanceof WebGLTexture}function eN(e){return typeof GPUBuffer!="undefined"&&e!=null&&typeof e=="object"&&"buffer"in e&&e.buffer instanceof GPUBuffer}function _t(e,t){if(e.dtype===t.dtype)return[e,t];let n=fa(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function tN(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function LM(e,t){return t.some(n=>n.id===e.id)}function Ev(e){let t=[];return nN(e,t,new Set),t}function nN(e,t,n){if(e==null)return;if(e instanceof Ce){t.push(e);return}if(!zM(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),nN(s,t,n))}}function zM(e){return Array.isArray(e)||typeof e=="object"}function sx(e){return e.kernelName!=null}var Yk=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()}},_v=class Tx{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Yk}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let t=this.getSortedBackends();for(let n=0;n<t.length;n++){let a=t[n];if(await this.initializeBackend(a).success){await this.setBackend(a);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:t,asyncInit:n}=this.initializeBackendsAndReturnBest();if(n)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry))if(t in this.registryFactory){let{asyncInit:n}=this.initializeBackend(t);if(n)return null}else return null;return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,n,a=1){return t in this.registryFactory?(Zr(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:n,priority:a},!0)}async setBackend(t){if(this.registryFactory[t]==null)throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,this.registry[t]==null){this.backendInstance=null;let{success:n,asyncInit:a}=this.initializeBackend(t);if(!(a?await n:n))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new TM(this.backendInstance),!0}setupRegisteredKernels(){qh(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){qh(t).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[t])})}initializeBackend(t){let n=this.registryFactory[t];if(n==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{let a=n.factory();if(a&&!(a instanceof Fc)&&typeof a.then=="function"){let r=++this.pendingBackendInitId,s=a.then(i=>r<this.pendingBackendInitId?!1:(this.registry[t]=i,this.pendingBackendInit=null,!0)).catch(i=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,Zr(`Initialization of backend ${t} failed`),Zr(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[t]=a,{success:!0,asyncInit:!1}}catch(a){return Zr(`Initialization of backend ${t} failed`),Zr(a.stack||a.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(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((t,n)=>this.registryFactory[n].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){let t=this.getSortedBackends();for(let n=0;n<t.length;n++){let a=t[n],{success:r,asyncInit:s}=this.initializeBackend(a);if(s||r)return{name:a,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,n){let a=this.state.tensorInfo.get(n),r=a.backend,s=this.readSync(n),i=r.refCount(n);r.disposeData(n,!0),a.backend=t,t.move(n,s,a.shape,a.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,n){let a=null;if(n==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");n=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof n!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");a=t}let r;return this.scopedRun(()=>this.startScope(a),()=>this.endScope(r),()=>(r=n(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(t,n,a){t();try{let r=a();return n(),r}catch(r){throw n(),r}}nextTensorId(){return Tx.nextTensorId++}nextVariableId(){return Tx.nextVariableId++}clone(t){let n=P.runKernel(eo,{x:t}),a={x:t},r=i=>({x:()=>{let o="float32",l={x:i},u={dtype:o};return P.runKernel(Mi,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,a,[n],r,s,{}),n}runKernel(t,n,a){if(this.backendName==null&&this.backend,fc(t,this.backendName)==null)throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:n,attrs:a})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,n,a){let r=this.backend.numDataIds(),s=0;a.forEach(l=>{s+=l.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-n-s-i;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${t}'`)}runKernelFunc(t){let n,a=[],r=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let l,u=sx(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(sx(t)){let{kernelName:m,inputs:f,attrs:g}=t;this.backendName==null&&this.backend;let b=fc(m,this.backendName);A(b!=null,()=>`Cannot find registered kernel '${m}' for backend '${this.backendName}'`),o=()=>{let y=this.backend.numDataIds();l=b.kernelFunc({inputs:f,attrs:g,backend:this.backend});let x=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(m,y,x);let v=x.map(I=>I.rank!=null?I:this.makeTensorFromTensorInfo(I));if(r){let I=this.getTensorsForGradient(m,f,v);a=this.saveTensorsForBackwardMode(I)}return v}}else{let{forwardFunc:m}=t,f=g=>{r&&(a=g.map(b=>this.keep(this.clone(b))))};o=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>m(this.backend,f));let b=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,b),b}}let{inputs:p,attrs:d}=t,c=sx(t)?null:t.backwardsFunc,h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?n=o():(h=this.profiler.profileKernel(u,p,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),n=h.outputs)}),r&&this.addTapeNode(u,p,n,c,a,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(p).map(m=>p[m]!=null?p[m].shape:null),outputShapes:n.map(m=>m.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(l)?n:n[0]}saveTensorsForBackwardMode(t){return t.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(t,n,a){let r=xx(t);if(r!=null){let s=r.inputsToSave||[],i=r.outputsToSave||[],o;r.saveAllInputs?(A(Array.isArray(n),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(n).map(u=>n[u])):o=s.map(u=>n[u]);let l=a.filter((u,p)=>i[p]);return o.concat(l)}return[]}makeTensor(t,n,a,r){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");a=a||"float32",r=r||this.backend;let s=t;a==="string"&&Jr(t[0])&&(s=t.map(l=>nd(l)));let i=r.write(s,n,a),o=new Ce(n,a,i,this.nextTensorId());if(this.trackTensor(o,r),a==="string"){let l=this.state.tensorInfo.get(i),u=zS(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return o}makeTensorFromDataId(t,n,a,r){a=a||"float32";let s={dataId:t,shape:n,dtype:a};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(t,n){let{dataId:a,shape:r,dtype:s}=t,i=new Ce(r,s,a,this.nextTensorId());return this.trackTensor(i,n),i}makeVariable(t,n=!0,a,r){a=a||this.nextVariableId().toString(),r!=null&&r!==t.dtype&&(t=t.cast(r));let s=new os(t,n,a,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(t,n){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let a=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(a=t.size*Uh(t.dtype)),this.state.numBytes+=a,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:n||this.backend,dtype:t.dtype,shape:t.shape,bytes:a})),t instanceof os||this.track(t)}incRef(t,n){this.trackTensor(t,n),this.backend.incRef(t.dataId)}removeDataId(t,n){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===n&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;let n=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=n.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){let a=t.size*Uh(t.dtype);this.state.numBytes-=a}n.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,n.backend)}disposeVariables(){for(let t in this.state.registeredVariables){let n=this.state.registeredVariables[t];this.disposeVariable(n)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){let t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;let n=this.state.numBytes,a=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),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-n,this.state.activeProfile.newTensors=this.state.numTensors-a;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(t,n,a,r,s,i){let o={id:this.state.nextTapeNodeId++,kernelName:t,inputs:n,outputs:a,saved:s},l=xx(t);l!=null&&(r=l.gradFunc),r!=null&&(o.gradient=u=>(u=u.map((p,d)=>{if(p==null){let c=a[d],h=xm(c.size,c.dtype);return this.makeTensor(h,c.shape,c.dtype)}return p}),r(u.length>1?u:u[0],s,i))),this.state.activeTape.push(o)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){let n={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(n.name=t),this.state.scopeStack.push(n),this.state.activeScope=n}endScope(t){let n=Ev(t),a=new Set(n.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!a.has(i.id)&&i.dispose()}let r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(s=>{!s.kept&&s.scopeId===r.id&&this.track(s)})}gradients(t,n,a,r=!1){if(A(n.length>0,()=>"gradients() received an empty list of xs."),a!=null&&a.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${a.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));A(s instanceof Ce,()=>"The result y returned by f() must be a tensor.");let i=_M(this.state.activeTape,n,s);if(!r&&i.length===0&&n.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]=a==null?WM(s.shape):a,AM(o,i,u=>this.tidy(u),BM);let l=n.map(u=>o[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let p of u.saved)p.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(t){return A(ss(t),()=>"The f passed in customGrad(f) must be a function."),(...n)=>{A(n.every(o=>o instanceof Ce),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let a,r={};n.forEach((o,l)=>{r[l]=o});let s=(o,l)=>(a=t(...n,l),A(a.value instanceof Ce,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(ss(a.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),a.value),i=(o,l)=>{let u=a.gradFunc(o,l),p=Array.isArray(u)?u:[u];A(p.length===n.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),A(p.every(c=>c instanceof Ce),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let d={};return p.forEach((c,h)=>{d[h]=()=>c}),d};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:r})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,n){return this.state.tensorInfo.get(t).backend.readToGPU(t,n)}async time(t){let n=gc(),a=await this.backend.time(t);return a.wallMs=gc()-n,a}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Yk;for(let t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};_v.nextTensorId=0;_v.nextVariableId=0;function WM(e){let t=Sv(ot(e),"float32");return P.makeTensor(t,e,"float32")}function aN(){let e=GS();if(e._tfengine==null){let t=new US(e);e._tfengine=new _v(t)}return lM(e._tfengine.ENV),RM(()=>e._tfengine),e._tfengine}var P=aN();function BM(e,t){let n={a:e,b:t};return P.runKernel(xs,n)}var ad={};_e(ad,{isBrowser:()=>rN,isMobile:()=>GM,mockIsMobile:()=>UM});function VM(){return typeof navigator!="undefined"&&navigator!=null}var Cx;function UM(e){Cx=e}function GM(e){if(Cx!==void 0)return Cx;if(e||VM()){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 rN(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var zn=G();zn.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.")});zn.registerFlag("IS_BROWSER",()=>rN());zn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");zn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));zn.registerFlag("IS_SAFARI",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));zn.registerFlag("PROD",()=>!1);zn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>zn.getBool("DEBUG"));zn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);zn.registerFlag("IS_TEST",()=>!1);zn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>zn.getBool("DEBUG"));zn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);zn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);zn.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function lr(e,t){let n=e;if(en(e))return t==="string"?[]:[e.length];if(QS(e)){let r=e.channels||"RGBA";return[e.height,e.width*r.length]}else if(eN(e))return[e.buffer.size/(t==null?4:Uh(t))];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||en(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&G().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&sN(e,a,[]),a}function sN(e,t,n){if(n=n||[],!Array.isArray(e)&&!en(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let r=0;r<e.length;++r)sN(e[r],a,n.concat(r))}function Zk(e,t,n,a){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${a}' must be ${e} tensor, but got ${t} tensor`)}}function E(e,t,n,a="numeric"){if(e instanceof Q())return Zk(a,e.dtype,t,n),e;let r=$c(e);if(r!=="string"&&["bool","int32","float32"].indexOf(a)>=0&&(r=a),Zk(a,r,t,n),e==null||!en(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${o}'`)}let s=lr(e,r);!en(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Rm(e,r):is(e,[],!0);return P.makeTensor(i,s,r)}function bc(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>E(r,`${t}[${s}]`,n,a))}var Av="__op";function L(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],a=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Av;let r=(...s)=>{P.startScope(n);try{let i=a(...s);return vm(i)&&console.error("Cannot return a Promise inside of tidy."),P.endScope(i),i}catch(i){throw P.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function HM(e,t){let n=E(e,"real","complex"),a=E(t,"imag","complex");Sn(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return P.runKernel(wm,r)}var Er=L({complex_:HM});function Is(e,t,n,a){if(a==null)a=$c(e);else if(a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(eN(e)||QS(e)){if(a!=="float32"&&a!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${a}.`);return P.backend.createTensorFromGPUData(e,t||n,a)}if(!en(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){na(t);let r=ot(t),s=ot(n);A(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i<n.length;++i){let o=n[i],l=i===n.length-1?o!==ot(t.slice(i)):!0;A(n[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!en(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?Rm(e,a):is(e,[],!0),P.makeTensor(e,t,a)}function bn(e,t,n){let a=lr(e,n);return Is(e,t,a,n)}var li={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Fr=class iN{static join(t){return new iN(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(a=>en(a)?a.buffer:a),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let n=0;for(let a=0;a<t.length;a++){let r=t[a];a!==t.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);let s=n+r.byteLength;this.shards.push({buffer:r,start:n,end:s}),n=s}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(t=0,n=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(t=isNaN(Number(t))?0:t,n=isNaN(Number(n))?0:n,t=Math.max(0,t),n=Math.min(this.byteLength,n),n<=t)return new ArrayBuffer(0);let a=this.findShardForByte(t);if(a===-1)throw new Error(`Could not find start shard for byte ${t}`);let r=n-t,s=new ArrayBuffer(r),i=new Uint8Array(s),o=0;for(let l=a;l<this.shards.length;l++){let u=this.shards[l],p=t+o-u.start,d=o,c=Math.min(n,u.end)-u.start,h=new Uint8Array(u.buffer,p,c-p);if(i.set(h,d),o+=h.length,n<u.end)break}return s}findShardForByte(t){if(this.shards.length===0||t<0||t>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function n(r){return t<r.start?-1:t>=r.end?1:0}if(n(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;let a=qM(this.shards,n);return a===-1?-1:(this.previousShardIndex=a,this.previousShardIndex)}};function qM(e,t){let n=0,a=e.length;for(;n<=a;){let r=Math.floor((a-n)/2)+n,s=t(e[r]);if(s===0)return r;s<0?a=r:n=r+1}return-1}function jM(){G().set("PROD",!0)}function KM(){G().set("DEBUG",!0)}function XM(){G().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Fv(e){G().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}OM(Fv);function YM(){P.disposeVariables()}function Ta(){return P}function Kh(){return P.memory()}function ZM(e){return P.profile(e)}function O(e,t){return P.tidy(e,t)}function Ee(e){Ev(e).forEach(t=>t.dispose())}function Ht(e){return P.keep(e)}function JM(e){return P.time(e)}function QM(e){return P.setBackend(e)}function eO(){return P.ready()}function oN(){return P.backendName}function tO(e){P.removeBackend(e)}function nO(e){return P.findBackend(e)}function aO(e){return P.findBackendFactory(e)}function Om(e,t,n=1){return P.registerBackend(e,t,n)}function $v(){return P.backend}function rO(e,t){G().setPlatform(e,t)}var ls=4;async function sO(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<r.length;++i){let o=r[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let u={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let p=new Promise(async d=>{let c=await l.bytes(),h=c.reduce((g,b)=>g+b.length,0)+ls*c.length,m=new Uint8Array(h),f=0;for(let g=0;g<c.length;g++){let b=c[g],y=new Uint8Array(new Uint32Array([b.length]).buffer);m.set(y,f),f+=ls,m.set(b,f),f+=b.length}d(m)});a.push(p)}else a.push(l.data());t!=null&&(u.group=t),n.push(u)}let s=await Promise.all(a);return{data:lO(s),specs:n}}function lN(e,t){let n=new Fr(e),a={},r=0;for(let s of t){let i=iO(s,(o,l)=>n.slice(r+o,r+l));a[s.name]=uN(s,n.slice(r,r+i)),r+=i}return a}function iO(e,t){let n=ot(e.shape),a;if("quantization"in e){let r=e.quantization;a=li[r.dtype]}else if(e.dtype==="string"){let r=0;for(let s=0;s<n;s++)r+=ls+new Uint32Array(t(r,r+ls))[0];return r}else a=li[e.dtype];return n*a}async function oO(e,t){let n=ot(e.shape),a;if("quantization"in e){let r=e.quantization;a=li[r.dtype]}else if(e.dtype==="string"){let r=0;for(let s=0;s<n;s++)r+=ls+new Uint32Array(await t(r,r+ls))[0];return r}else a=li[e.dtype];return n*a}function uN(e,t){let n=e.name,a=e.dtype,r=e.shape,s=ot(r),i,o=0;if("quantization"in e){let l=e.quantization;if(l.dtype==="uint8"||l.dtype==="uint16"){if(!("min"in l&&"scale"in l))throw new Error(`Weight ${e.name} with quantization ${l.dtype} doesn't have corresponding metadata min and scale.`)}else if(l.dtype==="float16"){if(a!=="float32")throw new Error(`Weight ${e.name} is quantized with ${l.dtype} which only supports weights of type float32 not ${a}.`)}else throw new Error(`Weight ${e.name} has unknown quantization dtype ${l.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let u=li[l.dtype],p=l.dtype==="uint8"?new Uint8Array(t):new Uint16Array(t);if(a==="float32")if(l.dtype==="uint8"||l.dtype==="uint16"){i=new Float32Array(p.length);for(let d=0;d<p.length;d++){let c=p[d];i[d]=c*l.scale+l.min}}else if(l.dtype==="float16")i=fO()(p);else throw new Error(`Unsupported quantization type ${l.dtype} for weight type float32.`);else if(a==="int32"){if(l.dtype!=="uint8"&&l.dtype!=="uint16")throw new Error(`Unsupported quantization type ${l.dtype} for weight type int32.`);i=new Int32Array(p.length);for(let d=0;d<p.length;d++){let c=p[d];i[d]=Math.round(c*l.scale+l.min)}}else throw new Error(`Unsupported dtype in weight '${n}': ${a}`);o+=s*u}else if(a==="string"){let l=ot(e.shape);i=[];for(let u=0;u<l;u++){let p=new Uint32Array(t.slice(o,o+ls))[0];o+=ls;let d=new Uint8Array(t.slice(o,o+p));i.push(d),o+=p}}else{let l=li[a];if(a==="float32")i=new Float32Array(t);else if(a==="int32")i=new Int32Array(t);else if(a==="bool")i=new Uint8Array(t);else if(a==="complex64"){i=new Float32Array(t);let u=new Float32Array(i.length/2),p=new Float32Array(i.length/2);for(let m=0;m<u.length;m++)u[m]=i[m*2],p[m]=i[m*2+1];let d=bn(u,r,"float32"),c=bn(p,r,"float32"),h=Er(d,c);return d.dispose(),c.dispose(),h}else throw new Error(`Unsupported dtype in weight '${n}': ${a}`);o+=s*l}return bn(i,r,a)}async function Jk(e,t,n){let a=new Uint8Array(t);for(;a.byteLength<n;){let{done:r,value:s}=await e.read();if(r&&s==null){let o=n-a.byteLength;throw new Error(`Reader is done but ${o} bytes are still expected`)}let i=new Uint8Array(a.length+s.byteLength);i.set(a,0),i.set(new Uint8Array(s),a.length),a=i}return a.buffer}async function pN(e,t){let n={},a=e.getReader(),r=new ArrayBuffer(0);for(let s of t){let i=await oO(s,async(u,p)=>(r=await Jk(a,r,p),r.slice(u,p)));r=await Jk(a,r,i);let o=r.slice(0,i);r=r.slice(i);let l=uN(s,o);if(n[s.name]=l,oN()==="webgpu"){let u=$v();"uploadToGPU"in u&&ot(l.shape)>=G().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&u.uploadToGPU(l.dataId)}}return n}function lO(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(s=>{if(t+=s.byteLength,n.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let a=new Uint8Array(t),r=0;return n.forEach(s=>{a.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),a.buffer}var Dv=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Qk(e){return Dv?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function uO(e){if(Dv)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a<r;a++)n+=String.fromCharCode(t[a]);return btoa(n)}function pO(e){if(Dv){let a=Buffer.from(e,"base64");return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;++a)n.set([t.charCodeAt(a)],a);return n.buffer}function cO(e){return Fr.join(e)}function eI(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 cN(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.initializerSignature!=null&&(n.initializerSignature=e.initializerSignature),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}function dN(e,t,n){let a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(a.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");a.weightSpecs=t,a.weightData=n}return e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(a.initializerSignature=e.initializerSignature),a}async function Rv(e,t){let n,a;return e.weightsManifest!=null&&([n,a]=await t(e.weightsManifest)),dN(e,n,a)}function rd(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:Qk(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Qk(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:new Fr(e.weightData).byteLength}}function Ex(e){let t=[];for(let n of e)t.push(...n.weights);return t}function dO(){let e=n=>{let a=n<<13,r=0;for(;!(a&8388608);)r-=8388608,a<<=1;return a&=-8388609,r+=947912704,a|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function hO(){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 mO(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function fO(){let e=dO(),t=hO(),n=mO();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i<a.length;i++){let o=a[i],l=e[n[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var ga=class La{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return La.instance==null&&(La.instance=new La),La.instance}static registerSaveRouter(t){La.getInstance().saveRouters.push(t)}static registerLoadRouter(t){La.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return La.getHandlers(t,"save")}static getLoadHandlers(t,n){return La.getHandlers(t,"load",n)}static getHandlers(t,n,a){let r=[];return(n==="load"?La.getInstance().loadRouters:La.getInstance().saveRouters).forEach(s=>{let i=s(t,a);i!==null&&r.push(i)}),r}},gO=e=>ga.registerSaveRouter(e),bO=e=>ga.registerLoadRouter(e),yO=e=>ga.getSaveHandlers(e),xO=(e,t)=>ga.getLoadHandlers(e,t),_x="tensorflowjs",Ax=1,ei="models_store",Qr="model_info_store";function hN(){if(!G().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 Fx(e){let t=e.result;t.createObjectStore(ei,{keyPath:"modelPath"}),t.createObjectStore(Qr,{keyPath:"modelPath"})}var ui=class{constructor(e){if(this.indexedDB=hN(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,a)=>{let r=this.indexedDB.open(_x,Ax);r.onupgradeneeded=()=>Fx(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(ei,"readonly"),o=i.objectStore(ei).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{t.weightData=Fr.join(t.weightData);let i=rd(t),o=s.transaction(Qr,"readwrite"),l=o.objectStore(Qr),u;try{u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(d){return a(d)}let p;u.onsuccess=()=>{p=s.transaction(ei,"readwrite");let d=p.objectStore(ei),c;try{c=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(h){return a(h)}c.onsuccess=()=>n({modelArtifactsInfo:i}),c.onerror=h=>{l=o.objectStore(Qr);let m=l.delete(this.modelPath);m.onsuccess=()=>(s.close(),a(c.error)),m.onerror=f=>(s.close(),a(c.error))}},u.onerror=d=>(s.close(),a(u.error)),o.oncomplete=()=>{p==null?s.close():p.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};ui.URL_SCHEME="indexeddb://";var mN=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ui.URL_SCHEME)?vO(e.slice(ui.URL_SCHEME.length)):null;ga.registerSaveRouter(mN);ga.registerLoadRouter(mN);function vO(e){return new ui(e)}function wO(e){return e.startsWith(ui.URL_SCHEME)?e.slice(ui.URL_SCHEME.length):e}var kO=class{constructor(){this.indexedDB=hN()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(_x,Ax);n.onupgradeneeded=()=>Fx(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(Qr,"readonly"),s=r.objectStore(Qr).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),r.oncomplete=()=>a.close()},n.onerror=a=>t(n.error)})}async removeModel(e){return e=wO(e),new Promise((t,n)=>{let a=this.indexedDB.open(_x,Ax);a.onupgradeneeded=()=>Fx(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(Qr,"readwrite"),i=s.objectStore(Qr),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),p=()=>{l=r.transaction(ei,"readwrite");let d=l.objectStore(ei).delete(e);d.onsuccess=()=>t(o.result.modelArtifactsInfo),d.onerror=c=>n(o.error)};u.onsuccess=p,u.onerror=d=>(p(),r.close(),n(o.error))}},o.onerror=u=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},Nr="/",Nl="tensorflowjs_models",fN="info",IO="model_topology",SO="weight_specs",NO="weight_data",TO="model_metadata";function gN(e){return{info:[Nl,e,fN].join(Nr),topology:[Nl,e,IO].join(Nr),weightSpecs:[Nl,e,SO].join(Nr),weightData:[Nl,e,NO].join(Nr),modelMetadata:[Nl,e,TO].join(Nr)}}function bN(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function CO(e){let t=e.split(Nr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Nr)}function EO(e){return e.startsWith(pi.URL_SCHEME)?e.slice(pi.URL_SCHEME.length):e}var pi=class{constructor(e){if(!G().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=gN(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),a=rd(e),r=Fr.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,uO(r));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,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:a}}catch(s){throw bN(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=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=pO(s),t}};pi.URL_SCHEME="localstorage://";var yN=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(pi.URL_SCHEME)?_O(e.slice(pi.URL_SCHEME.length)):null;ga.registerSaveRouter(yN);ga.registerLoadRouter(yN);function _O(e){return new pi(e)}var AO=class{constructor(){A(G().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Nl+Nr,n=Nr+fN;for(let a=0;a<this.LS.length;++a){let r=this.LS.key(a);if(r.startsWith(t)&&r.endsWith(n)){let s=CO(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=EO(e);let t=gN(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 bN(t),n}},_l="://",us=class jr{constructor(){this.managers={}}static getInstance(){return jr.instance==null&&(jr.instance=new jr),jr.instance}static registerManager(t,n){A(t!=null,()=>"scheme must not be undefined or null."),t.endsWith(_l)&&(t=t.slice(0,t.indexOf(_l))),A(t.length>0,()=>"scheme must not be an empty string.");let a=jr.getInstance();A(a.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),a.managers[t]=n}static getManager(t){let n=jr.getInstance().managers[t];if(n==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return n}static getSchemes(){return Object.keys(jr.getInstance().managers)}};function Rh(e){if(e.indexOf(_l)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${us.getSchemes().join(",")}`);return{scheme:e.split(_l)[0],path:e.split(_l)[1]}}async function xN(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=ga.getLoadHandlers(e);A(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=ga.getSaveHandlers(t);A(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=Rh(e).scheme,l=Rh(e).path,u=o===Rh(e).scheme,p=await r.load();n&&u&&await us.getManager(o).removeModel(l);let d=await i.save(p);return n&&!u&&await us.getManager(o).removeModel(l),d.modelArtifactsInfo}async function FO(){let e=us.getSchemes(),t={};for(let n of e){let a=await us.getManager(n).listModels();for(let r in a){let s=n+_l+r;t[s]=a[r]}}return t}async function $O(e){let t=Rh(e);return us.getManager(t.scheme).removeModel(t.path)}async function DO(e,t){return xN(e,t,!1)}async function RO(e,t){return xN(e,t,!0)}var MO=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}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)}setTimeoutCustom(e,t){if(typeof window=="undefined"||!G().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",n=>{if(n.source===window&&n.data.name===this.messageName){n.stopPropagation();let a=this.functionRefs[n.data.index];a(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return XS(e)}};if(G().get("IS_BROWSER")){G().setPlatform("browser",new MO);try{us.registerManager(pi.URL_SCHEME,new AO)}catch(e){}try{us.registerManager(ui.URL_SCHEME,new kO)}catch(e){}}var OO={importFetch:()=>CR()},ix,PO=class{constructor(){this.util=ER(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return G().global.fetch!=null?G().global.fetch(e,t):(ix==null&&(ix=OO.importFetch()),ix(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)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}};G().get("IS_NODE")&&!G().get("IS_BROWSER")&&G().setPlatform("node",new PO);function Oe(e,t="float32",n){return t=t||"float32",na(e),new Wt(e,t,n)}function LO(e,t){let n=E(e,"x","cast");if(!LS(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let a={x:n},r={dtype:t};return P.runKernel(Mi,a,r)}var re=L({cast_:LO});function zO(e){let t={x:E(e,"x","clone","string_or_numeric")};return P.runKernel(eo,t)}var sr=L({clone_:zO});function Mv(e,t=!1){console.log(e.toString(t))}aN();var WO={buffer:Oe,cast:re,clone:sr,print:Mv};MM(WO);function BO(e,t){let n=E(e,"a","add"),a=E(t,"b","add");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(xs,r)}var X=L({add_:BO});function VO(e,t){let n=E(e,"a","floorDiv"),a=E(t,"b","floorDiv");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(Zi,r)}var Pm=L({floorDiv_:VO});function UO(e,t){let n=E(e,"a","div"),a=E(t,"b","div");if([n,a]=_t(n,a),n.dtype==="int32"&&a.dtype==="int32")return Pm(n,a);let r={a:n,b:a},s={};return P.runKernel(Hi,r,s)}var he=L({div_:UO});function GO(e,t){let n=E(e,"a","mul"),a=E(t,"b","mul");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(bo,r)}var z=L({mul_:GO});function HO(e){let t=E(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return P.runKernel(Oc,n)}else{let n={x:t};return P.runKernel(Yl,n)}}var Lt=L({abs_:HO});function qO(e){let t={x:E(e,"x","acos")};return P.runKernel(Ni,t)}var Ov=L({acos_:qO});function jO(e){let t={x:E(e,"x","acosh")};return P.runKernel(Ti,t)}var Pv=L({acosh_:jO});function KO(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>E(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Ar(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return P.runKernel(Ci,a)}var vN=L({addN_:KO});function XO(e,t=null,n=!1){let a={x:E(e,"x","all","bool")},r={axis:t,keepDims:n};return P.runKernel(Zl,a,r)}var Lm=L({all_:XO});function YO(e,t=null,n=!1){let a={x:E(e,"x","any","bool")},r={axis:t,keepDims:n};return P.runKernel(Jl,a,r)}var yc=L({any_:YO});function ZO(e,t=0){let n={x:E(e,"x","argMax")},a={axis:t};return P.runKernel(Ql,n,a)}var ci=L({argMax_:ZO});function JO(e,t=0){let n={x:E(e,"x","argMin")},a={axis:t};return P.runKernel(eu,n,a)}var Lv=L({argMin_:JO});function QO(e){let t={x:E(e,"x","asin")};return P.runKernel(Ei,t)}var zv=L({asin_:QO});function eP(e){let t={x:E(e,"x","asinh")};return P.runKernel(_i,t)}var Wv=L({asinh_:eP});function tP(e){let t={x:E(e,"x","atan")};return P.runKernel(Ai,t)}var Bv=L({atan_:tP});function nP(e,t){let n=E(e,"a","atan2"),a=E(t,"b","atan2");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel($i,r)}var Vv=L({atan2_:nP});function aP(e){let t={x:E(e,"x","atanh")};return P.runKernel(Fi,t)}var Uv=L({atanh_:aP});function rP(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=IN(r);return sd(e,o,n,s,a,null,null,l)}function wN(e,t,n,a,r,s,i="channelsLast"){let[o,l]=xc(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return sd(e,u,n,a,r,s,!1,i)}function sP(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=$x(t),p,d;if(i==="NDHWC")d="channelsLast",p=[o,l,u,e[4],e[4]];else if(i==="NCDHW")d="channelsFirst",p=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return kN(e,p,n,a,r,!1,d,s)}function sd(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,p,d]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,p,d]=e;else if(o==="channelsFirst")[l,d,u,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[c,h,,m]=t,[f,g]=xc(n),[b,y]=xc(a),x=Al(c,b),v=Al(h,y),{padInfo:I,outHeight:N,outWidth:C}=lP(r,u,p,f,g,x,v,s,o),_=i?m*d:m,F;return o==="channelsFirst"?F=[l,_,N,C]:o==="channelsLast"&&(F=[l,N,C,_]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:p,inChannels:d,outHeight:N,outWidth:C,outChannels:_,padInfo:I,strideHeight:f,strideWidth:g,filterHeight:c,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:b,dilationWidth:y,inShape:e,outShape:F,filterShape:t}}function kN(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,u,p,d,c]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,d,c]=e;else if(i==="channelsFirst")[l,c,u,p,d]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,m,f,,g]=t,[b,y,x]=$x(n),[v,I,N]=$x(a),C=Al(h,v),_=Al(m,I),F=Al(f,N),{padInfo:D,outDepth:$,outHeight:S,outWidth:M}=uP(r,u,p,d,b,y,x,C,_,F,o),B=s?g*c:g,U;return i==="channelsFirst"?U=[l,B,$,S,M]:i==="channelsLast"&&(U=[l,$,S,M,B]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:d,inChannels:c,outDepth:$,outHeight:S,outWidth:M,outChannels:B,padInfo:D,strideDepth:b,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:_,effectiveFilterWidth:F,dilationDepth:v,dilationHeight:I,dilationWidth:N,inShape:e,outShape:U,filterShape:t}}function iP(e,t,n,a,r){a==null&&(a=Gv(e,t,n));let s=e[0],i=e[1],o=vc((s-t+2*a)/n+1,r),l=vc((i-t+2*a)/n+1,r);return[o,l]}function oP(e,t,n,a,r,s){r==null&&(r=Gv(e,t[0],a[0]));let i=[0,0,0,n];for(let o=0;o<3;o++)e[o]+2*r>=t[o]&&(i[o]=vc((e[o]-t[o]+2*r)/a[o]+1,s));return i}function Gv(e,t,n,a=1){let r=Al(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function xc(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function $x(e){return typeof e=="number"?[e,e,e]:e}function Al(e,t){return t<=1?e:e+(e-1)*(t-1)}function lP(e,t,n,a,r,s,i,o,l){let u,p,d;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let c=iP([t,n],s,a,e,o);p=c[0],d=c[1]}else if(e==="same"){p=Math.ceil(t/a),d=Math.ceil(n/r);let c=Math.max(0,(p-1)*a+s-t),h=Math.max(0,(d-1)*r+i-n),m=Math.floor(c/2),f=c-m,g=Math.floor(h/2),b=h-g;u={top:m,bottom:f,left:g,right:b,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-s+1)/a),d=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let c=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:c,bottom:h,left:m,right:f,type:c===0&&h===0&&m===0&&f===0?"VALID":"EXPLICIT"},p=vc((t-s+c+h)/a+1,o),d=vc((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:p,outWidth:d}}function uP(e,t,n,a,r,s,i,o,l,u,p){let d,c,h,m;if(e==="valid"&&(e=0),typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=oP([t,n,a,1],[o,l,u],1,[r,s,i],e,p);c=f[0],h=f[1],m=f[2]}else if(e==="same"){c=Math.ceil(t/r),h=Math.ceil(n/s),m=Math.ceil(a/i);let f=(c-1)*r+o-t,g=(h-1)*s+l-n,b=(m-1)*i+u-a,y=Math.floor(f/2),x=f-y,v=Math.floor(g/2),I=g-v,N=Math.floor(b/2),C=b-N;d={top:v,bottom:I,left:N,right:C,front:y,back:x,type:"SAME"}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:c,outHeight:h,outWidth:m}}function vc(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 ps(e){let[t,n,a]=xc(e);return t===1&&n===1&&a===1}function cr(e,t){return ps(e)||ps(t)}function di(e){return xc(e).every(t=>t>0)}function IN(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Nn(e,t,n){if(n!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if(typeof t=="number")A($l(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else if(typeof t=="object")t.forEach(a=>{a.forEach(r=>{A($l(r),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${r}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function pP(e,t){let n={x:E(e,"x","reshape","string_or_numeric")},a={shape:t};return P.runKernel(Ru,n,a)}var W=L({reshape_:pP});function cP(e,t,n,a,r){let s=E(e,"x","avgPool","float32"),i=1;A(cr(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),Nn("avgPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=P.runKernel(Di,u,p);return d=re(d,s.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ya=L({avgPool_:cP});function dP(e,t,n,a,r,s="NDHWC"){let i=E(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),A(typeof n=="number"&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`),Nn("avgPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=P.runKernel(tu,u,p);return d=re(d,o.dtype),l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Hv=L({avgPool3d_:dP});function hP(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=bc(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${s.dtype}. `)}),n.length===1)return sr(n[0]);let a=n,r={axis:t};return P.runKernel(su,a,r)}var et=L({concat_:hP});function mP(e,t,n=!1,a=!1){let r=E(e,"a","matMul"),s=E(t,"b","matMul");[r,s]=_t(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return P.runKernel(Ri,i,o)}var $e=L({matMul_:mP});function fP(e){let t={x:E(e,"x","sigmoid","float32")};return P.runKernel(Mo,t)}var ha=L({sigmoid_:fP});function gP(e,t,n){let a=E(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return P.runKernel(Bu,r,s)}var Ve=L({slice_:gP});function bP(e){let t={x:E(e,"x","tanh","float32")};return P.runKernel(Uo,t)}var hi=L({tanh_:bP});function yP(e,t,n,a,r,s){let i=E(e,"forgetBias","basicLSTMCell"),o=E(t,"lstmKernel","basicLSTMCell"),l=E(n,"lstmBias","basicLSTMCell"),u=E(a,"data","basicLSTMCell"),p=E(r,"c","basicLSTMCell"),d=E(s,"h","basicLSTMCell"),c=et([u,d],1),h=$e(c,o),m=X(h,l),f=m.shape[0],g=m.shape[1]/4,b=[f,g],y=Ve(m,[0,0],b),x=Ve(m,[0,g],b),v=Ve(m,[0,g*2],b),I=Ve(m,[0,g*3],b),N=X(z(ha(y),hi(x)),z(p,ha(X(i,v)))),C=z(hi(N),ha(I));return[N,C]}var SN=L({basicLSTMCell_:yP});function xP(e,t,n){let a=E(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);A(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(a.shape[0]%r===0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return P.runKernel(nu,s,i)}var id=L({batchToSpaceND_:xP});function vP(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function wP(e,t,n,a,r,s){s==null&&(s=.001);let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),u;r!=null&&(u=E(r,"scale","batchNorm"));let p;a!=null&&(p=E(a,"offset","batchNorm")),A(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:vP(i),scale:u,offset:p,mean:o,variance:l},c={varianceEpsilon:s},h=P.runKernel(Ji,d,c);return W(h,i.shape)}var Ss=L({batchNorm_:wP});function kP(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),u;r!=null&&(u=E(r,"scale","batchNorm"));let p;return a!=null&&(p=E(a,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Ss(i,o,l,p,u,s)}var qv=L({batchNorm2d_:kP});function IP(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),u;r!=null&&(u=E(r,"scale","batchNorm"));let p;return a!=null&&(p=E(a,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),A(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),Ss(i,o,l,p,u,s)}var jv=L({batchNorm3d_:IP});function SP(e,t,n,a,r,s){let i=E(e,"x","batchNorm"),o=E(t,"mean","batchNorm"),l=E(n,"variance","batchNorm"),u;r!=null&&(u=E(r,"scale","batchNorm"));let p;return a!=null&&(p=E(a,"offset","batchNorm")),A(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),A(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&A(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),Ss(i,o,l,p,u,s)}var Kv=L({batchNorm4d_:SP});function NP(e,t,n){let a=E(e,"x","bincount"),r=E(t,"weights","bincount");A(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return P.runKernel(au,s,i)}var Xv=L({bincount_:NP});function TP(e,t){let n=E(e,"x","bitwiseAnd"),a=E(t,"y","bitwiseAnd");if(!Ar(n.shape,a.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${a.shape}`);if(n.dtype!=="int32"||a.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${a.dtype}`);let r={a:n,b:a};return P.runKernel(ru,r)}var NN=L({bitwiseAnd_:TP});function CP(e,t){let n=E(e,"s0","broadcastArgs","int32"),a=E(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(a.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${a.rank}`);let r={s0:n,s1:a};return P.runKernel(Mc,r)}var TN=L({broadcastArgs_:CP});function EP(e,t){let n=E(e,"broadcastTo","x"),a=n.shape;if(na(t),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=W(n,l)}let r=n.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(r[l]===t[l])s[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return sr(n);let i={x:n},o={reps:s};return P.runKernel(ws,i,o)}var ni=L({broadcastTo_:EP});function _P(e){let t={x:E(e,"x","ceil","float32")};return P.runKernel(Oi,t)}var Yv=L({ceil_:_P});function yn(e,t,n){na(e),n=n||$c(t);let a={shape:e,value:t,dtype:n};return P.runKernel(zc,{},a)}function AP(e,t,n){let a=E(e,"x","clipByValue");if(A(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return yn(a.shape,t,a.dtype);let r={x:a},s={clipValueMin:t,clipValueMax:n};return P.runKernel(vs,r,s)}var an=L({clipByValue_:AP});function FP(e){return et(e,0)}var Zv=L({concat1d_:FP});function $P(e,t){return et(e,t)}var Jv=L({concat2d_:$P});function DP(e,t){return et(e,t)}var Qv=L({concat3d_:DP});function RP(e,t){return et(e,t)}var ew=L({concat4d_:RP});function MP(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","conv2d","float32"),l=E(t,"filter","conv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Nn("conv2d",a,i);let d=r==="NHWC"?u.shape[3]:u.shape[1];A(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),A(cr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(di(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),A(di(n),()=>"Error in conv2D: Strides should be larger than 0.");let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=P.runKernel(Pi,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var $t=L({conv2d_:MP});function OP(e,t,n,a,r="NWC",s=1,i){let o=E(e,"x","conv1d"),l=E(t,"filter","conv1d"),u=o,p=!1;o.rank===2&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1]])),A(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Nn("conv1d",a,i),A(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(cr(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),A(di(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),A(di(n),()=>"Error in conv1D: Stride should be larger than 0."),A(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=W(l,[1,l.shape[0],l.shape[1],l.shape[2]]),c=W(u,[u.shape[0],1,u.shape[1],u.shape[2]]),h=$t(c,d,[1,n],a,"NHWC",[1,s],i);return p?W(h,[h.shape[2],h.shape[3]]):W(h,[h.shape[0],h.shape[2],h.shape[3]])}var zm=L({conv1d_:OP});function PP(e,t,n,a,r,s="NHWC",i){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),A(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let p=s==="NHWC"?o[3]:o[1],d=s==="NHWC"?l.shape[3]:l.shape[1];A(p===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${n.shape[2]}.`),A(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),Nn("conv2dDerInput",r,i);let c={dy:l,filter:n},h={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=P.runKernel(Li,c,h);return u?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var tw=L({conv2DBackpropInput_:PP});function LP(e,t,n,a,r,s){let i=E(e,"x","conv2dTranspose"),o=E(t,"filter","conv2dTranspose");return tw(n,i,o,a,r,"NHWC",s)}var Wm=L({conv2dTranspose_:LP});function zP(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=E(e,"x","conv3d"),o=E(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),A(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),A(cr(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),A(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`),A(di(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),A(di(n),()=>"Error in conv3D: Strides should be larger than 0.");let p={x:l,filter:o},d={strides:n,pad:a,dataFormat:r,dilations:s},c=P.runKernel(zi,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var nw=L({conv3d_:zP});function WP(e,t,n,a,r){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];A(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),A(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),A(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),A(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),A(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let p={dy:i,filter:n},d={pad:r,strides:a,inputShape:s},c=P.runKernel(ou,p,d);return o?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var CN=L({conv3DBackpropInput_:WP});function BP(e,t,n,a,r){let s=E(e,"x","conv3dTranspose"),i=E(t,"filter","conv3dTranspose");return CN(n,s,i,a,r)}var aw=L({conv3dTranspose_:BP});function VP(e){let t={x:E(e,"x","cos","float32")};return P.runKernel(Wi,t)}var od=L({cos_:VP});function UP(e){let t={x:E(e,"x","cosh","float32")};return P.runKernel(Bi,t)}var Bm=L({cosh_:UP});function GP(e,t=0,n=!1,a=!1){let r={x:E(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:a};return P.runKernel(lu,r,s)}var wc=L({cumprod_:GP});function HP(e,t=0,n=!1,a=!1){let r={x:E(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return P.runKernel(Vi,r,s)}var Vm=L({cumsum_:HP});function qP(e,t,n,a=!1){let r=E(e,"x","denseBincount"),s=E(t,"weights","denseBincount");A(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),A(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),A(n>=0,()=>`size must be non-negative, but got ${n}.`),A(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return P.runKernel(Pc,i,o)}var Xh=L({denseBincount_:qP});function jP(e,t,n="NHWC"){let a=E(e,"x","depthToSpace","float32"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];A(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),A(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${r} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),A(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),A(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return P.runKernel(pu,o,l)}var rw=L({depthToSpace_:jP});function KP(e,t,n,a,r="NHWC",s=[1,1],i){let o=E(e,"x","depthwiseConv2d","float32"),l=E(t,"filter","depthwiseConv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let d=r==="NHWC"?u.shape[3]:u.shape[1];A(d===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${l.shape[2]}.`),Nn("depthwiseConv2d",a,i);let c={x:u,filter:l},h={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=P.runKernel(Ui,c,h);return p?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ns=L({depthwiseConv2d_:KP});function XP(e){let t={x:E(e,"x","diag")};return P.runKernel(Lc,t)}var EN=L({diag_:XP});function YP(e,t,n,a,r=[1,1],s="NHWC"){let i=E(e,"x","dilation2d"),o=E(t,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0),A(l.shape[3]===o.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);let p={x:l,filter:o},d={strides:n,pad:a,dilations:r},c=P.runKernel(Gi,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var sw=L({dilation2d_:YP}),Ju={};_e(Ju,{assertAndGetBroadcastShape:()=>ct,getBroadcastDims:()=>_N,getReductionAxes:()=>Bt});function _N(e,t){let n=e.length,a=[];for(let r=0;r<n;r++){let s=n-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&a.unshift(s)}return a}function Bt(e,t){let n=[];for(let a=0;a<t.length;a++){let r=e[e.length-a-1],s=t.length-a-1,i=t[s];(r==null||r===1&&i>1)&&n.unshift(s)}return n}function ct(e,t){let n=Math.max(e.length,t.length),a=new Array(n);for(let r=0;r<n;r++){let s=e[e.length-r-1];s==null&&(s=1);let i=t[t.length-r-1];if(i==null&&(i=1),s===1)a[n-r-1]=i;else if(i===1)a[n-r-1]=s;else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else a[n-r-1]=s}return a}function ZP(e,t){let n=E(e,"a","equal","string_or_numeric"),a=E(t,"b","equal","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(du,r)}var Jn=L({equal_:ZP});function JP(e,t,n){let a=E(t,"a","where"),r=E(n,"b","where"),s=E(e,"condition","where","bool"),i=ct(ct(s.shape,a.shape),r.shape),o=ni(s,i),l=ni(a,i),u=ni(r,i),p={condition:o,t:l,e:u};return P.runKernel(Wu,p)}var nn=L({where_:JP});function QP(e){let t={x:E(e,"x","zerosLike")};return P.runKernel(Yu,t)}var je=L({zerosLike_:QP});function e3(e,t){let n=E(e,"a","div"),a=E(t,"b","div");[n,a]=_t(n,a);let r=he(n,a),s=je(r),i=Jn(a,s);return nn(i,s,r)}var iw=L({divNoNan_:e3});function t3(e,t){let n=E(e,"t1","dot"),a=E(t,"t2","dot");A((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${a.rank}.`);let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(A(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=W(n,[1,-1]),o=W(a,[-1,1]),l=$e(i,o);return W(l,[])}else if(n.rank===1&&a.rank===2){let i=W(n,[1,-1]),o=W(a,[a.shape[0],a.shape[1]]),l=$e(i,o);return W(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=W(a,[-1,1]),o=$e(n,i);return W(o,[o.size])}else{let i=W(a,[a.shape[0],a.shape[1]]);return $e(n,i)}}var ow=L({dot_:t3});function n3(e,...t){let n=t.map((r,s)=>E(r,`tensors${s}`,"einsum")),a={equation:e};return P.runKernel(Tm,n,a)}var Ys=L({einsum_:n3});function a3(e){let t={x:E(e,"x","elu","float32")};return P.runKernel(qi,t)}var Qu=L({elu_:a3});function r3(e,t){let n=E(e,"x","ensureShape","string_or_numeric");if(!RS(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}var AN=L({ensureShape_:r3});function s3(e){let t=E(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=re(t,"float32"));let n={x:t};return P.runKernel(ji,n)}var lw=L({erf_:s3});function uw(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function FN(e,t,n){let a=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<a;o++)n.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function $N(e,t){let n=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&n.push(e[s]);let r=t.map(s=>e[s]);return[n,r]}function mi(e,t){let n=t.map(a=>1);return FN(e,n,t)}function i3(e,t,n){A(uw(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function DN(e,t){if(uw(e,t))return null;let n=[];for(let a=0;a<t;++a)e.indexOf(a)===-1&&n.push(a);return e.forEach(a=>n.push(a)),n}function pw(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function o3(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function l3(e,t=null,n=!1){let a={x:E(e,"x","max")},r={reductionIndices:t,keepDims:n};return P.runKernel(lo,a,r)}var ma=L({max_:l3});function u3(e,t=null,n=!1){let a={x:E(e,"x","min")},r={axis:t,keepDims:n};return P.runKernel(ho,a,r)}var Ol=L({min_:u3});function p3(e,t){let n=E(e,"base","pow"),a=E(t,"exp","pow");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(vo,r)}var _r=L({pow_:p3});function ve(e,t){if((en(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&en(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Is(e,[],[],t)}function c3(e){let t={x:E(e,"x","sqrt","float32")};return P.runKernel(Po,t)}var cn=L({sqrt_:c3});function d3(e){let t=E(e,"x","square"),n={};return P.runKernel("Square",{x:t},n)}var pt=L({square_:d3});function h3(e,t=null,n=!1){let a=E(e,"x","sum");a.dtype==="bool"&&(a=re(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return P.runKernel(Lo,r,s)}var fe=L({sum_:h3});function m3(e,t="euclidean",n=null,a=!1){e=E(e,"x","norm");let r=RN(e,t,n),s=r.shape;if(a){let i=Aa(n,e.shape);s=mi(r.shape,i)}return W(r,s)}function RN(e,t,n=null){if(e.rank===0)return Lt(e);if(e.rank!==1&&n===null)return RN(W(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return fe(Lt(e),n);if(t===1/0)return ma(Lt(e),n);if(t===-1/0)return Ol(Lt(e),n);if(t==="euclidean"||t===2)return cn(fe(_r(Lt(e),ve(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return ma(fe(Lt(e),n[0]),n[1]-1);if(t===1/0)return ma(fe(Lt(e),n[1]),n[0]);if(t===-1/0)return Ol(fe(Lt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return cn(fe(pt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var ep=L({norm_:m3});function f3(e,t=null,n=!1){return ep(e,"euclidean",t,n)}var cw=L({euclideanNorm_:f3});function g3(e){let t={x:E(e,"x","exp")};return P.runKernel(Ki,t)}var dn=L({exp_:g3});function b3(e,t=0){let n=E(e,"x","expandDims","string_or_numeric");A(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return P.runKernel(hu,a,r)}var Gt=L({expandDims_:b3});function y3(e){let t={x:E(e,"x","expm1")};return P.runKernel(Xi,t)}var dw=L({expm1_:y3});function x3(e,t){let n=E(e,"x","tile","string_or_numeric");A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return P.runKernel(ws,a,r)}var Mn=L({tile_:x3});function v3(e,t,n,a="float32"){t==null&&(t=e);let r=Oe([e,t],a),s=e<=t?e:t;for(let o=0;o<s;++o)r.set(1,o,o);let i=W(r.toTensor(),[e,t]);if(n==null)return i;if(n.length===1)return Mn(Gt(i,0),[n[0],1,1]);if(n.length===2)return Mn(Gt(Gt(i,0),0),[n[0],n[1],1,1]);if(n.length===3)return Mn(Gt(Gt(Gt(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var Um=L({eye_:v3});function w3(e){let t={x:E(e,"x","floor","float32")};return P.runKernel(Yi,t)}var tp=L({floor_:w3});function k3(e,t,n=0,a=0){let r=E(e,"x","gather"),s=E(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:n,batchDims:a};return P.runKernel(fu,i,o)}var np=L({gather_:k3});function I3(e,t){let n=E(e,"a","greater","string_or_numeric"),a=E(t,"b","greater","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(bu,r)}var Tn=L({greater_:I3});function S3(e,t){let n=E(e,"a","greaterEqual","string_or_numeric"),a=E(t,"b","greaterEqual","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Qi,r)}var $r=L({greaterEqual_:S3});function N3(e){let t={input:E(e,"input","imag")};return P.runKernel(_m,t)}var ld=L({imag_:N3});function T3(e){let t={x:E(e,"x","isFinite")};return P.runKernel(to,t)}var hw=L({isFinite_:T3});function C3(e){let t={x:E(e,"x","isInf")};return P.runKernel(no,t)}var mw=L({isInf_:C3});function E3(e){let t={x:E(e,"x","isNaN")};return P.runKernel(ao,t)}var fw=L({isNaN_:E3});function _3(e,t=.2){let n={x:E(e,"x","leakyRelu")},a={alpha:t};return P.runKernel(ro,n,a)}var ud=L({leakyRelu_:_3});function A3(e,t){let n=E(e,"a","less","string_or_numeric"),a=E(t,"b","less","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(yu,r)}var Pl=L({less_:A3});function F3(e,t){let n=E(e,"a","lessEqual","string_or_numeric"),a=E(t,"b","lessEqual","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(xu,r)}var Ts=L({lessEqual_:F3});function MN(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let a={start:e,stop:t,num:n};return P.runKernel(vu,{},a)}function $3(e,t=5,n=1,a=1,r=.5){let s=E(e,"x","localResponseNormalization");A(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),A($l(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=W(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},p=P.runKernel(oo,l,u);return o?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var gw=L({localResponseNormalization_:$3});function D3(e){let t={x:E(e,"x","log","float32")};return P.runKernel(so,t)}var Qn=L({log_:D3});function R3(e){let t={x:E(e,"x","log1p")};return P.runKernel(io,t)}var pd=L({log1p_:R3});function M3(e){return A(ss(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=E(t,"x","tf.grad","string_or_numeric"),r=n!=null?E(n,"dy","tf.grad"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(a),[a],r);return r!=null&&Sn(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Gm(i),i[0]})}}function O3(e){return A(ss(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=bc(t,"args","tf.grads","string_or_numeric"),r=n!=null?E(n,"dy","tf.grads"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(...a),a,r);return r!=null&&Sn(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Gm(i),i})}}function P3(e){return A(ss(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof Ce,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof Ce,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=P.gradients(()=>e(t),[t],n);return Gm(a),{grad:a[0],value:r}}}function L3(e){return A(ss(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(r=>r instanceof Ce),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof Ce,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=P.gradients(()=>e(...t),t,n);return n!=null&&Sn(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Gm(a.grads),a}}function ON(e,t){A(ss(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(u=>u instanceof os),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in P.registeredVariables)t.push(P.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=P.gradients(e,t,null,s);A(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),A(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,p)=>{o[p]!=null&&(l[u.name]=o[p])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function ur(e){return P.customGrad(e)}function Gm(e){if(e.filter(t=>t==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
|
|
the f you passed encloses all operations that lead from x to y.`)}function z3(e){let t={x:E(e,"x","neg")};return P.runKernel(Cu,t)}var yt=L({neg_:z3});function W3(e){let t={x:E(e,"x","softplus")};return P.runKernel(Oo,t)}var Go=L({softplus_:W3});function B3(e){let t=E(e,"x","logSigmoid");return ur(n=>({value:yt(Go(yt(n))),gradFunc:a=>z(a,ha(yt(n)))}))(t)}var bw=L({logSigmoid_:B3});function V3(e,t){let n=E(e,"a","sub"),a=E(t,"b","sub");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(Bo,r)}var pe=L({sub_:V3});function U3(e,t=-1){let n=E(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return ur((a,r)=>{let s=ma(a,t,!0),i=pe(a,s),o=pe(re(i,"float32"),Qn(fe(dn(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[p]=u,d=!0,c=dn(p);return pe(l,z(fe(l,t,d),c))}}})(n)}var Hm=L({logSoftmax_:U3});function G3(e,t=null,n=!1){let a=E(e,"x","logSumExp"),r=Aa(t,a.shape),s=ma(a,r,!0),i=pe(a,s),o=dn(i),l=fe(o,r),u=Qn(l),p=X(W(s,u.shape),u);if(n){let d=mi(p.shape,r);return W(p,d)}return p}var cd=L({logSumExp_:G3});function H3(e,t){let n=E(e,"a","logicalAnd","bool"),a=E(t,"b","logicalAnd","bool");ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(wu,r)}var _a=L({logicalAnd_:H3});function q3(e){let t={x:E(e,"x","logicalNot","bool")};return P.runKernel(ku,t)}var dd=L({logicalNot_:q3});function j3(e,t){let n=E(e,"a","logicalOr","bool"),a=E(t,"b","logicalOr","bool");ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Iu,r)}var qm=L({logicalOr_:j3});function K3(e,t){let n=E(e,"a","logicalXor","bool"),a=E(t,"b","logicalXor","bool");return ct(n.shape,a.shape),_a(qm(e,t),dd(_a(e,t)))}var yw=L({logicalXor_:K3}),vh=2147483648;function X3(e,t,n="left"){let a=E(e,"sortedSequence","searchSorted"),r=E(t,"values","searchSorted"),s=a.shape[a.shape.length-1],i=r.shape[r.shape.length-1],o=W(a,[-1,s]),l=W(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(ot(l.shape)>=vh)throw new Error(`values tensor size must less than ${vh}`);if(o.shape[1]>=vh)throw new Error(`trailing dim_size must less than ${vh} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},p={side:n};return P.runKernel(zu,u,p)}var jm=L({searchSorted_:X3});function PN(e,t){return jm(e,t,"left")}function Y3(e,t,n,a,r){let s=E(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),A(cr(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),Nn("maxPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=P.runKernel(po,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Dt=L({maxPool_:Y3});function Z3(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=E(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Nn("maxPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=P.runKernel(Nu,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var xw=L({maxPool3d_:Z3});function J3(e,t,n,a,r=!1){let s={x:E(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=P.runKernel(Vc,s,i);return{result:o[0],indexes:o[1]}}var LN=L({maxPoolWithArgmax_:J3});function Q3(e,t){let n=E(e,"a","maximum"),a=E(t,"b","maximum");[n,a]=_t(n,a),n.dtype==="bool"&&(n=re(n,"int32"),a=re(a,"int32")),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(uo,r)}var dr=L({maximum_:Q3});function eL(e,t=null,n=!1){let a={x:E(e,"x","mean")},r={axis:t,keepDims:n};return P.runKernel(co,a,r)}var Ct=L({mean_:eL});function It(e,t="float32"){if(na(e),t==="complex64"){let a=It(e,"float32"),r=It(e,"float32");return Er(a,r)}let n=xm(ot(e),t);return P.makeTensor(n,e,t)}function On(e,t="float32"){if(na(e),t==="complex64"){let a=On(e,"float32"),r=It(e,"float32");return Er(a,r)}let n=Sv(ot(e),t);return P.makeTensor(n,e,t)}function zN(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let a=E(e,"x","meshgrid",e instanceof Ce?e.dtype:"float32");if(t===void 0)return[a];let r=E(t,"y","meshgrid",t instanceof Ce?t.dtype:"float32"),s=ot(a.shape),i=ot(r.shape);return n==="xy"?(a=W(a,[1,-1]),r=W(r,[-1,1]),[$e(On([i,1],a.dtype),a),$e(r,On([1,s],r.dtype))]):(a=W(a,[-1,1]),r=W(r,[1,-1]),[$e(a,On([1,i],a.dtype)),$e(On([s,1],r.dtype),r)])}function tL(e,t){let n=E(e,"a","minimum"),a=E(t,"b","minimum");[n,a]=_t(n,a),n.dtype==="bool"&&(n=re(n,"int32"),a=re(a,"int32")),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(mo,r)}var cs=L({minimum_:tL});function nL(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=E(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let o=0;o<a.rank;o++)A(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return P.runKernel(fo,i,s)}var vw=L({mirrorPad_:nL});function aL(e,t){let n=E(e,"a","mod"),a=E(t,"b","mod");[n,a]=_t(n,a);let r={a:n,b:a};return P.runKernel(go,r)}var ww=L({mod_:aL});function rL(e,t=null,n=!1){e=E(e,"x","moments");let a=Aa(t,e.shape),r=Ct(e,a,n),s=r.shape;n||(s=mi(r.shape,a));let i=pt(pe(re(e,"float32"),W(r,s))),o=Ct(i,a,n);return{mean:r,variance:o}}var hd=L({moments_:rL});function sL(e,t,n,a){let r=E(t,"data","multiRNNCell"),s=bc(n,"c","multiRNNCell"),i=bc(a,"h","multiRNNCell"),o=r,l=[];for(let d=0;d<e.length;d++){let c=e[d](o,s[d],i[d]);l.push(c[0]),l.push(c[1]),o=c[1]}let u=[],p=[];for(let d=0;d<l.length;d+=2)u.push(l[d]),p.push(l[d+1]);return[u,p]}var WN=L({multiRNNCell_:sL});function iL(e,t,n,a=!1){let r=E(e,"logits","multinomial"),s=r.size,i=r.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?W(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},u=P.runKernel(Tu,o,l);return i===1?W(u,[u.size]):u}var BN=L({multinomial_:iL});function oL(e,t){let n=E(e,"a","notEqual","string_or_numeric"),a=E(t,"b","notEqual","string_or_numeric");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Eu,r)}var fi=L({notEqual_:oL});function lL(e,t,n=1,a=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let s={indices:E(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:a};return P.runKernel(yo,s,i)}var Ll=L({oneHot_:lL});function uL(e){let t={x:E(e,"x","onesLike")};return P.runKernel($u,t)}var ea=L({onesLike_:uL});function pL(e,t){let n=E(e,"v1","outerProduct"),a=E(t,"v2","outerProduct");A(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=W(n,[-1,1]),s=W(a,[1,-1]);return $e(r,s)}var VN=L({outerProduct_:pL});function cL(e,t,n=0){let a=E(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return P.runKernel(xo,s,r)}var xa=L({pad_:cL});function dL(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),xa(e,[t],n)}var UN=L({pad1d_:dL});function hL(e,t,n=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),xa(e,t,n)}var GN=L({pad2d_:hL});function mL(e,t,n=0){return A(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),xa(e,t,n)}var HN=L({pad3d_:mL});function fL(e,t,n=0){return A(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),xa(e,t,n)}var qN=L({pad4d_:fL});function gL(e,t,n){let a=E(e,"x","spaceToBatchND");A(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),A(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),A(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return P.runKernel(Vu,r,s)}var md=L({spaceToBatchND_:gL});function bL(e,t,n,a,r,s,i){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let o=E(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(cr(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let p=wN(l.shape,t,s,r,a),d=[p.dilationHeight,p.dilationWidth],c;a==="same"?c=xL([p.filterHeight,p.filterWidth],d):c=[[0,0],[0,0]];let h=d[0]===1&&d[1]===1,[m,f]=yL([p.inHeight,p.inWidth],d,c),g=h?a:"valid",b=h?l:md(l,d,m),y=(n==="avg"?()=>ya(b,t,s,g,i):()=>Dt(b,t,s,g,i))(),x=h?y:id(y,d,f);return u?W(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function yL(e,t,n){let a=n.map(p=>p[0]),r=n.map(p=>p[1]),s=e.concat(a,r),i=t.map((p,d)=>(p-s[d]%p)%p),o=r.map((p,d)=>p+i[d]),l=t.map((p,d)=>[a[d],o[d]]),u=t.map((p,d)=>[0,i[d]]);return[l,u]}function xL(e,t){let n=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=n.map(s=>Math.floor(s/2)),r=n.map((s,i)=>s-a[i]);return n.map((s,i)=>[a[i],r[i]])}var kw=L({pool_:bL});function vL(e,t){let n=E(e,"x","prelu"),a=E(t,"alpha","prelu"),r={x:n,alpha:a};return P.runKernel(wo,r)}var fd=L({prelu_:vL});function wL(e,t=null,n=!1){let a=E(e,"x","prod");a.dtype==="bool"&&(a=re(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return P.runKernel(ko,r,s)}var Iw=L({prod_:wL});function kL(e,t,n,a){let r=e.map((p,d)=>E(p,`tensors${d}`,"raggedGather","int32")),s=E(t,"paramsDenseValues","raggedGather"),i=E(n,"indices","raggedGather","int32"),o={paramsNestedSplits:r,paramsDenseValues:s,indices:i},l={outputRaggedRank:a},u=P.runKernel(Am,o,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var jN=L({raggedGather_:kL});function IL(e,t,n){let a=E(e,"starts","raggedRange"),r=E(t,"limits","raggedRange",a.dtype),s=E(n,"deltas","raggedRange",a.dtype),i={starts:a,limits:r,deltas:s},o=P.runKernel(Fm,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var KN=L({raggedRange_:IL});function SL(e,t,n,a,r){let s=E(e,"shape","raggedTensorToTensor","int32"),i=E(t,"values","raggedTensorToTensor"),o=E(n,"defaultValue","raggedTensorToTensor",i.dtype),l=a.map((d,c)=>E(d,`tensors${c}`,"raggedTensorToTensor","int32")),u={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},p={rowPartitionTypes:r};return P.runKernel($m,u,p)}var XN=L({raggedTensorToTensor_:SL});function NL(e,t,n){na(e);let a=ot(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s<a;s++)r[s]=t();return P.makeTensor(r,e,n)}var YN=L({rand_:NL}),Sw=ys(bm()),ZN={};_e(ZN,{TEST_EPSILON_FLOAT16:()=>JN,createVideoElement:()=>DL,encodeStrings:()=>QN,expectArrayBuffersEqual:()=>$L,expectArraysClose:()=>CL,expectArraysEqual:()=>_L,expectNumbersClose:()=>AL,expectPromiseToFail:()=>EL,expectValuesInRange:()=>FL,play:()=>RL,testEpsilon:()=>Nw});var TL=.001,JN=.1;function CL(e,t,n){return n==null&&(n=Nw()),Dx(e,t,(a,r)=>Tw(a,r,n))}function Nw(){return P.backend.floatPrecision()===32?TL:JN}function Dx(e,t,n){let a=!0;if((en(e)||en(t))&&(a=!1),en(e)&&en(t)&&(a=!0),a){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=lr(e),o=lr(t);if(!Ar(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=en(e)?e:is(e),s=en(t)?t:is(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}.
|
|
Actual: ${r}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!n(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
|
|
Actual: ${r}.
|
|
Expected: ${s}.`)}typeof expect!="undefined"&&expect().nothing()}function EL(e,t){e().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function _L(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Jr(e)||Jr(e[0])||Jr(t)||Jr(t[0])?Dx(e,n,(a,r)=>a==r):Dx(e,t,(a,r)=>Tw(a,r,0))}function AL(e,t,n){if(n==null&&(n=Nw()),!Tw(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function Tw(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function FL(e,t,n){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>n)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${n}`)}function $L(e,t){let n=new Float32Array(e),a=new Float32Array(t);if(n.length!==a.length)throw new Error(`Expected ArrayBuffer to be of length ${a.length}, but it was ${n.length}`);for(let r=0;r<a.length;r++)if(n[r]!==a[r])throw new Error(`Expected ArrayBuffer value at ${r} to be ${a[r]} but got ${n[r]} instead`)}function QN(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?QN(n):e[t]=nd(n)}return e}function DL(e){let t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise(n=>{t.addEventListener("loadeddata",a=>n(t)),t.load()})}async function RL(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var Cw=class{constructor(e,t,n,a,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=a,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=r||Math.random();this.random=Sw.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let a=this.nextVal;return this.nextVal=NaN,a}let e,t,n=!1;for(;!n;){let a,r,s;do a=2*this.random()-1,r=2*this.random()-1,s=a*a+r*r;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*r*i,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},ML=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=Sw.alea(r.toString()),this.randn=new Cw(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,a,r,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),r<t||Math.log(r)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},OL=class{constructor(e=0,t=1,n,a){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Sw.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function PL(e,t,n=1,a="float32",r){if(na(e),n==null&&(n=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new ML(t,n,a,r),i=Oe(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var eT=L({randomGamma_:PL});function LL(e,t=0,n=1,a,r){if(na(e),a!=null&&a==="bool")throw new Error(`Unsupported data type ${a}`);let s=new Cw(t,n,a,!1,r),i=Oe(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Km=L({randomNormal_:LL});function zL(e,t,n){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return Km(e,0,1,t,n)}var tT=L({randomStandardNormal_:zL});function WL(e,t=0,n=1,a="float32",r){na(e);let s=Oe(e,a),i=new OL(t,n,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Cs=L({randomUniform_:WL});function BL(e,t,n,a){return Cs(e,t,n,"int32",a)}var nT=L({randomUniformInt_:BL});function gi(e,t,n=1,a="float32"){if(n===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:n,dtype:a};return P.runKernel(Uc,{},r)}function VL(e){let t={input:E(e,"input","real")};return P.runKernel(Dm,t)}var zl=L({real_:VL});function UL(e){let t={x:E(e,"x","reciprocal")};return P.runKernel(Io,t)}var Ew=L({reciprocal_:UL});function GL(e){let t={x:E(e,"x","relu")};return P.runKernel(So,t)}var Ke=L({relu_:GL});function HL(e){let t={x:E(e,"x","relu6")};return P.runKernel(Co,t)}var Xm=L({relu6_:HL});function qL(e,t){let n={x:E(e,"x","reverse")},a={dims:t};return P.runKernel(Eo,n,a)}var ba=L({reverse_:qL});function jL(e){let t=E(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),ba(t,0)}var aT=L({reverse1d_:jL});function KL(e,t){let n=E(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),ba(n,t)}var rT=L({reverse2d_:KL});function XL(e,t){let n=E(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),ba(n,t)}var sT=L({reverse3d_:XL});function YL(e,t){let n=E(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),ba(n,t)}var iT=L({reverse4d_:YL});function ZL(e){let t={x:E(e,"x","round")};return P.runKernel(_o,t)}var Ym=L({round_:ZL});function JL(e){let t={x:E(e,"x","rsqrt","float32")};return P.runKernel(Ao,t)}var Zm=L({rsqrt_:JL});function QL(e){let t={x:E(e,"x","selu")};return P.runKernel(Fo,t)}var Jm=L({selu_:QL});function ez(e,t,n,a,r,s=[1,1],i="NHWC"){let o=E(e,"x","separableConv2d"),l=E(t,"depthwiseFilter","separableConv2d"),u=E(n,"pointwiseFilter","separableConv2d"),p=o,d=!1;if(o.rank===3&&(d=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),A(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let c=l.shape[2],h=l.shape[3];A(u.shape[2]===c*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${c*h}, but got ${u.shape[2]}.`);let m=Ns(p,l,a,r,i,s),f=$t(m,u,1,"valid",i);return d?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Es=L({separableConv2d_:ez});async function tz(e,t){let n=E(e,"x","setdiff1d"),a=E(t,"y","setdiff1d");A(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),A(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),A(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let p=0;p<r.length;p++)i.has(r[p])||o++;let l=new Wt([o],n.dtype),u=new Wt([o],"int32");for(let p=0,d=0;p<r.length;p++)i.has(r[p])||(l.values[d]=r[p],u.values[d]=p,d++);return[l.toTensor(),u.toTensor()]}var oT=tz;function nz(e){let t={x:E(e,"x","sign")};return P.runKernel(Ro,t)}var _w=L({sign_:nz});function az(e){let t={x:E(e,"x","sin","float32")};return P.runKernel($o,t)}var Qm=L({sin_:az});function rz(e){let t={x:E(e,"x","sinh")};return P.runKernel(Do,t)}var ef=L({sinh_:rz});function sz(e,t,n){let a=E(e,"x","slice1d");return A(a.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),Ve(a,[t],[n])}var gd=L({slice1d_:sz});function iz(e,t,n){let a=E(e,"x","slice2d");return A(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),Ve(a,t,n)}var tf=L({slice2d_:iz});function oz(e,t,n){let a=E(e,"x","slice3d");return A(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),Ve(a,t,n)}var Ho=L({slice3d_:oz});function lz(e,t,n){let a=E(e,"x","slice4d");return A(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),Ve(a,t,n)}var Wl=L({slice4d_:lz});function uz(e,t=-1){let n=E(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let a={logits:n},r={dim:t};return P.runKernel(zo,a,r)}var ja=L({softmax_:uz});function pz(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return P.runKernel(Cm,t)}var bd=L({fft_:pz});function cz(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return P.runKernel(Em,t)}var Bl=L({ifft_:cz});function dz(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=W(e,[n,t]);a=Bl(r)}else{let r=[n,2*(t-1)],s=W(zl(e),[n,t]),i=W(ld(e),[n,t]),o=ba(Ve(s,[0,1],[n,t-2]),1),l=z(ba(Ve(i,[0,1],[n,t-2]),1),ve(-1)),u=et([s,o],1),p=et([i,l],1),d=W(Er(u,p),[r[0],r[1]]);a=Bl(d)}if(a=zl(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=W(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var nf=L({irfft_:dz});function hz(e,t,n=0){let a={x:E(e,"x","split")},r={numOrSizeSplits:t,axis:n};return P.runKernel(Uu,a,r)}var Pn=L({split_:hz});function mz(e,t){A(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],a=e.size/n,r;if(t!=null&&t<n){let m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=Ve(e,m,f),n=t}else if(t!=null&&t>n){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-n,r=et([e,It(m)],e.shape.length-1),n=t}else r=e;let s=je(r),i=W(Er(r,s),[a,n]),o=bd(i),l=Math.floor(n/2)+1,u=zl(o),p=ld(o),d=Pn(u,[l,n-l],u.shape.length-1),c=Pn(p,[l,n-l],p.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,W(Er(d[0],c[0]),h)}var yd=L({rfft_:mz});function fz(e,t){let n=E(e,"a","squaredDifference"),a=E(t,"b","squaredDifference");[n,a]=_t(n,a),ct(n.shape,a.shape);let r={a:n,b:a},s={};return P.runKernel(Wo,r,s)}var af=L({squaredDifference_:fz});function gz(e,t){let n=E(e,"x","squeeze","string_or_numeric");return W(n,MS(n.shape,t).newShape)}var _s=L({squeeze_:gz});function bz(e,t=0){let n=bc(e,"tensors","stack","string_or_numeric");A(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&A(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return P.runKernel(Du,a,r)}var At=L({stack_:bz});function yz(e,t=0){let n={x:E(e,"x","step")},a={alpha:t};return P.runKernel(ks,n,a)}var qo=L({step_:yz});function xz(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let u={x:E(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return P.runKernel(qu,u,p)}var Aw=L({stridedSlice_:xz});function vz(e){let t={x:E(e,"x","tan","float32")};return P.runKernel(Vo,t)}var Fw=L({tan_:vz});function qe(e,t){Si(e);let n=lr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Is(e,null,n,t)}function Ea(e,t,n){if(Si(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=lr(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Is(e,t,a,n)}function xd(e,t,n){if(Si(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=lr(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Is(e,t,a,n)}function Fa(e,t,n){if(Si(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=lr(e,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Is(e,t,a,n)}function lT(e,t,n){if(Si(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=lr(e,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Is(e,t,a,n)}function uT(e,t,n){if(Si(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=lr(e,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,Is(e,t,a,n)}var rf={};_e(rf,{calculateShapes:()=>pT,validateInput:()=>sf,validateUpdateShape:()=>$w});function $w(e,t,n){let a=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(s+` update.rank < ${r}. `);if(e.length<a+(n.rank-r))throw new Error(s+` Output shape length < ${a+(n.rank-r)}`);if(n.rank!==r+e.length-a)throw new Error(s+` update.rank != ${r+e.length-a}`);for(let i=0;i<r;++i)if(n.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${n.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<n.rank-r;++i)if(n.shape[i+r]!==e[i+a])throw new Error(s+` updates.shape[${i+r}] (${n.shape[i+r]}) != shape[${i+r}] (${e[i+r]})`)}function sf(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}`)}$w(n,t,e)}function pT(e,t,n){let a=t.shape.length,r=a>1?t.shape[a-1]:1,s=n.length,i=1;for(let d=r;d<s;++d)i*=n[d];let o=r<1?1:r,l=ot(t.shape)/o,u=[...Xl(n.slice(0,r)),1],p=ot(n);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:u,outputSize:p}}function wz(e,t,n){let a=E(e,"tensor","tensorScatterupdate"),r=E(t,"indices","tensorScatterupdate","int32"),s=E(n,"updates","tensorScatterupdate");if(sf(s,r,a.shape),a.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${a.dtype} and ${s.dtype}.`);let i={tensor:a,indices:r,updates:s},o={};return P.runKernel(Lu,i,o)}var cT=L({tensorScatterUpdate_:wz});function kz(e,t=1,n=!0){let a=E(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=P.runKernel(ju,s,i);return{values:o,indices:l}}var Dw=L({topk_:kz});function Iz(e,t=0,n=1,a,r){if(na(e),a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Cw(t,n,a,!0,r),i=Oe(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var of=L({truncatedNormal_:Iz});function Sz(e,t=0){let n=E(e,"x","unique","string_or_numeric");A(n.rank>0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=P.runKernel(Jc,a,r);return{values:s,indices:i}}var Rw=L({unique_:Sz});function Nz(e,t,n){let a=E(e,"x","unsortedSegmentSum"),r=E(t,"segmentIds","unsortedSegmentSum","int32");A($l(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return P.runKernel(Qc,s,i)}var lf=L({unsortedSegmentSum_:Nz});function Tz(e,t=0){let n=E(e,"x","unstack","string_or_numeric");A(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return P.runKernel(Xu,a,r)}var dt=L({unstack_:Tz});function dT(e,t){return jm(e,t,"right")}function Mw(e,t=!0,n,a){return P.makeVariable(e,t,n,a)}function hT(e,t){let n=[];for(let s=0;s<t.length;s++)t[s]&&n.push(s);let a=Oe(e,"int32"),r=Oe([n.length,e.length],"int32");for(let s=0;s<n.length;s++){let i=a.indexToLoc(n[s]),o=s*e.length;r.values.set(i,o)}return r.toTensor()}async function Cz(e){let t=E(e,"condition","whereAsync","bool"),n=await t.data(),a=hT(t.shape,n);return e!==t&&t.dispose(),a}var Ow=Cz;async function Ez(e,t,n){let a=E(e,"tensor","boolMask"),r=E(t,"mask","boolMask","bool"),s=n==null?0:n,i=r.rank,o=a.shape;A(i>0,()=>"mask cannot be scalar"),Sn(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f<s+i;f++)l*=o[f];let u=o.slice(0,s).concat([l],o.slice(s+i)),p=W(a,u),d=W(r,[-1]),c=await Ow(d),h=_s(c,[1]),m=np(p,h,s);return e!==a&&a.dispose(),t!==r&&r.dispose(),h.dispose(),p.dispose(),d.dispose(),c.dispose(),m}var mT=Ez;function _z(e,t,n){let a=E(e,"x","transpose");if(t==null&&(t=a.shape.map((i,o)=>o).reverse()),A(a.rank===t.length,()=>`Error in transpose: rank of input ${a.rank} must match length of perm ${t}.`),t.forEach(i=>{A(i>=0&&i<a.rank,()=>`All entries in 'perm' must be between 0 and ${a.rank-1} but got ${t}`)}),a.rank<=1)return a.clone();let r={x:a},s={perm:t};return a.dtype==="complex64"?O(()=>{let i=zl(a),o=ld(a);return i=P.runKernel(Tr,{x:i},s),o=P.runKernel(Tr,{x:o},s),n&&(o=yt(o)),Er(i,o)}):P.runKernel(Tr,r,s)}var De=L({transpose_:_z});function Az(e,t,n,a,r=!0){let s=E(e,"v","movingAverage"),i=E(t,"x","movingAverage"),o=E(n,"decay","movingAverage");tN(s,i),A(Ar(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=ve(1),u=pe(l,o),p=z(pe(i,s),u);if(r){A(a!=null,()=>"When using zeroDebias: true, step is required.");let d=E(a,"step","movingAverage");p=he(p,pe(l,_r(o,d)))}return X(s,p)}var fT=L({movingAverage_:Az});function Fz(e,t,n){na(n);let a=E(e,"indices","scatterND","int32"),r=E(t,"updates","scatterND");sf(r,a,n);let s={indices:a,updates:r},i={shape:n};return P.runKernel(Pu,s,i)}var gT=L({scatterND_:Fz});function $z(e,t,n,a){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Dz(e,t,n,a=0){na(n);let r=E(e,"sparseIndices","sparseToDense","int32"),s=E(t,"sparseValues","sparseToDense","string_or_numeric"),i=E(a,"defaultValue","sparseToDense",s.dtype);$z(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return P.runKernel(Hu,o,l)}var bT=L({sparseToDense_:Dz});function Rz(e,t){let n=E(t,"indices","gatherND","int32"),a={params:E(e,"x","gatherND","string_or_numeric"),indices:n};return P.runKernel(gu,a)}var yT=L({gatherND_:Rz});function Mz(e,t){if(t==null)return e.shape.slice();if(Ar(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a<e.shape.length;a++)t[a]==null&&e.shape[a]!=null?n.push(e.shape[a]):n.push(t[a]);return n}return t}function Oz(e,t,n,a){let r=E(e,"x","dropout");if(A(r.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ce?r.clone():r;let s=Mz(r,n),i=1-t,o=he(tp(X(Cs(s,0,1,"float32",a),i)),i);return z(r,o)}var Pw=L({dropout_:Oz});function Lw(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function uf(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+a-1);r[s]=t-n*Math.cos(i)}return qe(r,"float32")}async function Pz(e,t,n=1){let a=E(e,"predictions","inTopK"),r=E(t,"targets","inTopK");A(a.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),A(a.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${r.rank}`),Sn(a.shape.slice(0,a.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];A(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);let i=await a.data(),o=await r.data(),[l,u]=[i.length/s,s],p=OS("bool",l);for(let d=0;d<l;d++){let c=d*u,h=i.subarray(c,c+u),m=[];for(let f=0;f<h.length;f++)m.push({value:h[f],index:f});m.sort((f,g)=>g.value-f.value),p[d]=0;for(let f=0;f<n;f++)if(m[f].index===o[d]){p[d]=1;break}}return e!==a&&a.dispose(),t!==r&&r.dispose(),bn(p,r.shape,"bool")}var xT=Pz,Vl={};_e(Vl,{conv2d:()=>Wz,depthwiseConv2d:()=>Gz,matMul:()=>qz});function Lz(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),A(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];A(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),A(p===n[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${n[3]}).`),Nn("conv2dDerFilter",r,i);let d={x:o,dy:l},c={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return P.runKernel(km,d,c)}var zw=L({conv2DBackpropFilter_:Lz});function pf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return z(e,qo(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cf(e,t){let n=t,a=Bt(e.shape,t.shape);return a.length>0&&(n=fe(n,a)),W(n,e.shape)}function df(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Ke(e);if(t==="elu")return Qu(e);if(t==="relu6")return Xm(e);if(t==="prelu")return fd(e,n);if(t==="leakyrelu")return ud(e,a);if(t==="sigmoid")return ha(e);throw new Error(`Unknown fused activation ${t}.`)}var hf=(e,t)=>!(e>0)||t==="linear";function zz({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",hf(P.state.gradientDepth,l)===!1){A(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let N=$t(e,t,n,a,r,s,i);return o!=null&&(N=X(N,o)),df(N,l,u,p)}let d=E(e,"x","conv2d","float32"),c=E(t,"filter","conv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${c.rank}.`),Nn("fused conv2d",a,i);let f=r==="NHWC"?h.shape[3]:h.shape[1];A(c.shape[2]===f,()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${c.shape[2]}.`),A(cr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let g=sd(h.shape,c.shape,n,s,a,i),b;o!=null&&(b=E(o,"bias","fused conv2d"),[b]=_t(b,d),r==="NHWC"?ct(g.outShape,b.shape):(A(b.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`),A(b.shape.length===0||b.shape[0]===g.outChannels||b.shape[0]===1,()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let y;if(u!=null){let N=u.shape;if(A(N.length<=1||N.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${N.length}.`),N.length===1)A(N[0]===1||N[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${N}) is not compatible with the number of output channels (${g.outChannels}).`);else if(N.length===3)try{ct(N,g.outShape)}catch(C){let _=`Error in fused conv2d: PReLU activation weights (${N}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(_)}y=E(u,"prelu weights","fused conv2d")}let x=(N,C)=>{A(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[_,F,D,$]=C,S=pf(N,D,l);A(ps(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let M=tw(F.shape,S,_,n,a),B=zw(F,S,_.shape,n,a),U=[M,B];if($!=null){let H=cf($,S);U.push(H)}return U},v={x:h,filter:c,bias:b,preluActivationWeights:y},I={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?ur((N,C,_)=>{let F=P.runKernel(ii,v,I);return _([C,N,F]),m&&(F=W(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:x}})(h,c):ur((N,C,_,F)=>{let D=P.runKernel(ii,v,I);return F([C,N,D,_]),m&&(D=W(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:x}})(h,c,b)}var Wz=L({fusedConv2d_:zz});function Bz(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return P.runKernel(Im,u,p)}var vT=L({depthwiseConv2dNativeBackpropFilter_:Bz});function Vz(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:n},p={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},d=P.runKernel(Sm,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var wT=L({depthwiseConv2dNativeBackpropInput_:Vz});function Uz({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(hf(P.state.gradientDepth,l)===!1){let I=Ns(e,t,n,a,r,s,i);return o!=null&&(I=X(I,o)),df(I,l,u,p)}let d=E(e,"x","depthwiseConv2d","float32"),c=E(t,"filter","depthwiseConv2d","float32"),h=d,m=!1;d.rank===3&&(m=!0,h=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),A(h.shape[3]===c.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),s==null&&(s=[1,1]),A(cr(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),Nn("fused depthwiseConv2d",a,i);let f=sd(h.shape,c.shape,n,s,a,i,!0),g;o!=null&&(g=E(o,"bias","fused conv2d"),[g]=_t(g,d),ct(f.outShape,g.shape));let b;u!=null&&(b=E(u,"prelu weights","fused depthwiseConv2d"));let y=(I,N)=>{A(ps(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,_,F,D]=N,$=pf(I,F,l),S=wT(_.shape,$,C,n,a,s,i),M=vT(_,$,C.shape,n,a,s,i);if(D!=null){let B=cf(g,$);return[S,M,B]}return[S,M]},x={x:h,filter:c,bias:g,preluActivationWeights:b},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?ur((I,N,C)=>{let _=P.runKernel(oi,x,v);return C([N,I,_]),m&&(_=W(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(h,c):ur((I,N,C,_)=>{let F=P.runKernel(oi,x,v);return _([N,I,F,C]),m&&(F=W(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,c,g)}var Gz=L({fusedDepthwiseConv2d_:Uz});function Hz({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(hf(P.state.gradientDepth,s)===!1){let D=$e(e,t,n,a);return r!=null&&(D=X(D,r)),df(D,s,i,o)}let l=E(e,"a","fused matMul"),u=E(t,"b","fused matMul");[l,u]=_t(l,u);let p=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=a?u.shape[u.rank-1]:u.shape[u.rank-2],c=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=a?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=ot(m),b=ot(f);A(p===d,()=>`Error in fused matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${a} must match.`);let y=ct(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([c,h]),x=n?W(l,[g,p,c]):W(l,[g,c,p]),v=a?W(u,[b,h,d]):W(u,[b,d,h]),I;r!=null&&(I=E(r,"bias","fused matMul"),[I]=_t(I,l),ct(y,I.shape));let N;i!=null&&(N=E(i,"prelu weights","fused matMul"));let C=(D,$)=>{let[S,M,B,U]=$,H=pf(W(D,B.shape),B,s),j,K;if(!n&&!a?(j=$e(H,M,!1,!0),K=$e(S,H,!0,!1)):!n&&a?(j=$e(H,M,!1,!1),K=$e(H,S,!0,!1)):n&&!a?(j=$e(M,H,!1,!0),K=$e(S,H,!1,!1)):(j=$e(M,H,!0,!0),K=$e(H,S,!0,!0)),r!=null){let Z=cf(U,H);return[j,K,Z]}else return[j,K]},_={a:x,b:v,bias:I,preluActivationWeights:N},F={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?ur((D,$,S)=>{let M=P.runKernel(si,_,F);return S([D,$,M]),{value:W(M,y),gradFunc:C}})(x,v):ur((D,$,S,M)=>{let B=P.runKernel(si,_,F);return M([D,$,B,S]),{value:W(B,y),gradFunc:C}})(x,v,I)}var qz=L({fusedMatMul_:Hz});function jz(e){return uf(e,.54,.46)}var Kz=L({hammingWindow_:jz});function Xz(e){return uf(e,.5,.5)}var kT=L({hannWindow_:Xz});function Yz(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Ve(e,s,t)),s+=n;if(a)for(;s<e.size;){let o=s+t-e.size,l=et([Ve(e,s,t-o),yn([o],r)]);i.push(l),s+=n}return i.length===0?Ea([],[0,t]):W(et(i),[i.length,t])}var IT=L({frame_:Yz});function Zz(e,t,n,a,r=kT){a==null&&(a=Lw(t));let s=IT(e,t,n),i=z(s,r(t));return yd(i,a)}var Jz=L({stft_:Zz});function Qz(e,t,n,a,r="bilinear",s=0){let i=E(e,"image","cropAndResize"),o=E(t,"boxes","cropAndResize","float32"),l=E(n,"boxInd","cropAndResize","int32"),u=o.shape[0];A(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),A(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),A(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),A(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),A(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let p={image:i,boxes:o,boxInd:l},d={method:r,extrapolationValue:s,cropSize:a};return P.runKernel(uu,p,d)}var eW=L({cropAndResize_:Qz});function tW(e){let t=E(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return P.runKernel(mu,n,{})}var nW=L({flipLeftRight_:tW});function aW(e){let t=E(e,"image","grayscaleToRGB"),n=t.rank-1,a=t.shape[n];A(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),A(a===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${a}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Mn(t,r)}var rW=L({grayscaleToRGB_:aW});function sW(e){let t=E(e,"image","RGBToGrayscale"),n=t.rank-1,a=t.shape[n];A(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),A(a===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${a}.`);let r=t.dtype,s=re(t,"float32"),i=qe([.2989,.587,.114]),o;switch(t.rank){case 2:o=Ys("ij,j->i",s,i);break;case 3:o=Ys("ijk,k->ij",s,i);break;case 4:o=Ys("ijkl,l->ijk",s,i);break;case 5:o=Ys("ijklm,m->ijkl",s,i);break;case 6:o=Ys("ijklmn,n->ijklm",s,i);break;default:throw new Error("Not a valid tensor rank.")}return o=Gt(o,-1),re(o,r)}var iW=L({rgbToGrayscale_:sW});function oW(e,t,n=0,a=.5){let r=E(e,"image","rotateWithOffset","float32");A(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return P.runKernel(Zu,s,i)}var lW=L({rotateWithOffset_:oW});function ap(e,t,n,a,r,s){a==null&&(a=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return n=Math.min(n,i),A(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),A(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function uW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppression","float32"),i=E(t,"scores","nonMaxSuppression","float32"),o=ap(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return P.runKernel(_u,{boxes:s,scores:i},l)}var pW=L({nonMaxSuppression_:uW});function cW(e,t,n){let a=dW(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function dW(e,t,n){return mW(e,t,n||hW)}function hW(e,t){return e>t?1:e<t?-1:0}function mW(e,t,n){let a=0,r=e.length,s=0,i=!1;for(;a<r;){s=a+(r-a>>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function ST(e,t,n,a,r){return Ww(e,t,n,a,r,0)}function NT(e,t,n,a,r,s){return Ww(e,t,n,a,r,0,!1,s,!0)}function TT(e,t,n,a,r,s){return Ww(e,t,n,a,r,s,!0)}function Ww(e,t,n,a,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>r&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(tI);let p=s>0?-.5/s:0,d=[],c=[];for(;d.length<n&&u.length>0;){let g=u.pop(),{score:b,boxIndex:y,suppressBeginIndex:x}=g;if(b<r)break;let v=!1;for(let I=d.length-1;I>=x;--I){let N=fW(e,y,d[I]);if(N>=a){v=!0;break}if(g.score=g.score*gW(a,p,N),g.score<=r)break}g.suppressBeginIndex=d.length,v||(g.score===b?(d.push(y),c.push(g.score)):g.score>r&&cW(u,g,tI))}let h=d.length,m=n-h;o&&m>0&&(d.push(...new Array(m).fill(0)),c.push(...new Array(m).fill(0)));let f={selectedIndices:d};return i&&(f.selectedScores=c),l&&(f.validOutputs=h),f}function fW(e,t,n){let a=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),u=Math.min(r[0],r[2]),p=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),c=Math.max(r[1],r[3]),h=(o-s)*(l-i),m=(d-u)*(c-p);if(h<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,p),b=Math.min(o,d),y=Math.min(l,c),x=Math.max(b-f,0)*Math.max(y-g,0);return x/(h+m-x)}function gW(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function tI(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function bW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=E(e,"boxes","nonMaxSuppressionAsync"),i=E(t,"scores","nonMaxSuppressionAsync"),o=ap(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:d}=ST(u,p,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),qe(d,"int32")}var yW=bW;function xW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=ap(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},p={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},d=P.runKernel(Fu,u,p);return{selectedIndices:d[0],selectedScores:d[1]}}var vW=L({nonMaxSuppressionWithScore_:xW});async function wW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=ap(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),p=u[0],d=u[1],{selectedIndices:c,selectedScores:h}=TT(p,d,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:qe(c,"int32"),selectedScores:qe(h)}}var kW=wW;function IW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppression"),o=E(t,"scores","nonMaxSuppression"),l=ap(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,c={boxes:i,scores:o},h={maxOutputSize:u,iouThreshold:p,scoreThreshold:d,padToMaxOutputSize:s},m=P.runKernel(Au,c,h);return{selectedIndices:m[0],validOutputs:m[1]}}var SW=L({nonMaxSuppressionPadded_:IW});async function NW(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=E(e,"boxes","nonMaxSuppressionAsync"),o=E(t,"scores","nonMaxSuppressionAsync"),l=ap(i,o,n,a,r,null),u=l.maxOutputSize,p=l.iouThreshold,d=l.scoreThreshold,[c,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=NT(c,h,u,p,d,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:qe(m,"int32"),validOutputs:ve(f,"int32")}}var TW=NW;function CW(e,t,n=!1,a=!1){let r=E(e,"images","resizeBilinear");A(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),A(a===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=P.runKernel(To,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var CT=L({resizeBilinear_:CW});function EW(e,t,n=!1,a=!1){let r=E(e,"images","resizeNearestNeighbor");A(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(a===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=P.runKernel(No,o,l);return i?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var ET=L({resizeNearestNeighbor_:EW});function _W(e,t="binary",n=!1,a=.5){let r=E(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=z(qe([a]),255),p,d,c,h;if(A(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),A(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),A(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),A(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[p,d,c]=Pn(r,[1,1,1],-1);let f=z(p,s),g=z(d,i),b=z(c,o);h=X(X(f,g),b)}else h=e;if(t==="otsu"){let f=Xv(re(Ym(h),"int32"),bn([]),256);u=AW(f,l)}let m=n?Ts(h,u):Tn(h,u);return re(z(m,255),"int32")}function AW(e,t){let n=qe([-1]),a=qe([0]),r=qe([0]),s,i,o,l,u,p;for(let d=0;d<e.size-1;d++){s=Ve(e,0,d+1),i=Ve(e,d+1),u=he(fe(s),t),p=he(fe(i),t);let c=fe(z(s,gi(0,s.size)));o=he(c,fe(s));let h=yn(i.shape,s.size),m=X(gi(0,i.size),h),f=z(i,m);l=he(fe(f),fe(i));let g=pe(o,l),b=pe(o,l),y=z(u,p);r=z(z(y,g),b);let x=Tn(r,a);a=nn(x,r,a),n=nn(x,qe([d]),n)}return n}var FW=L({threshold_:_W});function $W(e,t,n="nearest",a="constant",r=0,s){let i=E(e,"image","transform","float32"),o=E(t,"transforms","transform","float32");A(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),A(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:n,fillMode:a,fillValue:r,outputShape:s};return P.runKernel(Ku,l,u)}var DW=L({transform_:$W});function RW(e,t,n){let a=E(e,"a","bandPart");A(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let r=a.shape,[s,i]=a.shape.slice(-2),o,l;typeof t=="number"?(A(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),o=E(t<0?s:t,"numLower","bandPart")):(A(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),o=nn(Pl(t,0),s,cs(t,s))),typeof n=="number"?(A(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`),A(n<=i,()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`),l=E(n<0?i:n,"numUpper","bandPart")):(A(n.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=nn(Pl(n,0),i,cs(n,i)));let u=W(gi(0,s,1,"int32"),[-1,1]),p=gi(0,i,1,"int32"),d=pe(u,p),c=_a(Ts(d,o),$r(d,yt(l))),h=It([s,i],a.dtype);return W(At(dt(W(a,[-1,s,i])).map(m=>nn(c,m,h))),r)}var MW=L({bandPart_:RW});function OW(e){let t;if(Array.isArray(e)){t=!1,A(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s<e.length;++s)A(e[s].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=Pn(e,e.shape[0],0).map(r=>_s(r,[0]));A(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r<e.length;++r)n.push(P.tidy(()=>{let s=a[r];if(r>0)for(let i=0;i<r;++i){let o=z(fe(z(n[i],s)),n[i]);s=pe(s,o)}return he(s,ep(s,"euclidean"))}));return t?At(n,0):n}var PW=L({gramSchmidt_:OW});function LW(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return nI(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),a=dt(W(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[u,p]=nI(l,t);r.push(u),s.push(p)});let i=W(At(r,0),e.shape),o=W(At(s,0),e.shape);return[i,o]}}function nI(e,t=!1){return P.tidy(()=>{A(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],a=e.shape[1],r=Um(n),s=sr(e),i=Ea([[1]],[1,1]),o=sr(i),l=n>=a?a:n;for(let u=0;u<l;++u){let p=s,d=o,c=r;[o,s,r]=P.tidy(()=>{let h=Ve(s,[u,u],[n-u,1]),m=ep(h),f=Ve(s,[u,u],[1,1]),g=nn(Tn(f,0),Ea([[-1]]),Ea([[1]])),b=pe(f,z(g,m)),y=he(h,b);y.shape[0]===1?o=sr(i):o=et([i,Ve(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=yt(he($e(g,b),m)),v=Ve(s,[u,0],[n-u,a]),I=z(x,o),N=De(o);if(u===0)s=pe(v,$e(I,$e(N,v)));else{let F=pe(v,$e(I,$e(N,v)));s=et([Ve(s,[0,0],[u,a]),F],0)}let C=De(I),_=Ve(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=pe(_,$e($e(_,o),C));else{let F=pe(_,$e($e(_,o),C));r=et([Ve(r,[0,0],[n,u]),F],1)}return[o,s,r]}),Ee([p,d,c])}return!t&&n>a&&(r=Ve(r,[0,0],[n,a]),s=Ve(s,[0,0],[a,a])),[r,s]})}var zW=L({qr_:LW}),wn;(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"})(wn||(wn={}));function WW(e,t,n=wn.SUM_BY_NONZERO_WEIGHTS){let a=E(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=E(t,"weights","computeWeightedLoss"));let s=r==null?a:z(a,r);if(n===wn.NONE)return s;if(n===wn.SUM)return fe(s);if(n===wn.MEAN){if(r==null)return Ct(s);{let i=a.size/r.size,o=he(fe(s),fe(r));return i>1?he(o,ve(i)):o}}if(n===wn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return he(fe(s),ve(a.size));{let i=z(r,On(a.shape)),o=re(fe(fi(i,ve(0))),"float32");return he(fe(s),o)}}throw Error(`Unknown reduction: ${n}`)}var Dr=L({computeWeightedLoss_:WW});function BW(e,t,n,a=wn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","absoluteDifference"),s=E(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=E(n,"weights","absoluteDifference")),Sn(r.shape,s.shape,"Error in absoluteDifference: ");let o=Lt(pe(r,s));return Dr(o,i,a)}var VW=L({absoluteDifference_:BW});function UW(e,t,n,a,r=wn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","cosineDistance"),i=E(t,"predictions","cosineDistance"),o=null;a!=null&&(o=E(a,"weights","cosineDistance")),Sn(s.shape,i.shape,"Error in cosineDistance: ");let l=ve(1),u=pe(l,fe(z(s,i),n,!0));return Dr(u,o,r)}var GW=L({cosineDistance_:UW});function HW(e,t,n,a=wn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","hingeLoss"),s=E(t,"predictions","hingeLoss"),i=null;n!=null&&(i=E(n,"weights","hingeLoss")),Sn(r.shape,s.shape,"Error in hingeLoss: ");let o=ve(1);r=pe(z(ve(2),r),o);let l=Ke(pe(o,z(r,s)));return Dr(l,i,a)}var qW=L({hingeLoss_:HW});function jW(e,t,n,a=1,r=wn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","huberLoss"),i=E(t,"predictions","huberLoss"),o=null;n!=null&&(o=E(n,"weights","huberLoss")),Sn(s.shape,i.shape,"Error in huberLoss: ");let l=ve(a),u=Lt(pe(i,s)),p=cs(u,l),d=pe(u,p),c=X(z(ve(.5),pt(p)),z(l,d));return Dr(c,o,r)}var KW=L({huberLoss_:jW});function XW(e,t,n,a=1e-7,r=wn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"labels","logLoss"),i=E(t,"predictions","logLoss"),o=null;n!=null&&(o=E(n,"weights","logLoss")),Sn(s.shape,i.shape,"Error in logLoss: ");let l=ve(1),u=ve(a),p=yt(z(s,Qn(X(i,u)))),d=z(pe(l,s),Qn(X(pe(l,i),u))),c=pe(p,d);return Dr(c,o,r)}var YW=L({logLoss_:XW});function ZW(e,t,n,a=wn.SUM_BY_NONZERO_WEIGHTS){let r=E(e,"labels","meanSquaredError"),s=E(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=E(n,"weights","meanSquaredError")),Sn(r.shape,s.shape,"Error in meanSquaredError: ");let o=af(r,s);return Dr(o,i,a)}var JW=L({meanSquaredError_:ZW});function QW(e,t){let n=E(e,"labels","sigmoidCrossEntropyWithLogits"),a=E(t,"logits","sigmoidCrossEntropyWithLogits");Sn(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Ke(a),s=z(a,n),i=pd(dn(yt(Lt(a))));return X(pe(r,s),i)}function eB(e,t,n,a=0,r=wn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"multiClassLabels","sigmoidCrossEntropy"),i=E(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","sigmoidCrossEntropy")),Sn(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let u=ve(a),p=ve(1),d=ve(.5);s=X(z(s,pe(p,u)),z(d,u))}let l=QW(s,i);return Dr(l,o,r)}var tB=L({sigmoidCrossEntropy_:eB});function nB(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 ur((a,r,s)=>{let i=cd(r,[n],!0),o=pe(re(r,"float32"),i);s([a,o]);let l=yt(z(o,a));return{value:fe(l,[n]),gradFunc:(u,p)=>{let[d,c]=p,h=mi(u.shape,[n]);return[z(W(u,h),pe(re(d,"float32"),dn(c))),z(W(u,h),pe(dn(c),re(d,"float32")))]}}})(e,t)}function aB(e,t,n,a=0,r=wn.SUM_BY_NONZERO_WEIGHTS){let s=E(e,"onehotLabels","softmaxCrossEntropy"),i=E(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=E(n,"weights","softmaxCrossEntropy")),Sn(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let u=ve(a),p=ve(1),d=ve(s.shape[1]);s=X(z(s,pe(p,u)),he(u,d))}let l=nB(s,i);return Dr(l,o,r)}var rB=L({softmaxCrossEntropy_:aB});function sB(e,t,n,a){let r=E(e,"indices","sparseFillEmptyRows","int32"),s=E(t,"values","sparseFillEmptyRows"),i=E(n,"denseShape","sparseFillEmptyRows","int32"),o=E(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${r.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=P.runKernel(Gc,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var iB=L({sparseFillEmptyRows_:sB});function oB(e,t,n){let a=E(e,"inputIndices","sparseReshape","int32"),r=E(t,"inputShape","sparseReshape","int32"),s=E(n,"newShape","sparseReshape","int32");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${a.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:r,newShape:s},o=P.runKernel(Gu,i);return{outputIndices:o[0],outputShape:o[1]}}var lB=L({sparseReshape_:oB});function uB(e,t,n){let a=E(e,"data","sparseSegmentMean"),r=E(t,"indices","sparseSegmentMean","int32"),s=E(n,"segmentIds","sparseSegmentMean","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:a,indices:r,segmentIds:s};return P.runKernel(Hc,i)}var pB=L({sparseSegmentMean_:uB});function cB(e,t,n){let a=E(e,"data","sparseSegmentSum"),r=E(t,"indices","sparseSegmentSum","int32"),s=E(n,"segmentIds","sparseSegmentSum","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:a,indices:r,segmentIds:s};return P.runKernel(qc,i)}var dB=L({sparseSegmentSum_:cB});function hB(e,t,n,a,r,s,i,o){let l=E(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=E(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},d={data:l,dataSplits:u},c=P.runKernel(Xc,d,p);return{nGrams:c[0],nGramsSplits:c[1]}}var mB=L({stringNGrams_:hB});function fB(e,t,n=!0){let a=E(e,"input","stringSplit","string"),r=E(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:n},i={input:a,delimiter:r},o=P.runKernel(Yc,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var gB=L({stringSplit_:fB});function bB(e,t){let n=E(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return P.runKernel(Zc,r,a)}var yB=L({stringToHashBucketFast_:bB});function xB(e,t,n,a=!0){let r=E(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:a};return P.runKernel(Kc,{x:r},s)}var vB=L({staticRegexReplace_:xB}),_T={fft:bd,ifft:Bl,rfft:yd,irfft:nf},AT={hammingWindow:Kz,hannWindow:kT,frame:IT,stft:Jz},Zn={flipLeftRight:nW,grayscaleToRGB:rW,resizeNearestNeighbor:ET,resizeBilinear:CT,rgbToGrayscale:iW,rotateWithOffset:lW,cropAndResize:eW,nonMaxSuppression:pW,nonMaxSuppressionAsync:yW,nonMaxSuppressionWithScore:vW,nonMaxSuppressionWithScoreAsync:kW,nonMaxSuppressionPadded:SW,nonMaxSuppressionPaddedAsync:TW,threshold:FW,transform:DW},Bw={bandPart:MW,gramSchmidt:PW,qr:zW},FT={absoluteDifference:VW,computeWeightedLoss:Dr,cosineDistance:GW,hingeLoss:qW,huberLoss:KW,logLoss:YW,meanSquaredError:JW,sigmoidCrossEntropy:tB,softmaxCrossEntropy:rB},$T={sparseFillEmptyRows:iB,sparseReshape:lB,sparseSegmentMean:pB,sparseSegmentSum:dB},DT={stringNGrams:mB,stringSplit:gB,stringToHashBucketFast:yB,staticRegexReplace:vB},ne={};_e(ne,{Serializable:()=>RT,SerializationMap:()=>MT,getRegisteredName:()=>kB,registerClass:()=>OT});var wB=new Map,Rx=new Map,RT=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},MT=class Tl{constructor(){this.classNameMap={}}static getMap(){return Tl.instance==null&&(Tl.instance=new Tl),Tl.instance}static register(t){Tl.getMap().classNameMap[t.className]=[t,t.fromConfig]}};function OT(e,t,n){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof t=="undefined"&&(t="Custom"),typeof n=="undefined"&&(n=e.className);let a=n,r=t+">"+a;return MT.register(e),wB.set(r,e),Rx.set(e,r),e}function kB(e){return Rx.has(e)?Rx.get(e):e.className}var Rr=class extends RT{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return Ee(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ON(e,t)}dispose(){this.iterations_!=null&&Ee(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ve(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(Rr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Vw=class extends Rr{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:O(()=>je(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:O(()=>je(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;O(()=>{let l=X(z(i,this.rho),z(pt(s),1-this.rho)),u=z(he(cn(X(o,this.epsilon)),cn(X(i,this.epsilon))),s),p=X(z(o,this.rho),z(pt(u),1-this.rho));i.assign(l),o.assign(p);let d=X(z(u,-this.learningRate),a);a.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ee(this.accumulatedGrads.map(e=>e.variable)),Ee(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}},Uw=class extends Rr{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.registeredVariables[t];this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:O(()=>yn(a.shape,this.initialAccumulatorValue).variable(!1))});let r=Array.isArray(e)?e[n].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[n].variable;O(()=>{let i=X(s,pt(r));s.assign(i);let o=X(z(he(r,cn(X(i,P.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ee(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)}},Gw=class extends Rr{static get className(){return"Adam"}constructor(e,t,n,a=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],O(()=>{this.accBeta1=ve(t).variable(),this.accBeta2=ve(n).variable()}),a==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);O(()=>{let n=pe(1,this.accBeta1),a=pe(1,this.accBeta2);t.forEach((r,s)=>{let i=P.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:O(()=>je(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:O(()=>je(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedSecondMoment[s].variable,d=X(z(u,this.beta1),z(l,1-this.beta1)),c=X(z(p,this.beta2),z(pt(l),1-this.beta2)),h=he(d,n),m=he(c,a);u.assign(d),p.assign(c);let f=X(z(he(h,X(cn(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(z(this.accBeta1,this.beta1)),this.accBeta2.assign(z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ee(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ee(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),O(()=>{this.accBeta1.assign(_r(this.beta1,this.iterations_+1)),this.accBeta2.assign(_r(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}},Hw=class extends Rr{static get className(){return"Adamax"}constructor(e,t,n,a=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],O(()=>{this.iteration=ve(0).variable(),this.accBeta1=ve(t).variable()}),a==null&&(this.epsilon=P.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);O(()=>{let n=pe(1,this.accBeta1),a=he(-this.learningRate,X(z(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=P.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:je(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:je(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedWeightedInfNorm[s].variable,d=X(z(u,this.beta1),z(l,1-this.beta1)),c=z(p,this.beta2),h=Lt(l),m=dr(c,h);u.assign(d),p.assign(m);let f=X(z(he(a,n),he(d,X(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(X(this.iteration,1)),this.accBeta1.assign(z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ee(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ee(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)}},mf=class extends Rr{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=P.registeredVariables[t];O(()=>{let s=X(z(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Ht(ve(-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)}},qw=class extends mf{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=ve(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.registeredVariables[t];this.accumulations[n]==null&&(this.accumulations[n]={originalName:`${t}/momentum`,variable:O(()=>je(a).variable(!1))});let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&O(()=>{let i,o=X(z(this.m,r),s);this.useNesterov?i=X(z(this.c,X(s,z(o,this.m))),a):i=X(z(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ee(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)}},jw=class extends Rr{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,a=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=P.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=P.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:O(()=>je(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:O(()=>je(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:O(()=>je(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;O(()=>{let l=X(z(i,this.decay),z(pt(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[n].variable,p=X(z(u,this.decay),z(s,1-this.decay)),d=he(z(s,this.learningRate),cn(pe(l,X(pt(p),this.epsilon)))),c=X(z(o,this.momentum),d);i.assign(l),u.assign(p),o.assign(c);let h=pe(a,c);a.assign(h)}else{let u=X(z(i,this.decay),z(pt(s),1-this.decay)),p=X(z(o,this.momentum),he(z(s,this.learningRate),cn(X(u,this.epsilon))));i.assign(u),o.assign(p);let d=pe(a,p);a.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ee(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ee(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ee(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}},IB=[Vw,Uw,Gw,Hw,qw,jw,mf];function SB(){for(let e of IB)OT(e)}var qt={};_e(qt,{CompositeArrayBuffer:()=>Fr,browserFiles:()=>FB,browserHTTPRequest:()=>PB,concatenateArrayBuffers:()=>cO,copyModel:()=>DO,decodeWeights:()=>lN,decodeWeightsStream:()=>pN,encodeWeights:()=>sO,fromMemory:()=>zB,fromMemorySync:()=>BT,getLoadHandlers:()=>xO,getModelArtifactsForJSON:()=>Rv,getModelArtifactsForJSONSync:()=>dN,getModelArtifactsInfoForJSON:()=>rd,getSaveHandlers:()=>yO,getWeightSpecs:()=>Ex,http:()=>Xw,isHTTPScheme:()=>Ox,listModels:()=>FO,loadWeights:()=>DB,moveModel:()=>RO,registerLoadRouter:()=>bO,registerSaveRouter:()=>gO,removeModel:()=>$O,weightsLoaderFactory:()=>LT,withSaveHandler:()=>WB,withSaveHandlerSync:()=>BB});var NB="model",TB=".json",CB=".weights.bin";function aI(e){return new Promise(t=>setTimeout(t)).then(e)}var Yh=class Mx{constructor(t){if(!G().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(Mx.URL_SCHEME)&&(t=t.slice(Mx.URL_SCHEME.length)),(t==null||t.length===0)&&(t=NB),this.modelJsonFileName=t+TB,this.weightDataFileName=t+CB}async save(t){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let n=Fr.join(t.weightData),a=window.URL.createObjectURL(new Blob([n],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let r=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],s=cN(t,r),i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),o=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(o.download=this.modelJsonFileName,o.href=i,await aI(()=>o.dispatchEvent(new MouseEvent("click"))),t.weightData!=null){let l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=a,await aI(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:rd(t)}}}};Yh.URL_SCHEME="downloads://";var EB=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=a=>{let r=JSON.parse(a.target.result),s=r.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:s});return}let i=Rv(r,o=>this.loadWeights(o));e(i)},n.onerror=a=>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 s of e)t.push(...s.weights),n.push(...s.paths);let a=this.checkManifestAndWeightFiles(e),r=n.map(s=>this.loadWeightsFile(s,a[s]));return Promise.all(r).then(s=>[t,s])}loadWeightsFile(e,t){return new Promise((n,a)=>{let r=new FileReader;r.onload=s=>{let i=s.target.result;n(i)},r.onerror=s=>a(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>eI(r.name)),a={};for(let r of e)r.paths.forEach(s=>{let i=eI(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),n.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);a[s]=this.weightsFiles[n.indexOf(i)]});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 a}},_B=e=>G().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Yh.URL_SCHEME)?AB(e.slice(Yh.URL_SCHEME.length)):null;ga.registerSaveRouter(_B);function AB(e="model"){return new Yh(e)}function FB(e){return new EB(e)}function rI(e,t,n,a){i(e),n=n==null?0:n,a=a==null?1:a,o(n,a);let r=0,s=l=>(l.then(u=>{let p=n+ ++r/e.length*(a-n);return t(p),u}),l);function i(l){A(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){A(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),A(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),A(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function PT(e,t){t==null&&(t={});let n=t.fetchFunc==null?G().platform.fetch:t.fetchFunc,a=e.map(s=>n(s,t.requestInit,{isBinary:!0})),r=(t.onProgress==null?await Promise.all(a):await rI(a,t.onProgress,0,.5)).map(s=>s.arrayBuffer());return t.onProgress==null?await Promise.all(r):await rI(r,t.onProgress,.5,1)}function $B(e,t){var n;let a=t.fetchFunc==null?G().platform.fetch:t.fetchFunc,r=0,s;return(n=t.onProgress)===null||n===void 0||n.call(t,0),new ReadableStream({pull:async i=>{for(var o;r<e.length;){s||(s=(await a(e[r],t.requestInit,{isBinary:!0})).body.getReader());let{done:l,value:u}=await s.read();if(l){r++,s=void 0,(o=t.onProgress)===null||o===void 0||o.call(t,r/e.length);continue}i.enqueue(u);return}i.close()}})}async function DB(e,t="",n,a){return LT(r=>PT(r,{requestInit:a}))(e,t,n)}function LT(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((h,m)=>{let f=0;h.weights.forEach(g=>{let b="quantization"in g?g.quantization.dtype:g.dtype,y=li[b]*ot(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:y})};a!=null?a.forEach((v,I)=>{v===g.name&&(x(),i[I]=!0)}):x(),o.push(g.name),f+=y})}),!i.every(h=>h)){let h=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
|
|
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let p=await e(u),d={},c=0;return l.forEach(h=>{let m=t[h].paths.length,f=new Fr(p.slice(c,c+m));s[h].forEach(g=>{let b=f.slice(g.groupOffset,g.groupOffset+g.sizeBytes),y=lN(b,[g.manifestEntry]);for(let x in y)d[x]=y[x]}),c+=m}),d}}var RB="application/octet-stream",MB="application/json",Kw=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(A(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=G().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a=cN(e,n);if(t.body.append("model.json",new Blob([JSON.stringify(a)],{type:MB}),"model.json"),e.weightData!=null){let s=Fr.join(e.weightData);t.body.append("model.weights.bin",new Blob([s],{type:RB}),"model.weights.bin")}let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:rd(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){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(r){let s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let n=t.modelTopology,a=t.weightsManifest;if(n==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();let e=await this.loadModelJSON();return Rv(e,t=>this.loadWeights(t))}async loadStream(){let e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Ex(e.weightsManifest),a=()=>$B(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:a})}async getWeightUrls(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=OB(t),r=this.weightPathPrefix||n,s=[],i=[];for(let o of e)for(let l of o.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):s.push(r+l+a);return this.weightUrlConverter&&s.push(...await Promise.all(i)),s}async loadWeights(e){let t=await this.getWeightUrls(e),n=Ex(e),a=await PT(t,this.loadOptions);return[n,a]}};Kw.URL_SCHEME_REGEX=/^https?:\/\//;function OB(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function Ox(e){return e.match(Kw.URL_SCHEME_REGEX)!=null}var zT=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>Ox(a)):n=Ox(e),n)return Xw(e,t)}return null};ga.registerSaveRouter(zT);ga.registerLoadRouter(zT);function Xw(e,t){return new Kw(e,t)}function PB(e,t){return Xw(e,t)}var ox=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},WT=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},LB=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function zB(e,t,n,a){let r=arguments;return new LB(BT(...r))}function BT(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new ox(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 ox({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 ox({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function WB(e){return new WT(e)}function BB(e){return new WT(e)}var VT={};_e(VT,{confusionMatrix:()=>UB});function VB(e,t,n){let a=E(e,"labels","confusionMatrix"),r=E(t,"predictions","confusionMatrix");A(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),A(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),A(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),A(a.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),A(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=Ll(re(a,"int32"),n),i=Ll(re(r,"int32"),n),o=De(s),l=$e(o,i);return re(l,"int32")}var UB=L({confusionMatrix_:VB}),jo={};_e(jo,{draw:()=>ZB,fromPixels:()=>JB,fromPixelsAsync:()=>KB,toPixels:()=>YB});var Hs,sI=!1;function UT(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,a=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(fc(Hh,P.backendName)!=null){let c={pixels:e},h={numChannels:t};return P.runKernel(Hh,c,h)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(i)p=e.getContext("2d").getImageData(0,0,l,u).data;else if(a||n)p=e.data;else if(s||r||o){if(Hs==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")Hs=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Hs=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Hs.canvas.width=l,Hs.canvas.height=u,Hs.drawImage(e,0,0,l,u),p=Hs.getImageData(0,0,l,u).data}let d;if(t===4)d=new Int32Array(p);else{let c=l*u;d=new Int32Array(c*t);for(let h=0;h<c;h++)for(let m=0;m<t;++m)d[h*t+m]=p[h*4+m]}return xd(d,[u,l,t],"int32")}function GB(e){return e!=null&&e.data instanceof Uint8Array}function HB(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function qB(e){return e!=null&&e.width!==0&&e.height!==0}function jB(e){return HB()&&!(e instanceof ImageBitmap)&&qB(e)&&!GB(e)}async function KB(e,t=3){let n=null;if(G().getBool("WRAP_TO_IMAGEBITMAP")&&jB(e)){let a;try{a=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(r){a=null}a!=null&&a.width===e.width&&a.height===e.height?n=a:n=e}else n=e;return UT(n,t)}function GT(e){if(e.rank!==2&&e.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);let t=e.rank===2?1:e.shape[2];if(t>4||t===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}function XB(e){let t=(e==null?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}async function YB(e,t){let n=E(e,"img","toPixels");if(!(e instanceof Ce)){let u=n;n=re(u,"int32"),u.dispose()}GT(n);let[a,r]=n.shape.slice(0,2),s=n.rank===2?1:n.shape[2],i=await n.data(),o=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*a*4);for(let u=0;u<a*r;++u){let p=[0,0,0,255];for(let c=0;c<s;c++){let h=i[u*s+c];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);s===1?(p[0]=h*o,p[1]=h*o,p[2]=h*o):p[c]=h*o}let d=u*4;l[d+0]=Math.round(p[0]),l[d+1]=Math.round(p[1]),l[d+2]=Math.round(p[2]),l[d+3]=Math.round(p[3])}if(t!=null){sI||fc(Nm,P.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),sI=!0),t.width=r,t.height=a;let u=t.getContext("2d"),p=new ImageData(l,r,a);u.putImageData(p,0,0)}return n!==e&&n.dispose(),l}function ZB(e,t,n){let a=E(e,"img","draw");if(!(e instanceof Ce)){let i=a;a=re(i,"int32"),i.dispose()}GT(a),XB(n==null?void 0:n.imageOptions);let r={image:a},s={canvas:t,options:n};P.runKernel(Nm,r,s)}var JB=L({fromPixels_:UT}),Yw={};_e(Yw,{prepareAndValidate:()=>HT});function HT(e,t){let n=e.shape.length,a=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(ot(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let d=0;d<r.length-1;++d)i*=r[d];let o=e.shape,l=r.slice();l.pop();let u=1;for(let d=s;d<n;++d)u*=o[d],l.push(o[d]);let p=[...Xl(e.shape).map(d=>d/u),1].slice(0,s);return[l,i,u,p]}var Kt={};_e(Kt,{assertParamsValid:()=>e4,computeFlatOffset:()=>s4,computeOutShape:()=>n4,getNormalizedAxes:()=>a4,isSliceContinous:()=>r4,maskToAxes:()=>t4,parseSliceParams:()=>e2,sliceInfo:()=>i4,startForAxis:()=>JT,startIndicesWithElidedDims:()=>XT,stopForAxis:()=>QT,stopIndicesWithElidedDims:()=>YT,stridesForAxis:()=>ZT,stridesWithElidedDims:()=>qT});var Px=-2,QB=-1;function e4(e,t,n){let a=e.shape.length;A(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),A(a===n.length,()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`);for(let r=0;r<a;++r)A(t[r]+n[r]<=e.shape[r],()=>`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function t4(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function n4(e,t,n){let a=[];for(let r=0;r<e.length;r++)a[r]=Math.ceil((t[r]-e[r])/n[r]);return a}function qT(e,t,n,a){let r=[...e];for(let s=r.length;s<a.length;s++)r.push(1);for(let s=0;s<n;s++)s===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function jT(e,t,n){return n<=e?n:n-(t-1)}function KT(e,t){let n=[];for(let a=0;a<e;a++)n.push(t+a);return n}function a4(e,t,n,a,r,s,i,o,l){let u=e.length,p=new Array(u),d=new Array(u),c=new Array(u);if(t.length&&n>0){let h=t[0],m=n+1;p=XT(i,h,m,a,e),d=YT(o,h,m,r,e),c=qT(s,h,m,e)}else for(let h=0;h<u;h++)p[h]=JT(i,a,s,e,h,l),d[h]=QT(o,r,s,e,h,l),c[h]=ZT(s,h,l);return{begin:p,end:d,strides:c}}function XT(e,t,n,a,r){let s=[...r],i=KT(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=jT(t,n,o),u=a[l];e&1<<l&&(u=0),s[o]=u}return s}function YT(e,t,n,a,r){let s=[...r],i=KT(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=jT(t,n,o),u=a[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[o]=u}for(let o=0;o<s.length;o++){let l=r[o];s[o]<0&&(s[o]+=l),s[o]=hc(0,s[o],r[o])}return s}function ZT(e,t,n){let a=e[t];return(n&1<<t||a==null)&&(a=1),a}function JT(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=hc(0,i,l-1),i}function QT(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=hc(0,i,l):i=hc(-1,i,l-1),i}function r4(e,t,n){let a=n.length;for(let r=0;r<n.length;r++)if(n[r]>1){a=r;break}for(let r=a+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function s4(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a<e.length-1;a++)n+=e[a]*t[a];return n}function e2(e,t,n){let a,r=e.shape.length;typeof t=="number"?a=[t,...new Array(r-1).fill(0)]:t.length<r?a=t.concat(new Array(r-t.length).fill(0)):a=t.slice(),a.forEach(i=>{A(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return n==null?s=new Array(r).fill(-1):typeof n=="number"?s=[n,...new Array(r-1).fill(-1)]:n.length<r?s=n.concat(new Array(r-n.length).fill(-1)):s=n,s=s.map((i,o)=>i>=0?i:(A(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-a[o])),[a,s]}function i4(e,t,n,a,r,s,i,o,l){let u;if(a==null?(u=new Array(t.length),u.fill(1)):u=a,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let p=!1,d={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let y=0;y<d.dims;y++)p&&1<<y&o&&d.numAddAxisAfterEllipsis++,1<<y&i&&(p=!0);p||(d.ellipsisMask|=1<<d.dims,d.dims++);let c={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};o4(d,c);let h=!0,m=!0,f=!0,g=[],b=[];for(let y=0;y<e.length;++y){if(c.strides[y]===0)throw Error(`strides[${y}] must be non-zero`);let x=!!(c.shrinkAxisMask&1<<y),v=e[y];if(v===-1){g.push(x?1:-1);continue}let I=[c.beginMask&1<<y,c.endMask&1<<y],N=[c.strides[y]>0?0:-1,c.strides[y]>0?v:v-1];if(x&&c.strides[y]<=0)throw Error("only stride 1 allowed on non-range indexing.");f=f&&c.strides[y]===1;let C=!!(c.beginMask&1<<y&&c.endMask&1<<y);if(c.beginValid&&c.endValid){if(x){let $=c.begin[y]<0?v+c.begin[y]:c.begin[y];if(c.begin[y]=$,c.end[y]=c.begin[y]+1,$<0||$>=v)throw Error(`slice index ${c.begin[y]} of dimension ${y} out of bounds.`)}else c.begin[y]=iI(c.begin[y],0,c.strides[y],v,I,N),c.end[y]=iI(c.end[y],1,c.strides[y],v,I,N);let D=c.strides[y]===1&&c.begin[y]===0&&c.end[y]===v;h=h&&D,m=m&&(y===0&&c.strides[y]===1||D)}else h=h&&c.strides[y]===1&&C,m=m&&(y===0&&c.strides[y]===1||C);let _,F=!1;if(c.beginValid&&c.endValid?(_=c.end[y]-c.begin[y],F=!0):x?(_=1,F=!0):C&&v>=0&&(c.strides[y]<0?_=-v:_=v,F=!0),F){let D;_===0||_<0!=c.strides[y]<0?D=0:D=Math.trunc(_/c.strides[y])+(_%c.strides[y]!==0?1:0),g.push(D)}else g.push(-1)}for(let y=0;y<c.finalShapeGatherIndices.length;++y){let x=c.finalShapeGatherIndices[y];x>=0?b.push(g[x]):x===Px&&b.push(1)}return{finalShapeSparse:b.filter((y,x)=>c.finalShapeGatherIndices[x]!==Px),finalShape:b,isIdentity:h,sliceDim0:m,isSimpleSlice:f,begin:c.begin,end:c.end,strides:c.strides}}function o4(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let a=0;a<e.dims;a++)if(1<<a&e.ellipsisMask){let r=Math.min(t.dims-(e.dims-a)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<r;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=a}else if(1<<a&e.newAxisMask)t.finalShapeGatherIndices.push(Px),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[n]=e.begin[a]),e.end!=null&&(t.end[n]=e.end[a]),t.strides[n]=e.strides[a],e.beginMask&1<<a&&(t.beginMask|=1<<n),e.endMask&1<<a&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<a?(t.finalShapeGatherIndices.push(QB),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(a)),t.inputShapeGatherIndicesSparse[n]=a,n++}}function iI(e,t,n,a,r,s){if(r[t])return n>0?s[t]:s[t+1&1];{let i=e<0?a+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var l4="4.16.0",t2=class{static sgd(e){return new mf(e)}static momentum(e,t,n=!1){return new qw(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new jw(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new Gw(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new Vw(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new Hw(e,t,n,a,r)}static adagrad(e,t=.1){return new Uw(e,t)}},Ks=t2,u4=typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e();function Zw(){return new Promise(e=>u4(()=>e()))}var T={};_e(T,{ERF_A1:()=>S4,ERF_A2:()=>N4,ERF_A3:()=>T4,ERF_A4:()=>C4,ERF_A5:()=>E4,ERF_P:()=>I4,PARALLELIZE_THRESHOLD:()=>Jw,RowPartitionType:()=>er,SELU_SCALE:()=>a2,SELU_SCALEALPHA:()=>n2,applyActivation:()=>df,assertAndGetBroadcastShape:()=>ct,assertAxesAreInnerMostDims:()=>i3,assertParamsConsistent:()=>p4,assignToTypedArray:()=>R4,axesAreInnerMostDims:()=>uw,calculateShapes:()=>pT,checkEinsumDimSizes:()=>W4,checkPadOnDimRoundingMode:()=>Nn,combineLocations:()=>FN,combineRaggedTensorToTensorShapes:()=>d4,complexWithEvenIndex:()=>F4,complexWithOddIndex:()=>$4,computeConv2DInfo:()=>sd,computeConv3DInfo:()=>kN,computeDefaultPad:()=>Gv,computeDilation2DInfo:()=>rP,computeOptimalWindowSize:()=>g4,computeOutAndReduceShapes:()=>$N,computeOutShape:()=>c4,computePool2DInfo:()=>wN,computePool3DInfo:()=>sP,convertConv2DDataFormat:()=>IN,decodeEinsumEquation:()=>L4,eitherStridesOrDilationsAreOne:()=>cr,expandShapeToKeepDim:()=>mi,exponent:()=>O4,exponents:()=>M4,fromStringArrayToUint8:()=>oV,fromUint8ToStringArray:()=>iV,getAxesPermutation:()=>DN,getBroadcastDims:()=>_N,getComplexWithIndex:()=>D4,getEinsumComputePath:()=>B4,getEinsumPermutation:()=>z4,getFusedBiasGradient:()=>cf,getFusedDyActivation:()=>pf,getImageCenter:()=>b4,getInnerMostAxes:()=>o3,getPermuted:()=>x4,getRaggedRank:()=>m4,getReductionAxes:()=>Bt,getReshaped:()=>y4,getReshapedPermuted:()=>v4,getRowPartitionTypesHelper:()=>h4,getSliceBeginCoords:()=>w4,getSliceSize:()=>k4,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>H4,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>q4,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>j4,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Y4,getSparseReshapeInputOutputMismatchErrorMessage:()=>J4,getSparseReshapeInputOutputMultipleErrorMessage:()=>Z4,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>K4,getSparseReshapeNegativeOutputDimErrorMessage:()=>X4,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>nV,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>Q4,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>eV,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>tV,getUndoAxesPermutation:()=>pw,isIdentityPermutation:()=>V4,log:()=>mM,mergeRealAndImagArrays:()=>_4,prepareAndValidate:()=>HT,prepareSplitSize:()=>G4,segment_util:()=>r2,shouldFuse:()=>hf,slice_util:()=>Kt,splitRealAndImagArrays:()=>A4,stridesOrDilationsArePositive:()=>di,tupleValuesAreOne:()=>ps,upcastType:()=>fa,validateDefaultValueShape:()=>f4,validateInput:()=>sf,validateUpdateShape:()=>$w,warn:()=>Zr});function p4(e,t){let n=e[0].length;e.forEach((r,s)=>{A(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),A(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let a=e[0];e.forEach((r,s)=>{for(let i=0;i<n;i++)A(i===t||r[i]===a[i],()=>`Error in concat${n}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function c4(e,t){let n=e[0].slice();for(let a=1;a<e.length;a++)n[t]+=e[a][t];return n}var er;(function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"})(er||(er={}));function d4(e,t,n){let a=new Array;if(n==null&&t==null)return a;if(t==null)for(;a.length<e+n.length;)a.push(-1);else a=t.slice();if(n==null)return a;if(e+n.length!==a.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${a.length}`);for(let r=1;r<n.length;++r){let s=n[r],i=a[a.length-n.length+r],o=a[i];if(s>=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${s} but shape[${r+e}] = ${o}`)}else a[i]=s}return a}function h4(e){let t={FIRST_DIM_SIZE:er.FIRST_DIM_SIZE,VALUE_ROWIDS:er.VALUE_ROWIDS,ROW_LENGTHS:er.ROW_LENGTHS,ROW_SPLITS:er.ROW_SPLITS,ROW_LIMITS:er.ROW_LIMITS,ROW_STARTS:er.ROW_STARTS},n=[];for(let a of e)if(a in t)n.push(t[a]);else break;return n}function m4(e){return e.length===0?0:e[0]===er.FIRST_DIM_SIZE?e.length-1:e.length}function f4(e,t){if(e==null||t==null)return;let n=e.length,a=t.length;if(n>=a)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${a})`);for(let r=0;r<Math.min(n,a-1);++r){let s=e[r],i=t[r+1];if(s>=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${s} but ragged tensor input.flatValues.shape[${r-e.length}] = ${i}`)}}var Jw=30;function g4(e){return e<=Jw?e:Gh(e,Math.floor(Math.sqrt(e)))}function b4(e,t,n){let a=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[a,r]}function y4(e,t,n,a=!0){let r=[];if(a)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)r=r.concat([e[i+1]/t[i],t[i]]);r=r.concat(e.slice(s+1))}return r}function x4(e,t,n=!0){let a=[];if(n){a.push(t);for(let r=t+1;r<e;++r)r<=2*t?(a.push(r),a.push(r-(t+1))):a.push(r)}else{let r=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function v4(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s<e.length;++s)s<=t.length?a?r.push(t[s-1]*e[s]):r.push(e[s]/t[s-1]):r.push(e[s]);return r}function w4(e,t){let n=[0];for(let a=0;a<t;++a)n.push(e[a][0]);return n}function k4(e,t,n){let a=e.slice(0,1);for(let r=0;r<n;++r)a.push(e[r+1]-t[r][0]-t[r][1]);return a}var n2=1.7580993408473768,a2=1.0507009873554805,I4=.3275911,S4=.254829592,N4=-.284496736,T4=1.421413741,C4=-1.453152027,E4=1.061405429;function _4(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let n=new Float32Array(e.length*2);for(let a=0;a<n.length;a+=2)n[a]=e[a/2],n[a+1]=t[a/2];return n}function A4(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let a=0;a<e.length;a+=2)t[a/2]=e[a],n[a/2]=e[a+1];return{real:t,imag:n}}function F4(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=0;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function $4(e){let t=Math.floor(e.length/4),n=new Float32Array(t),a=new Float32Array(t);for(let r=2;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],a[Math.floor(r/4)]=e[r+1];return{real:n,imag:a}}function D4(e,t){let n=e[t*2],a=e[t*2+1];return{real:n,imag:a}}function R4(e,t,n,a){e[a*2]=t,e[a*2+1]=n}function M4(e,t){let n=new Float32Array(e/2),a=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){let s=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(s),a[r]=Math.sin(s)}return{real:n,imag:a}}function O4(e,t,n){let a=(n?2:-2)*Math.PI*(e/t),r=Math.cos(a),s=Math.sin(a);return{real:r,imag:s}}var lx="->",P4=/->/g,oI=",",lI="...";function L4(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(P4,"").length)/lx.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 ("${lx}").`);let[a,r]=e.split(lx);A(a.indexOf(lI)===-1,()=>`The ellipsis notation ("${lI}") is not supported yet.`);let s=a.split(oI),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let c=0;c<r.length;++c){let h=r[c];if(!s.some(m=>m.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);o.indexOf(h)===-1&&o.push(h)}for(let c=0;c<a.length;++c){let h=a[c];o.indexOf(h)===-1&&h!==oI&&o.push(h)}let l=new Array(s.length);for(let c=0;c<i;++c){if(new Set(s[c].split("")).size!==s[c].length)throw new Error(`Found duplicate axes in input component ${s[c]}. Support for duplicate axes in input is not implemented yet.`);l[c]=[];for(let h=0;h<s[c].length;++h)l[c].push(o.indexOf(s[c][h]))}let u=o.length,p=r.length,d=[];for(let c=p;c<u;++c)d.push(c);return{allDims:o,summedDims:d,idDims:l}}function z4(e,t){let n=new Array(e);n.fill(-1);for(let r=0;r<t.length;++r)n[t[r]]=r;let a=[];for(let r=0;r<e;++r)n[r]===-1&&a.push(r);return n=n.filter(r=>r!==-1),{permutationIndices:n,expandDims:a}}function W4(e,t,n){let a=new Array(e);for(let r=0;r<n.length;++r){let s=n[r].shape;for(let i=0;i<t[r].length;++i)a[t[r][i]]===void 0?a[t[r][i]]=s[i]:A(a[t[r][i]]===s[i],()=>`Expected dimension ${a[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function B4(e,t){let n=e,a=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let i=0;i<r;++i)a.push([]);let s=[];for(let i=0;i<n.length;++i){let o=n[i],l=U4(t,o);for(let u of l)s.indexOf(u)===-1&&(a[i].push(u),s.push(u))}return{path:n,steps:a}}function V4(e){return e.every((t,n)=>t===n)}function U4(e,t){let n=[];for(let a=0;a<e.length;++a)(e[a].length===0||e[a].indexOf(t)!==-1||t===-1)&&n.push(a);return n}function G4(e,t,n=0){let a=[];if(typeof t=="number")A(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);A(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[n]-i}A(e.shape[n]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}function H4(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function q4(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function j4(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function K4(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function X4(e,t){return`size ${e} must be non-negative, not ${t}`}function Y4(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function Z4(e,t){let n=ot(e),a=ot(t);return`Input to reshape is a SparseTensor with ${n}
|
|
dense values, but the requested shape requires a multiple of ${a}. inputShape=${e} outputShape= ${t}`}function J4(e,t){let n=ot(e),a=ot(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${a}. inputShape=${e} outputShape=${t}`}function Q4(){return"segment ids must be >= 0"}function eV(){return"segment ids are not increasing"}function tV(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function nV(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var r2={};_e(r2,{collectGatherOpShapeInfo:()=>sV,computeOutShape:()=>rV,segOpComputeOptimalWindowSize:()=>aV});function aV(e,t){let n=!1,a;for(e<=Jw?(a=e,n=!0):a=Gh(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=Gh(e,a+1);return a}function rV(e,t,n){let a=[],r=e.length;for(let s=0;s<r;s++)s!==t?a.push(e[s]):a.push(n);return a}function sV(e,t,n,a){let r=t.shape.length,s=e.shape.length;if(a!==0&&(a<-r||a>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${a}`);if(a<0&&(a+=r),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) (
|
|
${s}).`);if(n<a)throw new Error(`batchDims (${a}) must be less than or equal to axis (${n}).`);for(let d=0;d<a;++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 i=e.shape[n],o=[],l=1,u=1,p=1;for(let d=0;d<a;++d)o.push(e.shape[d]),l*=e.shape[d];for(let d=a;d<n;d++)o.push(e.shape[d]),u*=e.shape[d];for(let d=a;d<r;d++)o.push(t.shape[d]);for(let d=n+1;d<s;d++)o.push(e.shape[d]),p*=e.shape[d];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:o}}function iV(e){try{return e.map(t=>jh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function oV(e){return e.map(t=>nd(t))}var hr={};_e(hr,{nonMaxSuppressionV3Impl:()=>ST,nonMaxSuppressionV4Impl:()=>NT,nonMaxSuppressionV5Impl:()=>TT,whereImpl:()=>hT});SB();var s2={kernelName:Yl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,qo(re(n,"float32"),-1))}}},lV={kernelName:Ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=pt(re(n,"float32")),r=cn(pe(ve(1),a));return yt(he(e,r))}}}},uV={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=cn(pe(pt(re(n,"float32")),1));return he(e,a)}}}},pV={kernelName:xs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=e,i=Bt(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Bt(a.shape,r);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}},cV={kernelName:Ci,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},dV={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>je(n)}}},hV={kernelName:eu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>je(n)}}},mV={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,cn(pe(ve(1),pt(re(n,"float32")))))}}},fV={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=cn(X(ve(1),pt(re(n,"float32"))));return he(e,a)}}}},gV={kernelName:$i,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=X(pt(n),pt(a)),i=z(e,he(a,s)),o=Bt(n.shape,r);return o.length>0&&(i=fe(i,o)),W(i,n.shape)},b:()=>{let s=X(pt(n),pt(a)),i=yt(z(e,he(n,s))),o=Bt(a.shape,r);return o.length>0&&(i=fe(i,o)),W(i,a.shape)}}}},bV={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,X(pt(re(n,"float32")),1))}}},yV={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,pe(ve(1),pt(re(n,"float32"))))}}};function xV(e,t,n,a,r,s){let i=E(e,"dy","avgPool3dGrad"),o=E(t,"input","avgPool3dGrad"),l=i,u=o,p=!1;o.rank===4&&(p=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Nn("avgPool3dGrad",r,s);let d={dy:l,input:u},c={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=P.runKernel(Rc,d,c);return p?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var vV=L({avgPool3dGrad_:xV}),wV={kernelName:tu,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>vV(e,a,r,s,i,o)}}};function kV(e,t,n,a,r){let s=E(e,"dy","avgPoolGrad"),i=E(t,"input","avgPoolGrad");A(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),A(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let p={dy:l,input:o},d={filterSize:n,strides:a,pad:r},c=P.runKernel(Dc,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var IV=L({avgPoolGrad_:kV}),SV={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>IV(e,a,r,s,i)}}},NV={kernelName:Ri,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[a,r]=t,{transposeA:s,transposeB:i}=n;return!s&&!i?{a:()=>$e(e,r,!1,!0),b:()=>$e(a,e,!0,!1)}:!s&&i?{a:()=>$e(e,r,!1,!1),b:()=>$e(e,a,!0,!1)}:s&&!i?{a:()=>$e(r,e,!1,!0),b:()=>$e(a,e,!1,!1)}:{a:()=>$e(r,e,!0,!0),b:()=>$e(e,a,!0,!0)}}},TV={kernelName:nu,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>md(e,a,r)}}},CV={kernelName:HS,gradFunc:(e,t,n)=>{let a=n,r=a.inputShape,s=a.shape,i=Array.from(s);for(let l=r.length-1;l>=0;l--)if(r[l]===s[l])i[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>fe(e,o,!0)}}},EV={kernelName:Mi,gradFunc:e=>({x:()=>e.clone()})},_V={kernelName:Oi,gradFunc:e=>({x:()=>je(e)})},AV={kernelName:vs,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>nn(_a($r(a,r),Ts(a,s)),e,je(e))}}},FV={kernelName:Oc,inputsToSave:["x"],gradFunc:s2.gradFunc},$V={kernelName:su,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=Aa(r,t[0].shape)[0],i=a.map(o=>o[s]);return Pn(e,i,s).map(o=>()=>o)}},DV={kernelName:Pi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return A(ps(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>tw(a.shape,e,r,i,o,l),filter:()=>zw(a,e,r.shape,i,o,l)}}},RV={kernelName:Li,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>$t(e,r,s,i,o,1,l),filter:()=>zw(e,a,r.shape,s,i,o,l)}}};function MV(e,t,n,a,r){let s=e;e.rank===4&&(s=W(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),A(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),A(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),A(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),A(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),A(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);let o={x:s,dy:i},l={strides:a,pad:r,filterShape:n};return P.runKernel(iu,o,l)}var OV=L({conv3DBackpropFilter_:MV}),PV={kernelName:zi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;A(ps(a),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let[i,o]=t;return{x:()=>CN(i.shape,e,o,r,s),filter:()=>OV(i,e,o.shape,r,s)}}},LV={kernelName:Wi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(yt(Qm(re(n,"float32"))),e)}}},zV={kernelName:Bi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(ef(re(n,"float32")),e)}}},WV={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=DN([r],a.rank),l=Vm(e,r,s,!i);return o!=null&&(l=De(l,o)),l}}}},BV={kernelName:Ui,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;A(ps(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),A(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),A(cr(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),Nn("depthwiseConv2d",s,i),{x:()=>wT(l.shape,e,u,r,s,o,i),filter:()=>vT(l,e,u.shape,r,s,o,i)}}},VV={kernelName:Gi,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,s={x:a,filter:r,dy:e},i={x:a,filter:r,dy:e};return{x:()=>P.runKernel(Dl,s,n),filter:()=>P.runKernel(Rl,i,n)}}},UV={kernelName:qi,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>P.runKernel(cu,a)}}},GV={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(dn(yt(pt(n))),2/Math.sqrt(Math.PI));return{x:()=>z(e,a)}}},HV={kernelName:Ki,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,n)}}},qV={kernelName:hu,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>W(e,n.shape)}}},jV={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,dn(n))}}},KV={kernelName:Yi,gradFunc:e=>({x:()=>je(e)})},XV={kernelName:Zi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=he(e,re(a,"float32")),i=Bt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,re(n,"float32")),i=Bt(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=pt(a);return yt(he(s,re(o,"float32")))}}}},YV={kernelName:Ji,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?ve(1):o,u=Bt(s.shape,r.shape),p=[];if(s.rank===1){for(let f=0;f<r.shape.length-1;++f)p.push(r.shape[f]);p.push(1)}let d=pe(r,s),c=z(e,l),h=Zm(X(i,ve(a))),m=z(z(z(h,h),h),ve(-.5));return{x:()=>s.rank===1?W(z(z(e,Mn(W(h,[1,1,1,s.shape[0]]),p)),l),r.shape):W(z(z(e,h),l),r.shape),mean:()=>{let f=z(z(h,ve(-1)),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},variance:()=>{let f=z(z(m,d),c);return s.rank===1&&(f=fe(f,u)),W(f,s.shape)},scale:()=>{let f=z(d,h),g=z(e,f);return s.rank===1&&(g=fe(g,u)),W(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=fe(f,u)),W(f,s.shape)}}}},ZV={kernelName:fu,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s,batchDims:i}=n,o=Aa(s,a.shape)[0],l=(u,p,d)=>()=>{let c=u.shape,h=p.size,m=c.slice(0,o),f=m.length,g=c.slice(s,c.length).slice(1),b=g.length,y=uI(0,f),x=uI(f+1,f+1+b),v=pI([m,[h],g]),I=W(d,v),N=W(p,[h]),C=pI([[f],y,x]),_=De(I,C),F=lf(_,N,u.shape[o]),D=pw(C);return F=De(F,D),F};if(i===1){let u=a.shape[0],p=a.split(u,0);return{x:()=>At(p.map((d,c)=>l(d,r.slice(c,1),e.slice(c,1))())).reshape(a.shape),indices:()=>r}}else return{x:l(a,r,e),indices:()=>r}}};function uI(e,t){let n=[];for(let a=e;a<t;++a)n.push(a);return n}function pI(e){let t=[];for(let n=0;n<e.length;++n)for(let a=0;a<e[n].length;++a)t.push(e[n][a]);return t}var JV={kernelName:Qi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>je(n),b:()=>je(a)}}},QV={kernelName:eo,gradFunc:e=>({x:()=>re(e,"float32")})},eU={kernelName:to,gradFunc:e=>({x:()=>je(e)})},tU={kernelName:no,gradFunc:e=>({x:()=>je(e)})},nU={kernelName:ao,gradFunc:e=>({x:()=>je(e)})},aU={kernelName:ro,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=Tn(a,0);return{x:()=>nn(s,e,z(e,r))}}},rU={kernelName:io,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,X(n,1))}}},sU={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,re(n,"float32"))}}},iU={kernelName:jS,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=dn(a);return pe(e,z(fe(e,r,!0),s))}}}};function oU(e,t,n,a=5,r=1,s=1,i=.5){let o={x:e,y:t,dy:n},l={depthRadius:a,bias:r,alpha:s,beta:i};return P.runKernel(Su,o,l)}var lU=L({localResponseNormalizationBackprop_:oU}),uU={kernelName:oo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>lU(a,r,e,s,i,o,l)}}};function i2(e,t,n,a){return t.rank<n.rank&&(t=W(t,mi(t.shape,a))),e.rank<n.rank&&(e=W(e,mi(e.shape,a))),{x:()=>z(e,re(Jn(n,t),e.dtype))}}var cI={kernelName:lo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=Aa(r,s.shape),l=i2(e,i,s,o);return{x:()=>l.x()}}},pU={kernelName:uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,re($r(n,a),"float32")),b:()=>z(e,re(Pl(n,a),"float32"))}}};function cU(e,t,n,a,r,s,i){let o=E(e,"dy","maxPool3dGrad"),l=E(t,"input","maxPool3dGrad"),u=E(n,"output","maxPool3dGrad"),p=o,d=l,c=u,h=!1;l.rank===4&&(h=!0,p=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),d=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),c=W(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),A(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),A(c.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${c.rank}.`),Nn("maxPool3dGrad",s,i);let m={dy:p,input:d,output:c},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=P.runKernel(Bc,m,f);return h?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var dU=L({maxPool3dGrad_:cU}),hU={kernelName:Nu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>dU(e,a,r,s,i,o,l)}}};function mU(e,t,n,a,r,s,i){let o=E(e,"dy","maxPoolGrad"),l=E(t,"input","maxPoolGrad"),u=E(n,"output","maxPoolGrad");A(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),A(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Nn("maxPoolGrad",s,i);let p={dy:o,input:l,output:u},d={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return P.runKernel(Wc,p,d)}var fU=L({maxPoolGrad_:mU}),gU={kernelName:po,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>fU(e,a,r,s,i,o)}}},bU={kernelName:co,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=Aa(r,a.shape),i=$N(a.shape,s)[1],o=ot(i);return{x:()=>{let l=a.shape.slice();s.forEach(p=>{l[p]=1});let u=W(e,l);return he(z(u,On(a.shape,"float32")),o)}}}},yU={kernelName:ho,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=Aa(r,s.shape),l=i2(e,i,s,o);return{x:()=>l.x()}}},xU={kernelName:mo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>z(e,re(Ts(n,a),"float32")),b:()=>z(e,re(Tn(n,a),"float32"))}}},vU={kernelName:fo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Ve(e,s,a.shape)}}},wU={kernelName:go,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=Bt(n.shape,r);return s.length>0?W(fe(e,s),n.shape):e},b:()=>{let s=z(e,yt(tp(he(n,a)))),i=Bt(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},kU={kernelName:bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=z(e,re(a,"float32")),i=Bt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,re(n,"float32")),i=Bt(a.shape,r);return i.length>0?W(fe(s,i),a.shape):s}}}},IU={kernelName:Cu,gradFunc:e=>({x:()=>yt(e)})},SU={kernelName:yo,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>It(n.shape,"float32")}}},NU={kernelName:$u,gradFunc:e=>({x:()=>je(e)})},TU={kernelName:Du,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return dt(e,a).map(r=>()=>r)}},dI={kernelName:xo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>Ve(e,s,a.shape)}}},CU={kernelName:vo,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=ct(s.shape,i.shape);return{a:()=>{let l=re(i,"float32"),u=z(e,z(l,_r(s,pe(l,ve(1))))),p=Bt(s.shape,o);return p.length>0&&(u=fe(u,p)),W(u,s.shape)},b:()=>{let l=Tn(s,0),u=nn(l,Qn(s),je(s)),p=z(e,z(r,u)),d=Bt(i.shape,o);return d.length>0&&(p=fe(p,d)),W(p,i.shape)}}}},EU={kernelName:wo,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=Tn(n,0);return{x:()=>nn(r,e,z(e,a)),alpha:()=>{let s=nn(r,je(e),z(e,n)),i=Bt(a.shape,e.shape);return i.length>0&&(s=fe(s,i)),W(s,a.shape)}}}};function _U(e,t,n){let a=e.shape.slice();a[n]=1;let r=W(t,a),s=wc(e,n,!0,!1),i=wc(e,n,!0,!0),o=z(s,i);return z(r,o)}function AU(e,t,n){let a=e.shape.length,r=a-n.length,s=T.getAxesPermutation(n,a),i=e;s!=null&&(i=De(e,s));let o=i.shape.slice(),l=o.splice(a-n.length,n.length).reduce((d,c)=>d*c,1);o.push(l);let u=i.reshape(o),p=_U(u,t,r);if(p=p.reshape(i.shape),s!=null){let d=T.getUndoAxesPermutation(s);p=De(p,d)}return p}var FU={kernelName:ko,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=[];return r==null?s=a.shape.map((i,o)=>o):typeof r=="number"?s=[r]:s=r,{x:()=>AU(a,e,s)}}},$U={kernelName:Hi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=he(e,re(a,"float32")),i=Bt(n.shape,r);return i.length>0?W(fe(s,i),n.shape):s},b:()=>{let s=z(e,re(n,"float32")),i=Bt(a.shape,r);i.length>0&&(s=W(fe(s,i),a.shape));let o=pt(a);return yt(he(s,re(o,"float32")))}}}},DU={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,yt(pt(n)))}}},RU={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=z(Ts(n,6),qo(n));return{x:()=>z(e,re(a,"float32"))}}},MU={kernelName:So,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,re(qo(n),"float32"))}}},OU={kernelName:Ru,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n.shape)}}},PU={kernelName:To,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>P.runKernel(Ou,r,n)}}},LU={kernelName:No,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>P.runKernel(Mu,r,n)}}},zU={kernelName:Eo,gradFunc:(e,t,n)=>{let{dims:a}=n,r=Aa(a,e.shape);return{x:()=>ba(e,r)}}},WU={kernelName:_o,gradFunc:e=>({x:()=>je(e)})},BU={kernelName:Ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>yt(he(e,z(_r(n,1.5),2)))}}},VU={kernelName:Wu,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>re(je(n),"float32"),t:()=>z(e,re(n,e.dtype)),e:()=>z(e,re(dd(n),e.dtype))}}},UU={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Tn(n,ve(0)),r=ve(n2),s=ve(a2),i=z(e,s),o=z(z(e,r),dn(re(n,"float32")));return nn(a,i,o)}}}},GU={kernelName:Mo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(n,pe(ve(1),n)))}}},HU={kernelName:Ro,gradFunc:e=>({x:()=>je(e)})},qU={kernelName:$o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(od(re(n,"float32")),e)}}},jU={kernelName:Do,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(Bm(re(n,"float32")),e)}}},KU={kernelName:Bu,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=e2(a,r,s),u=[];for(let p=0;p<e.rank;p++)u.push([o[p],i[p]-o[p]-l[p]]);return{x:()=>xa(e,u)}}},XU={kernelName:zo,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=z(e,a);return{logits:()=>pe(i,z(fe(i,[r],s),a))}}},YU={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,ha(n))}}},hI={kernelName:Vu,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>id(e,a,r)}}},mI={kernelName:Uu,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>et(e,a)}}},ZU={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,z(cn(re(n,"float32")),2))}}},JU={kernelName:jc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(e,z(re(n,"float32"),2))}}},QU={kernelName:Wo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ve(2);return{a:()=>z(e,z(r,pe(n,a))),b:()=>z(e,z(r,pe(a,n)))}}},eG={kernelName:ks,gradFunc:e=>({x:()=>je(e)})},tG={kernelName:Bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ct(n.shape,a.shape);return{a:()=>{let s=e,i=Bt(n.shape,r);return i.length>0&&(s=fe(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Bt(a.shape,r);return i.length>0&&(s=fe(s,i)),W(yt(s),a.shape)}}}},nG={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;Aa(s,a.shape).forEach(l=>{r[l]=1});let i=W(e,r),o=z(i,On(a.shape,"float32"));return{x:()=>o}}},aG={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,pt(od(n)))}}},rG={kernelName:Uo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>z(pe(ve(1),pt(n)),e)}}},sG={kernelName:ws,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{reps:r}=n;return{x:()=>{let s=je(a);if(a.rank===1)for(let i=0;i<r[0];++i)s=X(s,Ve(e,[i*a.shape[0]],[a.shape[0]]));else if(a.rank===2)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)s=X(s,Ve(e,[i*a.shape[0],o*a.shape[1]],[a.shape[0],a.shape[1]]));else if(a.rank===3)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)s=X(s,Ve(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2]],[a.shape[0],a.shape[1],a.shape[2]]));else if(a.rank===4)for(let i=0;i<r[0];++i)for(let o=0;o<r[1];++o)for(let l=0;l<r[2];++l)for(let u=0;u<r[3];++u)s=X(s,Ve(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2],u*a.shape[3]],[a.shape[0],a.shape[1],a.shape[2],a.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${a.rank} tensors yet.`);return s}}}},iG={kernelName:Tr,gradFunc:(e,t,n)=>{let a=n,{perm:r}=a,s=pw(r);return{x:()=>De(e,s)}}},oG={kernelName:Xu,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>At(e,r)}}},lG={kernelName:Qc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>uG(e,n)}}};function uG(e,t){let n=dr(t,je(t)),a=np(e,n),r=$r(t,ve(0,"int32")),s=a.rank-r.rank;for(let o=0;o<s;++o)r=Gt(r,o+1);r=_a(r,On(a.shape,"bool"));let i=je(a);return nn(r,a,i)}var pG={kernelName:Yu,gradFunc:e=>({x:()=>je(e)})},cG=[s2,lV,uV,pV,cV,dV,hV,mV,fV,gV,bV,yV,wV,SV,NV,TV,CV,EV,_V,AV,FV,$V,RV,DV,PV,LV,zV,WV,BV,VV,$U,UV,GV,HV,qV,jV,XV,KV,YV,ZV,JV,QV,eU,tU,nU,aU,rU,sU,iU,uU,cI,cI,pU,hU,gU,bU,yU,xU,vU,wU,kU,IU,SU,NU,TU,dI,dI,CU,EU,FU,DU,RU,MU,OU,PU,LU,zU,WU,BU,VU,UU,GU,HU,qU,jU,KU,XU,YU,hI,hI,mI,mI,ZU,QU,JU,eG,tG,nG,aG,rG,sG,iG,oG,lG,pG];for(let e of cG)KS(e);Q().prototype.abs=function(){return this.throwIfDisposed(),Lt(this)};Q().prototype.acos=function(){return this.throwIfDisposed(),Ov(this)};Q().prototype.acosh=function(){return this.throwIfDisposed(),Pv(this)};Q().prototype.add=function(e){return this.throwIfDisposed(),X(this,e)};Q().prototype.all=function(e,t){return this.throwIfDisposed(),Lm(this,e,t)};Q().prototype.any=function(e,t){return this.throwIfDisposed(),yc(this,e,t)};Q().prototype.argMax=function(e){return this.throwIfDisposed(),ci(this,e)};Q().prototype.argMin=function(e){return this.throwIfDisposed(),Lv(this,e)};Q().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),W(this,[])};Q().prototype.asType=function(e){return this.throwIfDisposed(),re(this,e)};Q().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};Q().prototype.as2D=function(e,t){return this.throwIfDisposed(),W(this,[e,t])};Q().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),W(this,[e,t,n])};Q().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),W(this,[e,t,n,a])};Q().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),W(this,[e,t,n,a,r])};Q().prototype.asin=function(){return this.throwIfDisposed(),zv(this)};Q().prototype.asinh=function(){return this.throwIfDisposed(),Wv(this)};Q().prototype.atan=function(){return this.throwIfDisposed(),Bv(this)};Q().prototype.atan2=function(e){return this.throwIfDisposed(),Vv(this,e)};Q().prototype.atanh=function(){return this.throwIfDisposed(),Uv(this)};Q().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),ya(this,e,t,n,a)};Q().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),id(this,e,t)};Q().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),Ss(this,e,t,n,a,r)};Q().prototype.broadcastTo=function(e){return this.throwIfDisposed(),ni(this,e)};Q().prototype.cast=function(e){return this.throwIfDisposed(),re(this,e)};Q().prototype.ceil=function(){return this.throwIfDisposed(),Yv(this)};Q().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),an(this,e,t)};Q().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ce&&(e=[e]),et([this,...e],t)};Q().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),zm(this,e,t,n,a,r,s)};Q().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),Wm(this,e,t,n,a,r)};Q().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),$t(this,e,t,n,a,r,s)};Q().prototype.cos=function(){return this.throwIfDisposed(),od(this)};Q().prototype.cosh=function(){return this.throwIfDisposed(),Bm(this)};Q().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),wc(this,e,t,n)};Q().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Vm(this,e,t,n)};Q().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),rw(this,e,t)};Q().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Ns(this,e,t,n,a,r,s)};Q().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),sw(this,e,t,n,a,r)};Q().prototype.divNoNan=function(e){return this.throwIfDisposed(),iw(this,e)};Q().prototype.div=function(e){return this.throwIfDisposed(),he(this,e)};Q().prototype.dot=function(e){return this.throwIfDisposed(),ow(this,e)};Q().prototype.elu=function(){return this.throwIfDisposed(),Qu(this)};Q().prototype.equal=function(e){return this.throwIfDisposed(),Jn(this,e)};Q().prototype.erf=function(){return this.throwIfDisposed(),lw(this)};Q().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),cw(this,e,t)};Q().prototype.exp=function(){return this.throwIfDisposed(),dn(this)};Q().prototype.expandDims=function(e){return this.throwIfDisposed(),Gt(this,e)};Q().prototype.expm1=function(){return this.throwIfDisposed(),dw(this)};Q().prototype.fft=function(){return this.throwIfDisposed(),bd(this)};Q().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};Q().prototype.floor=function(){return this.throwIfDisposed(),tp(this)};Q().prototype.floorDiv=function(e){return this.throwIfDisposed(),Pm(this,e)};Q().prototype.gather=function(e,t,n){return this.throwIfDisposed(),np(this,e,t,n)};Q().prototype.greaterEqual=function(e){return this.throwIfDisposed(),$r(this,e)};Q().prototype.greater=function(e){return this.throwIfDisposed(),Tn(this,e)};Q().prototype.ifft=function(){return this.throwIfDisposed(),Bl(this)};Q().prototype.irfft=function(){return this.throwIfDisposed(),nf(this)};Q().prototype.isFinite=function(){return this.throwIfDisposed(),hw(this)};Q().prototype.isInf=function(){return this.throwIfDisposed(),mw(this)};Q().prototype.isNaN=function(){return this.throwIfDisposed(),fw(this)};Q().prototype.leakyRelu=function(e){return this.throwIfDisposed(),ud(this,e)};Q().prototype.lessEqual=function(e){return this.throwIfDisposed(),Ts(this,e)};Q().prototype.less=function(e){return this.throwIfDisposed(),Pl(this,e)};Q().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),gw(this,e,t,n,a)};Q().prototype.logSigmoid=function(){return this.throwIfDisposed(),bw(this)};Q().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Hm(this,e)};Q().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),cd(this,e,t)};Q().prototype.log=function(){return this.throwIfDisposed(),Qn(this)};Q().prototype.log1p=function(){return this.throwIfDisposed(),pd(this)};Q().prototype.logicalAnd=function(e){return this.throwIfDisposed(),_a(this,e)};Q().prototype.logicalNot=function(){return this.throwIfDisposed(),dd(this)};Q().prototype.logicalOr=function(e){return this.throwIfDisposed(),qm(this,e)};Q().prototype.logicalXor=function(e){return this.throwIfDisposed(),yw(this,e)};Q().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),$e(this,e,t,n)};Q().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),Dt(this,e,t,n,a)};Q().prototype.max=function(e,t){return this.throwIfDisposed(),ma(this,e,t)};Q().prototype.maximum=function(e){return this.throwIfDisposed(),dr(this,e)};Q().prototype.mean=function(e,t){return this.throwIfDisposed(),Ct(this,e,t)};Q().prototype.min=function(e,t){return this.throwIfDisposed(),Ol(this,e,t)};Q().prototype.minimum=function(e){return this.throwIfDisposed(),cs(this,e)};Q().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),vw(this,e,t)};Q().prototype.mod=function(e){return this.throwIfDisposed(),ww(this,e)};Q().prototype.mul=function(e){return this.throwIfDisposed(),z(this,e)};Q().prototype.neg=function(){return this.throwIfDisposed(),yt(this)};Q().prototype.norm=function(e,t,n){return this.throwIfDisposed(),ep(this,e,t,n)};Q().prototype.notEqual=function(e){return this.throwIfDisposed(),fi(this,e)};Q().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Ll(this,e,t,n)};Q().prototype.onesLike=function(){return this.throwIfDisposed(),ea(this)};Q().prototype.pad=function(e,t){return this.throwIfDisposed(),xa(this,e,t)};Q().prototype.pool=function(e,t,n,a,r,s){return this.throwIfDisposed(),kw(this,e,t,n,a,r,s)};Q().prototype.pow=function(e){return this.throwIfDisposed(),_r(this,e)};Q().prototype.prelu=function(e){return this.throwIfDisposed(),fd(this,e)};Q().prototype.prod=function(e,t){return this.throwIfDisposed(),Iw(this,e,t)};Q().prototype.reciprocal=function(){return this.throwIfDisposed(),Ew(this)};Q().prototype.relu=function(){return this.throwIfDisposed(),Ke(this)};Q().prototype.relu6=function(){return this.throwIfDisposed(),Xm(this)};Q().prototype.reshapeAs=function(e){return this.throwIfDisposed(),W(this,e.shape)};Q().prototype.reshape=function(e){return this.throwIfDisposed(),W(this,e)};Q().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),CT(this,e,t,n)};Q().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),ET(this,e,t,n)};Q().prototype.reverse=function(e){return this.throwIfDisposed(),ba(this,e)};Q().prototype.rfft=function(){return this.throwIfDisposed(),yd(this)};Q().prototype.round=function(){return this.throwIfDisposed(),Ym(this)};Q().prototype.rsqrt=function(){return this.throwIfDisposed(),Zm(this)};Q().prototype.selu=function(){return this.throwIfDisposed(),Jm(this)};Q().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Es(this,e,t,n,a,r,s)};Q().prototype.sigmoid=function(){return this.throwIfDisposed(),ha(this)};Q().prototype.sign=function(){return this.throwIfDisposed(),_w(this)};Q().prototype.sin=function(){return this.throwIfDisposed(),Qm(this)};Q().prototype.sinh=function(){return this.throwIfDisposed(),ef(this)};Q().prototype.slice=function(e,t){return this.throwIfDisposed(),Ve(this,e,t)};Q().prototype.softmax=function(e){return this.throwIfDisposed(),ja(this,e)};Q().prototype.softplus=function(){return this.throwIfDisposed(),Go(this)};Q().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),md(this,e,t)};Q().prototype.split=function(e,t){return this.throwIfDisposed(),Pn(this,e,t)};Q().prototype.sqrt=function(){return this.throwIfDisposed(),cn(this)};Q().prototype.square=function(){return this.throwIfDisposed(),pt(this)};Q().prototype.squaredDifference=function(e){return this.throwIfDisposed(),af(this,e)};Q().prototype.squeeze=function(e){return this.throwIfDisposed(),_s(this,e)};Q().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Ce?[this,e]:[this,...e];return At(n,t)};Q().prototype.step=function(e){return this.throwIfDisposed(),qo(this,e)};Q().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),Aw(this,e,t,n,a,r,s,i,o)};Q().prototype.sub=function(e){return this.throwIfDisposed(),pe(this,e)};Q().prototype.sum=function(e,t){return this.throwIfDisposed(),fe(this,e,t)};Q().prototype.tan=function(){return this.throwIfDisposed(),Fw(this)};Q().prototype.tanh=function(){return this.throwIfDisposed(),hi(this)};Q().prototype.tile=function(e){return this.throwIfDisposed(),Mn(this,e)};Q().prototype.toBool=function(){return this.throwIfDisposed(),re(this,"bool")};Q().prototype.toFloat=function(){return this.throwIfDisposed(),re(this,"float32")};Q().prototype.toInt=function(){return this.throwIfDisposed(),re(this,"int32")};Q().prototype.topk=function(e,t){return this.throwIfDisposed(),Dw(this,e,t)};Q().prototype.transpose=function(e){return this.throwIfDisposed(),De(this,e)};Q().prototype.unique=function(e){return this.throwIfDisposed(),Rw(this,e)};Q().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),lf(this,e,t)};Q().prototype.unstack=function(e){return this.throwIfDisposed(),dt(this,e)};Q().prototype.where=function(e,t){return this.throwIfDisposed(),nn(e,this,t)};Q().prototype.zerosLike=function(){return this.throwIfDisposed(),je(this)};var Xr=class o2 extends Error{constructor(t){super(t),Object.setPrototypeOf(this,o2.prototype)}},ar=class l2 extends Error{constructor(t){super(t),Object.setPrototypeOf(this,l2.prototype)}},V=class u2 extends Error{constructor(t){super(t),Object.setPrototypeOf(this,u2.prototype)}},ze=class p2 extends Error{constructor(t){super(t),Object.setPrototypeOf(this,p2.prototype)}},dG=class c2 extends Error{constructor(t){super(t),Object.setPrototypeOf(this,c2.prototype)}},d2=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let n=this.cache.keys().next().value;this.cache.delete(n)}this.maxEntries=e}};function bi(e,t){if(Array.isArray(e)){let n=[];for(let a=0;a<t;a++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function tr(e,t){if(!e)throw new dG(t)}function fI(e,t){let n=0;for(let a of e)a===t&&n++;return n}function Rn(e){return e.length===1?e[0]:e}function it(e){return Array.isArray(e)?e:[e]}function kr(e){let t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function Zs(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var Sa={};function Qw(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Lx(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Lx(t));else{let t=Object.keys(e);for(let n of t){let a=e[n];a!=null&&typeof a=="object"&&(!Array.isArray(a)&&a.type==="ndarray"&&typeof a.value=="number"?e[n]=a.value:Lx(a))}}}function vd(e,t={},n={},a="object",r=!1){if(typeof e=="string"){let s=e,i;if(s in n)i=n[s];else if(s in Sa)i=Sa[s];else if(i=t[s],i==null)throw new V(`Unknown ${a}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new V(`${a}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in Sa?[o,l]=Sa.className:i in t&&([o,l]=t[i]),o==null)throw new V(`Unknown ${a}: ${i}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let h of Object.keys(Sa))u[h]=Sa[h];for(let h of Object.keys(n))u[h]=n[h];let p=s.config;p.customObjects=u;let d=Object.assign({},Sa);for(let h of Object.keys(n))Sa[h]=n[h];Lx(s.config);let c=l(o,s.config,n,r);return Sa=Object.assign({},d),c}else{let u=Object.assign({},Sa);for(let d of Object.keys(n))Sa[d]=n[d];let p=new o(s.config);return Sa=Object.assign({},u),p}}}function hG(e,t){return e<t?-1:e>t?1:0}function wh(e,t){return-1*hG(e,t)}function as(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function mG(e){if(e==null)throw new V(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Ko(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new V(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function e0(e,t,n=0,a=1/0){return tr(n>=0),tr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function tn(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>tn(n,`element ${a+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${h2(e)}.`)}function h2(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>h2(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function fG(e,t,n){let a=n!=null?n():w.now(),r;return(...s)=>{let i=n!=null?n():w.now();return i-a<t||(a=i,r=e(...s)),r}}function m2(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var gG=0;function f2(){return gG++}var kh={};function ff(e=""){return e in kh||(kh[e]=0),kh[e]+=1,e+kh[e].toString()}var bG=["channelsFirst","channelsLast"],yG=["nearest","bilinear"],xG=["valid","same","causal"],vG=["max","avg"],wG=["sum","mul","concat","ave"],kl=new Map;function Rt(e){Ko(bG,"DataFormat",e)}function kG(e){Ko(yG,"InterpolationFormat",e)}function va(e){Ko(xG,"PaddingMode",e)}function g2(e){Ko(vG,"PoolMode",e)}var pc=[],gI="/";function ai(e,t){pc.push(e);try{let n=t();return pc.pop(),n}catch(n){throw pc.pop(),n}}function IG(){return pc.length===0?"":pc.join(gI)+gI}function b2(e){if(!x2(e))throw new Error("Not a valid tensor name: '"+e+"'");return IG()+e}function y2(e){if(!x2(e))throw new Error("Not a valid tensor name: '"+e+"'");kl.has(e)||kl.set(e,0);let t=kl.get(e);if(kl.set(e,kl.get(e)+1),t>0){let n=`${e}_${t}`;return kl.set(n,1),n}else return e}var SG=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function x2(e){return!!e.match(SG)}function NG(e){return e===parseInt(e.toString(),10)}function rs(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;r<n;++r)a*=e[r];return a}function Ul(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a<t&&(t=a)}return t}function ds(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a>t&&(t=a)}return t}function Ua(e,t){if(t<e)throw new V(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let a=e;a<t;++a)n.push(a);return n}var ux;function jt(){return ux==null&&(ux=$v().epsilon()),ux}function Ga(){return"channelsLast"}function ir(e,t){return re(e,t)}function wd(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),W(e,n)}function TG(e,t){return O(()=>{if(e.shape.length!==2)throw new V(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=wd(e,1);return zx(n,[1,t,1])})}function CG(e){let t=[rs(e.shape)];return W(e,t)}function EG(e){if(e.rank<=1)throw new V(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],rs(e.shape,1)];return W(e,t)}function ri(e,t,n){return O(()=>{switch(e.rank){case 1:return gd(e,t,n);case 2:return tf(e,[t,0],[n,e.shape[1]]);case 3:return Ho(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Wl(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Ve(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Ve(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 V(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function px(e,t,n){return O(()=>{switch(e.rank){case 1:return gd(e,t,n);case 2:return tf(e,[0,t],[e.shape[0],n]);case 3:return Ho(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Wl(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Ih(e,t,n,a){return O(()=>{switch(e.rank){case 1:return gd(e,t,n);case 2:switch(a){case 1:return ri(e,t,n);case 2:return px(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return ri(e,t,n);case 2:return Ho(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return px(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return ri(e,t,n);case 2:return Wl(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Wl(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return px(e,t,n);default:throw new V(`The axis is not within the rank of the tensor ${a}`)}default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function t0(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),et(e,t)}function bI(e,t){switch(e.rank){case 1:return Zv([e,t]);case 2:return Jv([e,t],0);case 3:return Qv([e,t],0);case 4:return ew([e,t],0);default:throw new V(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function zx(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new V(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Mn(e,t)}function gf(e,t=0,n=1,a,r){return Km(e,t,n,a,r)}function or(e,t,n,a){if(e.rank<2||t.rank<2)throw new ze(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(r!==s)throw new ze(`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)return Vl.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:a?Wx(e.rank,a,Ga()):null,activation:n});{let r=e.shape.slice(),s=r.pop();e=W(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],p=Array.from({length:t.rank},(c,h)=>h===0?t.rank-2:h<=t.rank-2?h-1:h);t=W(De(t,p),[l,-1]);let d=[...r,...u];return W(Vl.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:a?Wx(e.rank,a,Ga()):null,activation:n}),d)}}function v2(e,t,n){return O(()=>(Array.isArray(t)?t=qe(t,"int32"):t=re(t,"int32"),np(e,t,n)))}function kd(e){return z(e,e)}function Wx(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new V(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1,1]):W(t,[1,a[3],a[0],a[1],a[2]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===4){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1,1]):W(t,[1,a[2],a[0],a[1]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,1,a[0]]):W(t,[1].concat(a))}else if(e===3){if(n==="channelsFirst")return a.length===1?W(t,[1,a[0],1]):W(t,[1,a[1],a[0]]);if(n==="channelsLast")return a.length===1?W(t,[1,1,a[0]]):W(t,[1].concat(a))}else if(e<3)return t;throw new V(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ka(e,t,n){return O(()=>(n==null&&(n=Ga()),Rt(n),X(e,Wx(e.rank,t,n))))}function _G(e,t=1){if(t!==1)throw new ze(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Qu(e)}function AG(e){return O(()=>he(e,X(Lt(e),1)))}function w2(e,t,n,a){return O(()=>Pw(e,t,n,a))}function FG(e){return O(()=>{let t=X(.5,z(.2,e));return an(t,0,1)})}function Id(e,t,n=!1){return n?e():t()}var $G=["fanIn","fanOut","fanAvg"],DG=["normal","uniform","truncatedNormal"];function RG(e){Ko($G,"FanMode",e)}function MG(e){Ko(DG,"Distribution",e)}var $a=class extends ne.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},n0=class extends $a{apply(e,t){return It(e,t)}};n0.className="Zeros";ne.registerClass(n0);var bf=class extends $a{apply(e,t){return On(e,t)}};bf.className="Ones";ne.registerClass(bf);var a0=class extends $a{constructor(e){if(super(),typeof e!="object")throw new V(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new V(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return O(()=>z(ve(this.value),On(e,t)))}getConfig(){return{value:this.value}}};a0.className="Constant";ne.registerClass(a0);var r0=class extends $a{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 Cs(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};r0.className="RandomUniform";ne.registerClass(r0);var s0=class extends $a{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 ze(`randomNormal does not support dType ${t}.`);return gf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};s0.className="RandomNormal";ne.registerClass(s0);var i0=class extends $a{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 ze(`truncatedNormal does not support dType ${t}.`);return of(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};i0.className="TruncatedNormal";ne.registerClass(i0);var o0=class extends $a{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return O(()=>{if(e.length!==2||e[0]!==e[1])throw new V("Identity matrix initializer can only be used for 2D square matrices.");return z(this.gain,Um(e[0]))})}getConfig(){return{gain:this.gain}}};o0.className="Identity";ne.registerClass(o0);function OG(e,t="channelsLast"){let n,a;if(Rt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=rs(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=rs(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=rs(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var Wn=class extends $a{constructor(e){if(super(),e.scale<0)throw new V(`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,RG(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,MG(this.distribution),this.seed=e.seed}apply(e,t){let n=OG(e),a=n[0],r=n[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,a):this.mode==="fanOut"?s/=Math.max(1,r):s/=Math.max(1,(a+r)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`${this.getClassName()} does not support dType ${t}.`);return of(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Cs(e,-i,i,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Wn.className="VarianceScaling";ne.registerClass(Wn);var yf=class extends Wn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};yf.className="GlorotUniform";ne.registerClass(yf);var xf=class extends Wn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};xf.className="GlorotNormal";ne.registerClass(xf);var vf=class extends Wn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};vf.className="HeNormal";ne.registerClass(vf);var wf=class extends Wn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};wf.className="HeUniform";ne.registerClass(wf);var kf=class extends Wn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};kf.className="LeCunNormal";ne.registerClass(kf);var If=class extends Wn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Wn.className}};If.className="LeCunUniform";ne.registerClass(If);var l0=class extends $a{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return O(()=>{if(e.length<2)throw new ze("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);t=t;let n=w.sizeFromShape(e.slice(0,-1)),a=e[e.length-1],r=n*a;r>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);let s=[Math.max(a,n),Math.min(a,n)],i=gf(s,0,1,t,this.seed),o=Bw.qr(i,!1),l=o[0],u=o[1].flatten().stridedSlice([0],[Math.min(a,n)*Math.min(a,n)],[Math.min(a,n)+1]);return l=z(l,u.sign()),n<a&&(l=l.transpose()),z(ve(this.gain),l.reshape(e))})}getConfig(){return{gain:this.gain,seed:this.seed}}};l0.className="Orthogonal";ne.registerClass(l0);var yI={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 xI(e,t={}){return vd(e,ne.SerializationMap.getMap().classNameMap,t,"initializer")}function Et(e){return Qw(e)}function St(e){if(typeof e=="string"){let t=e in yI?yI[e]:e;if(t==="GlorotNormal")return new xf;if(t==="GlorotUniform")return new yf;if(t==="HeNormal")return new vf;if(t==="HeUniform")return new wf;if(t==="LeCunNormal")return new kf;if(t==="LeCunUniform")return new If;{let n={};return n.className=t,n.config={},xI(n)}}else return e instanceof $a?e:xI(e)}function Bx(e){return Array.isArray(e)&&Array.isArray(e[0])}function Zh(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Te(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new V(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Je(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new V(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Jh(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((a,r)=>a*r);return t}var vI="Variable",k2=class{constructor(e,t="float32",n=vI,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=f2(),n=n==null?vI:n,this.originalName=b2(n),this.name=y2(this.originalName),this.trainable_=a,this.constraint=r,this.val=Mw(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),PG(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 PG(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Vx(e){return e.map(t=>t.read())}function u0(e){e.forEach(t=>{t[0].write(t[1])})}var zt=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||{}}},Ha=class{constructor(e,t,n,a,r,s,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=a,this.callArgs=r,this.outputTensorIndex=i,this.id=f2(),s!=null&&(this.originalName=b2(s),this.name=y2(this.originalName)),this.rank=t.length}},LG=0,Sf=class{constructor(e,t){this.callArgs=t,this.id=LG++,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}}},zG=0,We=class extends ne.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=zG++,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=kr(n)+"_"+ff(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new ar(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new V(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Rn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Rn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Xr(`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 Xr(`Layer ${this.name} is not connected, no input to return.`);return Rn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Xr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Xr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Rn(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){let t=it(e);if(this.inputSpec==null||this.inputSpec.length===0)return;let n=it(this.inputSpec);if(t.length!==n.length)throw new V(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let a=0;a<t.length;a++){let r=t[a],s=n[a];if(s==null)continue;let i=r.rank;if(s.ndim!=null&&i!==s.ndim)throw new V(`Input ${a} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${i}`);if(s.maxNDim!=null&&i>s.maxNDim)throw new V(`Input ${a} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${i}`);if(s.minNDim!=null&&i<s.minNDim)throw new V(`Input ${a} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${i}.`);if(s.dtype!=null&&r.dtype!==s.dtype)throw new V(`Input ${a} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${r.dtype}.`);if(s.axes){let o=r.shape;for(let l in s.axes){let u=Number(l),p=s.axes[l],d=u>=0?o[u]:o[o.length+u];if(p!=null&&[p,null].indexOf(d)===-1)throw new V(`Input ${a} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${p} but got shape ${o}.`)}}if(s.shape!=null)for(let o=0;o<s.shape.length;++o){let l=s.shape[o],u=r.shape[o];if(l!=null&&u!=null&&l!==u)throw new V(`Input ${a} 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=it(e),a=VG(e),r=UG(e);if(a===r)throw new V("Arguments to apply() must be all SymbolicTensors or all Tensors");return ai(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of it(e))s.push(i.shape);this.build(Rn(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,s);let i=it(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=Rn(o),this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=WG(e),i=this.computeOutputShape(s),o,l=BG(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,p)=>new Ha(l,u,this,it(e),t,this.name,p)):o=new Ha(l,i,this,it(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,a)=>{n!=null&&e[a]!=null&&e[a]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Xr(`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 Xr(`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 ar(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Jh(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Vx(e?this.trainableWeights:this.weights)}setWeights(e){O(()=>{let t=this.weights;if(t.length!==e.length)throw new V(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],a=Vx(t);for(let r=0;r<a.length;++r){let s=a[r],i=t[r],o=e[r];if(!w.arraysEqual(s.shape,o.shape))throw new V(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}u0(n)})}addWeight(e,t,n,a,r,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new V(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(a=o!=null?o():St("zeros"));let l=a.apply(t,n),u=new k2(l,n,e,s,i);return l.dispose(),r!=null&&this.addLoss(()=>r.apply(u.read())),s==null&&(s=!0),s?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=it(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}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;let a=this.computeMask(e,n),r=it(t),s=it(a);if(r.length!==s.length)throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);for(let i=0;i<r.length;i++)r[i].kerasMask=s[i]}addInboundNode(e,t,n,a,r,s,i=null){let o=it(e);t=it(t),n=it(n),a=it(a),r=Zh(r),s=Zh(s);let l=[],u=[],p=[];for(let d of o)l.push(d.sourceLayer),u.push(d.nodeIndex),p.push(d.tensorIndex);new Sf({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:p,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:a,inputShapes:r,outputShapes:s},i);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 WG(e){e=it(e);let t=[];for(let n of e)t.push(n.shape);return Rn(t)}function BG(e){return"float32"}function I2(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let a=t.inboundNodes[n];if(a.inboundLayers.length===0)return a.inputTensors;{let r=[];for(let s=0;s<a.inboundLayers.length;s++){let i=a.inputTensors[s],o=a.inboundLayers[s],l=a.nodeIndices[s],u=I2(i,o,l);for(let p of u)r.indexOf(p)===-1&&r.push(p)}return r}}}function VG(e){let t=!0;for(let n of it(e))if(!(n instanceof Ha)){t=!1;break}return t}function UG(e){let t=!0;for(let n of it(e))if(n instanceof Ha){t=!1;break}return t}var rp=class extends We{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:ff("input").toString()}),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 V("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 V("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new V("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let a=new Ha(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new Sf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new V(`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}}};rp.className="InputLayer";ne.registerClass(rp);function S2(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 V("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 rp({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function GG(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return re(t,e.dtype)}catch(n){throw new V(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var Cl=class N2{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof N2)for(let n in t.id2Value)this.id2Value[n]=t.id2Value[n],n in t.id2Mask&&(this.id2Mask[n]=t.id2Mask[n]);else{if(t==null)return;for(let n of t)this.add(n.key,n.value)}}add(t,n,a){if(this.id2Value[t.id]==null)this.id2Value[t.id]=GG(t,n),this.name2Id[t.name]=t.id,a!=null&&(this.id2Mask[t.id]=a);else throw new V(`Duplicate key: name=${t.name}, id=${t.id}`);return this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return this.id2Value[t.id]!=null}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof Ha){if(this.id2Value[t.id]==null)throw new V(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}else{let n=this.name2Id[t];if(n==null)throw new V(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[n]}}getMask(t){if(t instanceof Ha){if(this.id2Value[t.id]==null)throw new V(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}else{let n=this.name2Id[t];if(n==null)throw new V(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[n]}}disposeMasks(){this.id2Mask!=null&&Ee(this.id2Mask)}},Qh=new d2,em=new d2;function HG(e){Qh!=null&&Qh.setMaxEntries(e),em!=null&&em.setMaxEntries(e)}function tc(e,t,n,a){let r=n==null?!1:n.training,s=Array.isArray(e),i=s?e:[e],o=i.map(m=>m.name),l=[],u=t.names();for(let m of o)u.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);a!=null&&(a.maxNumTensors=-1/0,a.minNumTensors=1/0);let p=o.join(",")+"|"+t.names().sort().join(","),d=Qh.get(p),c;if(d==null){let m=qG(i,t);d=m.sorted,c=m.recipientCounts,Qh.put(p,d),em.put(p,c)}c={},r||Object.assign(c,em.get(p));let h=new Cl(t);for(let m=0;m<d.length;++m){if(a!=null){let F=Kh().numTensors;F>a.maxNumTensors&&(a.maxNumTensors=F),F<a.minNumTensors&&(a.minNumTensors=F)}let f=d[m],g=f.sourceLayer;if(g instanceof rp)continue;let b=[],y=[],x=[],v=!1;for(let F of f.inputs){let D=h.getValue(F),$=h.getMask(F);b.push(D),y.push($),$!=null&&(v=!0),r||(c[F.name]--,c[F.name]===0&&!t.hasKey(F)&&o.indexOf(F.name)===-1&&!D.isDisposed&&F.sourceLayer.stateful!==!0&&x.push(D))}v&&(n=n||{},n.mask=y[0]);let I=it(g.apply(b,n)),N=null;g.supportsMasking&&(N=g.computeMask(b,y));let C=KG(f),_=Array.isArray(C)?C:[C];for(let F=0;F<_.length;++F){h.hasKey(_[F])||h.add(_[F],I[F],Array.isArray(N)?N[0]:N);let D=o.indexOf(_[F].name);D!==-1&&(l[D]=I[F])}r||Ee(x)}return h.disposeMasks(),s?l:l[0]}function qG(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=wI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=wI(s,t);for(let l of i)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in o)a[l]==null&&(a[l]=new Set),o[l].forEach(u=>a[l].add(u))}}return{sorted:n,recipientCounts:jG(a)}}function jG(e){let t={};for(let n in e)t[n]=e[n].size;return t}function wI(e,t){let n=new Set,a=[],r={};for(let o of t.names())n.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(n.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),a.push(o),n.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(o.name),!n.has(u.name)&&s.push(u)}}return{sorted:a,recipientMap:r}}function KG(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;a<e.sourceLayer.inboundNodes.length;++a)for(let r of e.sourceLayer.inboundNodes[a].outputTensors)if(r.id===e.id){n=a;break}t=e.sourceLayer.getOutputAt(n)}return t}var XG=G();XG.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,HG);var T2={};_e(T2,{maxNorm:()=>YG,minMaxNorm:()=>QG,nonNeg:()=>JG,unitNorm:()=>ZG});function p0(e,t){return O(()=>cn(fe(z(e,e),t,!0)))}var Sd=class extends ne.Serializable{getConfig(){return{}}},c0=class extends Sd{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 O(()=>{let t=p0(e,this.axis),n=an(t,0,this.maxValue);return z(e,he(n,X(jt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};c0.className="MaxNorm";ne.registerClass(c0);var d0=class extends Sd{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return O(()=>he(e,X(jt(),p0(e,this.axis))))}getConfig(){return{axis:this.axis}}};d0.className="UnitNorm";ne.registerClass(d0);var h0=class extends Sd{apply(e){return Ke(e)}};h0.className="NonNeg";ne.registerClass(h0);var m0=class extends Sd{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 O(()=>{let t=p0(e,this.axis),n=X(z(this.rate,an(t,this.minValue,this.maxValue)),z(1-this.rate,t));return z(e,he(n,X(jt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};m0.className="MinMaxNorm";ne.registerClass(m0);var kI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Xt(e){return Qw(e)}function II(e,t={}){return vd(e,ne.SerializationMap.getMap().classNameMap,t,"constraint")}function Yt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in kI?kI[e]:e,config:{}};return II(t)}else return e instanceof Sd?e:II(e)}function YG(e){return new c0(e)}function ZG(e){return new d0(e)}function JG(){return new h0}function QG(e){return new m0(e)}var C2={};_e(C2,{constant:()=>nH,glorotNormal:()=>uH,glorotUniform:()=>lH,heNormal:()=>pH,heUniform:()=>cH,identity:()=>iH,leCunNormal:()=>dH,leCunUniform:()=>hH,ones:()=>tH,orthogonal:()=>mH,randomNormal:()=>rH,randomUniform:()=>aH,truncatedNormal:()=>sH,varianceScaling:()=>oH,zeros:()=>eH});function eH(){return new n0}function tH(){return new bf}function nH(e){return new a0(e)}function aH(e){return new r0(e)}function rH(e){return new s0(e)}function sH(e){return new i0(e)}function iH(e){return new o0(e)}function oH(e){return new Wn(e)}function lH(e){return new yf(e)}function uH(e){return new xf(e)}function pH(e){return new vf(e)}function cH(e){return new wf(e)}function dH(e){return new kf(e)}function hH(e){return new If(e)}function mH(e){return new l0(e)}var E2={};_e(E2,{Layer:()=>We,RNN:()=>Mr,RNNCell:()=>Td,activation:()=>G6,add:()=>Q6,alphaDropout:()=>Oq,average:()=>eq,averagePooling1d:()=>T1,averagePooling2d:()=>C1,averagePooling3d:()=>E1,avgPool1d:()=>uq,avgPool2d:()=>cq,avgPool3d:()=>hq,avgPooling1d:()=>pq,avgPooling2d:()=>dq,avgPooling3d:()=>mq,batchNormalization:()=>iq,bidirectional:()=>Eq,categoryEncoding:()=>Bq,centerCrop:()=>zq,concatenate:()=>tq,conv1d:()=>M6,conv2d:()=>O6,conv2dTranspose:()=>P6,conv3d:()=>L6,conv3dTranspose:()=>z6,convLstm2d:()=>Sq,convLstm2dCell:()=>Nq,cropping2D:()=>B6,dense:()=>H6,depthwiseConv2d:()=>U6,dot:()=>sq,dropout:()=>q6,elu:()=>_6,embedding:()=>J6,flatten:()=>K6,gaussianDropout:()=>Mq,gaussianNoise:()=>Rq,globalAveragePooling1d:()=>fq,globalAveragePooling2d:()=>gq,globalMaxPool1d:()=>Aq,globalMaxPool2d:()=>Fq,globalMaxPooling1d:()=>EC,globalMaxPooling2d:()=>_C,gru:()=>yq,gruCell:()=>xq,input:()=>q2,inputLayer:()=>E6,layerNormalization:()=>oq,leakyReLU:()=>F6,lstm:()=>vq,lstmCell:()=>wq,masking:()=>Pq,maxPool1d:()=>$q,maxPool2d:()=>Dq,maxPooling1d:()=>AC,maxPooling2d:()=>FC,maxPooling3d:()=>bq,maximum:()=>nq,minimum:()=>aq,multiply:()=>rq,permute:()=>Z6,prelu:()=>$6,randomWidth:()=>Vq,reLU:()=>A6,repeatVector:()=>X6,rescaling:()=>Lq,reshape:()=>Y6,resizing:()=>Wq,rnn:()=>Tq,separableConv2d:()=>W6,simpleRNN:()=>kq,simpleRNNCell:()=>Iq,softmax:()=>D6,spatialDropout1d:()=>j6,stackedRNNCells:()=>Cq,thresholdedReLU:()=>R6,timeDistributed:()=>_q,upSampling2d:()=>V6,zeroPadding2d:()=>lq});async function Kr(e){if(e==null)return;let t=[],n=[],a=[];for(let r in e){let s=e[r];if(typeof s!="number"){let i=s;t.push(i.data()),n.push(r),a.push(i)}}if(t.length>0){let r=await Promise.all(t);for(let s=0;s<r.length;++s)e[n[s]]=r[s][0];Ee(a)}}function _2(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var SI;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(SI||(SI={}));var fH=125,Gl=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){}},A2=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)}},gH=class extends Gl{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let a in t){let r=t[a];if(typeof r=="number")this.totals.hasOwnProperty(a)||(this.totals[a]=0),this.totals[a]=this.totals[a]+r*n;else{let s;a in this.totals?s=this.totals[a]:this.totals[a]=0;let i=O(()=>X(this.totals[a],z(r,n)));this.totals[a]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:O(()=>{let a=z(he(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),Ht(t[n])}))}},F2=class extends Gl{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let s=this.history[r];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(r),n.push(i)}}let a=await Promise.all(e);for(let r=0;r<a.length;++r)this.history[t[r]][n[r]].dispose(),this.history[t[r]][n[r]]=a[r][0]}},$2=class extends Gl{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Zw,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=fH),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=fG(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 a=[];this.yield!=null&&(await Kr(n),a.push(this.yield(e,t,n))),a.push(this.nextFrameFunc()),await Promise.all(a)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Kr(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await Kr(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 Kr(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await Kr(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 Kr(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Kr(e),await this.trainEnd(e))}};function D2(e,t){return e==null&&(e={}),e instanceof Gl?[e]:Array.isArray(e)&&e[0]instanceof Gl?e:it(e).map(n=>new $2(n,t))}var f0=class Ja{constructor(){}static registerCallbackConstructor(t,n){w.assert(t>=0&&Number.isInteger(t),()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`),Ja.checkForDuplicate(n),Ja.constructors[t]==null&&(Ja.constructors[t]=[]),Ja.constructors[t].push(n)}static checkForDuplicate(t){for(let n in Ja.constructors)Ja.constructors[+n].forEach(a=>{if(a===t)throw new V("Duplicate callback constructor.")})}static clear(){Ja.constructors={}}static createCallbacks(t){let n=[];for(let a in Ja.constructors){let r=+a;t>=r&&n.push(...Ja.constructors[r])}return n.map(a=>new a)}};f0.constructors={};function R2(e,t,n,a,r,s,i,o,l){let u=new F2,p=[new gH,...f0.createCallbacks(t)];e!=null&&p.push(...e),p.push(u);let d=new A2(p);return d.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:d,history:u}}function Ba(e,t={},n=!1){return vd(e,ne.SerializationMap.getMap().classNameMap,t,"layer",n)}function tm(e,t){return O(()=>{e.dtype!=="float32"&&(e=re(e,"float32"));let n=fe(kd(e),t,!0),a=yn(n.shape,jt()),r=cn(dr(n,a));return he(e,r)})}function Xo(e,t){return O(()=>Ct(kd(pe(t,e)),-1))}function Nf(e,t){return O(()=>Ct(Lt(pe(t,e)),-1))}function sp(e,t){return O(()=>{let n=pe(e,t),a=an(Lt(e),jt(),Number.MAX_VALUE),r=Lt(he(n,a));return z(100,Ct(r,-1))})}function bH(e,t){return O(()=>{let n=an(t,jt(),Number.MAX_VALUE),a=Qn(X(1,n)),r=an(e,jt(),Number.MAX_VALUE),s=Qn(X(1,r));return Ct(kd(pe(a,s)),-1)})}function yH(e,t){return O(()=>{let n=dr(0,pe(1,z(e,t)));return Ct(kd(n),-1)})}function xH(e,t){return O(()=>{let n=dr(0,pe(1,z(e,t)));return Ct(n,-1)})}function vH(e,t){return O(()=>{let n=fe(z(e,t),-1),a=ma(z(pe(1,e),t),-1);return dr(0,X(1,pe(a,n)))})}function wH(e,t){return O(()=>{let n=Math.log(2),a=pe(t,e),r=pe(X(a,Go(z(-2,a))),n);return Ct(r,-1)})}function kc(e,t,n=!1){return O(()=>{if(n)t=ja(t);else{let a=fe(t,t.shape.length-1,!0);t=he(t,a)}return t=an(t,jt(),1-jt()),yt(fe(z(re(e,"float32"),Qn(t)),t.shape.length-1))})}function nm(e,t,n=!1){return O(()=>{let a=re(tp(CG(e)),"int32");t=an(t,jt(),1-jt());let r=t.shape,s=W(Ll(a,r[r.length-1]),r);return kc(s,t,n)})}function kH(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new V(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return O(()=>{let n=Ke(t),a=yt(Lt(t));return X(pe(n,z(t,e)),pd(dn(a)))})}function Tf(e,t){return O(()=>{let n;return n=an(t,jt(),1-jt()),n=Qn(he(n,pe(1,n))),Ct(kH(e,n),-1)})}function IH(e,t){return O(()=>{let n=an(e,jt(),1),a=an(t,jt(),1);return fe(z(e,Qn(he(n,a))),-1)})}function SH(e,t){return O(()=>{let n=Qn(X(jt(),t));return Ct(pe(t,z(e,n)),-1)})}function g0(e,t){return O(()=>{let n=tm(e,-1),a=tm(t,-1),r=z(n,a);return yt(fe(r,-1))})}var am={meanSquaredError:Xo,meanAbsoluteError:Nf,meanAbsolutePercentageError:sp,meanSquaredLogarithmicError:bH,squaredHinge:yH,hinge:xH,categoricalHinge:vH,logcosh:wH,categoricalCrossentropy:kc,sparseCategoricalCrossentropy:nm,binaryCrossentropy:Tf,kullbackLeiblerDivergence:IH,poisson:SH,cosineProximity:g0};function cx(e){if(typeof e=="string"){if(e in am)return am[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 V(t)}else return e}function b0(e,t){return O(()=>{let n=z(.5,ea(t)),a=ir(Tn(t,n),e.dtype);return Ct(Jn(e,a),-1)})}function y0(e,t){return O(()=>ir(Jn(ci(e,-1),ci(t,-1)),"float32"))}function M2(e,t){return O(()=>re(fe(_a(Jn(e,1),Jn(t,1))),"float32"))}function NH(e,t){return O(()=>re(fe(_a(Jn(e,1),Jn(t,0))),"float32"))}function TH(e,t){return O(()=>re(fe(_a(Jn(e,0),Jn(t,1))),"float32"))}function O2(e,t){return O(()=>{let n=M2(e,t),a=TH(e,t),r=X(n,a);return re(nn(Tn(r,0),he(n,r),0),"float32")})}function CH(e,t){return O(()=>{let n=M2(e,t),a=NH(e,t),r=X(n,a);return re(nn(Tn(r,0),he(n,r),0),"float32")})}function P2(e,t){return Tf(e,t)}function L2(e,t){return e.rank===t.rank&&(e=_s(e,[e.rank-1])),t=ci(t,-1),t.dtype!==e.dtype&&(t=re(t,e.dtype)),re(Jn(e,t),"float32")}var EH=Xo,_H=Xo,AH=Nf,FH=Nf,$H=sp,DH=sp,x0=kc,RH=g0,z2=nm,rm={binaryAccuracy:b0,categoricalAccuracy:y0,precision:O2,categoricalCrossentropy:x0,sparseCategoricalCrossentropy:z2,mse:EH,MSE:_H,mae:AH,MAE:FH,mape:$H,MAPE:DH,cosine:RH};function MH(e){if(typeof e=="string"&&e in rm)return rm[e];if(typeof e!="string"&&e!=null)return e;throw new V(`Unknown metric ${e}`)}function Sh(e){if(tr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(am))if(am[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(rm))if(rm[n]===e){t=n;break}return t!==void 0?t:e.name}}function OH(e){let t={Adagrad:()=>Ks.adagrad(.01),Adadelta:()=>Ks.adadelta(1,.95,jt()),Adam:()=>Ks.adam(.001,.9,.999,jt()),Adamax:()=>Ks.adamax(.002,.9,.999,jt(),0),RMSProp:()=>Ks.rmsprop(.001,.9,0,jt()),SGD:()=>Ks.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 V(`Unknown Optimizer ${e}`)}function NI(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Ux(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let a=JSON.stringify(e);a.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${a.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Ux(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"||!Ux(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Ux(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function PH(e,t,n,a=console.log){let r=zH(e),s=["Layer (type)","Input Shape","Output shape","Param #"];r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(p=>Math.floor(t*p)));let i;if(!r){s.push("Receives inputs"),i=[];for(let p in e.nodesByDepth)i.push(...e.nodesByDepth[p])}a("_".repeat(t)),sm(s,n,a),a("=".repeat(t));let o=e.layers;for(let p=0;p<o.length;++p)r?WH(o[p],n,a):BH(o[p],n,i,a),a((p===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=LH(e),u=Jh(e.nonTrainableWeights);a(`Total params: ${l+u}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${u}`),a("_".repeat(t))}function LH(e){let t;return e.collectedTrainableWeights!=null?t=Jh(e.collectedTrainableWeights):t=Jh(e.trainableWeights),t}function zH(e){let t=!0,n=[],a=[];for(let r in e.nodesByDepth)n.push(e.nodesByDepth[r]);for(let r of n){if(r.length>1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}a.push(...r)}if(t)for(let r of e.layers){let s=!1;for(let i of r.inboundNodes)if(a.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function sm(e,t,n=console.log){let a="";for(let r=0;r<e.length;++r)r>0&&(a=a.slice(0,a.length-1)+" "),a+=e[r],a=a.slice(0,t[r]),a+=" ".repeat(t[r]-a.length);n(a)}function WH(e,t,n){let a,r;try{r=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){r="multiple"}try{a=JSON.stringify(e.outputShape)}catch(l){a="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,r,a,e.countParams().toString()];sm(o,t,n)}function BH(e,t,n,a){let r,s;try{s=e.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch(d){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(d){r="multiple"}let i=[];for(let d of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(d)===-1))for(let c=0;c<d.inboundLayers.length;++c){let h=d.inboundLayers[c].name,m=d.nodeIndices[c],f=d.tensorIndices[c];i.push(`${h}[${m}][${f}]`)}let o=e.name,l=e.getClassName(),u=i.length===0?"":i[0],p=[`${o} (${l})`,s,r,e.countParams().toString(),u];sm(p,t,a);for(let d=1;d<i.length;++d)sm(["","","","",i[d]],t,a)}function W2(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Ic(e,t){if(e===null)return null;if(typeof e=="string")return Zs(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];W2(t,r,s)?n.push(s):n.push(Ic(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a];if(a==="name"&&typeof r=="string")n[a]=r;else{let s=Zs(a);n[s]=Ic(r,s)}}return n}}function Gx(e,t){if(e==null)return null;if(typeof e=="string")return kr(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],a=e.length;for(let r=0;r<a;++r){let s=e[r];W2(t,r,s)?n.push(s):n.push(Gx(s,t))}return n}else{let n={};for(let a of Object.keys(e)){let r=e[a],s=kr(a);(a==="name"||a==="className")&&typeof r=="string"?n[s]=r:n[s]=Gx(r,a)}return n}}var v0="4.16.0",VH=e=>{let t=Object.keys(e);if(t.length===0)return!1;let n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))},UH=class Qa extends We{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=ff(y)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],as(this.inputs).length!==this.inputs.length)throw new V(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);as(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let x=y.sourceLayer,v=y.nodeIndex,I=y.tensorIndex;this.outputLayers.push(x),this.outputLayersNodeIndices.push(v),this.outputLayersTensorIndices.push(I)}for(let y of this.inputs){let x=y.sourceLayer,v=y.nodeIndex,I=y.tensorIndex;tr(v===0,"input layer has >1 nodes"),tr(I===0,"input layer has >1 tensors"),this.inputLayers.push(x),this.inputLayersNodeIndices.push(v),this.inputLayersTensorIndices.push(I)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let x=this.inputLayers[y];if(!(x instanceof rp))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${y} (0-based) originates from layer type ${x.getClassName()}.`);this.inputNames.push(x.name),this.feedInputShapes.push(x.batchInputShape),this.feedInputNames.push(x.name)}for(let y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let n={},a={},r={},s={},i={},o=[],l=(y,x,v,I,N,C)=>{(I==null||N==null||C==null)&&(I=y.sourceLayer,N=y.nodeIndex,C=y.tensorIndex);let _=I.inboundNodes[N];if(v.indexOf(_)!==-1)throw new ar(`The tensor ${y.name} at layer "${I.name}" is part of a cycle.`);if(x.indexOf(_)!==-1)return;this.containerNodes.add(Qa.nodeKey(I,N)),I.id in i||(i[I.id]=Object.keys(i).length),v.indexOf(_)===-1&&v.push(_);let F=_.inboundLayers.length;for(let D=0;D<F;D++){let $=_.inputTensors[D],S=_.inboundLayers[D],M=_.nodeIndices[D],B=_.tensorIndices[D];l($,x,v,S,M,B)}for(x.push(_);v.indexOf(_)>=0;)v.splice(v.indexOf(_),1);o.push(_)},u=[],p=[];for(let y of this.outputs)l(y,u,p);let d=o.slice().reverse();for(let y of d){a[y.id]=y,y.id in n||(n[y.id]=0);let x=n[y.id],v=r[y.outboundLayer.id]==null?0:r[y.outboundLayer.id];x=Math.max(x,v),r[y.outboundLayer.id]=x,s[y.outboundLayer.id]=y.outboundLayer,n[y.id]=x;for(let I=0;I<y.inboundLayers.length;I++){let N=y.inboundLayers[I],C=y.nodeIndices[I],_=N.inboundNodes[C],F=n[_.id]==null?0:n[_.id];n[_.id]=Math.max(x+1,F),a[_.id]=_}}let c={};for(let y in n){let x=n[y];x in c||(c[x]=[]),c[x].push(a[y])}let h={};for(let y in r){let x=r[y];x in h||(h[x]=[]),h[x].push(s[y])}let m=Object.keys(h).map(y=>parseInt(y,10)).sort(wh);this.layers=[];for(let y of m){let x=h[y];x.sort((v,I)=>{let N=i[v.id],C=i[I.id];return N<C?-1:N>C?1:0});for(let v of x)v instanceof Qa&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=h,m=Object.keys(c).map(y=>parseInt(y,10)).sort(wh);let f=this.inputs.slice(),g=[];for(let y of m)for(let x of c[y]){let v=x.outboundLayer;if(v!=null){for(let I of x.inputTensors)if(f.indexOf(I)===-1)throw new ar(`Graph disconnected: cannot obtain value for tensor ${I} at layer "${v.name}". The following previous layers were accessed without issue: ${g}`);for(let I of x.outputTensors)f.push(I);g.push(v.name)}}this.nodesByDepth=c;let b=this.layers.map(y=>y.name);for(let y of b){let x=b.filter(v=>v===y).length;if(x!==1)throw new ar(`The name "${y}" is used ${x} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(b))}this.outboundNodes=[],this.inboundNodes=[],new Sf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let t={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let n of this.layers)t.numDisposedVariables+=n.dispose().numDisposedVariables;for(let n of this.internalContainerRefs)t.numDisposedVariables+=n.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(n=>{n._trainableWeights.forEach(a=>a.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new V("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 t=[];for(let n of this.layers)t=t.concat(n.trainableWeights);return t}get nonTrainableWeights(){let t=[];for(let n of this.layers)t.push(...n.nonTrainableWeights);if(!this.trainable){let n=[];for(let a of this.layers)n.push(...a.trainableWeights);return n.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,n=!0){let a={},r=0,s=VH(t);s&&this.parseWeights(t);for(let o of this.layers)for(let[l,u]of o.weights.entries()){let p=s?`${u.name.split("/").slice(0,-1).join("/")+"/"}${l}`:u.originalName;if(a[p]!=null)throw new V(`Duplicate weight name: ${p}`);a[p]=u,r++}let i=[];for(let o in t){let l=o;if(a[o]==null){let u=o.split("/");l=u.slice(0,-2).concat([u[u.length-1]]).join("/")}if(a[l]!=null)i.push([a[l],t[o]]);else if(n)throw new V(`Provided weight data has no target variable: ${o}`);delete a[l]}if(n){let o=[];for(let l in a)o.push(l);if(o.length>0)throw new V(`${o.length} of ${r} weights are not set: ${o}`)}u0(i)}parseWeights(t){for(let n in Object.keys(t)){let a=n.split("/"),r=["vars","layer_checkpoint_dependencies"],s=a.map(i=>i.startsWith("_")?i.slice(1):i).filter(i=>!r.includes(i)).join("/");s!==n&&(t[s]=t[n],delete t[n])}}updatedConfig(){let t=this.getConfig(),n={};return n.className=this.getClassName(),n.config=t,n.kerasVersion=`tfjs-layers ${v0}`,n.backend="TensorFlow.js",n}toJSON(t,n=!0){let a=Gx(this.updatedConfig());return n?JSON.stringify(a):a}call(t,n){return O(()=>{t=it(t);let a=new Cl;for(let r=0;r<this.inputs.length;++r)a.add(this.inputs[r],t[r]);return tc(this.outputs,a,n)})}computeMask(t,n){return O(()=>{t=it(t);let a;return n==null?a=bi(null,t.length):a=it(n),this.runInternalGraph(t,a)[1]})}computeOutputShape(t){let n=Zh(t);if(n.length!==this.inputLayers.length)throw new V(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);let a={};for(let o=0;o<n.length;o++){let l=this.inputLayers[o],u=n[o],p=l.name+"_0_0";a[p]=u}let r=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(wh);if(r.length>1)for(let o of r){let l=this.nodesByDepth[o];for(let u of l){let p=u.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(p.id)!==-1)continue;let d=[];for(let f=0;f<u.inboundLayers.length;f++){let g=u.inboundLayers[f],b=u.nodeIndices[f],y=u.tensorIndices[f],x=`${g.name}_${b}_${y}`,v=a[x];d.push(v)}let c=p.computeOutputShape(Rn(d)),h=Zh(c),m=p.inboundNodes.indexOf(u);for(let f=0;f<h.length;f++){let g=`${p.name}_${m}_${f}`;a[g]=h[f]}}}let s=[],i=[];for(let o=0;o<this.outputLayers.length;o++){let l=this.outputLayers[o],u=this.outputLayersNodeIndices[o],p=this.outputLayersTensorIndices[o],d=`${l.name}_${u}_${p}`;i.push(d)}for(let o=0;o<i.length;o++){let l=i[o];tr(l in a),s.push(a[l])}return Rn(s)}runInternalGraph(t,n){n==null&&(n=bi(null,t.length));let a={};for(let l=0;l<this.inputs.length;++l){let u=this.inputs[l],p=t[l],d=n[l];a[u.id]=[p,d]}let r=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(wh);for(let l of r){let u=this.nodesByDepth[l];for(let p of u){let d=p.outboundLayer,c=p.inputTensors,h=p.outputTensors,m=new Array;for(let f of c)f.id in a&&m.push(a[f.id]);if(m.length===c.length){let f={},g,b,y,x;if(p.callArgs!=null&&(f=p.callArgs),m.length===1){let[v,I]=m[0];f.mask==null&&(f.mask=I),y=it(d.call(v,f)),x=it(d.computeMask(v,I)),g=[v],b=[I]}else g=m.map(v=>v[0]),b=m.map(v=>v[1]),f.mask==null&&(f.mask=b),y=it(d.call(g,f)),x=it(d.computeMask(g,b));if(d.activityRegularizer)throw new ze("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let v=0;v<h.length;++v){let I=h[v],N=y[v],C=x[v];a[I.id]=[N,C]}}}}let s=[],i=[],o=[];for(let l of this.outputs){tr(l.id in a,`Could not compute output ${l.name} : ${l.id}`);let[u,p]=a[l.id];o.push(u.shape),s.push(u),i.push(p)}return[s,i,o]}buildNodeConversionMap(t){let n={},a;for(let r of this.layers){a=r instanceof Qa?1:0;for(let s=0;s<r.inboundNodes.length;s++){let i=Qa.nodeKey(r,s);this.containerNodes.has(i)&&(n[i]=a,a+=1)}}return n}getLayer(t,n){if(n!=null)return this.findLayer(n);if(t==null)throw new V("Provide either a layer name or layer index");if(typeof t=="number")return this.findLayer(t);for(let a of this.layers)if(a.name===t)return a;throw new V(`No such layer: ${t}`)}findLayer(t){if(this.layers.length<=t)throw new V(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}calculateLosses(){return O(()=>{let t=[];for(let n of this.layers)for(let a=0;a<n.inboundNodes.length;++a){let r=Qa.nodeKey(n,a);this.containerNodes.has(r)&&t.push(...n.calculateLosses())}return t})}getConfig(){let t={name:this.name},n=this.buildNodeConversionMap(this.layers),a=[];for(let i of this.layers){let o=i.getClassName(),l=i.getConfig(),u=[];for(let d=0;d<i.inboundNodes.length;d++){let c=i.inboundNodes[d],h=Qa.nodeKey(i,d),m={};if(this.containerNodes.has(h)){if(c.callArgs)try{JSON.stringify(c.callArgs),m=c.callArgs}catch(f){console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${c.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),m={}}if(c.inboundLayers.length>0){let f=[];for(let g=0;g<c.inboundLayers.length;g++){let b=c.inboundLayers[g],y=c.nodeIndices[g],x=c.tensorIndices[g],v=Qa.nodeKey(b,y),I=n[v];I==null&&(I=0),f.push([b.name,I,x,m])}u.push(f)}}}let p={};p.name=i.name,p.className=o,p.config=l,p.inboundNodes=u,a.push(p)}t.layers=a;let r=[];for(let i=0;i<this.inputLayers.length;i++){let o=this.inputLayers[i],l=this.inputLayersNodeIndices[i],u=Qa.nodeKey(o,l);if(!this.containerNodes.has(u))continue;let p=n[u];p==null&&(p=0);let d=this.inputLayersTensorIndices[i];r.push([o.name,p,d])}t.inputLayers=r;let s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],u=Qa.nodeKey(o,l);if(!this.containerNodes.has(u))continue;let p=n[u];p==null&&(p=0);let d=this.outputLayersTensorIndices[i];s.push([o.name,p,d])}return t.outputLayers=s,t}static fromConfig(t,n,a={},r=!1){let s={},i={};function o(g,b){g.name in i?i[g.name].push(b):i[g.name]=[b]}function l(g,b){let y=[],x;for(let v of b){let I=v[0],N=v[1],C=v[2];if(x=v[3]==null?{}:v[3],!(I in s)){o(g,b);return}let _=s[I];if(_.inboundNodes.length<=N){o(g,b);return}let F=_.inboundNodes[N];y.push(F.outputTensors[C])}y.length>0&&g.apply(Rn(y),x)}function u(g){let b=g.name,y=Ba(g,n.customObjects!=null?n.customObjects:{});y.setFastWeightInitDuringBuild(r),s[b]=y,g.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new V(`Corrupted configuration, expected array for nodeData: ${x}`);o(y,x)})}let p=n.name,d=n.layers;for(let g of d)u(g);for(;!mG(i);)for(let g of d){let b=s[g.name];if(b.name in i){let y=i[b.name];delete i[b.name];for(let x of y)l(b,x)}}let c=[],h=[],m=n.inputLayers;for(let g of m){let b=g[0],y=g[1],x=g[2];tr(b in s);let v=s[b].inboundNodes[y].outputTensors;c.push(v[x])}let f=n.outputLayers;for(let g of f){let b=g[0],y=g[1],x=g[2];tr(b in s);let v=s[b].inboundNodes[y].outputTensors;h.push(v[x])}return new t({inputs:c,outputs:h,name:p})}get stateful(){if(this._stateful)throw new V("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 t of this.layers)if(t.stateful)return!0;return!1}resetStates(){O(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}};function GH(e,t,n){let a=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(a===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==a)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${a} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(s=>{s in e?r.push(e[s]):r.push(null)}),r}else throw new Error(`The model has multiple (${a}) outputs, so ${n} must be either an array with ${a} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function B2(e,t){return GH(e,t,"classWeight")}async function V2(e,t,n,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=O(()=>{if(e.shape.length===1)return sr(e);if(e.shape.length===2){if(e.shape[1]>1)return ci(e,1);if(e.shape[1]===1)return W(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.`)}),s=Array.from(await r.data());Ee(r);let i=[];return s.forEach(o=>{if(n[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(n[o])}),qe(i,"float32")}else return null}function HH(e,t){return z(e,t)}var qH=32;function U2(e,t){let n,a,r=t;n=r.xs,a=r.ys,w.assert(n!=null&&a!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let s=TI("input",e.inputNames,n),i=TI("output",e.outputNames,a),o=s[0].shape[0];w.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)w.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)w.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function TI(e,t,n){if(n instanceof Ce)return[n];if(Array.isArray(n))return w.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let a=[];for(let r of t){if(n[r]==null)throw new V(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function jH(e){if(e.length===3)throw new ze("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function KH(e,t,n){let a=n.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),w.assert(!a||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),w.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,s,i;if(r)if(CI(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=jH(n.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;r?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let p=D2(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:c,history:h}=R2(p,d,n.epochs,null,null,XH(t,n),null,r,u);c.setModel(e),e.history=h,await c.onTrainBegin(),e.stopTraining_=!1;let m=n.initialEpoch==null?0:n.initialEpoch,f=await t.iterator();for(;m<n.epochs;){let g={};await c.onEpochBegin(m);let b=0,y=0;for(a||(f=await t.iterator());!a||b<n.batchesPerEpoch;){let x=await f.next();if(a&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${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(x.value!=null){let{xs:v,ys:I}=U2(e,x.value),N={};N.batch=y,N.size=v[0].shape[0],await c.onBatchBegin(y,N);let C=[];if(n.classWeight!=null){let D=B2(n.classWeight,e.outputNames);for(let $=0;$<D.length;++$)C.push(await V2(I[$],null,D[$]))}let _=v.concat(I).concat(C),F=o(_);Ee(_);for(let D=0;D<l.length;++D){let $=l[D],S=F[D];N[$]=S,Ht(S)}await c.onBatchEnd(y,N),_2(N),y++,b++}if(a?b>=n.batchesPerEpoch:x.done){if(r){let v;CI(n.validationData)?v=it(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):v=it(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?qH:n.validationBatchSize,verbose:0}));for(let I=0;I<e.metricsNames.length;++I)g[`val_${e.metricsNames[I]}`]=v[I]}break}if(e.stopTraining_)break}if(await c.onEpochEnd(m,g),m++,e.stopTraining_)break}return await c.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function XH(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function CI(e){return typeof e.iterator=="function"}function YH(e){return typeof e.next=="function"}async function ZH(e,t,n){n=n||{};let a=n.batches!=null,r=e.testFunction,s=[];if(n.verbose>0)throw new ze("Verbose mode is not implemented yet.");w.assert(!a||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let i=YH(t)?t:await t.iterator(),o=0,l=0;for(;!a||l<n.batches;){let u=await i.next();if(s=O(()=>{if(u.value){let{xs:p,ys:d}=U2(e,u.value),c=p.concat(d),h=O(()=>r(c));if(Ee(c),l===0)for(let f=0;f<h.length;++f)s.push(ve(0));let m=c[0].shape[0];for(let f=0;f<h.length;++f){let g=h[f],b=s[f];s[f]=O(()=>X(s[f],z(m,g))),l>0&&Ee(b)}Ee(h),o+=m,++l}return s}),u.done){a&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u<s.length;++u){let p=s[u];s[u]=he(s[u],o),Ee(p)}return Rn(s)}function dx(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Xp(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>ri(a,t,n-t)):ri(e,t,n-t)}function Hx(e,t){return O(()=>e==null?null:Array.isArray(e)?e.map(n=>Hx(n,t)):v2(e,t.dtype==="int32"?t:re(t,"int32")))}function hx(e,t){let n=[],a=0,r=null;for(;a<e;)r=a+t,r>=e&&(r=e),n.push([a,r]),a=r;return n}function G2(e){let t=[];e instanceof Ce&&(e=[e]);for(let n=0;n<e.length;++n){let a=e[n];if(a.rank===1)t.push(wd(a,1));else{if(a.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(a)}}return t}function Pa(e,t){if(e==null)return;let n=[];if(t instanceof Ce)n.push(t.id);else if(Array.isArray(t))t.forEach(r=>n.push(r.id));else if(t!=null)for(let r in t){let s=t[r];n.push(s.id)}let a=[];if(e instanceof Ce)n.indexOf(e.id)===-1&&a.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&a.push(r)});else if(e!=null)for(let r in e){let s=e[r];n.indexOf(s.id)===-1&&a.push(s)}a.forEach(r=>{r.isDisposed||r.dispose()})}function JH(e){return e instanceof Ce}function qx(e){return Array.isArray(e)}function EI(e){return!JH(e)&&!qx(e)}function _I(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(qx(e)&&e.length>0)i=!0;else if(EI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new V(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(EI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new V(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(qx(e)){if(e=e,e.length!==t.length)throw new V(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(e=e,t.length>1)throw new V(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=G2(s),n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new V(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let u=o.shape[l],p=n[i][l];if(p!=null&&p>=0&&u!==p)throw new V(`${r} expected a batch of elements where each example has shape [${n[i].slice(1,n[i].length)}] (i.e.,tensor shape [*,${n[i].slice(1,n[i].length)}]) but the ${r} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function QH(e,t,n){let a=as(e.map(s=>s.shape[0]));a.sort();let r=as(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new V(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(r.length>1)throw new V(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&r.length>0&&!w.arraysEqual(a,r))throw new V(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${r[0]} target sample(s).`)}function e6(e,t,n){let a=[Xo,Tf,kc];for(let r=0;r<e.length;++r){let s=e[r],i=t[r],o=n[r];if(i!=null){if(i===kc&&s.shape[s.shape.length-1]===1)throw new V(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(a.indexOf(i)!==-1){let l=s.shape.slice(1),u=o.slice(1);for(let p=0;p<l.length;++p){let d=l[p],c=u[p];if(c!=null&&d!==c)throw new V(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function AI(e,t,n,a=!0,r=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new V(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new V(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(n!=null)for(let i=0;i<t.length;++i){if(n[i]==null)continue;let o=s[i];if(o.shape.length!==n[i].length)throw new V(`Error when checking ${r}: expected ${t[i]} to have ${n[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<n[i].length;++l){if(l===0&&!a)continue;let u=o.shape[l],p=n[i][l];if(p!=null&&p!==u)throw new V(`Error when checking ${r}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function t6(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(a=>n);{let a=[];for(let r of t){let s=n.hasOwnProperty(r)?n[r]:[];Array.isArray(s)||(s=[s]),a.push(s)}return a}}var n6="layers-model",Cr=class extends UH{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new V("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).");PH(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=OH(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Rr))throw new V("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new V(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(cx(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new V(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(s=>cx(s))}else{let s=cx(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ai("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=t6(e.metrics,this.outputNames),r=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};ai("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(n.indexOf(s)!==-1)continue;let i=a[s];(o=>{let l="",u,p,d;for(let c of o){if(typeof c=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(c)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===Tf?["accuracy","acc"].indexOf(c)!==-1?p=b0:["crossentropy","ce"].indexOf(c)!==-1&&(p=P2):this.lossFunctions[s]===nm?["accuracy","acc"].indexOf(c)!==-1?p=L2:["crossentropy","ce"].indexOf(c)!==-1&&(p=z2):["accuracy","acc"].indexOf(c)!==-1?p=y0:["crossentropy","ce"].indexOf(c)!==-1&&(p=x0);let f;["accuracy","acc"].indexOf(c)!==-1?f="acc":["crossentropy","ce"].indexOf(c)!==-1&&(f="ce"),d=p,u=l+f}else d=MH(c),u=l+Sh(c);let h;ai(u,()=>{h=d}),r(s,u,h)}})(i)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let a=n.batchSize==null?32:n.batchSize;dx(a);let r=this.standardizeUserDataXY(e,t,!0,a);try{let s=r[0].concat(r[1]);this.makeTestFunction();let i=this.testFunction,o=this.testLoop(i,s,a,n.verbose,n.steps);return Rn(o)}finally{Pa(r[0],e),Pa(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),ZH(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new V(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new V(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new V("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new Cl;if(e instanceof Ce&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new V(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new V(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=tc(r,s);return n?i:i[0]}retrieveSymbolicTensors(e){let t=bi(null,e.length),n=e.length;for(let a of this.layers){let r=Array.isArray(a.output)?a.output:[a.output],s=r.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=r[o],n--),n===0)break}if(n===0)break}if(n>0){let a=[];throw t.forEach((r,s)=>{r==null&&a.push(e[s])}),new V(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return O(()=>{let a=this.checkNumSamples(e);if(n)throw new ze("Verbose predictLoop() is not implemented yet.");let r=hx(a,t),s=this.outputs.map(i=>[]);for(let i=0;i<r.length;++i)O(()=>{let o=r[i][0],l=r[i][1],u=Xp(e,o,l),p=[];if(Array.isArray(u))for(let c=0;c<u.length;++c)p.push({key:this.inputs[c],value:u[c]});else p.push({key:this.inputs[0],value:u});let d=new Cl(p);return tc(this.outputs,d)}).forEach((o,l)=>s[l].push(o));return Rn(s.map(i=>et(i,0)))})}predict(e,t={}){let n=G2(e);AI(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return dx(a),this.predictLoop(n,a)}finally{Pa(n,e)}}predictOnBatch(e){AI(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,a){if(this.optimizer_==null)throw new ar("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===nm?r.push(i.slice(0,i.length-1).concat([1])):r.push(i)}if(e=_I(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=_I(t,this.feedOutputNames,r,!1,"target"),QH(e,t,null),e6(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!==0)throw new V(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,a,r=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,r,s);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let u=B2(a,this.outputNames);l=[];for(let p=0;p<u.length;++p)l.push(await V2(o[p],null,u[p]))}return[i,o,l]}testLoop(e,t,n,a=0,r){return O(()=>{let s=this.checkNumSamples(t,n,r,"steps"),i=[];if(a>0)throw new ze("Verbose mode is not implemented yet.");if(r!=null)throw new ze("steps mode in testLoop() is not implemented yet");{let o=hx(s,n),l=qe(Ua(0,s));for(let u=0;u<o.length;++u){let p=o[u][0],d=o[u][1],c=ri(l,p,d-p),h=Hx(t,c),m=e(h);if(u===0)for(let f=0;f<m.length;++f)i.push(ve(0));for(let f=0;f<m.length;++f){let g=m[f];i[f]=X(i[f],z(d-p,g))}}for(let u=0;u<i.length;++u)i[u]=he(i[u],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let a=e[n],r=a;if(fI(e,a)>1){let s=fI(e.slice(0,n),a);r+=`_${s}`}t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let l=[];for(let c=0;c<this.inputs.length;++c)l.push({key:this.inputs[c],value:n[c]});let u=new Cl(l),p=tc(this.outputs,u,{training:!0}),d;for(let c=0;c<this.lossFunctions.length;++c){let h=this.lossFunctions[c],m=h(a[c],p[c]);r[c]!=null&&(m=HH(m,r[c]));let f=Ct(m);t.push(f),c===0?d=m:d=X(d,m)}for(let c=0;c<this.metricsTensors.length;++c){let h;if(this.outputs.length>1&&c<this.outputs.length)h=t[c];else{let m=this.metricsTensors[c][0],f=this.metricsTensors[c][1];h=Ct(m(a[f],p[f]))}Ht(h),s.push(h)}return d=Ct(d),this.calculateLosses().forEach(c=>{d=X(d,c)}),d},o=this.collectedTrainableWeights.map(l=>l.read());return[this.optimizer_.minimize(i,!0,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>O(()=>{let t=[],n,a=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:a[l]});let i=new Cl(s),o=tc(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let u=this.lossFunctions[l],p=Ct(u(r[l],o[l]));l===0?n=p:n=X(n,p),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let u=this.metricsTensors[l][0],p=this.metricsTensors[l][1],d=Ct(u(r[p],o[p]));t.push(d)}return t})}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");this.isTraining=!0;let a,r,s,i,o,l,u,p,d;try{let c=n.batchSize==null?32:n.batchSize;dx(c);let h=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,!1,c);a=h[0],r=h[1],d=h[2];let m=!1,f;if(n.validationData!=null&&n.validationData.length>0){if(m=!0,n.validationData.length===2)o=n.validationData[0],l=n.validationData[1];else throw n.validationData.length===3?new ze("validationData including sample weights is not supported yet."):new V(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let N=await this.standardizeUserData(o,l,null,null,!0,c);u=N[0],p=N[1],f=u.concat(p)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){m=!0;let N=Math.floor(a[0].shape[0]*(1-n.validationSplit)),C=a[0].shape[0];u=Xp(a,N,C),s=a,a=Xp(a,0,N),p=Xp(r,N,C),i=r,r=Xp(r,0,N),f=u.concat(p)}else n.validationSteps!=null&&(m=!0);let g=a.concat(r).concat(d);this.checkTrainableWeightsConsistency();let b=this.makeTrainFunction(),y=this.getDedupedMetricsNames(),x,v;m?(this.makeTestFunction(),x=this.testFunction,v=y.slice().concat(y.map(N=>"val_"+N))):(x=null,f=[],v=y.slice());let I=D2(n.callbacks,n.yieldEvery);return await this.fitLoop(b,g,y,c,n.epochs,n.verbose,I,x,f,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,Pa(a,e),Pa(r,t),Pa(s,e),Pa(i,t),Pa(u,o),Pa(p,l),d!=null&&Ee(d)}}async fitLoop(e,t,n,a,r,s,i,o,l,u,p,d,c,h){a==null&&(a=32),r==null&&(r=1),u==null&&(u=!0),d==null&&(d=0);let m=!1;if(o!=null&&l!=null&&(m=!0),h!=null&&(m=!0,c==null))throw new V("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let f=this.checkNumSamples(t,a,c,"steps_per_epoch"),g;f!=null&&(g=Ua(0,f)),s==null&&(s=1);let{callbackList:b,history:y}=R2(i,s,r,d,f,c,a,m,p);b.setModel(this),this.history=y,await b.onTrainBegin(),this.stopTraining_=!1;for(let x=d;x<r;++x){await b.onEpochBegin(x);let v={};if(c!=null)throw new ze("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new ze("batch shuffling is not implemneted yet");u&&w.shuffle(g);let I=qe(g),N=hx(f,a);for(let C=0;C<N.length;++C){let _={};if(await b.onBatchBegin(C,_),O(()=>{let F=N[C][0],D=N[C][1],$=ri(I,F,D-F);_.batch=C,_.size=D-F;let S=Hx(t,$),M=e(S);for(let B=0;B<n.length;++B){let U=n[B],H=M[B];_[U]=H,Ht(H)}if(C===N.length-1&&m){let B=this.testLoop(o,l,a);for(let U=0;U<n.length;++U){let H=n[U],j=B[U];Ht(j),v["val_"+H]=j}}}),await b.onBatchEnd(C,_),_2(_),this.stopTraining_)break}I.dispose()}if(await b.onEpochEnd(x,v),this.stopTraining_)break}return await b.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return KH(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),a=n[0],r=n[1],s=this.makeTrainFunction()(a.concat(r)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return Ee(s),Pa(n[0],e),Pa(n[1],t),Rn(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,a=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let s=0;s<a.length;++s)n&&!a[s].trainable||t.push({name:a[s].originalName,tensor:r[s]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=Kh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Kh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=kr(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=>kr(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let a of t)if(typeof n[a]=="string")e[a]=kr(n[a]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[kr(Sh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>kr(Sh(e)));{let e={};for(let t in this.metrics)e[t]=kr(Sh(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=Ic(e.optimizer_config),n=Ba(t),a;if(typeof e.loss=="string")a=Zs(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>Zs(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=Zs(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>Zs(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=Zs(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let r=qt.getSaveHandlers(e);if(r.length===0)throw new V(`Cannot find any save handlers for URL '${e}'`);if(r.length>1)throw new V(`Found more than one (${r.length}) save handlers for URL '${e}'`);e=r[0]}if(e.save==null)throw new V("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await qt.encodeWeights(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:n6,generatedBy:`TensorFlow.js tfjs-layers v${v0}`,convertedBy:null};if(t!=null&&t.includeOptimizer&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();let r="optimizer",{data:s,specs:i}=await qt.encodeWeights(await this.optimizer.getWeights(),r);n.specs.push(...i),n.data=qt.concatenateArrayBuffers([n.data,s])}return this.userDefinedMetadata!=null&&(NI(this.userDefinedMetadata,this.name,!0),a.userDefinedMetadata=this.userDefinedMetadata),a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){NI(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Cr.className="Model";ne.registerClass(Cr);var H2=class extends Cr{};H2.className="Functional";ne.registerClass(H2);async function a6(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=Ic(n),r=Ba(a,t);if(e.weightsManifest!=null){let s=await qt.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(o=>o.originalName)),i={};for(let o of r.weights)i[o.originalName]=s[o.originalName];r.loadWeights(i),Ee(s)}return r}async function r6(e,t){if(t==null&&(t={}),typeof e=="string"){let n=qt.getLoadHandlers(e,t);if(n.length===0)n.push(qt.browserHTTPRequest(e,t));else if(n.length>1)throw new V(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return s6(e,void 0,t)}async function s6(e,t,n){if(n==null&&(n={}),e.load==null)throw new V("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),r=a.modelTopology;r.model_config!=null&&(r=r.model_config);let s=n.strict==null?!0:n.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=Ba(Ic(r),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new V("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:p}=i6(a.weightData,a.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&p.length>0&&await o.optimizer.setWeights(p),Ee(u),Ee(p.map(d=>d.tensor))}return o}function i6(e,t){let n=qt.decodeWeights(e,t),a={},r=[];return t.forEach(s=>{s.group==="optimizer"?r.push({name:s.name,tensor:n[s.name]}):a[s.name]=n[s.name]}),{modelWeights:a,optimizerWeights:r}}var Cf=class jx extends Cr{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=t.name!=null?t.name:ff("sequential_"),t.layers!=null)for(let n of t.layers)this.add(n)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new V(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){let n=t instanceof jx||t instanceof Cr,a;if(n){if(a=t,a.outputs.length!==1)throw new V("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(a.inputs.length!==1)throw new V("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(t.inboundNodes.length===0){if(t.batchInputShape==null)throw new V("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let r=S2({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(r)}if(n)this.outputs=a.outputs,this.inputs=a.inputs;else{if(t.inboundNodes.length!==1)throw new V(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(t.inboundNodes[0].outputTensors.length!==1)throw new V("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=I2(this.outputs[0])}this.inboundNodes=[],new Sf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:bi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(r=>r.shape),outputShapes:this.outputs[0].shape})}else{let r=t.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(t),this.outputs=[r],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),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 t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,n){return this.model==null&&this.build(),this.model.call(t,n)}build(t){if(Je(t),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Cr({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(t,n,a=console.log){this.built||this.build(),super.summary(t,n,a)}setWeights(t){this.model==null&&this.build(),this.model.setWeights(t)}evaluate(t,n,a={}){if(!this.built)throw new ar("The model needs to be compiled before being used.");return this.model.evaluate(t,n,a)}async evaluateDataset(t,n){if(!this.built)throw new ar("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,n)}predict(t,n={}){return this.model==null&&this.build(),this.model.predict(t,n)}predictOnBatch(t){return this.model==null&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),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(t){this.model.optimizer=t}async fit(t,n,a={}){if(!this.built)throw new ar("The model needs to be compiled before being used.");return this.model.fit(t,n,a)}async fitDataset(t,n){if(!this.built)throw new ar("The model needs to be compiled before being used.");return this.model.fitDataset(t,n)}async trainOnBatch(t,n){return this.model.trainOnBatch(t,n)}static fromConfig(t,n,a={},r=!1){let s,i={};if(n instanceof Array){if(n[0].className==null||n[0].className==="Merge")throw new V("Legacy serialization format not supported yet.");s=n}else w.assert(n.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=n.layers,delete n.layers,i=n;let o=new t(i);if(!(o instanceof jx))throw new ze(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let l of s){let u=Ba(l,void 0,r);r&&u.setFastWeightInitDuringBuild(!0),o.add(u)}return o}set stopTraining(t){if(this.model==null)throw new V("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(this.model==null)throw new V("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let t=[];for(let n of this.layers){let a={};a.className=n.getClassName(),a.config=n.getConfig(),t.push(a)}return{name:this.name,layers:t}}};Cf.className="Sequential";ne.registerClass(Cf);function o6(e){return new Cr(e)}function l6(e){return new Cf(e)}function q2(e){return S2(e)}function u6(e,t){f0.registerCallbackConstructor(e,t)}var Vn=class extends ne.Serializable{getConfig(){return{}}},j2=class extends Vn{apply(e,t=1){return _G(e,t)}};j2.className="elu";ne.registerClass(j2);var K2=class extends Vn{apply(e){return Jm(e)}};K2.className="selu";ne.registerClass(K2);var X2=class extends Vn{apply(e){return Ke(e)}};X2.className="relu";ne.registerClass(X2);var Y2=class extends Vn{apply(e){return O(()=>cs(6,Ke(e)))}};Y2.className="relu6";ne.registerClass(Y2);var Z2=class extends Vn{apply(e){return e}};Z2.className="linear";ne.registerClass(Z2);var J2=class extends Vn{apply(e){return ha(e)}};J2.className="sigmoid";ne.registerClass(J2);var Q2=class extends Vn{apply(e){return FG(e)}};Q2.className="hardSigmoid";ne.registerClass(Q2);var eC=class extends Vn{apply(e){return Go(e)}};eC.className="softplus";ne.registerClass(eC);var tC=class extends Vn{apply(e){return AG(e)}};tC.className="softsign";ne.registerClass(tC);var nC=class extends Vn{apply(e){return hi(e)}};nC.className="tanh";ne.registerClass(nC);var w0=class extends Vn{apply(e,t=-1){return ja(e,t)}};w0.className="softmax";ne.registerClass(w0);var aC=class extends Vn{apply(e,t=-1){return Hm(e,t)}};aC.className="logSoftmax";ne.registerClass(aC);var rC=class extends Vn{apply(e,t=1){return O(()=>z(ha(z(e,t)),e))}};rC.className="swish";ne.registerClass(rC);var sC=class extends Vn{apply(e){return O(()=>z(e,hi(Go(e))))}};sC.className="mish";ne.registerClass(sC);function hs(e){return e.getClassName()}function mx(e,t={}){return vd(e,ne.SerializationMap.getMap().classNameMap,t,"activation")}function ms(e){if(e==null){let t={};return t.className="linear",t.config={},mx(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},mx(t)}else return e instanceof Vn?e:mx(e)}function k0(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 iC=class extends ne.Serializable{},Nd=class extends iC{constructor(e){super(),k0(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 O(()=>{let t=It([1]);return this.hasL1&&(t=X(t,fe(z(this.l1,Lt(e))))),this.hasL2&&(t=X(t,fe(z(this.l2,kd(e))))),W(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Nd.className="L1L2";ne.registerClass(Nd);function p6(e){return k0(e),new Nd({l1:e!=null?e.l1:null,l2:0})}function c6(e){return k0(e),new Nd({l2:e!=null?e.l2:null,l1:0})}var FI={l1l2:"L1L2"};function ft(e){return Qw(e)}function $I(e,t={}){return vd(e,ne.SerializationMap.getMap().classNameMap,t,"regularizer")}function Nt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in FI?FI[e]:e,config:{}};return $I(t)}else return e instanceof iC?e:$I(e)}var I0=class extends We{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Te(e);let n=Ke(e);return this.maxValue!=null&&(n=an(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};I0.className="ReLU";ne.registerClass(I0);var S0=class extends We{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=Te(e);return ud(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};S0.className="LeakyReLU";ne.registerClass(S0);var N0=class extends We{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=St(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Nt(e.alphaRegularizer),this.alphaConstraint=Yt(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 V(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Je(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a<e.length;++a)n[a]=e[a];this.inputSpec=[new zt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Te(e),fd(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Et(this.alphaInitializer),alphaRegularizer:ft(this.alphaRegularizer),alphaConstraint:Xt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};N0.className="PReLU";ne.registerClass(N0);var T0=class extends We{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new ze(`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=Te(e);return Qu(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};T0.className="ELU";ne.registerClass(T0);var C0=class extends We{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=Te(e);return z(n,re(Tn(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};C0.className="ThresholdedReLU";ne.registerClass(C0);var E0=class extends We{constructor(e){super(e==null?{}:e),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new w0().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){return O(()=>{let n=Te(e),a=t.mask;if(a!=null){let r=z(pe(On(n.shape),re(a,n.dtype)),ve(-1e9));n=X(n,r)}return this.axis instanceof Array?this.axis.length>1?dn(pe(n,cd(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)})}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};E0.className="Softmax";ne.registerClass(E0);function Fl(e,t,n){if(typeof e=="number")return bi(e,t);if(e.length!==t)throw new V(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){let r=e[a];if(!NG(r))throw new V(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`)}return e}function Va(e,t,n,a,r=1){if(e==null)return e;let s=t+(t-1)*(r-1),i;return n==="same"?i=e:i=e-s+1,Math.floor((i+a-1)/a)}function nr(e,t,n,a){if(e==null)return null;if(a==="valid")e=e*t+ds([n-t,0]);else if(a==="same")e=e*t;else throw new V(`Unsupport padding mode: ${a}.`);return e}function _0(e,t){return O(()=>(Rt(t),t==="channelsFirst"?De(e,[0,2,3,1]):e))}function oC(e,t){return O(()=>(Rt(t),t==="channelsFirst"?De(e,[0,2,3,4,1]):e))}function d6(e,t,n,a=1,r="valid",s,i=1){return O(()=>{if(s==null&&(s=Ga()),Rt(s),e.shape.length!==3)throw new V(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new V(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new V(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=De(e,[0,2,1])),r==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=zm(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=Ka(o,n)),o})}function DI(e,t,n,a=[1,1],r="valid",s,i,o=null){return O(()=>{if(s==null&&(s=Ga()),Rt(s),e.rank!==3&&e.rank!==4)throw new V(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new V(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=_0(e,s);if(r==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Vl.conv2d({x:l,filter:t,strides:a,pad:r==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),s==="channelsFirst"&&(l=De(l,[0,3,1,2])),l})}function h6(e,t,n,a=[1,1,1],r="valid",s,i){return O(()=>{if(s==null&&(s=Ga()),Rt(s),e.rank!==4&&e.rank!==5)throw new V(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new V(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=oC(e,s);if(r==="causal")throw new ze("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=nw(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=Ka(o,n)),s==="channelsFirst"&&(o=De(o,[0,4,1,2,3])),o})}var lC=class uC extends We{constructor(t,n){if(super(n),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",uC.verifyArgs(n),this.rank=t,tn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new ze(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Fl(n.kernelSize,t,"kernelSize"),this.strides=Fl(n.strides==null?1:n.strides,t,"strides"),this.padding=n.padding==null?"valid":n.padding,va(this.padding),this.dataFormat=n.dataFormat==null?"channelsLast":n.dataFormat,Rt(this.dataFormat),this.activation=ms(n.activation),this.useBias=n.useBias==null?!0:n.useBias,this.biasInitializer=St(n.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Yt(n.biasConstraint),this.biasRegularizer=Nt(n.biasRegularizer),this.activityRegularizer=Nt(n.activityRegularizer),this.dilationRate=Fl(n.dilationRate==null?1:n.dilationRate,t,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new V(`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 V(`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 V(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(t){if(tr("kernelSize"in t,"required key 'kernelSize' not in config"),typeof t.kernelSize!="number"&&!e0(t.kernelSize,"number",1,3))throw new V(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){let t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:hs(this.activation),useBias:this.useBias,biasInitializer:Et(this.biasInitializer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),biasConstraint:Xt(this.biasConstraint)},n=super.getConfig();return Object.assign(t,n),t}},Ef=class pC extends lC{constructor(t,n){super(t,n),this.kernel=null,pC.verifyArgs(n),this.filters=n.filters,tn(this.filters,"filters"),this.kernelInitializer=St(n.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Yt(n.kernelConstraint),this.kernelRegularizer=Nt(n.kernelRegularizer)}build(t){t=Je(t);let n=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[n]==null)throw new V(`The channel dimension of the input should be defined. Found ${t[n]}`);let a=t[n],r=this.kernelSize.concat([a,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:{[n]:a}}],this.built=!0}call(t,n){return O(()=>{t=Te(t);let a,r=this.bias==null?null:this.bias.read(),s=m2(this.activation.getClassName());if(s!=null&&this.rank===2)a=DI(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)a=d6(t,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)a=DI(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)a=h6(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new ze("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(a=this.activation.apply(a))}return a})}computeOutputShape(t){t=Je(t);let n=[],a=this.dataFormat==="channelsLast"?t.slice(1,t.length-1):t.slice(2);for(let s=0;s<a.length;++s){let i=Va(a[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);n.push(i)}let r=[t[0]];return this.dataFormat==="channelsLast"?(r=r.concat(n),r.push(this.filters)):(r.push(this.filters),r=r.concat(n)),r}getConfig(){let t={filters:this.filters,kernelInitializer:Et(this.kernelInitializer),kernelRegularizer:ft(this.kernelRegularizer),kernelConstraint:Xt(this.kernelConstraint)},n=super.getConfig();return Object.assign(t,n),t}static verifyArgs(t){if(!("filters"in t)||typeof t.filters!="number"||t.filters<1)throw new V(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`)}},_f=class cC extends Ef{constructor(t){super(2,t),cC.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!e0(t.kernelSize,"number",1,2))throw new V(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}};_f.className="Conv2D";ne.registerClass(_f);var Af=class dC extends Ef{constructor(t){super(3,t),dC.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!(Array.isArray(t.kernelSize)&&(t.kernelSize.length===1||t.kernelSize.length===3)))throw new V(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}};Af.className="Conv3D";ne.registerClass(Af);var A0=class extends _f{constructor(e){if(super(e),this.inputSpec=[new zt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Je(e),e.length!==4)throw new V("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 V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new zt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return O(()=>{let n=Te(e);if(n.shape.length!==4)throw new V(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],u=this.kernelSize[0],p=this.kernelSize[1],d=this.strides[0],c=this.strides[1],h=nr(o,d,u,this.padding),m=nr(l,c,p,this.padding),f=[r,h,m,this.filters];this.dataFormat!=="channelsLast"&&(n=De(n,[0,2,3,1]));let g=Wm(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=De(g,[0,3,1,2])),this.bias!=null&&(g=Ka(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Je(e);let t=e.slice(),n,a,r;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3):(n=3,a=1,r=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[a]=nr(t[a],o,s,this.padding),t[r]=nr(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};A0.className="Conv2DTranspose";ne.registerClass(A0);var F0=class extends Af{constructor(e){if(super(e),this.inputSpec=[new zt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Je(e),e.length!==5)throw new V("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 V("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new zt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return O(()=>{let n=Te(e);if(n.shape.length!==5)throw new V(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=a[o],u=a[s],p=a[i],d=this.kernelSize[0],c=this.kernelSize[1],h=this.kernelSize[2],m=this.strides[0],f=this.strides[1],g=this.strides[2],b=nr(l,m,d,this.padding),y=nr(u,f,c,this.padding),x=nr(p,g,h,this.padding),v=[r,b,y,x,this.filters];this.dataFormat!=="channelsLast"&&(n=De(n,[0,2,3,4,1]));let I=aw(n,this.kernel.read(),v,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(I=De(I,[0,4,1,2,3])),this.bias!==null&&(I=Ka(I,this.bias.read(),this.dataFormat)),this.activation!==null&&(I=this.activation.apply(I)),I})}computeOutputShape(e){e=Je(e);let t=e.slice(),n,a,r,s;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3,s=4):(n=4,a=1,r=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],p=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[a]=nr(t[a],u,i,this.padding),t[r]=nr(t[r],p,o,this.padding),t[s]=nr(t[s],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};F0.className="Conv3DTranspose";ne.registerClass(F0);var hC=class extends Ef{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new V("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new V("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 V(`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=St(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Nt(t.depthwiseRegularizer),this.depthwiseConstraint=Yt(t.depthwiseConstraint),this.pointwiseInitializer=St(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Nt(t.pointwiseRegularizer),this.pointwiseConstraint=Yt(t.pointwiseConstraint)}build(e){if(e=Je(e),e.length<this.rank+2)throw new V(`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 V(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],a=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let i=0;i<this.rank;++i)r.push(1);r.push(n*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new zt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return O(()=>{e=Te(e);let n;if(this.rank===1)throw new ze("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=De(e,[0,2,3,1])),n=Es(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Ka(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=De(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=Et(this.depthwiseInitializer),e.pointwiseInitializer=Et(this.pointwiseInitializer),e.depthwiseRegularizer=ft(this.depthwiseRegularizer),e.pointwiseRegularizer=ft(this.pointwiseRegularizer),e.depthwiseConstraint=Xt(this.depthwiseConstraint),e.pointwiseConstraint=Xt(this.pointwiseConstraint),e}};hC.className="SeparableConv";var $0=class extends hC{constructor(e){super(2,e)}};$0.className="SeparableConv2D";ne.registerClass($0);var D0=class mC extends Ef{constructor(t){super(1,t),mC.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){let t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!e0(t.kernelSize,"number",1,1))throw new V(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}};D0.className="Conv1D";ne.registerClass(D0);var R0=class extends We{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 O(()=>{if(e=Te(e),this.dataFormat==="channelsLast"){let n=Ih(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ih(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Ih(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ih(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}};R0.className="Cropping2D";ne.registerClass(R0);var M0=class extends We{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,Rt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,kG(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 O(()=>{let n=Te(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=De(n,[0,2,3,1]);let r=this.size[0]*a[2],s=this.size[1]*a[3],i=this.interpolation==="nearest"?Zn.resizeNearestNeighbor(n,[r,s]):Zn.resizeBilinear(n,[r,s]);return De(i,[0,3,1,2])}else{let r=this.size[0]*a[1],s=this.size[1]*a[2];return this.interpolation==="nearest"?Zn.resizeNearestNeighbor(n,[r,s]):Zn.resizeBilinear(n,[r,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};M0.className="UpSampling2D";ne.registerClass(M0);function m6(e,t,n=[1,1],a="valid",r,s){return O(()=>{r==null&&(r=Ga()),Rt(r);let i=_0(e,r);if(e.rank!==4)throw new V(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new V(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Ns(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=De(i,[0,3,1,2])),i})}var O0=class extends lC{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=St(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Yt(e.depthwiseConstraint),this.depthwiseRegularizer=Nt(e.depthwiseRegularizer)}build(e){if(e=Je(e),e.length<4)throw new V(`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 V(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],a=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return O(()=>{e=Te(e);let n=m6(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Ka(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Va(t,this.kernelSize[0],this.padding,this.strides[0]),s=Va(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,r,s]:[e[0],r,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Et(this.depthwiseInitializer),e.depthwiseRegularizer=ft(this.depthwiseRegularizer),e.depthwiseConstraint=Xt(this.depthwiseRegularizer),e}};O0.className="DepthwiseConv2D";ne.registerClass(O0);function fC(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new V("When inputs is an array, neither initialState or constants should be provided");a!=null&&(n=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(s){return s==null||Array.isArray(s)?s:[s]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function gC(e,t,n,a=!1,r,s,i=!1,o=!1){return O(()=>{let l=t.shape.length;if(l<3)throw new V(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Ua(2,l));if(t=De(t,u),s!=null)throw new ze("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=re(re(r,"bool"),"float32"),r.rank===l-1&&(r=Gt(r,-1)),r=De(r,u)),a&&(t=ba(t,0),r!=null&&(r=ba(r,0)));let p=[],d,c=n,h=t.shape[0],m=dt(t),f;r!=null&&(f=dt(r));for(let b=0;b<h;++b){let y=m[b],x=O(()=>e(y,c));if(r==null)d=x[0],c=x[1];else{let v=O(()=>{let I=f[b],N=pe(ea(I),I),C=X(z(x[0],I),z(c[0],N)),_=c.map((F,D)=>X(z(x[1][D],I),z(F,N)));return{output:C,newStates:_}});d=v.output,c=v.newStates}o&&p.push(d)}let g;return o&&(g=At(p,1)),[d,g,c]})}var Mr=class bC extends We{constructor(t){super(t);let n;if(t.cell==null)throw new V("cell property is missing for the constructor of RNN.");if(Array.isArray(t.cell)?n=new Df({cells:t.cell}):n=t.cell,n.stateSize==null)throw new V("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=n,this.returnSequences=t.returnSequences==null?!1:t.returnSequences,this.returnState=t.returnState==null?!1:t.returnState,this.goBackwards=t.goBackwards==null?!1:t.goBackwards,this._stateful=t.stateful==null?!1:t.stateful,this.unroll=t.unroll==null?!1:t.unroll,this.supportsMasking=!0,this.inputSpec=[new zt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Ua(0,t).map(n=>null)}else return this.states_}setStates(t){this.states_=t}computeOutputShape(t){Bx(t)&&(t=t[0]),t=t;let n=this.cell.stateSize;Array.isArray(n)||(n=[n]);let a=n[0],r;if(this.returnSequences?r=[t[0],t[1],a]:r=[t[0],a],this.returnState){let s=[];for(let i of n)s.push([t[0],i]);return[r].concat(s)}else return r}computeMask(t,n){return O(()=>{Array.isArray(n)&&(n=n[0]);let a=this.returnSequences?n:null;if(this.returnState){let r=this.states.map(s=>null);return[a].concat(r)}else return a})}get states(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,n=[];for(let a=0;a<t;++a)n.push(null);return n}else return this.states_}set states(t){this.states_=t}build(t){if(this.numConstants!=null)throw new ze("Constants support is not implemented in RNN yet.");Bx(t)&&(t=t[0]),t=t;let n=this.stateful?t[0]:null,a=t.slice(2);this.inputSpec[0]=new zt({shape:[n,null,...a]});let r=[t[0]].concat(t.slice(2));this.cell.build(r);let s;if(Array.isArray(this.cell.stateSize)?s=this.cell.stateSize:s=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),s))throw new V(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=s.map(i=>new zt({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(t,n=!1){O(()=>{if(!this.stateful)throw new Xr("Cannot call resetStates() on an RNN Layer that is not stateful.");let a=this.inputSpec[0].shape[0];if(a==null)throw new V("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=>It([a,r])):this.states_=[It([a,this.cell.stateSize])];else if(t==null)Ee(this.states_),this.keptStates!=null&&(Ee(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>It([a,r])):this.states_[0]=It([a,this.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new V(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);n===!0?this.keptStates.push(this.states_.slice()):Ee(this.states_);for(let r=0;r<this.states_.length;++r){let s=t[r],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[r]:this.cell.stateSize,o=[a,i];if(!w.arraysEqual(s.shape,o))throw new V(`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=>Ht(r.clone()))})}apply(t,n){let a=n==null?null:n.initialState,r=n==null?null:n.constants;n==null&&(n={});let s=fC(t,a,r,this.numConstants);t=s.inputs,a=s.initialState,r=s.constants;let i=[],o=[];if(a!=null){n.initialState=a,i=i.concat(a),this.stateSpec=[];for(let l of a)this.stateSpec.push(new zt({shape:l.shape}));o=o.concat(this.stateSpec)}if(r!=null&&(n.constants=r,i=i.concat(r),this.numConstants=r.length),i[0]instanceof Ha){let l=[t].concat(i),u=this.inputSpec.concat(o),p=this.inputSpec;this.inputSpec=u;let d=super.apply(l,n);return this.inputSpec=p,d}else return super.apply(t,n)}call(t,n){return O(()=>{let a=n==null?null:n.mask,r=n==null?null:n.training,s=n==null?null:n.initialState;t=Te(t),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(t));let i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==i)throw new V(`RNN Layer has ${i} 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},l=gC((h,m)=>{let f=this.cell.call([h].concat(m),o);return[f[0],f.slice(1)]},t,s,this.goBackwards,a,null,this.unroll,this.returnSequences),u=l[0],p=l[1],d=l[2];this.stateful&&this.resetStates(d,r);let c=this.returnSequences?p:u;return this.returnState?[c].concat(d):c})}getInitialState(t){return O(()=>{let n=It(t.shape);return n=fe(n,[1,2]),n=wd(n),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(a=>a>1?zx(n,[1,a]):n):this.cell.stateSize>1?[zx(n,[1,this.cell.stateSize])]:[n]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){let t=super.getConfig(),n={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(n.numConstants=this.numConstants);let a=this.cell.getConfig();return this.getClassName()===bC.className&&(n.cell={className:this.cell.getClassName(),config:a}),Object.assign(Object.assign(Object.assign({},a),t),n)}static fromConfig(t,n,a={}){let r=n.cell,s=Ba(r,a);return new t(Object.assign(n,{cell:s}))}};Mr.className="RNN";ne.registerClass(Mr);var Td=class extends We{},Ff=class extends Td{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,tn(this.units,"units"),this.activation=ms(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Nt(e.kernelRegularizer),this.recurrentRegularizer=Nt(e.recurrentRegularizer),this.biasRegularizer=Nt(e.biasRegularizer),this.kernelConstraint=Yt(e.kernelConstraint),this.recurrentConstraint=Yt(e.recurrentConstraint),this.biasConstraint=Yt(e.biasConstraint),this.dropout=Ul([1,ds([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ul([1,ds([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Je(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 O(()=>{if(e=e,e.length!==2)throw new V(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=fs({ones:()=>ea(e),rate:this.dropout,training:a,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=fs({ones:()=>ea(n),rate:this.recurrentDropout,training:a,dropoutFunc:this.dropoutFunc}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=or(z(e,s),this.kernel.read()):r=or(e,this.kernel.read()),this.bias!=null&&(r=Ka(r,this.bias.read())),i!=null&&(n=z(n,i));let o=X(r,or(n,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:hs(this.activation),useBias:this.useBias,kernelInitializer:Et(this.kernelInitializer),recurrentInitializer:Et(this.recurrentInitializer),biasInitializer:Et(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Xt(this.kernelConstraint),recurrentConstraint:Xt(this.recurrentConstraint),biasConstraint:Xt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}};Ff.className="SimpleRNNCell";ne.registerClass(Ff);var P0=class extends Mr{constructor(e){e.cell=new Ff(e),super(e)}call(e,t){return O(()=>{this.cell.dropoutMask!=null&&(Ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return new e(t)}};P0.className="SimpleRNN";ne.registerClass(P0);var $f=class extends Td{constructor(e){if(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",e.resetAfter)throw new V("GRUCell does not support reset_after parameter set to true.");this.units=e.units,tn(this.units,"units"),this.activation=ms(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ms(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Nt(e.kernelRegularizer),this.recurrentRegularizer=Nt(e.recurrentRegularizer),this.biasRegularizer=Nt(e.biasRegularizer),this.kernelConstraint=Yt(e.kernelConstraint),this.recurrentConstraint=Yt(e.recurrentConstraint),this.biasConstraint=Yt(e.biasConstraint),this.dropout=Ul([1,ds([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ul([1,ds([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=Je(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 O(()=>{if(e=e,e.length!==2)throw new V(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,a=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=fs({ones:()=>ea(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=fs({ones:()=>ea(a),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=z(e,r[0]));let u=or(e,this.kernel.read());this.useBias&&(u=Ka(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(a=z(a,s[0]));let p=this.recurrentKernel.read(),[d,c]=Pn(p,[2*this.units,this.units],p.rank-1),h=or(a,d),[m,f,g]=Pn(u,3,u.rank-1),[b,y]=Pn(h,2,h.rank-1);i=this.recurrentActivation.apply(X(m,b)),o=this.recurrentActivation.apply(X(f,y));let x=or(z(o,a),c);l=this.activation.apply(X(g,x));let v=X(z(i,a),z(X(1,yt(i)),l));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:hs(this.activation),recurrentActivation:hs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Et(this.kernelInitializer),recurrentInitializer:Et(this.recurrentInitializer),biasInitializer:Et(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Xt(this.kernelConstraint),recurrentConstraint:Xt(this.recurrentConstraint),biasConstraint:Xt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}};$f.className="GRUCell";ne.registerClass($f);var L0=class extends Mr{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 $f(e),super(e)}call(e,t){return O(()=>{this.cell.dropoutMask!=null&&(Ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};L0.className="GRU";ne.registerClass(L0);var Cd=class extends Td{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,tn(this.units,"units"),this.activation=ms(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ms(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=St(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Nt(e.kernelRegularizer),this.recurrentRegularizer=Nt(e.recurrentRegularizer),this.biasRegularizer=Nt(e.biasRegularizer),this.kernelConstraint=Yt(e.kernelConstraint),this.recurrentConstraint=Yt(e.recurrentConstraint),this.biasConstraint=Yt(e.biasConstraint),this.dropout=Ul([1,ds([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ul([1,ds([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=Je(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let a;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,s=this.units;a=new(t=class extends $a{apply(i,o){let l=r.apply([s]),u=new bf().apply([s]),p=r.apply([s*2]);return bI(bI(l,u),p)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return O(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new V(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=fs({ones:()=>ea(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=fs({ones:()=>ea(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,p;0<this.dropout&&this.dropout<1&&(e=z(e,s[0]));let d=or(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=z(a,i[0])),d=X(d,or(a,this.recurrentKernel.read())),this.useBias&&(d=Ka(d,this.bias.read()));let[c,h,m,f]=Pn(d,4,d.rank-1);o=this.recurrentActivation.apply(c),l=this.recurrentActivation.apply(h),u=X(z(l,r),z(o,this.activation.apply(m))),p=this.recurrentActivation.apply(f);let g=z(p,this.activation.apply(u));return[g,g,u]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:hs(this.activation),recurrentActivation:hs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Et(this.kernelInitializer),recurrentInitializer:Et(this.recurrentInitializer),biasInitializer:Et(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:ft(this.kernelRegularizer),recurrentRegularizer:ft(this.recurrentRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Xt(this.kernelConstraint),recurrentConstraint:Xt(this.recurrentConstraint),biasConstraint:Xt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}};Cd.className="LSTMCell";ne.registerClass(Cd);var z0=class extends Mr{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 Cd(e),super(e)}call(e,t){return O(()=>{this.cell.dropoutMask!=null&&(Ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};z0.className="LSTM";ne.registerClass(z0);var Df=class extends Td{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 O(()=>{e=e;let n=e.slice(1),a=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?a.push(n.splice(0,i.stateSize.length)):a.push(n.splice(0,1));a.reverse();let r=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];n=a[i],i===0?s=[e[0]].concat(n):s=[s[0]].concat(n),s=o.call(s,t),r.push(s.slice(1))}n=[];for(let i of r.slice().reverse())n.push(...i);return[s[0]].concat(n)})}build(e){Bx(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,a)=>{ai(`RNNCell_${a}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=a=>({className:a.getClassName(),config:a.getConfig()}),n={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),n)}static fromConfig(e,t,n={}){let a=[];for(let r of t.cells)a.push(Ba(r,n));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return Vx(e)}setWeights(e){let t=[];for(let n of this.cells){let a=n.weights.length,r=e.splice(a);for(let s=0;s<n.weights.length;++s)t.push([n.weights[s],r[s]])}u0(t)}};Df.className="StackedRNNCells";ne.registerClass(Df);function fs(e){let{ones:t,rate:n,training:a=!1,count:r=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),n):w2(t(),n),o=()=>Id(i,t,a);return!r||r<=1?Ht(o().clone()):Array(r).fill(void 0).map(o).map(l=>Ht(l.clone()))}var f6=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n},yC=class extends Mr{constructor(e){if(e.unroll)throw new ze("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ze("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new zt({ndim:5})]}call(e,t){return O(()=>{if(this.cell.dropoutMask!=null&&(Ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new V("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return O(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=It(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){O(()=>{if(!this.stateful)throw new Xr("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)];if(n[0]==null)throw new V("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(()=>It(r)):this.states_=[It(r)];else if(e==null)Ee(this.states_),this.keptStates!=null&&(Ee(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>It(r)):this.states_[0]=It(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`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()):Ee(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=r;if(!w.arraysEqual(i.shape,o))throw new V(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>Ht(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:a,padding:r,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],p=Va(l,a[0],r,s[0],i[0]),d=Va(u,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,p,d]:[p,d,n]]}};yC.className="ConvRNN2D";var Rf=class extends Cd{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,tn(this.filters,"filters"),this.kernelSize=Fl(n,2,"kernelSize"),this.kernelSize.forEach(o=>tn(o,"kernelSize")),this.strides=Fl(a||1,2,"strides"),this.strides.forEach(o=>tn(o,"strides")),this.padding=r||"valid",va(this.padding),this.dataFormat=s||"channelsLast",Rt(this.dataFormat),this.dilationRate=Fl(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>tn(o,"dilationRate"))}build(e){var t;e=Je(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[n]}`);let a=e[n],r=4,s=this.kernelSize.concat([a,this.filters*r]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;o=new(t=class extends $a{apply(p,d){let c=l.apply([u]),h=On([u]),m=l.apply([u*2]);return t0([c,h,m])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return O(()=>{if(e.length!==3)throw new V(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,a=e[0],r=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=fs({ones:()=>ea(a),rate:this.dropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(Z,J,ee)=>!J||!J[ee]?Z:z(J[ee],Z),u=l(a,o,0),p=l(a,o,1),d=l(a,o,2),c=l(a,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=fs({ones:()=>ea(r),rate:this.recurrentDropout,training:n,count:i,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,m=l(r,h,0),f=l(r,h,1),g=l(r,h,2),b=l(r,h,3),y=3,[x,v,I,N]=Pn(this.kernel.read(),i,y),[C,_,F,D]=this.useBias?Pn(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,C,this.padding),p=this.inputConv(p,v,_,this.padding),d=this.inputConv(d,I,F,this.padding),c=this.inputConv(c,N,D,this.padding);let[$,S,M,B]=Pn(this.recurrentKernel.read(),i,y);m=this.recurrentConv(m,$),f=this.recurrentConv(f,S),g=this.recurrentConv(g,M),b=this.recurrentConv(b,B);let U=this.recurrentActivation.apply(X(u,m)),H=this.recurrentActivation.apply(X(p,f)),j=X(z(H,s),z(U,this.activation.apply(X(d,g)))),K=z(this.recurrentActivation.apply(X(c,b)),this.activation.apply(j));return[K,K,j]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=f6(e,["units"]),a={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),a)}inputConv(e,t,n,a){let r=$t(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Ka(r,n,this.dataFormat):r}recurrentConv(e,t){return $t(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Rf.className="ConvLSTM2DCell";ne.registerClass(Rf);var W0=class extends yC{constructor(e){let t=new Rf(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}};W0.className="ConvLSTM2D";ne.registerClass(W0);var Mf=class extends We{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let a=0;a<this.noiseShape.length;++a)n.push(this.noiseShape[a]==null?t[a]:this.noiseShape[a]);return n}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,r=this.getNoiseShape(n);return Id(()=>w2(n,this.rate,r,this.seed),()=>n,a)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Mf.className="Dropout";ne.registerClass(Mf);var B0=class extends Mf{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};B0.className="SpatialDropout1D";ne.registerClass(B0);var V0=class extends We{constructor(e){if(super(e),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,tn(this.units,"units"),this.activation=ms(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=St(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=St(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Yt(e.kernelConstraint),this.biasConstraint=Yt(e.biasConstraint),this.kernelRegularizer=Nt(e.kernelRegularizer),this.biasRegularizer=Nt(e.biasRegularizer),this.activityRegularizer=Nt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Je(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=Je(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e),a=m2(this.activation.getClassName()),r;return a!=null?r=or(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=or(n,this.kernel.read()),this.bias!=null&&(r=Ka(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:hs(this.activation),useBias:this.useBias,kernelInitializer:Et(this.kernelInitializer),biasInitializer:Et(this.biasInitializer),kernelRegularizer:ft(this.kernelRegularizer),biasRegularizer:ft(this.biasRegularizer),activityRegularizer:ft(this.activityRegularizer),kernelConstraint:Xt(this.kernelConstraint),biasConstraint:Xt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};V0.className="Dense";ne.registerClass(V0);var U0=class extends We{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Je(e);for(let t of e.slice(1))if(t==null)throw new V(`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],rs(e,1)]}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r<n.rank;++r)a.push(r);a.push(1),n=De(n,a)}return EG(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};U0.className="Flatten";ne.registerClass(U0);var G0=class extends We{constructor(e){super(e),this.supportsMasking=!0,this.activation=ms(e.activation)}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e);return this.activation.apply(n)})}getConfig(){let e={activation:hs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};G0.className="Activation";ne.registerClass(G0);var H0=class extends We{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 O(()=>(e=Te(e),TG(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};H0.className="RepeatVector";ne.registerClass(H0);var q0=class extends We{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",a=t.slice(),r=1,s=null;for(let o=0;o<a.length;++o){let l=a[o];if(this.isUnknown(l))if(s===null)s=o;else throw new V("Can only specifiy one unknown dimension.");else r*=l}let i=rs(e);if(s!==null){if(r===0||i%r!==0)throw new V(n);a[s]=i/r}else if(i!==r)throw new V(n);return a}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e),a=n.shape,r=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return W(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};q0.className="Reshape";ne.registerClass(q0);var j0=class extends We{constructor(e){if(super(e),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=Ua(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 zt({ndim:this.dims.length+1})]}computeOutputShape(e){e=Je(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return De(Te(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};j0.className="Permute";ne.registerClass(j0);var K0=class extends We{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=Te(e);return yc(fi(n,this.maskValue),-1)}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e),a=yc(fi(n,this.maskValue),-1,!0);return z(n,re(a,n.dtype))})}};K0.className="Masking";ne.registerClass(K0);var X0=class extends We{constructor(e){if(super(e),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(it(e.inputLength))}this.inputDim=e.inputDim,tn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,tn(this.outputDim,"outputDim"),this.embeddingsInitializer=St(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Nt(e.embeddingsRegularizer),this.activityRegularizer=Nt(e.activityRegularizer),this.embeddingsConstraint=Yt(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 O(()=>this.maskZero?(e=Te(e),fi(e,je(e))):null)}computeOutputShape(e){if(e=Je(e),this.inputLength==null)return[...e,this.outputDim];let t=it(this.inputLength);if(t.length!==e.length-1)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a<t.length;++a){let r=t[a],s=e[a+1];if(r!=null&&s!=null&&r!==s)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);r==null&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return O(()=>{this.invokeCallHook(e,t);let n=Te(e);n.dtype!=="int32"&&(n=ir(n,"int32"));let a=v2(this.embeddings.read(),W(n,[n.size]));return W(a,Je(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Et(this.embeddingsInitializer),embeddingsRegularizer:ft(this.embeddingsRegularizer),activityRegularizer:ft(this.activityRegularizer),embeddingsConstraint:Xt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};X0.className="Embedding";ne.registerClass(X0);var Yo=class extends We{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new ze}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let a=0;a<t.length;++a){let r=e[e.length-t.length+a],s=t[a];if(r==null||s==null||r<0||s<0)n.push(null);else if(r===1)n.push(s);else if(s===1)n.push(r);else{if(r!==s)throw new V("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Je(e)]),e=e,e.length<2)throw new V(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let r of e)r!=null&&r[0]!==null&&t.push(r[0]);if(t=as(t),t.length>1)throw new V(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}let a=e.map(r=>r.length);e.indexOf(null)===-1&&as(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return O(()=>{if(e=e,this.reshapeRequired){let n=[],a=e.map(r=>r.rank);if(a.indexOf(null)===-1){let r=ds(a);for(let s of e){let i=s.rank;for(let o=0;o<r-i;++o)s=wd(s,1);n.push(s)}return this.mergeFunction(n)}else{let r=!1;for(let o of e){let l=o.rank;if(l==null){let u=o.shape,p=u[0],d=u.slice(1).concat([p]),c=W(o,[p].concat(rs(u.slice(1))));c=De(c,[1,0]),c=W(c,d),n.push(c),r=!0}else if(l>1){let u=Ua(1,l).concat([0]);n.push(De(o,u)),r=!0}else n.push(o)}let s=this.mergeFunction(n),i=s.rank;if(r){if(i==null){let o=s.shape,l=o.length,u=o[l-1],p=[u].concat(o.slice(0,o.length-1));s=W(De(W(s,[-1,u]),[1,0]),p)}else if(i>1){let o=[i-1].concat(Ua(0,i-1));s=De(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a<e.length;++a){let r=e[a]==null?null:e[a].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(let a of e)a!=null&&a[0]!==null&&n.push(a[0]);return n=as(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return O(()=>{if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an Array");if(!Array.isArray(e))throw new V("`inputs` should be an Array");if(t.length!==e.length)throw new V(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:Gt(a,0));let n=t[0];for(let a=1;a<t.length-1;++a)n=_a(n,t[a]);return n})}},Y0=class extends Yo{constructor(e){super(e)}mergeFunction(e){return O(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return t})}};Y0.className="Add";ne.registerClass(Y0);var Z0=class extends Yo{constructor(e){super(e)}mergeFunction(e){return O(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=z(t,e[n]);return t})}};Z0.className="Multiply";ne.registerClass(Z0);var J0=class extends Yo{constructor(e){super(e)}mergeFunction(e){return O(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return z(1/e.length,t)})}};J0.className="Average";ne.registerClass(J0);var Q0=class extends Yo{constructor(e){super(e)}mergeFunction(e){return O(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=dr(t,e[n]);return t})}};Q0.className="Maximum";ne.registerClass(Q0);var e1=class extends Yo{constructor(e){super(e)}mergeFunction(e){return O(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=cs(t,e[n]);return t})}};e1.className="Minimum";ne.registerClass(e1);var t1=class extends Yo{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 V("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let a of e)if(a!=null){t=!1;break}if(t)return;let n=[];for(let a=0;a<e.length;++a){let r=e[a].slice();r.splice(this.axis,1);let s=!1;for(let i of n)if(w.arraysEqual(i,r)){s=!0;break}s||n.push(r)}if(n.length>1)throw new V("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return O(()=>t0(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new V("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),a=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[a]==null||r[a]==null){n[a]=null;break}n[a]+=r[a]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new V("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new V(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return O(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s<e.length;++s)t[s]==null?a.push(re(ea(e[s]),"bool")):t[s].rank<e[s].rank?a.push(Gt(t[s],-1)):a.push(t[s]);let r=et(a,this.axis);return Lm(r,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};t1.className="Concatenate";ne.registerClass(t1);function Yp(e,t){for(;e<0;)e+=t;return e}function g6(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new ze("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 ze("batchDot is not implemented for complex64-type Tensors yet.");let a=e.shape.length,r=t.shape.length;n==null&&(n=[a-1,r-2]);let s=n;return O(()=>{let i;if(a>r){i=a-r;let l=[];for(let u=0;u<i;++u)l.push(1);t=W(t,t.shape.concat(l))}else if(r>a){i=r-a;let l=[];for(let u=0;u<i;++u)l.push(1);e=W(e,e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=fe(z(e,t),s[0]):o=fe(z(De(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,u=s[1]===t.shape.length-1;o=$e(e,t,l,u)}if(i>0){let l;a>r?l=a+r-3:l=a-1;let u=[];for(let p=l;p<l+i;++p)u.push(p);o=_s(o,u)}return o.shape.length===1&&(o=Gt(o,1)),o})}var n1=class extends Yo{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 ze("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);if(t[a[0]]!==n[a[1]])throw new V(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new V(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((r,s)=>Yp(r,e[s].shape.length)):a=[Yp(this.axes,t.shape.length),Yp(this.axes,n.shape.length)],this.normalize&&(t=tm(t,a[0]),n=tm(n,a[1])),g6(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Yp(this.axes,e.length),Yp(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 ze("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);t.splice(a[0],1),n.splice(a[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};n1.className="Dot";ne.registerClass(n1);var a1=class extends We{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 O(()=>{this.invokeCallHook(e,t);let n=Te(e);return Id(()=>X(gf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};a1.className="GaussianNoise";ne.registerClass(a1);var r1=class extends We{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 O(()=>{this.invokeCallHook(e,t);let n=Te(e);return this.rate>0&&this.rate<1?Id(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return z(n,gf(n.shape,1,a))},()=>n,t.training||!1):n})}};r1.className="GaussianDropout";ne.registerClass(r1);var s1=class extends We{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Te(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 O(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Id(()=>{let a=Te(e),r=-1.6732632423543772*1.0507009873554805,s=$r(Cs(n),this.rate);s=ir(s,"float32");let i=((1-this.rate)*(1+this.rate*r**2))**-.5,o=-i*r*this.rate,l=X(z(a,s),z(X(s,-1),r));return X(z(l,i),o)},()=>Te(e),t.training||!1)}return e})}};s1.className="AlphaDropout";ne.registerClass(s1);function Sc(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=qv(e,t,n,a,r,s);else if(e.rank===3)i=jv(e,t,n,a,r,s);else if(e.rank===4)i=Kv(e,t,n,a,r,s);else throw new ze(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function b6(e,t,n,a,r=.001){return O(()=>{let s=hd(e,a),i=s.mean,o=s.variance;return[Sc(e,i,o,n,t,r),i,o]})}function y6(e,t,n,a,r=.001){return O(()=>{let s=hd(e,a),i=s.mean,o=s.variance,l=[];for(let h of Ua(0,e.rank))a.indexOf(h)!==-1?l.push(1):l.push(e.shape[h]);let u=W(i,l),p=W(o,l),d=t==null?null:W(t,l),c=n==null?null:W(n,l);return[Sc(e,u,p,c,d,r),i,o]})}function x6(e,t,n,a,r=.001){return w.arraysEqual(a.slice().sort(),Ua(0,e.rank-1))?b6(e,t,n,a,r):y6(e,t,n,a,r)}var i1=class extends We{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=St(e.betaInitializer||"zeros"),this.gammaInitializer=St(e.gammaInitializer||"ones"),this.movingMeanInitializer=St(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=St(e.movingVarianceInitializer||"ones"),this.betaConstraint=Yt(e.betaConstraint),this.gammaConstraint=Yt(e.gammaConstraint),this.betaRegularizer=Nt(e.betaRegularizer),this.gammaRegularizer=Nt(e.gammaRegularizer)}build(e){e=Je(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new V(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new zt({ndim:e.length,axes:{[t]:n}})];let a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return O(()=>{let n=t.training==null?!1:t.training,a=Te(e),r=a.shape,s=r.length,i=Ua(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=bi(1,s);l[o]=r[o];let u=i.slice();u.sort();let p=!w.arraysEqual(u,Ua(0,s).slice(0,s-1)),d=()=>{if(p){let g=W(this.movingMean.read(),l),b=W(this.movingVariance.read(),l),y=this.center?W(this.beta.read(),l):null,x=this.scale?W(this.gamma.read(),l):null;return Sc(a,g,b,y,x,this.epsilon)}else return Sc(a,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[c,h,m]=x6(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,b,y)=>{O(()=>{let x=1-y,v=g.read(),I=z(pe(v,b),x);g.write(pe(v,I))})};return f(this.movingMean,h,this.momentum),f(this.movingVariance,m,this.momentum),c})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Et(this.betaInitializer),gammaInitializer:Et(this.gammaInitializer),movingMeanInitializer:Et(this.movingMeanInitializer),movingVarianceInitializer:Et(this.movingVarianceInitializer),betaRegularizer:ft(this.betaRegularizer),gammaRegularizer:ft(this.gammaRegularizer),betaConstraint:Xt(this.betaConstraint),gammaConstraint:Xt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};i1.className="BatchNormalization";ne.registerClass(i1);var o1=class extends We{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=St(e.betaInitializer||"zeros"),this.gammaInitializer=St(e.gammaInitializer||"ones"),this.betaRegularizer=Nt(e.betaRegularizer),this.gammaRegularizer=Nt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Je(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r<this.axis.length;++r)this.axis[r]<0&&(this.axis[r]+=t);for(let r of this.axis)if(r<0||r>=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==as(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),a=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,a):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,a):this.beta=null,this.built=!0}call(e,t){let n=Te(e),a=n.shape,r=a.length;return O(()=>{let{mean:s,variance:i}=hd(n,this.axis,!0),o=bi(1,r);for(let h of this.axis)o[h]=a[h];let l=h=>h!=null&&h.shape.length!==r?W(h,o):h,u=this.scale?l(this.gamma.read()):null,p=this.center?l(this.beta.read()):null,d=[],c=[];for(let h=0;h<r;++h)this.axis.indexOf(h)!==-1?(d.push(a[h]),c.push(1)):(d.push(1),c.push(a[h]));return s=Mn(s,d),i=Mn(i,d),u!=null&&(u=Mn(u,c)),p!=null&&(p=Mn(p,c)),Sc(n,s,i,p,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Et(this.betaInitializer),gammaInitializer:Et(this.gammaInitializer),betaRegularizer:ft(this.betaRegularizer),gammaRegularizer:ft(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};o1.className="LayerNormalization";ne.registerClass(o1);function v6(e,t,n){return O(()=>{if(e.rank!==4)throw new V(`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 V("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=Ga()),n!=="channelsLast"&&n!=="channelsFirst")throw new V(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return n==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],xa(e,a)})}var l1=class extends We{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Ga():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 V(`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 V(`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 V(`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 zt({ndim:4})]}computeOutputShape(e){e=Je(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 O(()=>v6(Te(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};l1.className="ZeroPadding2D";ne.registerClass(l1);function Of(e,t,n,a,r,s){return O(()=>{Rt(r),g2(s),va(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=Ga()),s==null&&(s="max"),e=_0(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Dt(e,t,n,o):i=ya(e,t,n,o),r==="channelsFirst"&&(i=De(i,[0,3,1,2])),i})}function xC(e,t,n,a,r,s){return O(()=>{Rt(r),g2(s),va(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=Ga()),s==null&&(s="max"),e=oC(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=xw(e,t,n,o):i=Hv(e,t,n,o),r==="channelsFirst"&&(i=De(i,[0,4,1,2,3])),i})}var vC=class extends We{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new V(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(tn(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 V(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,va(this.padding),this.inputSpec=[new zt({ndim:3})]}computeOutputShape(e){e=Je(e);let t=Va(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return O(()=>{this.invokeCallHook(e,t),e=wd(Te(e),2);let n=this.poolingFunction(Te(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return _s(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},u1=class extends vC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),Of(e,t,n,a,r,"max")}};u1.className="MaxPooling1D";ne.registerClass(u1);var p1=class extends vC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),Of(e,t,n,a,r,"avg")}};p1.className="AveragePooling1D";ne.registerClass(p1);var wC=class extends We{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new V(`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];tn(this.poolSize,"poolSize"),tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),va(this.padding),this.inputSpec=[new zt({ndim:4})]}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Va(t,this.poolSize[0],this.padding,this.strides[0]),n=Va(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 O(()=>(this.invokeCallHook(e,t),this.poolingFunction(Te(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}},c1=class extends wC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),Of(e,t,n,a,r,"max")}};c1.className="MaxPooling2D";ne.registerClass(c1);var d1=class extends wC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),Of(e,t,n,a,r,"avg")}};d1.className="AveragePooling2D";ne.registerClass(d1);var kC=class extends We{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new V(`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];tn(this.poolSize,"poolSize"),tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),va(this.padding),this.inputSpec=[new zt({ndim:5})]}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Va(t,this.poolSize[0],this.padding,this.strides[0]),n=Va(n,this.poolSize[1],this.padding,this.strides[1]),a=Va(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,a]:[e[0],t,n,a,e[4]]}call(e,t){return O(()=>(this.invokeCallHook(e,t),this.poolingFunction(Te(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}},h1=class extends kC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),xC(e,t,n,a,r,"max")}};h1.className="MaxPooling3D";ne.registerClass(h1);var m1=class extends kC{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Rt(r),va(a),xC(e,t,n,a,r,"avg")}};m1.className="AveragePooling3D";ne.registerClass(m1);var IC=class extends We{constructor(e){super(e),this.inputSpec=[new zt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ze}},f1=class extends IC{constructor(e){super(e||{})}call(e,t){return O(()=>{let n=Te(e);return Ct(n,1)})}};f1.className="GlobalAveragePooling1D";ne.registerClass(f1);var g1=class extends IC{constructor(e){super(e||{})}call(e,t){return O(()=>{let n=Te(e);return ma(n,1)})}};g1.className="GlobalMaxPooling1D";ne.registerClass(g1);var SC=class extends We{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),this.inputSpec=[new zt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ze}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},b1=class extends SC{call(e,t){return O(()=>{let n=Te(e);return this.dataFormat==="channelsLast"?Ct(n,[1,2]):Ct(n,[2,3])})}};b1.className="GlobalAveragePooling2D";ne.registerClass(b1);var y1=class extends SC{call(e,t){return O(()=>{let n=Te(e);return this.dataFormat==="channelsLast"?ma(n,[1,2]):ma(n,[2,3])})}};y1.className="GlobalMaxPooling2D";ne.registerClass(y1);var NC=class extends We{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let a=t.layer,r=Ba(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},x1=class extends NC{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=Je(e),e.length<3)throw new V(`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=Je(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return O(()=>(e=Te(e),gC((n,a)=>[Te(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};x1.className="TimeDistributed";ne.registerClass(x1);function w6(e){Ko(wG,"BidirectionalMergeMode",e)}var k6="concat",v1=class extends NC{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Ba(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=Ba(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?k6:e.mergeMode,w6(this.mergeMode),e.weights)throw new ze("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,a,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,a=[n]):this.mergeMode==null?a=[n,n.slice()]:a=[n],this.returnState?this.mergeMode==null?a.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):Rn(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=fC(e,n,a,this.numConstants);if(e=r.inputs,n=r.initialState,a=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(n!=null){let l=n.length;if(l%2>0)throw new V("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);let u=n.map(p=>new zt({shape:p.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(a!=null)throw new ze("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Ha;for(let l of s)if(l instanceof Ha!==o)throw new V("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),u=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=u;let d=super.apply(l,t);return this.inputSpec=p,d}else return super.apply(e,t)}call(e,t){return O(()=>{let n=t.initialState,a,r;if(n==null)a=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let o=n.slice(0,n.length/2),l=n.slice(n.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(r.slice(1))),a=a[0],r=r[0]),this.returnSequences&&(r=ba(r,1));let i;return this.mergeMode==="concat"?i=t0([a,r]):this.mergeMode==="sum"?i=X(a,r):this.mergeMode==="ave"?i=z(.5,X(a,r)):this.mergeMode==="mul"?i=z(a,r):this.mergeMode==null&&(i=[a,r]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){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 a=this.forwardLayer.states.map(r=>null);return Array.isArray(n)?n.concat(a).concat(a):[n].concat(a).concat(a)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=Ba(t.layer);if(delete t.layer,t.numConstants!=null)throw new ze("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};v1.className="Bidirectional";ne.registerClass(v1);var w1=class extends We{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){let e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return O(()=>(e=Te(e),e.dtype!=="float32"&&(e=ir(e,"float32")),X(z(e,this.scale),this.offset)))}};w1.className="Rescaling";ne.registerClass(w1);var{resizeBilinear:I6,cropAndResize:S6}=Zn,k1=class extends We{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,a,r,s,i,o){return O(()=>{let l,u=!1,p=t/s,d=n/i,c=(a+t)/s,h=(r+n)/i,m=[p,d,c,h],f=[];e.rank===3?(u=!0,l=At([e])):l=e;for(let x=0;x<l.shape[0];x++)f.push(m);let g=bn(f,[f.length,4]),b=gi(0,f.length,1,"int32"),y=S6(l,g,b,[a,r],"nearest");return ir(u?Te(dt(y)):y,o)})}upsize(e,t,n,a){return O(()=>{let r=I6(e,[t,n]);return ir(r,a)})}call(e,t){return O(()=>{let n=Te(e),a=n.dtype,r=n.shape,s=r[r.length-3],i=r[r.length-2],o=0;s!==this.height&&(o=Math.floor((s-this.height)/2));let l=0;return i!==this.width&&(l=Math.floor((i-this.width)/2),l===0&&(l=1)),o>=0&&l>=0?this.centerCrop(n,o,l,this.height,this.width,s,i,a):this.upsize(e,this.height,this.width,a)})}getConfig(){let e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Je(e);let t=e.length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}};k1.className="CenterCrop";ne.registerClass(k1);function N6(e,t,n,a){let r=Te(e);if(r.dtype!=="int32"&&(r=ir(r,"int32")),t==="int")return r;let s=r.shape;if(r.rank===0&&(r=Gt(r,-1)),t==="oneHot"&&r.shape[r.shape.length-1]!==1&&(r=Gt(r,-1)),r.rank>2)throw new V(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${r.rank}.`);let i=["multiHot","oneHot"].includes(t),o=r,l;if(typeof a!="undefined"&&t==="count"?l=Xh(o,a,n,i):l=Xh(o,[],n,i),t!=="tfIdf")return l;if(a)return z(l,a);throw new V("When outputMode is 'tfIdf', weights must be provided.")}var I1=class extends We{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){let e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=Je(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return O(()=>{e=Te(e),e.dtype!=="int32"&&(e=ir(e,"int32"));let n;if(typeof t.countWeights!="undefined"){if(this.outputMode!=="count")throw new V(`countWeights is not used when outputMode !== count.
|
|
Received countWeights=${t.countWeights}`);n=Te(t.countWeights)}let a=ma(e),r=Ol(e),s=Tn(this.numTokens,a).bufferSync().get(0),i=$r(r,0).bufferSync().get(0);if(!(s&&i))throw new V(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return N6(e,this.outputMode,this.numTokens,n)})}};I1.className="CategoryEncoding";ne.registerClass(I1);var T6=["bilinear","nearest"],RI=new Set(T6),S1=class extends We{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(RI.has(e.interpolation))this.interpolation=e.interpolation;else throw new V(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){e=Je(e);let t=e[2];return[this.height,this.width,t]}getConfig(){let e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return O(()=>{let n=[this.height,this.width];if(this.interpolation==="bilinear")return Zn.resizeBilinear(e,n,!this.cropToAspectRatio);if(this.interpolation==="nearest")return Zn.resizeNearestNeighbor(e,n,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...RI]} are supported`)})}};S1.className="Resizing";ne.registerClass(S1);var TC=class{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}};TC.className="RandomSeed";var CC=class extends We{constructor(e){super(e),this.randomGenerator=new TC(e.seed)}getConfig(){let e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}};CC.className="BaseRandomLayer";var C6=["bilinear","nearest"],MI=new Set(C6),N1=class extends CC{constructor(e){super(e);let{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new V(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new V(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new V(`factor cannot have upper bound less than lower bound.
|
|
Got upper bound: ${this.widthUpper}.
|
|
Got lower bound: ${this.widthLower}
|
|
`);if(n)if(MI.has(n))this.interpolation=n;else throw new V(`Invalid interpolation parameter: ${n} is not implemented`)}getConfig(){let e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Je(e);let t=e[2];return[this.imgHeight,-1,t]}call(e,t){return O(()=>{let n=Te(e);this.imgHeight=n.shape[n.shape.length-3];let a=n.shape[n.shape.length-2];this.widthFactor=Cs([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*a;r=Math.round(r);let s=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return Zn.resizeBilinear(e,s);case"nearest":return Zn.resizeNearestNeighbor(e,s);default:throw new Error(`Interpolation is ${this.interpolation}
|
|
but only ${[...MI]} are supported`)}})}};N1.className="RandomWidth";ne.registerClass(N1);function E6(e){return new rp(e)}function _6(e){return new T0(e)}function A6(e){return new I0(e)}function F6(e){return new S0(e)}function $6(e){return new N0(e)}function D6(e){return new E0(e)}function R6(e){return new C0(e)}function M6(e){return new D0(e)}function O6(e){return new _f(e)}function P6(e){return new A0(e)}function L6(e){return new Af(e)}function z6(e){return new F0(e)}function W6(e){return new $0(e)}function B6(e){return new R0(e)}function V6(e){return new M0(e)}function U6(e){return new O0(e)}function G6(e){return new G0(e)}function H6(e){return new V0(e)}function q6(e){return new Mf(e)}function j6(e){return new B0(e)}function K6(e){return new U0(e)}function X6(e){return new H0(e)}function Y6(e){return new q0(e)}function Z6(e){return new j0(e)}function J6(e){return new X0(e)}function Q6(e){return new Y0(e)}function eq(e){return new J0(e)}function tq(e){return new t1(e)}function nq(e){return new Q0(e)}function aq(e){return new e1(e)}function rq(e){return new Z0(e)}function sq(e){return new n1(e)}function iq(e){return new i1(e)}function oq(e){return new o1(e)}function lq(e){return new l1(e)}function T1(e){return new p1(e)}function uq(e){return T1(e)}function pq(e){return T1(e)}function C1(e){return new d1(e)}function cq(e){return C1(e)}function dq(e){return C1(e)}function E1(e){return new m1(e)}function hq(e){return E1(e)}function mq(e){return E1(e)}function fq(e){return new f1(e)}function gq(e){return new b1(e)}function EC(e){return new g1(e)}function _C(e){return new y1(e)}function AC(e){return new u1(e)}function FC(e){return new c1(e)}function bq(e){return new h1(e)}function yq(e){return new L0(e)}function xq(e){return new $f(e)}function vq(e){return new z0(e)}function wq(e){return new Cd(e)}function kq(e){return new P0(e)}function Iq(e){return new Ff(e)}function Sq(e){return new W0(e)}function Nq(e){return new Rf(e)}function Tq(e){return new Mr(e)}function Cq(e){return new Df(e)}function Eq(e){return new v1(e)}function _q(e){return new x1(e)}var Aq=EC,Fq=_C,$q=AC,Dq=FC;function Rq(e){return new a1(e)}function Mq(e){return new r1(e)}function Oq(e){return new s1(e)}function Pq(e){return new K0(e)}function Lq(e){return new w1(e)}function zq(e){return new k1(e)}function Wq(e){return new S1(e)}function Bq(e){return new I1(e)}function Vq(e){return new N1(e)}var $C={};_e($C,{MAPE:()=>Qq,MSE:()=>nj,binaryAccuracy:()=>Uq,binaryCrossentropy:()=>Gq,categoricalAccuracy:()=>qq,categoricalCrossentropy:()=>jq,cosineProximity:()=>Yq,mape:()=>ej,meanAbsoluteError:()=>Zq,meanAbsolutePercentageError:()=>Jq,meanSquaredError:()=>tj,mse:()=>aj,precision:()=>Kq,recall:()=>Xq,sparseCategoricalAccuracy:()=>Hq});function Uq(e,t){return b0(e,t)}function Gq(e,t){return P2(e,t)}function Hq(e,t){return L2(e,t)}function qq(e,t){return y0(e,t)}function jq(e,t){return x0(e,t)}function Kq(e,t){return O2(e,t)}function Xq(e,t){return CH(e,t)}function Yq(e,t){return g0(e,t)}function Zq(e,t){return Nf(e,t)}function Jq(e,t){return sp(e,t)}function Qq(e,t){return sp(e,t)}function ej(e,t){return sp(e,t)}function tj(e,t){return Xo(e,t)}function nj(e,t){return Xo(e,t)}function aj(e,t){return Xo(e,t)}var DC={};_e(DC,{modelFromJSON:()=>a6});var RC={};_e(RC,{l1:()=>sj,l1l2:()=>rj,l2:()=>ij});function rj(e){return new Nd(e)}function sj(e){return p6(e)}function ij(e){return c6(e)}var MC=class extends Gl{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Cr))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Nh(e,t){return e<t}function OI(e,t){return e>t}var OC=class extends MC{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new ze("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=Nh:this.mode==="max"?this.monitorFunc=OI:this.monitor.indexOf("acc")!==-1?this.monitorFunc=OI:this.monitorFunc=Nh,this.monitorFunc===Nh&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Nh?1/0:-1/0}async onEpochEnd(e,t){await Kr(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 oj(e){return new OC(e)}var lj={earlyStopping:oj},uj=G();uj.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var jn;(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_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",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",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"})(jn||(jn={}));var PI;(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={}))})(PI||(PI={}));var _1={};function pj(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};_1[e]=n}function PC(e){return _1[e]}function cj(e){delete _1[e]}function k(e,t,n,a,r){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd,u=o<0?t.inputNames.length+o:o;if(s.type==="tensor")return un(t.inputNames[u],n,a,r);if(s.type==="tensors"){let c=t.inputs.slice(o,l);return t.inputNames.slice(o,l).filter((h,m)=>{var f;return((f=c[m])===null||f===void 0?void 0:f.op)!=="NoOp"}).map(h=>un(h,n,a,r))}let p=un(t.inputNames[u],n,a,r),d=p.dataSync();return s.type==="number"?d[0]:w.toNestedArray(p.shape,d)}let i=t.attrParams[e];return i&&i.value}function un(e,t,n,a){let[r,s]=Xn(e,n);if(a!=null){let o=a.getHashTableHandleByName(r);if(o!=null)return o}let i=n.currentContextIds.find(o=>!!t[im(r,o)]);return i!==void 0?t[im(r,i)][s]:void 0}function LI(e,t,n){return t[im(e,n.currentContextId)]}function Ir(e,t){let[n,a,r]=Xn(e,t);return[im(n,t&&t.currentContextId),a,r]}function im(e,t){return t?`${e}-${t}`:e}function Xn(e,t){if(e==="")return["",0,void 0];let n=t!=null&&t.parseNodeNameCache!=null;if(n){let s=t.parseNodeNameCache.get(e);if(s!=null)return s}let a=e.split(":"),r;if(a.length===1)r=[e,0,void 0];else{let s=a[0],i=a.length===3?a[1]:void 0,o=Number(a[a.length-1]);r=[s,o,i]}return n&&t.parseNodeNameCache.set(e,r),r}function Mh(e,t,n){let a=k("pad",e,t,n);if(a==="explicit"){a=k("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)r[s][0]=a[s*2],r[s][1]=a[s*2+1];return r}return a}function Sr(e){return e.kept?e:sr(e)}var LC={};_e(LC,{json:()=>dj});var dj=[{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}]}],zC={};_e(zC,{json:()=>hj});var hj=[{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:"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}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],WC={};_e(WC,{json:()=>mj});var mj=[{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:"TensorListConcatV2",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"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],BC={};_e(BC,{json:()=>fj});var fj=[{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",defaultValue:.2}]},{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"}]}],VC={};_e(VC,{json:()=>gj});var gj=[{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"}]},{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:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{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:"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:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,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"}]}],UC={};_e(UC,{json:()=>bj});var bj=[{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}]}],GC={};_e(GC,{json:()=>yj});var yj=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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"}]}],HC={};_e(HC,{json:()=>xj});var xj=[{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"}]}],qC={};_e(qC,{json:()=>vj});var vj=[{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"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],jC={};_e(jC,{json:()=>wj});var wj=[{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"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],KC={};_e(KC,{json:()=>kj});var kj=[{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}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}],XC={};_e(XC,{json:()=>Ij});var Ij=[{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:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{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"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}],YC={};_e(YC,{json:()=>Sj});var Sj=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{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"}]}],ZC={};_e(ZC,{json:()=>Nj});var Nj=[{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"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",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"}]},{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"}]}],JC={};_e(JC,{json:()=>Tj});var Tj=[{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}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],QC={};_e(QC,{json:()=>Cj});var Cj=[{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"}]}],eE={};_e(eE,{json:()=>Ej});var Ej=[{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}]}],tE={};_e(tE,{json:()=>_j});var _j=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{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"}]}],nE={};_e(nE,{json:()=>Aj});var Aj=[{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:"EnsureShape",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:[]}],zI=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[LC,zC,WC,BC,VC,UC,GC,HC,qC,jC,KC,XC,YC,ZC,JC,QC,eE,tE,nE],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,a)=>(n[a.tfOpName]=a,n),{})}transformGraph(e,t={}){let n=e.node,a=[],r=[],s=[],i=n.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?a.push(m[f.name]):f.op==="Const"?r.push(m[f.name]):(f.input==null||f.input.length===0)&&s.push(m[f.name]),m),{}),o=[],l=[],u={},p={};t!=null&&(u=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));let d=Object.keys(i);d.forEach(m=>{let f=i[m];f.inputNames.forEach((g,b)=>{let[y,,x]=Ir(g),v=i[y];if(v.outputs!=null){let I=v.outputs.indexOf(x);if(I!==-1){let N=`${y}:${I}`;f.inputNames[b]=N}}f.inputs.push(v),v.children.push(f)})}),Object.keys(p).length===0?d.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(p).forEach(m=>{let[f]=Ir(m),g=i[f];g!=null&&(g.signatureKey=p[m],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(m=>{let[f]=Ir(m),g=i[f];g&&(g.signatureKey=u[m],o.push(g))}):o=a;let c={};e.library!=null&&e.library.function!=null&&(c=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let h={nodes:i,inputs:o,outputs:l,weights:r,placeholders:a,signature:t,functions:c};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=PC(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(a=>a.startsWith("^")?a.slice(1):a),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((a,r)=>(a[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},a),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((a,r)=>{let s=r.type,i;switch(r.type){case"string":i=Kx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Kx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=tv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=tv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=Yx(e.attr,r.tfName,r.defaultValue||0),i===void 0&&r.tfDeprecatedName&&(i=Yx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=ev(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=ev(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=Xx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Xx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=av(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=av(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=Qx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Qx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=nv(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=nv(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=Zx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Zx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=Jx(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=Jx(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=WI(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=WI(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return a[r.name]={value:i,type:s},a},{})),n}mapFunction(e){let t=e.nodeDef,n=[],a=[],r={};t!=null&&(r=t.reduce((u,p)=>(u[p.name]=this.mapNode(p),p.op==="Const"&&a.push(u[p.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[p]=Ir(u.name),d={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:A1(u.type),type:"dtype"}},children:[]};d.signatureKey=u.name,s.push(d),r[p]=d}),Object.keys(r).forEach(u=>{let p=r[u];p.inputNames.forEach((d,c)=>{let[h,,m]=Ir(d),f=r[h];if(f.outputs!=null){let g=f.outputs.indexOf(m);if(g!==-1){let b=`${h}:${g}`;p.inputNames[c]=b}}p.inputs.push(f),f.children.push(p)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[p,d]=Ir(o[u.name]),c=r[p];c!=null&&(c.defaultOutput=d,i.push(c))});let l=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:i,weights:a,placeholders:n,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function Fj(e){let t=G().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 aE(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):Fj(e);return t?n:n.toLowerCase()}function Kx(e,t,n,a=!1){let r=e[t];return r!=null?aE(r.s,a):n}function Xx(e,t,n){let a=e[t];return a?a.b:n}function Yx(e,t,n){let a=e[t]||{},r=a.i!=null?a.i:a.f!=null?a.f:n;return typeof r=="number"?r:parseInt(r,10)}function A1(e){switch(typeof e=="string"&&(e=jn[e]),e){case jn.DT_FLOAT:case jn.DT_HALF:return"float32";case jn.DT_INT32:case jn.DT_INT64:case jn.DT_INT8:case jn.DT_UINT8:return"int32";case jn.DT_BOOL:return"bool";case jn.DT_DOUBLE:return"float32";case jn.DT_STRING:return"string";case jn.DT_COMPLEX64:case jn.DT_COMPLEX128:return"complex64";default:return null}}function WI(e,t,n){let a=e[t];return a&&a.func?a.func.name:n}function Zx(e,t,n){let a=e[t];return a&&a.type?A1(a.type):n}function Jx(e,t,n){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(r=>A1(r)):n}function rE(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function Qx(e,t,n){let a=e[t];return a&&a.shape?rE(a.shape):n}function ev(e,t,n){let a=e[t];return a?((a.list.f&&a.list.f.length?a.list.f:a.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function tv(e,t,n,a=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>aE(s,a)):n}function nv(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>rE(r)):n}function av(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var $j=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(a=>this.getInput(a)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((a,r)=>(a[r]=this.getAttr(r),a),{}))}getInput(e){return un(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return un(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return Yx(this.node.rawAttrs,e,t);if(n.s!=null)return Kx(this.node.rawAttrs,e,t);if(n.b!=null)return Xx(this.node.rawAttrs,e,t);if(n.shape!=null)return Qx(this.node.rawAttrs,e,t);if(n.type!=null)return Zx(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return ev(this.node.rawAttrs,e,t);if(n.list.s!=null)return tv(this.node.rawAttrs,e,t);if(n.list.shape!=null)return nv(this.node.rawAttrs,e,t);if(n.list.b!=null)return av(this.node.rawAttrs,e,t);if(n.list.type!=null)return Jx(this.node.rawAttrs,e,t)}return t}},sn={};_e(sn,{OP_SCOPE_SUFFIX:()=>Av,abs:()=>Lt,acos:()=>Ov,acosh:()=>Pv,add:()=>X,addN:()=>vN,all:()=>Lm,any:()=>yc,argMax:()=>ci,argMin:()=>Lv,asin:()=>zv,asinh:()=>Wv,atan:()=>Bv,atan2:()=>Vv,atanh:()=>Uv,avgPool:()=>ya,avgPool3d:()=>Hv,basicLSTMCell:()=>SN,batchNorm:()=>Ss,batchNorm2d:()=>qv,batchNorm3d:()=>jv,batchNorm4d:()=>Kv,batchToSpaceND:()=>id,bincount:()=>Xv,bitwiseAnd:()=>NN,booleanMaskAsync:()=>mT,broadcastArgs:()=>TN,broadcastTo:()=>ni,buffer:()=>Oe,cast:()=>re,ceil:()=>Yv,clipByValue:()=>an,clone:()=>sr,complex:()=>Er,concat:()=>et,concat1d:()=>Zv,concat2d:()=>Jv,concat3d:()=>Qv,concat4d:()=>ew,conv1d:()=>zm,conv2d:()=>$t,conv2dTranspose:()=>Wm,conv3d:()=>nw,conv3dTranspose:()=>aw,cos:()=>od,cosh:()=>Bm,cosineWindow:()=>uf,cumprod:()=>wc,cumsum:()=>Vm,denseBincount:()=>Xh,depthToSpace:()=>rw,depthwiseConv2d:()=>Ns,diag:()=>EN,dilation2d:()=>sw,div:()=>he,divNoNan:()=>iw,dot:()=>ow,dropout:()=>Pw,einsum:()=>Ys,elu:()=>Qu,enclosingPowerOfTwo:()=>Lw,ensureShape:()=>AN,equal:()=>Jn,erf:()=>lw,euclideanNorm:()=>cw,exp:()=>dn,expandDims:()=>Gt,expm1:()=>dw,eye:()=>Um,fft:()=>bd,fill:()=>yn,floor:()=>tp,floorDiv:()=>Pm,fused:()=>Vl,gather:()=>np,gatherND:()=>yT,greater:()=>Tn,greaterEqual:()=>$r,ifft:()=>Bl,imag:()=>ld,image:()=>Zn,inTopKAsync:()=>xT,irfft:()=>nf,isFinite:()=>hw,isInf:()=>mw,isNaN:()=>fw,leakyRelu:()=>ud,less:()=>Pl,lessEqual:()=>Ts,linalg:()=>Bw,linspace:()=>MN,localResponseNormalization:()=>gw,log:()=>Qn,log1p:()=>pd,logSigmoid:()=>bw,logSoftmax:()=>Hm,logSumExp:()=>cd,logicalAnd:()=>_a,logicalNot:()=>dd,logicalOr:()=>qm,logicalXor:()=>yw,losses:()=>FT,lowerBound:()=>PN,matMul:()=>$e,max:()=>ma,maxPool:()=>Dt,maxPool3d:()=>xw,maxPoolWithArgmax:()=>LN,maximum:()=>dr,mean:()=>Ct,meshgrid:()=>zN,min:()=>Ol,minimum:()=>cs,mirrorPad:()=>vw,mod:()=>ww,moments:()=>hd,movingAverage:()=>fT,mul:()=>z,multiRNNCell:()=>WN,multinomial:()=>BN,neg:()=>yt,norm:()=>ep,notEqual:()=>fi,oneHot:()=>Ll,ones:()=>On,onesLike:()=>ea,op:()=>L,outerProduct:()=>VN,pad:()=>xa,pad1d:()=>UN,pad2d:()=>GN,pad3d:()=>HN,pad4d:()=>qN,pool:()=>kw,pow:()=>_r,prelu:()=>fd,print:()=>Mv,prod:()=>Iw,raggedGather:()=>jN,raggedRange:()=>KN,raggedTensorToTensor:()=>XN,rand:()=>YN,randomGamma:()=>eT,randomNormal:()=>Km,randomStandardNormal:()=>tT,randomUniform:()=>Cs,randomUniformInt:()=>nT,range:()=>gi,real:()=>zl,reciprocal:()=>Ew,relu:()=>Ke,relu6:()=>Xm,reshape:()=>W,reverse:()=>ba,reverse1d:()=>aT,reverse2d:()=>rT,reverse3d:()=>sT,reverse4d:()=>iT,rfft:()=>yd,round:()=>Ym,rsqrt:()=>Zm,scalar:()=>ve,scatterND:()=>gT,searchSorted:()=>jm,selu:()=>Jm,separableConv2d:()=>Es,setdiff1dAsync:()=>oT,sigmoid:()=>ha,sign:()=>_w,signal:()=>AT,sin:()=>Qm,sinh:()=>ef,slice:()=>Ve,slice1d:()=>gd,slice2d:()=>tf,slice3d:()=>Ho,slice4d:()=>Wl,softmax:()=>ja,softplus:()=>Go,spaceToBatchND:()=>md,sparse:()=>$T,sparseToDense:()=>bT,spectral:()=>_T,split:()=>Pn,sqrt:()=>cn,square:()=>pt,squaredDifference:()=>af,squeeze:()=>_s,stack:()=>At,step:()=>qo,stridedSlice:()=>Aw,string:()=>DT,sub:()=>pe,sum:()=>fe,tan:()=>Fw,tanh:()=>hi,tensor:()=>bn,tensor1d:()=>qe,tensor2d:()=>Ea,tensor3d:()=>xd,tensor4d:()=>Fa,tensor5d:()=>lT,tensor6d:()=>uT,tensorScatterUpdate:()=>cT,tile:()=>Mn,topk:()=>Dw,transpose:()=>De,truncatedNormal:()=>of,unique:()=>Rw,unsortedSegmentSum:()=>lf,unstack:()=>dt,upperBound:()=>dT,variable:()=>Mw,where:()=>nn,whereAsync:()=>Ow,zeros:()=>It,zerosLike:()=>je});var Dj=(e,t,n,a=sn)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[a.add(k("a",e,t,n),k("b",e,t,n))];case"AddN":return[a.addN(k("tensors",e,t,n))];case"FloorMod":case"Mod":return[a.mod(k("a",e,t,n),k("b",e,t,n))];case"Mul":return[a.mul(k("a",e,t,n),k("b",e,t,n))];case"RealDiv":case"Div":return[a.div(k("a",e,t,n),k("b",e,t,n))];case"DivNoNan":return[a.divNoNan(k("a",e,t,n),k("b",e,t,n))];case"FloorDiv":return[a.floorDiv(k("a",e,t,n),k("b",e,t,n))];case"Sub":return[a.sub(k("a",e,t,n),k("b",e,t,n))];case"Minimum":return[a.minimum(k("a",e,t,n),k("b",e,t,n))];case"Maximum":return[a.maximum(k("a",e,t,n),k("b",e,t,n))];case"Pow":return[a.pow(k("a",e,t,n),k("b",e,t,n))];case"SquaredDifference":return[a.squaredDifference(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Rj=(e,t,n,a=sn)=>{switch(e.op){case"Abs":case"ComplexAbs":return[a.abs(k("x",e,t,n))];case"Acos":return[a.acos(k("x",e,t,n))];case"Acosh":return[a.acosh(k("x",e,t,n))];case"Asin":return[a.asin(k("x",e,t,n))];case"Asinh":return[a.asinh(k("x",e,t,n))];case"Atan":return[a.atan(k("x",e,t,n))];case"Atan2":return[a.atan2(k("x",e,t,n),k("y",e,t,n))];case"Atanh":return[a.atanh(k("x",e,t,n))];case"Ceil":return[a.ceil(k("x",e,t,n))];case"Complex":return[a.complex(k("real",e,t,n),k("imag",e,t,n))];case"Cos":return[a.cos(k("x",e,t,n))];case"Cosh":return[a.cosh(k("x",e,t,n))];case"Elu":return[a.elu(k("x",e,t,n))];case"Erf":return[a.erf(k("x",e,t,n))];case"Exp":return[a.exp(k("x",e,t,n))];case"Expm1":return[a.expm1(k("x",e,t,n))];case"Floor":return[a.floor(k("x",e,t,n))];case"Log":return[a.log(k("x",e,t,n))];case"Log1p":return[a.log1p(k("x",e,t,n))];case"Imag":return[a.imag(k("x",e,t,n))];case"Neg":return[a.neg(k("x",e,t,n))];case"Reciprocal":return[a.reciprocal(k("x",e,t,n))];case"Real":return[a.real(k("x",e,t,n))];case"Relu":return[a.relu(k("x",e,t,n))];case"Round":return[a.round(k("x",e,t,n))];case"Selu":return[a.selu(k("x",e,t,n))];case"Sigmoid":return[a.sigmoid(k("x",e,t,n))];case"Sin":return[a.sin(k("x",e,t,n))];case"Sign":return[a.sign(k("x",e,t,n))];case"Sinh":return[a.sinh(k("x",e,t,n))];case"Softplus":return[a.softplus(k("x",e,t,n))];case"Sqrt":return[a.sqrt(k("x",e,t,n))];case"Square":return[a.square(k("x",e,t,n))];case"Tanh":return[a.tanh(k("x",e,t,n))];case"Tan":return[a.tan(k("x",e,t,n))];case"ClipByValue":return[a.clipByValue(k("x",e,t,n),k("clipValueMin",e,t,n),k("clipValueMax",e,t,n))];case"Relu6":return[a.relu6(k("x",e,t,n))];case"Rsqrt":return[a.rsqrt(un(e.inputNames[0],t,n))];case"LeakyRelu":return[a.leakyRelu(k("x",e,t,n),k("alpha",e,t,n))];case"Prelu":return[a.prelu(k("x",e,t,n),k("alpha",e,t,n))];case"IsNan":return[a.isNaN(un(e.inputNames[0],t,n))];case"IsInf":return[a.isInf(un(e.inputNames[0],t,n))];case"IsFinite":return[a.isFinite(un(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ca(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let a=0;a<e.length;a++){let r=e[a],s=t[a];w.assert(r<0||s<0||r===s,()=>n+` Shapes ${e} and ${t} must match`)}}}function BI(e){return!(typeof e=="number"||e.some(t=>t<0))}function Zp(e,t,n){let a=rv(e,n),r=!BI(a);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${a}`);if(r&&t.forEach(s=>{a=rv(s.shape,a)}),!BI(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function rv(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let a=0;a<e.length;++a){let r=e[a],s=t[a];if(r>=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[a]=r>=0?r:s}return n}var Mj=class{constructor(e,t,n,a,r,s,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=a,this.identicalElementShapes=r,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=ve(0),Ht(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),Ca(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,Ht(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,a)=>this.write(n,t[a]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let a=0;a<this.size();a++)e.push(a)}if(e.length===0)return bn([],[0].concat(this.elementShape));let n=this.readMany(e);return Ca(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),At(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 bn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return Ca(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),et(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,dt(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,a=e.map(o=>(n+=o,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let r=n===0?0:t.size/n,s=[];O(()=>{t=W(t,[1,n,r]);for(let o=0;o<e.length;++o){let l=[0,o===0?0:a[o-1],0],u=[1,e[o],r];s[o]=W(Ve(t,l,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},Pf=class sv{get id(){return this.idTensor.id}constructor(t,n,a,r=-1){this.tensors=t,this.elementShape=n,this.elementDtype=a,t!=null&&t.forEach(s=>{if(a!==s.dtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${s.dtype}`);Ca(n,s.shape,"TensorList shape mismatch: "),Ht(s)}),this.idTensor=ve(0),this.maxNumElements=r,Ht(this.idTensor)}copy(){return new sv([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(n=>{(t==null||!t.has(n.id))&&n.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,n,a=-1){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(a!==-1&&this.tensors.length!==a)throw new Error(`Operation expected a list with ${a} elements but got a list with ${this.tensors.length} elements.`);Ca(t,this.elementShape,"TensorList shape mismatch: ");let r=Zp(this.elementShape,this.tensors,t);return O(()=>{let s=this.tensors.map(i=>W(i,r));return At(s,0)})}popBack(t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let a=Zp(this.elementShape,this.tensors,t),r=this.tensors.pop();return r.kept=!1,Ca(r.shape,t,"TensorList shape mismatch: "),W(r,a)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(Ca(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Ht(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);let n=new sv([],this.elementShape,this.elementDtype,this.maxNumElements);n.tensors.length=t;for(let a=0;a<Math.min(this.tensors.length,t);++a)n.tensors[a]=this.tensors[a];return n}getItem(t,n,a){if(a!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);Ca(this.tensors[t].shape,n,"TensorList shape mismatch: ");let r=Zp(this.elementShape,this.tensors,n);return W(this.tensors[t],r)}setItem(t,n){if(n.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);Ca(this.elementShape,n.shape,"TensorList shape mismatch: "),Ht(n),this.tensors[t]!=null&&(this.tensors[t].kept=!1),this.tensors[t]=n}gather(t,n,a){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);Ca(this.elementShape,a,"TensorList shape mismatch: "),t=t.slice(0,this.size());let r=Zp(this.elementShape,this.tensors,a);return t.length===0?bn([],[0].concat(r)):O(()=>{let s=t.map(i=>W(this.tensors[i],r));return At(s,0)})}concat(t,n){if(t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);Ca(this.elementShape,n,"TensorList shape mismatch: ");let a=Zp(this.elementShape,this.tensors,n);return this.size()===0?bn([],[0].concat(a)):O(()=>{let r=this.tensors.map(s=>W(s,a));return et(r,0)})}};function Oj(e,t,n){let a=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);Ca(r,t,"TensorList shape mismatch: ");let s=dt(e);return new Pf(s,t,a)}function Pj(e,t,n,a){return new Pf([],e,t,a)}function Lj(e,t,n,a){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(a!=null&&a!==-1&&r>=a)throw new Error(`Max index must be < array size (${r} vs. ${a})`);let s=new Pf([],n,e.dtype,a),i=dt(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function zj(e,t,n){let a=0,r=t.map(p=>(a+=p,a));if(a!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${a}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=rv(s,n),o=a===0?0:e.size/a,l=O(()=>{let p=[];e=W(e,[1,a,o]);for(let d=0;d<t.length;++d){let c=[0,d===0?0:r[d-1],0],h=[1,t[d],o];p[d]=W(Ve(e,c,h),i)}return e.dispose(),p}),u=new Pf([],n,e.dtype,t.length);for(let p=0;p<l.length;p++)u.setItem(p,l[p]);return u}var Wj=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=k("thenBranch",e,t,n),r=k("elseBranch",e,t,n),s=k("cond",e,t,n),i=k("args",e,t,n);return(await s.data())[0]?n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let a=k("body",e,t,n),r=k("cond",e,t,n),s=k("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(p=>p.id),l=await i[0].data();i.forEach(p=>{!p.kept&&o.indexOf(p.id)===-1&&p.dispose()});let u=s;for(;l[0];){let p=u;u=await n.functionMap[a].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let d=u.map(h=>h.id);p.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let c=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await c[0].data(),c.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let a=k("pred",e,t,n);return[Sr(a)]}case"Switch":{let a=k("pred",e,t,n),r=k("data",e,t,n);return r.kept||(r=Sr(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>un(r,t,n)!==void 0);if(a){let r=un(a,t,n);return[Sr(r)]}return}case"Enter":{let a=k("frameName",e,t,n),r=k("tensor",e,t,n);return n.enterFrame(a),[Sr(r)]}case"Exit":{let a=k("tensor",e,t,n);return n.exitFrame(),[Sr(a)]}case"NextIteration":{let a=k("tensor",e,t,n);return n.nextIteration(),[Sr(a)]}case"TensorArrayV3":{let a=k("size",e,t,n),r=k("dtype",e,t,n),s=k("elementShape",e,t,n),i=k("dynamicSize",e,t,n),o=k("clearAfterRead",e,t,n),l=k("identicalElementShapes",e,t,n),u=k("name",e,t,n),p=new Mj(u,r,a,s,l,i,o);return n.addTensorArray(p),[p.idTensor,ve(1)]}case"TensorArrayWriteV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=k("tensorArrayId",e,t,n),r=k("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=k("tensorArrayId",e,t,n),r=k("indices",e,t,n),s=k("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=k("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=k("tensorArrayId",e,t,n),r=k("tensor",e,t,n),s=k("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[ve(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=k("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=k("tensorListId",e,t,n),r=k("index",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=k("indices",e,t,n),r=k("tensor",e,t,n),s=k("elementShape",e,t,n),i=k("numElements",e,t,n),o=Lj(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=k("elementShape",e,t,n),r=k("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,n),o=e.op==="TensorListReserve"?-1:i,l=Pj(a,r,i,o);return n.addTensorList(l),[l.idTensor]}case"TensorListGather":{let a=k("tensorListId",e,t,n),r=k("indices",e,t,n),s=k("elementShape",e,t,n),i=k("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}case"TensorListStack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=k("numElements",e,t,n);return[n.getTensorList(a.id).stack(r,s,i)]}case"TensorListFromTensor":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),i=Oj(a,r,s);return n.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let a=k("tensorListId",e,t,n),r=n.getTensorList(a.id),s=k("dtype",e,t,n),i=k("elementShape",e,t,n);return[r.concat(s,i)]}case"TensorListPushBack":{let a=k("tensorListId",e,t,n),r=k("tensor",e,t,n),s=n.getTensorList(a.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let a=k("tensorListId",e,t,n),r=k("elementShape",e,t,n),s=k("elementDType",e,t,n);return[n.getTensorList(a.id).popBack(r,s)]}case"TensorListSplit":{let a=k("tensor",e,t,n),r=k("elementShape",e,t,n),s=k("lengths",e,t,n),i=zj(a,s,r);return n.addTensorList(i),[i.idTensor]}case"TensorListLength":{let a=k("tensorListId",e,t,n),r=n.getTensorList(a.id);return[ve(r.size(),"int32")]}case"TensorListResize":{let a=k("tensorListId",e,t,n),r=k("size",e,t,n),s=n.getTensorList(a.id).resize(r);return n.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function VI(e,t,n){let[a,r]=k("fusedOps",e,t,n),s=a==="biasadd",i=!s,o=r==="prelu",l=a==="fusedbatchnorm",u=k("numArgs",e,t,n);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let p=k("strides",e,t,n),d=Mh(e,t,n),c=k("dataFormat",e,t,n).toUpperCase(),h=k("dilations",e,t,n),[m,f]=k("args",e,t,n);i&&(f=m,m=void 0);let g=k("leakyreluAlpha",e,t,n);return{stride:p,pad:d,dataFormat:c,dilations:h,biasArg:m,preluArg:f,activationFunc:r,leakyreluAlpha:g}}var Bj=(e,t,n,a=sn)=>{switch(e.op){case"Conv1D":{let r=k("stride",e,t,n),s=k("pad",e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilation",e,t,n);return[a.conv1d(k("x",e,t,n),k("filter",e,t,n),r,s,i,o)]}case"Conv2D":{let r=k("strides",e,t,n),s=Mh(e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[a.conv2d(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,i,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:d}=VI(e,t,n);return[a.fused.conv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:d}=VI(e,t,n);return[a.fused.depthwiseConv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=k("outputShape",e,t,n),s=k("strides",e,t,n),i=Mh(e,t,n);return[a.conv2dTranspose(k("x",e,t,n),k("filter",e,t,n),r,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=k("strides",e,t,n),s=Mh(e,t,n),i=k("dilations",e,t,n),o=k("dataFormat",e,t,n).toUpperCase();return[a.depthwiseConv2d(k("input",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,o,[i[1],i[2]])]}case"Conv3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[a.conv3d(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2],r[3]],s,i,[o[1],o[2],o[3]])]}case"AvgPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.avgPool(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.maxPool(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n),o=k("includeBatchInIndex",e,t,n),{result:l,indexes:u}=a.maxPoolWithArgmax(k("x",e,t,n),[i[1],i[2]],[r[1],r[2]],s,o);return[l,u]}case"AvgPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.avgPool3d(k("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("kernelSize",e,t,n);return[a.maxPool3d(k("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),i=k("dilations",e,t,n),o=r[1],l=r[2],u=i[1],p=i[2];return[a.dilation2d(k("x",e,t,n),k("filter",e,t,n),[o,l],s,[u,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Vj=(e,t,n,a=sn)=>{switch(e.op){case"Fill":{let r=k("shape",e,t,n),s=k("dtype",e,t,n),i=k("value",e,t,n);return[a.fill(r,i,s)]}case"LinSpace":{let r=k("start",e,t,n),s=k("stop",e,t,n),i=k("num",e,t,n);return[a.linspace(r,s,i)]}case"Multinomial":{let r=k("logits",e,t,n),s=k("numSamples",e,t,n),i=k("seed",e,t,n);return[a.multinomial(r,s,i)]}case"OneHot":{let r=k("indices",e,t,n),s=k("depth",e,t,n),i=k("onValue",e,t,n),o=k("offValue",e,t,n),l=k("dtype",e,t,n);return[a.oneHot(r,s,i,o,l)]}case"Ones":return[a.ones(k("shape",e,t,n),k("dtype",e,t,n))];case"OnesLike":return[a.onesLike(k("x",e,t,n))];case"RandomStandardNormal":return[a.randomStandardNormal(k("shape",e,t,n),k("dtype",e,t,n),k("seed",e,t,n))];case"RandomUniform":return[a.randomUniform(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("dtype",e,t,n))];case"RandomUniformInt":return[a.randomUniformInt(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("seed",e,t,n))];case"Range":{let r=k("start",e,t,n),s=k("stop",e,t,n),i=k("step",e,t,n);return[a.range(r,s,i,k("dtype",e,t,n))]}case"TruncatedNormal":{let r=k("shape",e,t,n),s=k("mean",e,t,n),i=k("stdDev",e,t,n),o=k("seed",e,t,n);return[a.truncatedNormal(r,s,i,k("dtype",e,t,n),o)]}case"Zeros":return[a.zeros(k("shape",e,t,n),k("dtype",e,t,n))];case"ZerosLike":return[a.zerosLike(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function fx(e,t,n){let a=k("boxes",e,t,n),r=k("scores",e,t,n),s=k("maxOutputSize",e,t,n),i=k("iouThreshold",e,t,n),o=k("scoreThreshold",e,t,n),l=k("softNmsSigma",e,t,n);return{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var Uj=async(e,t,n,a,r=sn)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u,softNmsSigma:p}=fx(e,t,n),d=await r.image.nonMaxSuppressionWithScoreAsync(s,i,o,l,u,p);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=fx(e,t,n),p=k("padToMaxOutputSize",e,t,n),d=await r.image.nonMaxSuppressionPaddedAsync(s,i,o,l,u,p);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=fx(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,i,o,l,u)]}case"Where":{let s=r.cast(k("condition",e,t,n),"bool"),i=[await r.whereAsync(s)];return s.dispose(),i}case"ListDiff":return r.setdiff1dAsync(k("x",e,t,n),k("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Gj=(e,t,n,a=sn)=>{switch(e.op){case"LowerBound":{let r=k("sortedSequence",e,t,n),s=k("values",e,t,n);return[a.lowerBound(r,s)]}case"TopKV2":{let r=k("x",e,t,n),s=k("k",e,t,n),i=k("sorted",e,t,n),o=a.topk(r,s,i);return[o.values,o.indices]}case"UpperBound":{let r=k("sortedSequence",e,t,n),s=k("values",e,t,n);return[a.upperBound(r,s)]}case"Unique":{let r=k("x",e,t,n),s=a.unique(r);return[s.values,s.indices]}case"UniqueV2":{let r=k("x",e,t,n),s=k("axis",e,t,n),i=a.unique(r,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Hj=(e,t,n,a=sn)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=k("default",e,t,n);return[un(e.name,t,n)||r];case"Placeholder":return[un(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let p=k("x",e,t,n);return[Sr(p)]}case"IdentityN":return k("x",e,t,n).map(p=>Sr(p));case"Snapshot":let s=k("x",e,t,n);return[Sr(s)];case"Shape":return[a.tensor1d(k("x",e,t,n).shape,"int32")];case"ShapeN":return k("x",e,t,n).map(p=>a.tensor1d(p.shape));case"Size":return[a.scalar(k("x",e,t,n).size,"int32")];case"Rank":return[a.scalar(k("x",e,t,n).rank,"int32")];case"NoOp":return[a.scalar(1)];case"Print":let i=k("x",e,t,n),o=k("data",e,t,n),l=k("message",e,t,n),u=k("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let p=0;p<o.length;p++)console.log(Array.prototype.slice.call(o[p].dataSync()).slice(0,u));return[i];default:throw TypeError(`Node type ${e.op} is not implemented`)}},qj=class{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=ve(0),this.tensorMap=new Map,Ht(this.handle)}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return ve(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),O(()=>{let a=dt(t),r=n.length,s=a.length;w.assert(r===s,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`);for(let i=0;i<r;i++){let o=n[i],l=a[i];Ht(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return O(()=>{let a=[];for(let r=0;r<n.length;r++){let s=n[r],i=this.findWithDefault(s,t);a.push(i)}return At(a)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},jj=async(e,t,n,a)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=a.getHashTableHandleByName(e.name);if(r!=null)return[r];{let s=k("keyDType",e,t,n),i=k("valueDType",e,t,n),o=new qj(s,i);return a.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("values",e,t,n);return[await a.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=k("tableHandle",e,t,n,a),s=k("keys",e,t,n),i=k("defaultValue",e,t,n);return[await a.getHashTableById(r.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=k("tableHandle",e,t,n,a);return[a.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Kj=(e,t,n,a=sn)=>{switch(e.op){case"ResizeBilinear":{let r=k("images",e,t,n),s=k("size",e,t,n),i=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[a.image.resizeBilinear(r,[s[0],s[1]],i,o)]}case"ResizeNearestNeighbor":{let r=k("images",e,t,n),s=k("size",e,t,n),i=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[a.image.resizeNearestNeighbor(r,[s[0],s[1]],i,o)]}case"CropAndResize":{let r=k("image",e,t,n),s=k("boxes",e,t,n),i=k("boxInd",e,t,n),o=k("cropSize",e,t,n),l=k("method",e,t,n),u=k("extrapolationValue",e,t,n);return[a.image.cropAndResize(r,s,i,o,l,u)]}case"ImageProjectiveTransformV3":{let r=k("images",e,t,n),s=k("transforms",e,t,n),i=k("outputShape",e,t,n),o=k("fillValue",e,t,n),l=k("interpolation",e,t,n),u=k("fillMode",e,t,n);return[a.image.transform(r,s,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Xj=(e,t,n,a=sn)=>{switch(e.op){case"Equal":return[a.equal(k("a",e,t,n),k("b",e,t,n))];case"NotEqual":return[a.notEqual(k("a",e,t,n),k("b",e,t,n))];case"Greater":return[a.greater(k("a",e,t,n),k("b",e,t,n))];case"GreaterEqual":return[a.greaterEqual(k("a",e,t,n),k("b",e,t,n))];case"Less":return[a.less(k("a",e,t,n),k("b",e,t,n))];case"LessEqual":return[a.lessEqual(k("a",e,t,n),k("b",e,t,n))];case"LogicalAnd":return[a.logicalAnd(k("a",e,t,n),k("b",e,t,n))];case"LogicalNot":return[a.logicalNot(k("a",e,t,n))];case"LogicalOr":return[a.logicalOr(k("a",e,t,n),k("b",e,t,n))];case"Select":case"SelectV2":return[a.where(k("condition",e,t,n),k("a",e,t,n),k("b",e,t,n))];case"BitwiseAnd":return[a.bitwiseAnd(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Yj=(e,t,n,a=sn)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[a.matMul(k("a",e,t,n),k("b",e,t,n),k("transposeA",e,t,n),k("transposeB",e,t,n))];case"Einsum":return[a.einsum(k("equation",e,t,n),...k("tensors",e,t,n))];case"Transpose":return[a.transpose(k("x",e,t,n),k("perm",e,t,n))];case"_FusedMatMul":let[r,s]=k("fusedOps",e,t,n),i=r==="biasadd",o=s==="prelu",l=k("numArgs",e,t,n),u=k("leakyreluAlpha",e,t,n);if(i){if(o&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[p,d]=k("args",e,t,n);return[a.fused.matMul({a:k("a",e,t,n),b:k("b",e,t,n),transposeA:k("transposeA",e,t,n),transposeB:k("transposeB",e,t,n),bias:p,activation:s,preluActivationWeights:d,leakyreluAlpha:u})];case"MatrixBandPart":return[a.linalg.bandPart(k("a",e,t,n),k("numLower",e,t,n),k("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Zj=(e,t,n,a=sn)=>{switch(e.op){case"EuclideanNorm":return[a.euclideanNorm(k("x",e,t,n),k("axis",e,t,n),k("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":return[a.batchNorm(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"FusedBatchNormV3":return[a.batchNorm(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"LRN":return[a.localResponseNormalization(k("x",e,t,n),k("radius",e,t,n),k("bias",e,t,n),k("alpha",e,t,n),k("beta",e,t,n))];case"Softmax":return[a.softmax(k("x",e,t,n))];case"LogSoftmax":return[a.logSoftmax(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Jj=(e,t,n,a=sn)=>{switch(e.op){case"RaggedGather":{let{outputNestedSplits:r,outputDenseValues:s}=a.raggedGather(k("paramsNestedSplits",e,t,n),k("paramsDenseValues",e,t,n),k("indices",e,t,n),k("outputRaggedRank",e,t,n));return r.concat(s)}case"RaggedRange":{let{rtNestedSplits:r,rtDenseValues:s}=a.raggedRange(k("starts",e,t,n),k("limits",e,t,n),k("splits",e,t,n));return[r,s]}case"RaggedTensorToTensor":return[a.raggedTensorToTensor(k("shape",e,t,n),k("values",e,t,n),k("defaultValue",e,t,n),k("rowPartitionTensors",e,t,n),k("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Qj=(e,t,n,a=sn)=>{switch(e.op){case"Max":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.max(k("x",e,t,n),o,l)]}case"Mean":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.mean(k("x",e,t,n),o,l)]}case"Min":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.min(k("x",e,t,n),o,l)]}case"Sum":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.sum(k("x",e,t,n),o,l)]}case"All":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.all(k("x",e,t,n),o,l)]}case"Any":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.any(k("x",e,t,n),o,l)]}case"ArgMax":{let o=k("axis",e,t,n);return[a.argMax(k("x",e,t,n),o)]}case"ArgMin":{let o=k("axis",e,t,n);return[a.argMin(k("x",e,t,n),o)]}case"Prod":{let o=k("axis",e,t,n),l=k("keepDims",e,t,n);return[a.prod(k("x",e,t,n),o,l)]}case"Cumprod":{let o=k("axis",e,t,n),l=k("exclusive",e,t,n),u=k("reverse",e,t,n);return[a.cumprod(k("x",e,t,n),o,l,u)]}case"Cumsum":{let o=k("axis",e,t,n),l=k("exclusive",e,t,n),u=k("reverse",e,t,n);return[a.cumsum(k("x",e,t,n),o,l,u)]}case"Bincount":let r=k("x",e,t,n),s=k("weights",e,t,n),i=k("size",e,t,n);return[a.bincount(r,s,i)];case"DenseBincount":{let o=k("x",e,t,n),l=k("weights",e,t,n),u=k("size",e,t,n),p=k("binaryOutput",e,t,n);return[a.denseBincount(o,l,u,p)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},e5=(e,t,n,a=sn)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=k("n",e,t,n),s=k("axis",e,t,n),i=k("tensors",e,t,n);return i=i.slice(0,r),[a.concat(i,s)]}case"Gather":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[a.gather(r,a.cast(s,"int32"),0)]}case"GatherV2":{let r=k("axis",e,t,n),s=k("batchDims",e,t,n),i=k("x",e,t,n),o=k("indices",e,t,n);return[a.gather(i,a.cast(o,"int32"),r,s)]}case"Reverse":{let r=k("dims",e,t,n),s=[];for(let o=0;o<r.length;o++)r[o]&&s.push(o);let i=k("x",e,t,n);return[a.reverse(i,s)]}case"ReverseV2":{let r=k("axis",e,t,n),s=k("x",e,t,n);return[a.reverse(s,r)]}case"Slice":{let r=k("begin",e,t,n),s=k("size",e,t,n);return[a.slice(k("x",e,t,n),r,s)]}case"StridedSlice":{let r=k("begin",e,t,n),s=k("end",e,t,n),i=k("strides",e,t,n),o=k("beginMask",e,t,n),l=k("endMask",e,t,n),u=k("ellipsisMask",e,t,n),p=k("newAxisMask",e,t,n),d=k("shrinkAxisMask",e,t,n),c=k("x",e,t,n);return[a.stridedSlice(c,r,s,i,o,l,u,p,d)]}case"Pack":return O(()=>{let r=k("axis",e,t,n),s=k("tensors",e,t,n),i=s[0].shape,o=a.squeeze(s[0]).shape,l=s.map(u=>{let p=w.arraysEqual(u.shape,i);if(!p&&!w.arraysEqual(a.squeeze(u).shape,o))throw new Error("the input tensors shape does not match");return p?u:a.reshape(u,i)});return[a.stack(l,r)]});case"Unpack":{let r=k("axis",e,t,n),s=k("tensor",e,t,n);return a.unstack(s,r)}case"Tile":{let r=k("reps",e,t,n);return[a.tile(k("x",e,t,n),r)]}case"Split":case"SplitV":{let r=k("axis",e,t,n),s=k("numOrSizeSplits",e,t,n),i=k("x",e,t,n);return a.split(i,s,r)}case"ScatterNd":{let r=k("indices",e,t,n),s=k("values",e,t,n),i=k("shape",e,t,n);return[a.scatterND(r,s,i)]}case"GatherNd":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[a.gatherND(r,s)]}case"SparseToDense":{let r=k("sparseIndices",e,t,n),s=k("outputShape",e,t,n),i=k("sparseValues",e,t,n),o=k("defaultValue",e,t,n);return[a.sparseToDense(r,i,s,i.dtype===o.dtype?o:a.cast(o,i.dtype))]}case"TensorScatterUpdate":{let r=k("indices",e,t,n),s=k("values",e,t,n),i=k("tensor",e,t,n);return[a.tensorScatterUpdate(i,r,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},t5=(e,t,n,a=sn)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:s,emptyRowIndicator:i,reverseIndexMap:o}=a.sparse.sparseFillEmptyRows(k("indices",e,t,n),k("values",e,t,n),k("denseShape",e,t,n),k("defaultValue",e,t,n));return[r,s,i,o]}case"SparseReshape":{let{outputIndices:r,outputShape:s}=a.sparse.sparseReshape(k("inputIndices",e,t,n),k("inputShape",e,t,n),k("newShape",e,t,n));return[r,s]}case"SparseSegmentMean":return[a.sparse.sparseSegmentMean(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];case"SparseSegmentSum":return[a.sparse.sparseSegmentSum(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},n5=(e,t,n,a=sn)=>{switch(e.op){case"FFT":return[a.fft(k("x",e,t,n))];case"IFFT":return[a.ifft(k("x",e,t,n))];case"RFFT":return[a.rfft(k("x",e,t,n))];case"IRFFT":return[a.irfft(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},a5=(e,t,n,a=sn)=>{switch(e.op){case"StaticRegexReplace":return[a.string.staticRegexReplace(k("input",e,t,n),k("pattern",e,t,n),k("rewrite",e,t,n),k("replaceGlobal",e,t,n))];case"StringNGrams":{let{nGrams:r,nGramsSplits:s}=a.string.stringNGrams(k("data",e,t,n),k("dataSplits",e,t,n),k("separator",e,t,n),k("nGramWidths",e,t,n),k("leftPad",e,t,n),k("rightPad",e,t,n),k("padWidth",e,t,n),k("preserveShortSequences",e,t,n));return[r,s]}case"StringSplit":{let{indices:r,values:s,shape:i}=a.string.stringSplit(k("input",e,t,n),k("delimiter",e,t,n),k("skipEmpty",e,t,n));return[r,s,i]}case"StringToHashBucketFast":return[a.string.stringToHashBucketFast(k("input",e,t,n),k("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},r5=(e,t,n,a=sn)=>{switch(e.op){case"Cast":return[a.cast(k("x",e,t,n),k("dtype",e,t,n))];case"ExpandDims":{let r=k("axis",e,t,n);return[a.expandDims(k("x",e,t,n),r)]}case"Squeeze":{let r=k("axis",e,t,n);return[a.squeeze(k("x",e,t,n),r)]}case"Reshape":return[a.reshape(k("x",e,t,n),k("shape",e,t,n))];case"EnsureShape":return[a.ensureShape(k("x",e,t,n),k("shape",e,t,n))];case"MirrorPad":return[a.mirrorPad(k("x",e,t,n),k("padding",e,t,n),k("mode",e,t,n))];case"PadV2":case"Pad":return[a.pad(k("x",e,t,n),k("padding",e,t,n),k("constantValue",e,t,n))];case"SpaceToBatchND":{let r=k("blockShape",e,t,n),s=k("paddings",e,t,n);return[a.spaceToBatchND(k("x",e,t,n),r,s)]}case"BatchToSpaceND":{let r=k("blockShape",e,t,n),s=k("crops",e,t,n);return[a.batchToSpaceND(k("x",e,t,n),r,s)]}case"DepthToSpace":{let r=k("blockSize",e,t,n),s=k("dataFormat",e,t,n).toUpperCase();return[a.depthToSpace(k("x",e,t,n),r,s)]}case"BroadcastTo":return[a.broadcastTo(k("x",e,t,n),k("shape",e,t,n))];case"BroadcastArgs":return[a.broadcastArgs(k("s0",e,t,n),k("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function UI(e,t,n,a,r=O){let s=((i,o,l)=>{switch(i.category){case"arithmetic":return r(()=>Dj(i,o,l));case"basic_math":return r(()=>Rj(i,o,l));case"control":return Wj(i,o,l);case"convolution":return r(()=>Bj(i,o,l));case"creation":return r(()=>Vj(i,o,l));case"dynamic":return Uj(i,o,l);case"evaluation":return r(()=>Gj(i,o,l));case"image":return r(()=>Kj(i,o,l));case"graph":return r(()=>Hj(i,o,l));case"logical":return r(()=>Xj(i,o,l));case"matrices":return r(()=>Yj(i,o,l));case"normalization":return r(()=>Zj(i,o,l));case"ragged":return r(()=>Jj(i,o,l));case"reduction":return r(()=>Qj(i,o,l));case"slice_join":return r(()=>e5(i,o,l));case"sparse":return r(()=>t5(i,o,l));case"spectral":return r(()=>n5(i,o,l));case"string":return r(()=>a5(i,o,l));case"transformation":return r(()=>r5(i,o,l));case"hash_table":return jj(i,o,l,a);case"custom":let u=PC(i.op);if(u&&u.customExecutor)return u.customExecutor(new $j(i,o,l));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.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(i=>[].concat(i)):[].concat(s)}var GI=class{constructor(e={},t={},n={},a={},r){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=a,this.parseNodeNameCache=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 HI(e,t,n,a){let r=new Set,s=[],i=null,o=null,l=new Set,u=new Set(Object.keys(e).map(c=>Xn(c)[0]));a=a||[];let p=new Set(a.map(c=>Xn(c.name)[0])),d=[...t];for(;d.length>0;){let c=d.pop();if((Js(c)||d5(c)||h5(c))&&i==null&&(i=c,o=i.children.map(h=>h.name).filter(h=>r.has(h))),r.add(c.name),n[c.name]==null&&!u.has(c.name)&&!p.has(c.name)){if(c.inputs.length===0){s.push(c.name);continue}c.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:s,dynamicNode:i,syncInputs:o}}function s5(e,t){let{usedNodes:n,inputs:a}=t,r=Object.keys(a).map(g=>Xn(g)[0]).map(g=>e.nodes[g]),s=e.initNodes||[],i=g=>n.has(typeof g=="string"?g:g.name);function o(g){return[...new Map(g.map(b=>[b.name,b])).values()]}let l=o([...r,...e.weights,...s]).filter(i),u=o([...l,...Object.values(e.nodes)]).filter(i),p=new Map(u.map(g=>[g.name,g])),d={};for(let g of u){d[g.name]=d[g.name]||0;for(let b of g.children)i(b)||(d[b.name]=Number.POSITIVE_INFINITY),d[b.name]=(d[b.name]||0)+1}let c=Object.entries(d).filter(([,g])=>g===0).map(([g])=>g),h=[...c];for(;c.length>0;){let g=c.pop(),b=p.get(g);for(let y of b.children.filter(i))--d[y.name]===0&&(h.push(y.name),c.push(y.name))}let m=h.map(g=>p.get(g)),f=i5(m,l);return o5(f,l),f}function i5(e,t){let n=new Map(e.map(s=>[s.name,s])),a=t.map(s=>s.name),r=new Set(a);for(;a.length>0;){let s=a.pop(),i=n.get(s);for(let o of i.children)!n.has(o.name)||r.has(o.name)||(r.add(o.name),a.push(o.name))}return e.filter(s=>r.has(s.name))}var Th=class extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}};function o5(e,t){let n=new Map(e.map((o,l)=>[o.name,l])),a=new Set(t.map(o=>o.name)),r=o=>a.has(typeof o=="string"?o:o.name),s=new Set(e.map(o=>o.name)),i=o=>s.has(typeof o=="string"?o:o.name);for(let o of e){for(let l of o.children.filter(i)){if(!n.has(l.name))throw new Th(`Child ${l.name} of node ${o.name} is unreachable.`);if(n.get(o.name)>n.get(l.name))throw new Th(`Node ${o.name} is scheduled to run after its child ${l.name}.`)}if(!r(o))for(let l of o.inputs){if(!n.has(l.name))throw new Th(`Input ${l.name} of node ${o.name} is unreachable.`);if(n.get(l.name)>n.get(o.name))throw new Th(`Node ${o.name} is scheduled to run before its input ${l.name}.`)}}}function l5(e){let t=new Map(e.map((o,l)=>[o.name,l])),n=Number.MAX_SAFE_INTEGER,a=e.map((o,l)=>Js(o)?n:l),r=o=>{let l=a[t.get(o.name)];return l==null?-1:l},s=e.map((o,l)=>o.children.map(r).reduce((u,p)=>Math.max(u,p),a[l])),i=new Map;for(let o=0;o<e.length;++o){let l=s[o];if(l===n)continue;let u=e[o],p=e[l];i.has(p.name)||i.set(p.name,[]),i.get(p.name).push(u)}return i}var u5=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),p5=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),c5=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Js(e){return u5.has(e.op)}function d5(e){return p5.has(e.op)}function h5(e){return c5.has(e.op)}var qI=class sE{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(t){let n=Object.keys(t).map(a=>t[a].map(r=>r.id));this._weightIds=[].concat(...n),this._weightMap=t}set resourceManager(t){this._resourceManager=t}get inputs(){return this._inputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(t=>t.signatureKey||t.name)}get outputNodes(){return this._outputs.map(t=>{let n=t.signatureKey||t.name;return t.defaultOutput?`${n}:${t.defaultOutput}`:n})}get functions(){return Object.keys(this._functions).reduce((t,n)=>(t[n]=this._functions[n].signature,t),{})}constructor(t,n){this.graph=t,this.parent=n,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(a=>{this._functionExecutorMap[a]=new sE(t.functions[a],this)})}getCompilationKey(t,n){let a=t.map(s=>s.name).sort(),r=n.map(s=>s.name).sort();return a.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(t,n){let a=HI(t,n,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:i}=a;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 [${i}]`);if(r.length>0){let u=n.map(d=>d.name),p=Object.keys(t);throw new Error(`Cannot compute the outputs [${u}] from the provided inputs [${p}]. Missing the following inputs: [${r}]`)}let o=s5(this.graph,a),l=l5(o);return{orderedNodes:o,nodeLiveUntilMap:l}}cloneAndKeepTensor(t){if(t==null)return null;let n=t.clone();return Ht(n),n}cloneTensorList(t){return t?t.map(n=>this.cloneAndKeepTensor(n)):null}cloneTensorMap(t){return Object.fromEntries(Object.entries(t).map(([n,a])=>[n,this.cloneTensorList(a)]))}execute(t,n){this.disposeIntermediateTensors(),t=this.mapInputs(t);let a=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),n=this.mapOutputs(n),this.checkOutputs(n);let r=a.map(c=>this.graph.nodes[Xn(c)[0]]),s=n.map(c=>Xn(c)[0]),i=new Set(s),o=s.map(c=>this.graph.nodes[c]);o.length===0&&(o=this._outputs);let l=this.getCompilationKey(r,o),u=this.compiledMap.get(l);u==null&&(u=this.compile(t,o),this.compiledMap.set(l,u));try{this.keepIntermediateTensors=G().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(c){this.keepIntermediateTensors=!1,console.warn(c.message)}let p={},d={};return O(()=>{let c=new GI(this.weightMap,p,d,this.functionExecutorMap,this.parseNodeNameCache),h=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(t).forEach(b=>{let[y,x]=Xn(b,c),v=[];v[x]=t[b],h[y]=v,this.keepIntermediateTensors&&(this.clonedTensorsMap[y]=this.cloneTensorList(v))});let m=this.getFrozenTensorIds(h),{orderedNodes:f,nodeLiveUntilMap:g}=u;for(let b of f){if(h[b.name])continue;let y=UI(b,h,c,this._resourceManager);if(w.isPromise(y))throw new Error(`The execution of the op '${b.op}' returned a promise. Please use model.executeAsync() instead.`);h[b.name]=y,this.keepIntermediateTensors&&(this.clonedTensorsMap[b.name]=this.cloneTensorList(y)),this.checkTensorForDisposalWithNodeLiveUntilInfo(b,h,c,m,i,g.get(b.name))}return this.parent==null&&c.dispose(m),n.map(b=>un(b,h,c))})}getFrozenTensorIds(t){let n=[].concat.apply([],Object.keys(t).map(a=>t[a]).map(a=>a.map(r=>r.id)));return new Set(n)}checkTensorForDisposal(t,n,a,r,s,i,o){if(!(Js(n)||i.has(t))){for(let l of a[t])l!=null&&(o[l.id]=(o[l.id]||0)+n.children.length);for(let l of n.inputs){if(Js(l))continue;let u=LI(l.name,a,r);if(u!=null)for(let p of u){if(!p||p.kept||s.has(p.id))continue;let d=o[p.id];d===1?(p.dispose(),delete o[p.id]):d!=null&&o[p.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(t,n,a,r,s,i){function o(l){return Js(l)||s.has(l.name)}if(!(Js(t)||i==null))for(let l of i){if(o(l))continue;let u=LI(l.name,n,a);for(let p of u)!p||p.kept||r.has(p.id)||p.dispose()}}async executeAsync(t,n){return this._executeAsync(t,n)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(t=>{for(let n of t)n&&!n.isDisposed&&n.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(t,n,a=!1,r={},s={}){this.disposeIntermediateTensors(),a||(t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),n=this.mapOutputs(n),this.checkOutputs(n));try{this.keepIntermediateTensors=G().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(c){this.keepIntermediateTensors=!1,console.warn(c.message)}let i=new GI(this.weightMap,r,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let o=await this.executeWithControlFlow(t,i,n,a),l=n.map(c=>un(c,o,i)),u=l.map(c=>c.id),p=Object.keys(t).map(c=>t[c].id),d=new Set([...u,...p,...this.weightIds]);return Object.values(o).forEach(c=>{c.forEach(h=>{h&&!h.isDisposed&&!d.has(h.id)&&h.dispose()})}),this.parent==null&&i.dispose(d),l}async executeFunctionAsync(t,n,a){let r=t.reduce((s,i,o)=>(s[this.inputs[o].name]=i,s),{});return this._executeAsync(r,this.outputNodes,!0,n,a)}async executeWithControlFlow(t,n,a,r){let s=Object.keys(t),i=s.map(v=>this.graph.nodes[Xn(v)[0]]),o=a.map(v=>Xn(v)[0]),l=new Set(o),u=o.map(v=>this.graph.nodes[v]);u.length===0&&(u=this._outputs);let{usedNodes:p,missingInputs:d,dynamicNode:c,syncInputs:h}=HI(t,u,this.weightMap,this._initNodes),m=[...i,...this.graph.weights,...this._initNodes||[]].map(v=>({node:v,contexts:n.currentContext})),f=Object.assign({},this.weightMap);Object.keys(t).forEach(v=>{let[I,N]=Xn(v),C=[];C[N]=t[v],f[I]=C});let g={},b=this.getFrozenTensorIds(f),y={};for(;m.length>0;){let v=this.processStack(i,m,n,f,y,b,l,g,p);await Promise.all(v)}c==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 x=u.filter(v=>!Js(v)&&!un(v.name,f,n)).map(v=>v.name);if(x.length>0){let v="";throw c!=null&&(v=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${x}] from the provided inputs [${s}]. Consider providing the following inputs: [${d}]. ${v}`)}return f}processStack(t,n,a,r,s,i,o,l,u){let p=[];for(;n.length>0;){let d=n.pop();a.currentContext=d.contexts;let c="";if(d.node.op==="Enter"&&k("isConstant",d.node,r,a)&&([c]=Ir(d.node.name,a)),r[d.node.name]==null){let h=UI(d.node,r,a,this._resourceManager);c||([c]=Ir(d.node.name,a));let m=a.currentContext;w.isPromise(h)?p.push(h.then(f=>(r[c]=f,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(f)),a.currentContext=m,this.checkTensorForDisposal(c,d.node,r,a,i,o,l),this.processChildNodes(d.node,n,a,r,s,u),f))):(r[c]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(h)),this.checkTensorForDisposal(c,d.node,r,a,i,o,l),this.processChildNodes(d.node,n,a,r,s,u))}else this.processChildNodes(d.node,n,a,r,s,u)}return p}processChildNodes(t,n,a,r,s,i){t.children.forEach(o=>{let[l]=Ir(o.name,a);s[l]||!i.has(o.name)||(o.op==="Merge"?o.inputNames.some(u=>!!un(u,r,a))&&(s[l]=!0,n.push({contexts:a.currentContext,node:o})):o.inputNames.every(u=>!!un(u,r,a))&&(s[l]=!0,n.push({contexts:a.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(t=>this.weightMap[t].forEach(n=>n.dispose()))}checkInputShapeAndType(t){Object.keys(t).forEach(n=>{let a=t[n],[r]=Xn(n),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){let i=s.attrParams.shape.value,o=i.length===a.shape.length&&a.shape.every((l,u)=>i[u]===-1||i[u]===l);w.assert(o,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${i}], but was [${a.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&w.assert(a.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${a.dtype}`)})}mapInputs(t){var n,a;let r={};for(let s in t){let i=(a=(n=this._signature)===null||n===void 0?void 0:n.inputs)===null||a===void 0?void 0:a[s];i!=null?r[i.name]=t[s]:r[s]=t[s]}return r}checkInputs(t){let n=Object.keys(t).filter(a=>{let[r]=Xn(a);return this.graph.nodes[r]==null});if(n.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${n}] that are not part of graph`)}mapOutputs(t){return t.map(n=>{var a,r;let s=(r=(a=this._signature)===null||a===void 0?void 0:a.outputs)===null||r===void 0?void 0:r[n];return s!=null?s.name:n},{})}checkOutputs(t){t.forEach(n=>{let[a]=Xn(n);if(!this.graph.nodes[a])throw new Error(`The output '${n}' is not found in the graph`)})}},m5=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]}},f5="?tfjs-format=file",g5="model.json",F1=class{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}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=qt){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,t==null&&(this.loadOptions={}),this.resourceManager=new m5}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{let t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.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]}}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=this.handler.load();return w.isPromise(e)?e.then(t=>t.getWeightStream==null?this.loadSync(t):this.loadStreaming(t)):this.loadSync(e)}loadSync(e){let t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(e.getWeightStream==null)throw new Error("Model artifacts missing streamWeights function");let t=await pN(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;let n=this.artifacts.modelTopology,a=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let r=this.artifacts.userDefinedMetadata;r.signature!=null&&(a=r.signature),r.structuredOutputKeys!=null&&(this.structuredOutputKeys=r.structuredOutputKeys)}if(this.signature=a,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new qI(zI.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=zI.Instance.transformGraph(e.modelInitializer);this.initializer=new qI(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){let n=this.io.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)}addStructuredOutputNames(e){if(this.structuredOutputKeys){let t=e instanceof Ce?[e]:e,n={};return t.forEach((a,r)=>n[this.structuredOutputKeys[r]]=a),n}return e}predict(e,t){let n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){let n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Ce)&&!Array.isArray(e)){let r=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(r!=null)for(let s in r){let i=r[s];i.resourceId!=null&&(e[s]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];let n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let a=0;return this.inputNodes.reduce((r,s)=>{var i,o,l;let u=(l=(o=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||o===void 0?void 0:o[s])===null||l===void 0?void 0:l.resourceId;return u!=null?r[s]=this.resourceIdToCapturedInput[u]:r[s]=e[a++],r},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){let t=this.initializerSignature.outputs,n=Object.keys(t);for(let a=0;a<n.length;a++){let r=n[a],s=t[r];this.resourceIdToCapturedInput[s.resourceId]=e[a]}}}execute(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),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){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Ee(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function b5(e,t={},n=qt){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&&typeof e=="string"&&(e=x5(e));let a=new F1(e,t,n);return await a.load(),a}function y5(e){if(e==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){let[a,r]=e;if(!a)throw new Error("modelJSON must be the first element of the array");if(!r||!(r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in a))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in a))throw new Error("Model JSON is missing 'weightsManifest'");let s=qt.getWeightSpecs(a.weightsManifest),i=qt.getModelArtifactsForJSONSync(a,s,r);t=qt.fromMemorySync(i)}else if("load"in e)t=e;else if("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e)t=qt.fromMemorySync(e);else throw new Error("Unknown model format");let n=new F1(t);return n.load(),n}function x5(e){return e.endsWith("/")||(e=e+"/"),`${e}${g5}${f5}`}var v5="4.16.0",iE={};_e(iE,{CSVDataset:()=>bE,Dataset:()=>ip,FileDataSource:()=>SE,TextLineDataset:()=>gE,URLDataSource:()=>NE,array:()=>U5,csv:()=>nK,func:()=>aK,generator:()=>rK,microphone:()=>iK,version_data:()=>oK,webcam:()=>sK,zip:()=>G5});var w5=ys(bm()),k5=ys(bm());function I5(e,t){return om(e,t)}function om(e,t,n=new Map,a=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(a.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(Hl(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=om(o,t,n,a);s[i]=l}return a.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function S5(e,t=lE){return oE(e,t)}function oE(e,t,n=new Set){let a=e[0];if(n.has(a))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(Hl(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(u=>u[i]),l=oE(o,t,n);s[i]=l}return n.delete(a),s}else throw new Error(`Can't recurse into non-iterable type: ${a}`);else return r.value}function lE(e){return e===null?null:Hl(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function uE(e,t){let n=new Map;om(e,t,n);for(let a of Array.from(n.keys())){let r=n.get(a);if(w.isPromise(r)){let s=await r;n.set(a,s)}}return om(e,t,n)}function Hl(e){let t=!1;if(G().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=FS();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ce)&&!(e instanceof Promise)&&!t)}function N5(e){return e==null||T5(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ce||w.isTypedArray(e)}function T5(e){return e===null||typeof e!="object"&&typeof e!="function"}function C5(e){return I5(e,E5)}function E5(e){return e instanceof Ce?{value:e.clone(),recurse:!1}:Hl(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var pE=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}},cE=class dE extends pE{constructor(){super(dE.INITIAL_CAPACITY)}isFull(){return!1}push(t){super.isFull()&&this.expand(),super.push(t)}unshift(t){super.isFull()&&this.expand(),super.unshift(t)}expand(){let t=this.capacity*2,n=new Array(t),a=this.length();for(let r=0;r<a;r++)n[r]=this.get(this.wrap(this.begin+r));this.data=n,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=a}};cE.INITIAL_CAPACITY=32;function hE(e){return new F5(e)}function $1(e){return new $5(e)}function _5(e,t){return new mE(e,t)}function A5(e,t=es.FAIL){return new B5(e,t)}var rn=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 z5(this,e)}filter(e){return new P5(this,e)}map(e){return new L5(this,e)}mapAsync(e){return new jI(this,e)}serialMapAsync(e){return new jI(this,e).serial()}flatmap(e){return new W5(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 O5(this,e,t)}columnMajorBatch(e,t=!0,n=lE){return this.rowMajorBatch(e,t).map(a=>S5(a,n))}concatenate(e,t){return new mE(hE([this,e]),t)}take(e){return e<0||e==null?this:new M5(this,e)}skip(e){return e<0||e==null?this:new R5(this,e)}prefetch(e){return new fE(this,e)}shuffle(e,t){return new V5(this,e,t)}serial(){return new D5(this)}},F5=class extends rn{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:C5(e),done:!1}}},$5=class extends rn{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}}},D5=class extends rn{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()}},R5=class extends rn{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;Ee(e.value)}return this.upstream.next()}},M5=class extends rn{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()}},O5=class extends rn{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}}},P5=class extends rn{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;Ee(e.value)}}},L5=class extends rn{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=Wa.getTensorsInContainer(e.value),n=this.transform(e.value),a=Wa.getTensorsInContainer(n);for(let r of t)Wa.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},z5=class extends rn{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}}}},jI=class extends rn{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=Wa.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Wa.getTensorsInContainer(n);for(let r of t)Wa.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},D1=class extends rn{constructor(){super(),this.outputQueue=new cE,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}}},W5=class extends D1{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=Wa.getTensorsInContainer(e.value),n=this.transform(e.value),a=Wa.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Wa.isTensorInList(r,a)||r.dispose();return!0}},mE=class extends rn{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}},es;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(es||(es={}));var B5=class extends rn{constructor(e,t=es.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function a(s){return s instanceof rn?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await uE(this.iterators,a);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case es.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case es.SHORTEST:return{value:null,done:!0};case es.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},fE=class extends rn{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new pE(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()}},V5=class extends fE{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=k5.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}}},ip=class{constructor(){this.size=null}batch(e,t=!0){let n=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let a;return this.size===1/0||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),Kn(async()=>(await n.iterator()).columnMajorBatch(e,t,H5),a)}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,Kn(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,Kn(async()=>(await t.iterator()).filter(a=>O(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Kn(async()=>(await t.iterator()).map(n=>O(()=>e(n))),this.size)}mapAsync(e){let t=this;return Kn(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 Kn(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,Kn(async()=>{let a=$1(async()=>({value:await t.iterator(),done:!1}));return _5(a.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,Kn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let a=this,r=w5.alea(t||w.now().toString());return Kn(async()=>{let s=r.int32();return n&&(s+=r.int32()),(await a.iterator()).shuffle(e,s.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,Kn(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()}};ip.MAX_BUFFER_SIZE=1e4;function Kn(e,t=null){return new class extends ip{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function U5(e){return Kn(async()=>hE(e),e.length)}function G5(e){if(!Hl(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 Kn(async()=>{let n=await uE(e,a=>{if(a instanceof ip)return{value:a.iterator(),recurse:!1};if(Hl(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return A5(n,es.SHORTEST)},t)}function H5(e){if(e===null)return null;let t=e[0];return N5(t)?{value:q5(e),recurse:!1}:{value:null,recurse:!0}}function q5(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ce?At(e):bn(e)}var gE=class extends ip{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},Ch='"',Jp=Symbol("out"),KI=Symbol("field"),Eh=Symbol("quote"),gx=Symbol("quoteafterquote"),XI=Symbol("quoteinquote"),bE=class extends ip{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!1)}else return null}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 gE(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 iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},a={};for(let r=0;r<this.fullColumnNames.length;r++){let s=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[r],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let u=Number(o);if(isNaN(u))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=u;else switch(i.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(o);break;default:l=u}}i&&i.isLabel?a[s]=l:n[s]=l}}return Object.keys(a).length===0?n:{xs:n,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],a=0,r=e.length,s=Jp;for(let i=0;i<r;i++)switch(s){case Jp:switch(e.charAt(i)){case Ch:a=i+1,s=Eh;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=Jp;break;default:s=KI,a=i;break}break;case KI:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=Jp,a=i+1;break;default:}break;case Eh:switch(e.charAt(i)){case Ch:s=gx;break;default:}break;case gx:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=Jp,a=i+1;break;case Ch:s=Eh;break;default:s=XI;break}break;case XI:switch(e.charAt(i)){case Ch:s=Eh;break;default:}break;default:}if(s===gx?n.push(e.substring(a,r-1)):n.push(e.substring(a)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},j5=class yE extends rn{constructor(t){super(),this.microphoneConfig=t,this.isClosed=!1,this.fftSize=t.fftSize||1024;let n=Math.log2(this.fftSize);if(this.fftSize<0||n<4||n>14||!Number.isInteger(n))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=t.numFramesPerSpectrogram||43,this.sampleRateHz=t.sampleRateHz,this.columnTruncateLength=t.columnTruncateLength||this.fftSize,this.audioTrackConstraints=t.audioTrackConstraints,this.smoothingTimeConstant=t.smoothingTimeConstant||0,this.includeSpectrogram=t.includeSpectrogram!==!1,this.includeWaveform=t.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(t={}){if(!G().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let n=new yE(t);return await n.start(),n}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(a){throw new Error(`Error thrown while initializing video stream: ${a.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let t=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new t,!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 n=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,n.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 t,n,a=await this.getAudioData();if(this.includeSpectrogram){let r=this.flattenQueue(a.freqDataQueue);t=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let r=this.flattenQueue(a.timeDataQueue);n=this.getTensorFromAudioDataArray(r,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:t,waveform:n},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let t=[],n=[],a=0;return new Promise(r=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:t,timeDataQueue:n}),t.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),n.push(this.timeData.slice())),++a===this.numFrames&&(clearInterval(s),r({freqDataQueue:t,timeDataQueue:n}))},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(t){let n=t[0].length,a=new Float32Array(t.length*n);return t.forEach((r,s)=>a.set(r,s*n)),a}getTensorFromAudioDataArray(t,n){let a=new Float32Array(w.sizeFromShape(n));return a.set(t,a.length-t.length),bn(a,n)}},K5=class xE extends rn{constructor(t,n){if(super(),this.webcamVideoElement=t,this.webcamConfig=n,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=qe([0],"int32"),this.webcamConfig.centerCrop){let a=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,r=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-a)/2,i=(1-r)/2,o=s+a,l=r+i;this.cropBox=Ea([i,s,l,o],[1,4])}else this.cropBox=Ea([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(t,n={}){if(!G().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!n.resizeWidth||!n.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=n.resizeWidth,t.height=n.resizeHeight}let a=new xE(t,n);return await a.start(),a}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(t){throw t.message=`Error thrown while initializing video stream: ${t.message}`,t}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(t=>{this.webcamVideoElement.onloadedmetadata=()=>{t()}})}async next(){if(this.isClosed)return{value:null,done:!0};let t;try{t=jo.fromPixels(this.webcamVideoElement)}catch(n){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(n)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(t),done:!1}}catch(n){throw new Error(`Error thrown cropping the video: ${n.message}`)}finally{t.dispose()}else return{value:t,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(t){return O(()=>{let n=Gt(re(t,"float32"),0),a;a=Zn.cropAndResize(n,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let r=a.shape;return W(a,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.")}},vE=class{},wE=class extends rn{split(e){return new X5(this,e)}},X5=class extends wE{constructor(e,t){super(),this.upstream=e,this.impl=new Y5(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Y5=class extends D1{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}},Z5=class extends rn{decodeUTF8(){return new J5(this)}},J5=class extends wE{constructor(e){super(),this.upstream=e,this.impl=new Q5(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Q5=class extends D1{constructor(e){if(super(),this.upstream=e,G().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=FS();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 G().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},kE=class extends Z5{constructor(e,t={}){super(),this.file=e,this.options=t,w.assert(e instanceof Uint8Array||(G().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((e,t)=>{let n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{let a=new FileReader;a.onload=s=>{let i=a.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},a.onabort=s=>t(new Error("Aborted")),a.onerror=s=>t(new Error(s.type));let r=this.file.slice(this.offset,n);a.readAsArrayBuffer(r)}this.offset=n}),done:!1}}};async function eK(e,t={},n){let a,r;typeof e=="string"?a=e:(a=e.url,r=tK(e));let s=await(n||w.fetch)(a,r);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new kE(i,t)}else throw new Error(s.statusText)}var tK=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 IE(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var SE=class extends vE{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(IE(this.input)&&G().get("IS_NODE")){let e=kv();this.input=e.readFileSync(this.input.slice(7))}return new kE(this.input,this.options)}},NE=class extends vE{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return IE(this.url)?new SE(this.url,this.fileOptions).iterator():eK(this.url,this.fileOptions)}};function nK(e,t={}){return new bE(new NE(e),t)}function aK(e){let t=$1(e);return Kn(async()=>t)}function rK(e){return Kn(async()=>{let t=await e();return $1(()=>t.next())})}async function sK(e,t){return K5.create(e,t)}async function iK(e){return j5.create(e)}var oK="4.16.0";function ge(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 lK=hr.whereImpl,R1=class TE extends Fc{nextDataId(){return TE.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new ym(this,Ta())}write(t,n,a){this.firstUse&&(this.firstUse=!1,G().get("IS_NODE")&&T.warn(`
|
|
============================
|
|
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let r={id:this.nextDataId()};return this.data.set(r,{values:t,dtype:a,refCount:1}),r}makeTensorInfo(t,n,a){let r;if(n==="string"&&a!=null&&a.length>0&&w.isString(a[0])){let s=a.map(i=>w.encodeString(i));r=this.write(s,t,n)}else r=this.write(a,t,n);return{dataId:r,shape:t,dtype:n}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let n=this.data.get(t);n.refCount++}decRef(t){if(this.data.has(t)){let n=this.data.get(t);n.refCount--}}move(t,n,a,r,s){this.data.set(t,{values:n,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:n,complexTensorInfos:a}=this.data.get(t);if(n==="complex64"){let r=this.readSync(a.real.dataId),s=this.readSync(a.imag.dataId);return T.mergeRealAndImagArrays(r,s)}return w.convertBackendValuesAndArrayBuffer(this.data.get(t).values,n)}bufferSync(t){let n=this.readSync(t.dataId);if(t.dtype==="string")try{let a=n.map(r=>w.decodeString(r));return Oe(t.shape,t.dtype,a)}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Oe(t.shape,t.dtype,n)}makeOutput(t,n,a){return Ta().makeTensorFromTensorInfo(this.makeTensorInfo(n,a,t),this)}disposeData(t,n=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!n&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:a}=this.data.get(t);a!=null&&(this.disposeData(a.real.dataId,!0),this.disposeData(a.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){let n=w.now();return t(),{kernelMs:w.now()-n}}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(t){ge([t],"where");let n=this.readSync(t.dataId);return lK(t.shape,n)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};R1.nextDataId=0;var M1={};_e(M1,{addImpl:()=>_E,bincountImpl:()=>P1,bincountReduceImpl:()=>AE,bitwiseAndImpl:()=>FE,castImpl:()=>EE,ceilImpl:()=>$E,concatImpl:()=>L1,equalImpl:()=>DE,expImpl:()=>ME,expm1Impl:()=>PE,floorDivImpl:()=>zE,floorImpl:()=>LE,gatherNdImpl:()=>WE,gatherV2Impl:()=>BE,greaterEqualImpl:()=>UE,greaterImpl:()=>VE,lessEqualImpl:()=>HE,lessImpl:()=>GE,linSpaceImpl:()=>qE,logImpl:()=>jE,maxImpl:()=>KE,maximumImpl:()=>XE,minimumImpl:()=>YE,multiplyImpl:()=>z1,negImpl:()=>ZE,notEqualImpl:()=>JE,prodImpl:()=>QE,raggedGatherImpl:()=>e_,raggedRangeImpl:()=>t_,raggedTensorToTensorImpl:()=>n_,rangeImpl:()=>B1,rsqrtImpl:()=>a_,scatterImpl:()=>ti,sigmoidImpl:()=>o8,simpleAbsImpl:()=>CE,sliceImpl:()=>um,sparseFillEmptyRowsImpl:()=>s_,sparseReshapeImpl:()=>i_,sparseSegmentReductionImpl:()=>V1,sqrtImpl:()=>p8,squaredDifferenceImpl:()=>o_,staticRegexReplaceImpl:()=>l_,stridedSliceImpl:()=>u_,stringNGramsImpl:()=>U1,stringSplitImpl:()=>G1,stringToHashBucketFastImpl:()=>H1,subImpl:()=>p_,tileImpl:()=>c_,topKImpl:()=>h_,transposeImpl:()=>W1,uniqueImpl:()=>j1});function CE(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var uK=e=>{let{x:t}=e.inputs,n=e.backend;ge(t,"abs");let a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=CE(r),n.makeOutput(a,t.shape,t.dtype)},pK={kernelName:Yl,backendName:"cpu",kernelFunc:uK};function Mt(e){return(t,n,a,r,s)=>{let i=T.assertAndGetBroadcastShape(t,n),o=i.length,l=w.computeStrides(i),u=w.sizeFromShape(i),p=w.getTypedArrayFromDType(s,u),d=t.length,c=n.length,h=w.computeStrides(t),m=w.computeStrides(n),f=T.getBroadcastDims(t,i),g=T.getBroadcastDims(n,i);if(f.length+g.length===0)for(let b=0;b<p.length;++b)p[b]=e(a[b%a.length],r[b%r.length]);else for(let b=0;b<p.length;++b){let y=w.indexToLoc(b,o,l),x=y.slice(-d);f.forEach(C=>x[C]=0);let v=w.locToIndex(x,d,h),I=y.slice(-c);g.forEach(C=>I[C]=0);let N=w.locToIndex(I,c,m);p[b]=e(a[v],r[N])}return[p,i]}}function Yn(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}var cK={kernelName:wm,backendName:"cpu",kernelFunc:Yn};function lm(e,t,n="float32"){if(n==="complex64"){let r=lm(e,t,"float32"),s=lm(e,t,"float32");return Yn({inputs:{real:r,imag:s},backend:e})}let a=w.makeZerosTypedArray(w.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function pr(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var dK={kernelName:eo,backendName:"cpu",kernelFunc:pr};function yi(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.real,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var hK={kernelName:Dm,backendName:"cpu",kernelFunc:yi};function EE(e,t,n,a){if(a==="int32"){let r=Int32Array.from(e);return[t,"int32",r]}if(a==="bool"){let r=w.toTypedArray([0],n),[s,i]=Mt((o,l)=>o!==l?1:0)(t,[],e,r,"bool");return[i,"bool",s]}throw new Error(`Error in Cast: failed to cast ${n} to ${a}`)}function gs(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return pr({inputs:{x:r},backend:n});let p=lm(n,r.shape,r.dtype),d=gs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),c=Yn({inputs:{real:d,imag:p},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),c}if(r.dtype==="complex64"){let p=yi({inputs:{input:r},backend:n}),d=gs({inputs:{x:p},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(p),d}if(!w.hasEncodingLoss(r.dtype,s)){let p=pr({inputs:{x:r},backend:n});return{dataId:p.dataId,shape:p.shape,dtype:s}}let i=n.data.get(r.dataId).values,[o,l,u]=EE(i,r.shape,r.dtype,s);return n.makeTensorInfo(o,l,u)}var mK={kernelName:Mi,backendName:"cpu",kernelFunc:gs};function Zt(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;ge([i,o],e);let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,d=i.dtype==="string"?T.fromUint8ToStringArray(u):u,c=i.dtype==="string"?T.fromUint8ToStringArray(p):p,h=a||i.dtype,[m,f]=t(i.shape,o.shape,d,c,h);return l.makeTensorInfo(f,h,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=gs({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(u.dataId),d=p.complexTensorInfos.real,c=p.complexTensorInfos.imag,h=l.data.get(d.dataId).values,m=l.data.get(c.dataId).values,f=gs({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),b=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,x=l.data.get(b.dataId).values,v=l.data.get(y.dataId).values,[I,N,C]=n(i.shape,o.shape,h,m,x,v),_=l.makeTensorInfo(C,"float32",I),F=l.makeTensorInfo(C,"float32",N),D=Yn({inputs:{real:_,imag:F},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(_),l.disposeIntermediateTensorInfo(F),D}else{let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,d=a||i.dtype,[c,h]=t(i.shape,o.shape,u,p,d);return l.makeTensorInfo(h,d,c)}}}function O1(e){return(t,n,a,r,s,i)=>{let o=T.assertAndGetBroadcastShape(t,n),l=w.sizeFromShape(o),u=o.length,p=w.computeStrides(o),d=w.getTypedArrayFromDType("float32",l),c=w.getTypedArrayFromDType("float32",l),h=T.getBroadcastDims(t,o),m=T.getBroadcastDims(n,o),f=T.mergeRealAndImagArrays(a,r),g=T.mergeRealAndImagArrays(s,i),b=t.length,y=w.computeStrides(t),x=n.length,v=w.computeStrides(n);if(h.length+m.length===0)for(let I=0;I<d.length;I++){let N=I%f.length,C=I%g.length,_=e(f[N*2],f[N*2+1],g[C*2],g[C*2+1]);d[I]=_.real,c[I]=_.imag}else for(let I=0;I<d.length;I++){let N=w.indexToLoc(I,u,p),C=N.slice(-b);h.forEach(S=>C[S]=0);let _=w.locToIndex(C,b,y),F=N.slice(-x);m.forEach(S=>F[S]=0);let D=w.locToIndex(F,x,v),$=e(f[_*2],f[_*2+1],g[D*2],g[D*2+1]);d[I]=$.real,c[I]=$.imag}return[d,c,o]}}var _E=Mt((e,t)=>e+t),fK=O1((e,t,n,a)=>({real:e+n,imag:t+a})),ql=Zt(xs,_E,fK),gK={kernelName:xs,backendName:"cpu",kernelFunc:ql};function P1(e,t,n,a,r){let s=w.sizeFromShape(a),i=w.makeZerosTypedArray(r,n);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function AE(e,t,n,a=!1){let r=e.shape[0],s=e.shape[1],i=Oe([r,n],t.dtype);for(let o=0;o<r;o++)for(let l=0;l<s;l++){let u=e.get(o,l);if(u<0)throw new Error("Input x must be non-negative!");u>=n||(a?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}var FE=Mt((e,t)=>e&t),bK=Zt(ru,FE),yK={kernelName:ru,backendName:"cpu",kernelFunc:bK};function mr(e){return(t,n,a)=>{let r=w.getArrayFromDType(n,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],a);return r}}function lt(e,t,n){let a=mr(t);return As(e,a,n)}function As(e,t,n){return({inputs:a,attrs:r,backend:s})=>{let{x:i}=a;ge(i,e);let o=s,l=o.data.get(i.dataId).values,u;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=T.fromUint8ToStringArray(l)}else u=l;let p=n||i.dtype,d=t(u,p,r);return o.makeTensorInfo(i.shape,p,d)}}var $E=mr(e=>Math.ceil(e)),xK=As(Oi,$E),vK={kernelName:Oi,backendName:"cpu",kernelFunc:xK};function L1(e,t,n,a){let r=w.getArrayFromDType(n,w.sizeFromShape(t));if(a&&n!=="string"){let s=0;e.forEach(i=>{let o=w.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=n==="string"?T.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let p=u*t[1]+s;for(let d=0;d<i.shape[1];++d)r[p+d]=o[l++]}s+=i.shape[1]})}return r}var DE=Mt((e,t)=>e===t?1:0),RE=Zt(du,DE,null,"bool"),wK={kernelName:du,backendName:"cpu",kernelFunc:RE},ME=mr(e=>Math.exp(e)),OE=As(Ki,ME,"float32"),kK={kernelName:Ki,backendName:"cpu",kernelFunc:OE},PE=mr(e=>Math.expm1(e)),IK=As(Xi,PE),SK={kernelName:Xi,backendName:"cpu",kernelFunc:IK},LE=mr(e=>Math.floor(e)),NK=As(Yi,LE),TK={kernelName:Yi,backendName:"cpu",kernelFunc:NK},zE=Mt((e,t)=>Math.floor(e/t)),CK=Zt(Zi,zE,null,"int32"),EK={kernelName:Zi,backendName:"cpu",kernelFunc:CK};function WE(e,t,n,a,r,s,i,o,l){let u=Oe([a,s],n);for(let p=0;p<a;p++){let d=[],c=0;for(let h=0;h<r;h++){let m=e[p*r+h];c+=m*i[h],d.push(m)}if(c<0||c>=l/s)throw new Error(`Invalid indices: ${d} does not index into ${o}`);for(let h=0;h<s;h++)u.values[p*s+h]=t.get(...t.indexToLoc(c*s+h))}return u}function BE(e,t,n){let a=Oe(n,e.dtype);for(let r=0;r<a.size;++r){let s=a.indexToLoc(r).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let u=e.locToIndex(s);0<=u&&u<e.values.length&&(a.values[r]=e.values[u])}return a}var VE=Mt((e,t)=>e>t?1:0),_K=Zt(bu,VE,null,"bool"),AK={kernelName:bu,backendName:"cpu",kernelFunc:_K},UE=Mt((e,t)=>e>=t?1:0),FK=Zt(Qi,UE,null,"bool"),$K={kernelName:Qi,backendName:"cpu",kernelFunc:FK},GE=Mt((e,t)=>e<t?1:0),DK=Zt(yu,GE,null,"bool"),RK={kernelName:yu,backendName:"cpu",kernelFunc:DK},HE=Mt((e,t)=>e<=t?1:0),MK=Zt(xu,HE,null,"bool"),OK={kernelName:xu,backendName:"cpu",kernelFunc:MK};function qE(e,t,n){let a=(t-e)/(n-1),r=w.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;s<r.length;s++)r[s]=r[s-1]+a;return r}var jE=mr(e=>Math.log(e)),PK=As(so,jE),LK={kernelName:so,backendName:"cpu",kernelFunc:PK};function KE(e,t,n,a){let r=w.getTypedArrayFromDType(a,w.sizeFromShape(n));for(let s=0;s<r.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let u=e[i+l];(Number.isNaN(u)||u>o)&&(o=u)}r[s]=o}return r}var XE=Mt((e,t)=>Math.max(e,t)),zK=Zt(uo,XE),WK={kernelName:uo,backendName:"cpu",kernelFunc:zK},YE=Mt((e,t)=>Math.min(e,t)),BK=Zt(mo,YE),VK={kernelName:mo,backendName:"cpu",kernelFunc:BK},z1=Mt((e,t)=>e*t),UK=O1((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),Lf=Zt(bo,z1,UK),GK={kernelName:bo,backendName:"cpu",kernelFunc:Lf};function ZE(e,t,n){let a=w.createScalarValue(-1,n);return z1([],t,a,e,n)}function HK(e){let{inputs:t,backend:n}=e,{x:a}=t;ge(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=ZE(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var qK={kernelName:Cu,backendName:"cpu",kernelFunc:HK},JE=Mt((e,t)=>e!==t?1:0),jK=Zt(Eu,JE,null,"bool"),KK={kernelName:Eu,backendName:"cpu",kernelFunc:jK};function W1(e,t,n,a,r){let s=t.length,i=w.sizeFromShape(t),o=w.computeStrides(t),l=w.computeStrides(r),u=w.getTypedArrayFromDType(n,w.sizeFromShape(r));for(let p=0;p<i;++p){let d=w.indexToLoc(p,s,o),c=new Array(d.length);for(let m=0;m<c.length;m++)c[m]=d[a[m]];let h=w.locToIndex(c,s,l);u[h]=e[p]}return u}function Bn(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{perm:s}=n;ge(r,"transpose");let i=r.shape.length,o=new Array(i);for(let p=0;p<o.length;p++)o[p]=r.shape[s[p]];let l=a.data.get(r.dataId).values,u=W1(l,r.shape,r.dtype,s,o);return{dataId:a.write(u,o,r.dtype),shape:o,dtype:r.dtype}}var XK={kernelName:Tr,backendName:"cpu",kernelFunc:Bn};function QE(e,t,n,a){let[r,s]=T.computeOutAndReduceShapes(e,a),i=fa(t,"int32"),o=w.makeZerosTypedArray(w.sizeFromShape(r),i),l=w.sizeFromShape(s);for(let u=0;u<o.length;++u){let p=u*l,d=1;for(let c=0;c<l;++c)d*=n[p+c];o[u]=d}return{outVals:o,outShape:r,outDtype:i}}function YK(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"prod");let o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=T.getAxesPermutation(l,o),p=l,d=r,c=[];u!=null&&(d=Bn({inputs:{x:r},backend:n,attrs:{perm:u}}),c.push(d),p=T.getInnerMostAxes(p.length,o));let h=n.data.get(d.dataId).values,{outVals:m,outShape:f,outDtype:g}=QE(d.shape,d.dtype,h,p),b=f;return i&&(b=T.expandShapeToKeepDim(f,l)),c.forEach(y=>n.disposeIntermediateTensorInfo(y)),n.makeTensorInfo(b,g,m)}var ZK={kernelName:ko,backendName:"cpu",kernelFunc:YK};function JK(e,t,n){e.forEach((a,r)=>{if(a<0||a>=n){let s=w.indexToLoc(r,t.length,w.computeStrides(t)).join(",");throw new Error(`indices[${s}] = ${a} is not in [0, ${n})`)}})}function QK(e,t){for(let n=0;n<e.length;++n){let a=e[n],r=n===e.length-1?t:e[n+1].length;if(a.length===0)throw new Error("Ragged splits may not be empty");if(a[0]<0)throw new Error("Ragged splits must be non-negative");if(a[a.length-1]>r)throw new Error("Ragged splits must not point past values");for(let s=1;s<a.length;++s)if(a[s-1]>a[s])throw new Error("Ragged splits must be sorted in ascending order")}}function e8(e,t,n,a){let r=[],s=0,i=t.length-1+n.length,o=new Array(i).fill(null).map(()=>[0]);QK(n,a);let l=1;for(let u=0;u<t.length-1;++u){l*=t[u];let p=t[u+1];for(let d=1;d<l+1;++d)o[u].push(d*p)}for(let u=0;u<e.length;++u){let p=e[u],d=e[u]+1;for(let c=0;c<n.length;++c){let h=n[c],m=c+t.length-1;if(m>=0){let f=o[m],g=f[f.length-1]-h[p];for(let b=p;b<d;++b)o[m].push(h[b+1]+g)}p=h[p],d=h[d]}d!==p&&(r.push([p,d]),s+=d-p)}return{outSplits:o,valueSlices:r,numValues:s}}function t8(e){let t=[];for(let n=0;n<e.length;++n){let a=e[n].length,r=w.getArrayFromDType("int32",a);t.push(r),e[n].forEach((s,i)=>r[i]=s)}return t}function YI(e,t){let n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let a=t;a<e.length;a++)n[t-1]*=e[a];return n}function n8(e,t,n,a,r,s){let i=YI(t,2)[1],o=YI(s,2)[1],l=0;for(let u of n)for(let p=u[0];p<u[1];++p){for(let d=0;d<a;++d)r[l*o+d]=e[p*i+d];++l}}function a8(e,t,n,a,r){let s=t.slice();s[0]=r;let i=w.getArrayFromDType(n,w.sizeFromShape(s)),o=e.length,l=o===0?0:o/t[0];return n8(e,t,a,l,i,s),[i,s]}function e_(e,t,n,a,r,s,i,o){if(e.length===0)throw new Error("paramsNestedSplits must be non empty");if(t[0].length===0)throw new Error("Split tensors must not be scalars");let l=t[0][0]-1;if(JK(s,i,l),a.length===0)throw new Error("params.rank must be nonzero");let u=a[0],{outSplits:p,valueSlices:d,numValues:c}=e8(s,i,e,u),h=t8(p),m=a8(n,a,r,d,c);return[h,m[0],m[1]]}var ZI=2147483647;function t_(e,t,n,a,r,s,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");let o=t.length===0,l=r.length===0,u=i.length===0,p=[];o||p.push(t[0]),l||p.push(r[0]),u||p.push(i[0]);for(let g=1;g<p.length;++g)if(p[g]!==p[g-1])throw new Error("starts, limits, and deltas must have the same shape");let d=p.length===0?1:p[0],c=w.getArrayFromDType("int32",d+1);c[0]=0;for(let g=0;g<d;++g){let b=o?e[0]:e[g],y=l?a[0]:a[g],x=u?s[0]:s[g];if(x===0)throw new Error("Requires delta != 0");let v;if(x>0&&y<b||x<0&&y>b)v=0;else if(v=Math.ceil(Math.abs((y-b)/x)),v>ZI)throw new Error(`Requires ((limit - start) / delta) <= ${ZI}`);c[g+1]=c[g]+v}let h=c[d],m=w.getArrayFromDType(n,h),f=0;for(let g=0;g<d;++g){let b=c[g+1]-c[g],y=o?e[0]:e[g],x=u?s[0]:s[g];for(let v=0;v<b;++v)m[f++]=y,y+=x}return[c,m]}var Na=T.RowPartitionType,r8=class iv{constructor(t,n,a,r,s,i,o,l,u,p){this.shape=t,this.shapeShape=n,this.values=a,this.valuesShape=r,this.valuesDType=s,this.defaultValue=i,this.defaultValueShape=o,this.rowPartitionValues=l,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=T.getRowPartitionTypesHelper(p),this.raggedRank=T.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===Na.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===Na.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){let n=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case Na.VALUE_ROWIDS:return iv.getMaxWidthValueRowID(n);case Na.ROW_SPLITS:return iv.getMaxWidthRowSplit(n);default:throw new Error(`Cannot handle partition type ${Na[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){let n=t.length;if(n===0||n===1)return 0;let a=0;for(let r=0;r<n-1;++r){let s=t[r+1]-t[r];s>a&&(a=s)}return a}static getMaxWidthValueRowID(t){let n=t.length;if(n===0)return 0;let a=0,r=t[0],s=0;for(let i=1;i<n;++i){let o=t[i];o!==r&&(r=o,s=Math.max(i-a,s),a=i)}return Math.max(n-a,s)}tensorShapeFromTensor(t,n,a=!0){if(n.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return QI(t,a)}calculateOutputSize(t){let n=this.valuesShape,a=this.defaultValueShape;T.validateDefaultValueShape(a,n);let r=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=T.combineRaggedTensorToTensorShapes(this.raggedRank,r,n);s[0]<0&&(s[0]=t);for(let i=1;i<=this.raggedRank;++i)s[i]<0&&(s[i]=this.getMaxWidth(i));return s}calculateFirstParentOutputIndex(t,n,a){let r=Math.min(t,a),s=[],i=0;for(let o=0;o<r;++o,i+=n)s.push(i);for(let o=r;o<t;++o)s.push(-1);return w.assert(s.length===t,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(t,n,a,r){let s=t.length,i=[];for(let o=0;o<s-1;++o){let l=t[o+1]-t[o],u=Math.min(r,l),p=n[o];p===-1&&(u=0);for(let d=0;d<u;++d)i.push(p),p+=a;for(let d=0;d<l-u;++d)i.push(-1)}if(s>0&&i.length!==t[s-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,n,a,r){let s=t.length,i=[];if(s===0)return[];let o=0,l=t[0];if(l>=n.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${n.length}`);let u=n[l];i.push(u);for(let p=1;p<s;++p){let d=t[p];if(d===l)u>=0&&(++o,o<r?u+=a:u=-1);else{if(o=0,l=d,d>=n.length)throw new Error(`Got nextValueRowId=${d} which is not less than ${n.length}`);u=n[d]}i.push(u)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,n,a,r){let s=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case Na.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,n,a,r);case Na.ROW_SPLITS:if(s.length-1>n.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${n.length}`);return this.calculateOutputIndexRowSplit(s,n,a,r);default:throw new Error(`Unsupported partition type: ${Na[i]}`)}}getFirstDimensionSize(){let t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let n=this.rowPartitionTypes[0];switch(n){case Na.FIRST_DIM_SIZE:return t[0];case Na.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Na.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Na[n]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let t=this.getFirstDimensionSize(),n=this.calculateOutputSize(t),a=new Array(this.raggedRank+1);a[a.length-1]=1;for(let i=a.length-2;i>=0;--i)a[i]=a[i+1]*n[i+1];let r=QI(n,!1),s=w.getArrayFromDType(this.valuesDType,w.sizeFromShape(r));if(a[0]*n[0]>0){let i=this.calculateFirstParentOutputIndex(t,a[0],n[0]);for(let o=1;o<=this.raggedRank;++o)i=this.calculateOutputIndex(o-1,i,a[o],n[o]);this.setOutput(this.raggedRank,i,s,r)}return[r,s]}setOutput(t,n,a,r){if(a.length===0)return;let s=this.values,i=a,o=r.slice();o=o.slice(t+1);let l=w.sizeFromShape(o),u=n.length,p=this.defaultValue;if(p.length!==l&&p.length!==1){let m=this.defaultValueShape;O(()=>{let f=W(p,m);p=ni(f,o).dataSync()})}let d=0,c=0,h=0;for(let m=0;m<=u;++m){let f=m<u?n[m]:-1;if(f===h){++h;continue}if(c<h){let g=s.subarray(d*l),b=i.subarray(c*l),y=(h-c)*l;JI(b,g,y)}if(m>=u){let g=a.length;f=Math.floor(g/l)}if(f>h)if(this.defaultValue.length===1)i.subarray(h*l,f*l).fill(this.defaultValue[0]),h=f;else for(;f>h;){let g=i.slice(h*l);JI(g,p,l),++h}f<0?(d=m+1,c=h):(d=m,c=h,h=c+1)}}};function JI(e,t,n){for(let a=0;a<n;a++)e[a]=t[a]}function QI(e,t){let n=[];for(let a of e){if(a<0){if(!t)throw new Error(`Dimension ${a} must be >= 0`);if(a<-1)throw new Error(`Dimension ${a} must be >= -1`);a=-1}n.push(a)}return n}function n_(e,t,n,a,r,s,i,o,l,u){return new r8(e,t,n,a,r,s,i,o,l,u).compute()}function B1(e,t,n,a){let r=e===t,s=e<t&&n<0,i=t<e&&n>1;if(r||s||i)return w.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=w.makeZerosTypedArray(o,a);t<e&&n===1&&(n=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+n;return l}var a_=mr(e=>1/Math.sqrt(e)),s8=As(Ao,a_),i8={kernelName:Ao,backendName:"cpu",kernelFunc:s8};function ti(e,t,n,a,r,s,i,o,l,u){let p=[a/r,r],d=e.values,c=t.values;if(a===0)return Oe(n,t.dtype);let h=l instanceof Wt?l:Oe(p,t.dtype);typeof l=="string"||typeof l=="number"?h.values.fill(l):typeof l=="boolean"&&h.values.fill(+l);for(let m=0;m<s;m++){let f=[],g=0;for(let b=0;b<i;b++){let y=d[m*i+b];f.push(y),g+=y*o[b]}if(g<0||g>=a/r)throw new Error(`Invalid indices: ${f} does not index into ${n}`);for(let b=0;b<r;b++)u?h.values[g*r+b]+=c[m*r+b]:h.values[g*r+b]=t.rank===0?c[0]:c[m*r+b]}return h}var o8=mr(e=>1/(1+Math.exp(-e))),r_=lt(Mo,e=>1/(1+Math.exp(-e))),l8={kernelName:Mo,backendName:"cpu",kernelFunc:r_};function um(e,t,n,a,r){let s=Kt.isSliceContinous(a,t,n),i=w.sizeFromShape(n),o=w.computeStrides(a);if(s){let d=Kt.computeFlatOffset(t,o);return r==="string"?e.slice(d,d+i):e.subarray(d,d+i)}let l=r==="string"?T.fromUint8ToStringArray(e):e,u=Oe(a,r,l),p=Oe(n,r);for(let d=0;d<p.size;++d){let c=p.indexToLoc(d),h=c.map((m,f)=>m+t[f]);p.set(u.get(...h),...c)}return r==="string"?T.fromStringArrayToUint8(p.values):p.values}function xi(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;ge(r,"slice");let[o,l]=Kt.parseSliceParams(r,s,i);Kt.assertParamsValid(r,o,l);let u=n.data.get(r.dataId).values,p=um(u,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}var u8={kernelName:Bu,backendName:"cpu",kernelFunc:xi};function s_(e,t,n,a,r,s,i){let o=t[0],l=s[0],u=new Array(l),p=new Array(o),d=t[1];if(l===0){if(o!==0)throw new Error(T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(r,0);return[g,[0,d],b,u,p]}let c=!0,h=0,m=new Array(l).fill(0);for(let g=0;g<o;++g){let b=e[g*d];if(b<0)throw new Error(T.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,b));if(b>=l)throw new Error(T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,b,l));++m[b],c=c&&b>=h,h=b}let f=!0;for(let g=0;g<l;++g){let b=m[g]===0;u[g]=b,f=f&&!b,m[g]=Math.max(m[g],1),g>0&&(m[g]+=m[g-1])}if(f&&c){let g=e,b=a;for(let y=0;y<o;++y)p[y]=y;return[g,[o,d],b,u,p]}else{let g=m[l-1],b=w.getArrayFromDType(n,g*d),y=w.getArrayFromDType(r,g),x=new Array(l).fill(0);for(let v=0;v<o;++v){let I=e[v*d],N=x[I],C=(I===0?0:m[I-1])+N;x[I]++;for(let _=0;_<d;++_)b[C*d+_]=e[v*d+_];y[C]=a[v],p[v]=C}for(let v=0;v<l;++v)if(x[v]===0){let I=v===0?0:m[v-1];b[I*d+0]=v;for(let N=1;N<d;++N)b[I*d+N]=0;y[I]=i}return[b,[g,d],y,u,p]}}function i_(e,t,n,a,r){let s=w.sizeFromShape(a),i=t[0],o=r.length,l=[],u=1,p=-1;for(let f=0;f<o;++f){let g=r[f];if(g===-1){if(p!==-1)throw new Error(T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(p,f));p=f,l.push(1)}else{if(g<0)throw new Error(T.getSparseReshapeNegativeOutputDimErrorMessage(f,g));u*=g,l.push(g)}}if(p!==-1){if(u<=0)throw new Error(T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let f=Math.trunc(s/u);if(u*f!==s)throw new Error(T.getSparseReshapeInputOutputMultipleErrorMessage(a,l));l[p]=f}if(w.sizeFromShape(l)!==s)throw new Error(T.getSparseReshapeInputOutputMismatchErrorMessage(a,l));let d=a.length,c=[];if(d>0){c[d-1]=1;for(let f=d-2;f>=0;--f)c[f]=c[f+1]*a[f+1]}let h=[];if(o>0){h[o-1]=1;for(let f=o-2;f>=0;--f)h[f]=h[f+1]*l[f+1]}let m=w.getArrayFromDType(n,i*o);for(let f=0;f<i;++f){let g=0;for(let b=0;b<d;++b)g+=e[f*d+b]*c[b];for(let b=0;b<o;++b)m[f*o+b]=Math.trunc(g/h[b]),g%=h[b]}return[m,[i,o],l]}function V1(e,t,n,a,r,s=!1,i=0){let o=a.length,l=[t[0],e.length/t[0]],u=l[1],p=o>0?r[o-1]+1:0;if(p<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=t.slice();d[0]=p;let c=d.reduce((y,x)=>y*x,1),h=w.getArrayFromDType(n,c);if(o===0)return p>0&&h.fill(i),[h,d];if(p<=0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,f=1,g=0,b=r[m];for(;;){let y=0;if(f<o){if(y=r[f],b===y){++f;continue}if(b>=y)throw new Error(T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(b<0||b>=p)throw new Error(T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b,p));b>g&&h.fill(i,g*u,b*u);for(let x=m;x<f;++x){let v=a[x];if(v<0||v>=l[0])throw new Error(T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,a[x],l[0]));for(let I=0;I<u;I++)h[b*u+I]+=e[v*u+I]}if(s)for(let x=0;x<u;x++)h[b*u+x]/=f-m;if(m=f,++f,g=b+1,b=y,f>o)break}return g<p&&h.fill(i,g*u,p*u),[h,d]}var p8=mr(e=>Math.sqrt(e)),c8=lt(Po,e=>Math.sqrt(e)),d8={kernelName:Po,backendName:"cpu",kernelFunc:c8},o_=Mt((e,t)=>{let n=e-t;return n*n}),h8=Zt(Wo,o_),m8={kernelName:Wo,backendName:"cpu",kernelFunc:h8},l_=mr((e,t)=>{let{pattern:n,replaceGlobal:a,rewrite:r}=t;return e.replace(new RegExp(n,a?"g":""),r)}),f8=As(Kc,l_),g8={kernelName:Kc,backendName:"cpu",kernelFunc:f8};function u_(e,t,n,a){let r=Oe(e,t.dtype);for(let s=0;s<r.size;s++){let i=r.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*n[l]+a[l];r.set(t.get(...o),...i)}return r}var b8=class{constructor(e,t,n,a,r,s){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(a),this.padWidth=r,this.preserveShort=s}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,a,r,s){for(let i=0;i<r;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),u=Math.max(0,o-(r-(i+1))),p=s-(l+u),d=t+(l>0?0:i-o),c=0;c+=l*this.leftPad.length;for(let b=0;b<p;++b)c+=e[d+b].length;c+=u*this.rightPad.length;let h=l+u+p-1;c+=h*this.separator.length,n[a+i]=new Uint8Array(c);let m=n[a+i],f=0,g=b=>b.forEach(y=>m[f++]=y);for(let b=0;b<l;++b)g(this.leftPad),g(this.separator);for(let b=0;b<p-1;++b)g(e[d+b]),g(this.separator);if(p>0){g(e[d+p-1]);for(let b=0;b<u;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<u-1;++b)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,a=t.length;if(a>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<a;++l){let u=t[l]>=o;if(u=u&&t[l]<=n,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${n}]`);o=t[l]}if(o!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${o}`)}let r=a-1,s=w.getArrayFromDType("int32",a);if(n===0||a===0){let o=new Array(n);for(let l=0;l<=r;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=r;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(p=>{u+=this.getNumNGrams(l,p)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[r]);for(let o=0;o<r;++o){let l=t[o],u=s[o];if(this.nGramWidths.forEach(p=>{let d=t[o+1]-t[o],c=this.getNumNGrams(d,p);this.createNGrams(e,l,i,u,c,p),u+=c}),this.preserveShort&&u===s[o]){let p=t[o+1]-t[o];if(p===0)continue;let d=p+2*this.padWidth;this.createNGrams(e,l,i,u,1,d)}}return[i,s]}};function U1(e,t,n,a,r,s,i,o){return new b8(n,a,r,s,i,o).compute(e,t)}function y8(e,t,n,a){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)a.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!n||o.length!==0)&&a.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!n||e.length!==0)&&a.push(e);return}let r=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(r,s);(!n||i.length!==0)&&a.push(i),r=s+1}}function G1(e,t,n){let a=e.length,r=[],s=0,i=0,o=new Array(a);for(let c=0;c<a;++c){let h=r.length;y8(e[c],t,n,r);let m=r.length-h;o[c]=m,s+=m,i=Math.max(i,m)}let l=w.getArrayFromDType("int32",s*2),u=new Array(s),p=[a,i],d=0;for(let c=0;c<a;++c)for(let h=0;h<o[c];++h)l[d*2]=c,l[d*2+1]=h,u[d]=r[d],++d;return[l,u,p]}function H1(e,t){let n=w.getArrayFromDType("int32",e.length);for(let a=0;a<e.length;++a)n[a]=w.fingerPrint64(e[a]).modulo(t).getLowBitsUnsigned();return n}var p_=Mt((e,t)=>e-t),x8=O1((e,t,n,a)=>({real:e-n,imag:t-a})),q1=Zt(Bo,p_,x8),v8={kernelName:Bo,backendName:"cpu",kernelFunc:q1};function c_(e,t){let n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];let a=Oe(n,e.dtype);for(let r=0;r<a.values.length;++r){let s=a.indexToLoc(r),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);a.values[r]=e.values[o]}return a}var nc=(e,t)=>{let n=t.value-e.value;return n===0?e.index-t.index:n};function d_(e,t,n=0,a=e.length-1){for(;a>n;){if(a-n>600){let o=a-n+1,l=t-n+1,u=Math.log(o),p=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*p*(o-p)/o)*Math.sign(l-o/2),c=Math.max(n,Math.floor(t-l*p/o+d)),h=Math.min(a,Math.floor(t+(o-l)*p/o+d));d_(e,t,c,h)}let r=e[t],s=n,i=a;for(w.swap(e,n,t),nc(e[a],r)>0&&w.swap(e,n,a);s<i;){for(w.swap(e,s,i),s++,i--;nc(e[s],r)<0;)s=s+1;for(;nc(e[i],r)>0;)i=i-1}nc(e[n],r)===0?w.swap(e,n,i):(i=i+1,w.swap(e,i,a)),i<=t&&(n=i+1),t<=i&&(a=i-1)}}function h_(e,t,n,a,r){let s=t[t.length-1],[i,o]=[e.length/s,s],l=w.getTypedArrayFromDType(n,i*a),u=w.getTypedArrayFromDType("int32",i*a);for(let d=0;d<i;d++){let c=d*o,h=e.subarray(c,c+o),m=new Array(h.length);h.forEach((y,x)=>m[x]={value:y,index:x}),a<m.length&&(d_(m,a),m=m.slice(0,a)),r&&m.sort(nc);let f=d*a,g=l.subarray(f,f+a),b=u.subarray(f,f+a);for(let y=0;y<a;y++)g[y]=m[y].value,b[y]=m[y].index}let p=t.slice();return p[p.length-1]=a,[Oe(p,n,l),Oe(p,"int32",u)]}function j1(e,t,n,a){let r=w.parseAxisParam(t,n)[0],s=[1,n[0],1];for(let m=0;m<r;m++)s[0]*=n[m];s[1]=n[r];for(let m=r+1;m<n.length;m++)s[2]*=n[m];let i=new Map,o=new Int32Array(n[r]),l=new Wt(s,a,e),u=[],p=s[0]===1&&s[2]===1;for(let m=0;m<n[r];m++){let f;if(p)f=e[m].toString();else{let b=[];for(let y=0;y<s[0];y++)for(let x=0;x<s[2];x++)b.push(l.get(y,m,x));f=b.join(",")}let g=i.get(f);if(g!=null)o[m]=g;else{let b=i.size;i.set(f,b),o[m]=b,u.push(m)}}let d=s.slice();d[1]=i.size;let c=new Wt(d,a);u.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let b=0;b<s[2];b++)c.set(l.get(g,m,b),g,f,b)});let h=n.slice();return h[r]=d[1],{outputValues:c.values,outputShape:h,indices:o}}var w8="4.16.0";Om("cpu",()=>new R1,1);var m_=lt(qi,e=>e>=0?e:Math.exp(e)-1),k8={kernelName:qi,backendName:"cpu",kernelFunc:m_};function f_(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;ge([r],"leakyRelu");let i=w.sizeFromShape(r.shape),o=n.data.get(r.dataId).values,l=w.getTypedArrayFromDType("float32",i);for(let u=0;u<o.length;u++)l[u]=o[u]<0?s*o[u]:o[u];return n.makeTensorInfo(r.shape,"float32",l)}var I8={kernelName:ro,backendName:"cpu",kernelFunc:f_},S8=Mt((e,t)=>e<0?t*e:e);function g_(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;ge([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=S8(a.shape,r.shape,s,i,"float32");return n.makeTensorInfo(l,"float32",o)}var N8={kernelName:wo,backendName:"cpu",kernelFunc:g_},b_=lt(So,e=>Math.max(0,e)),T8={kernelName:So,backendName:"cpu",kernelFunc:b_},y_=lt(Co,e=>Math.min(Math.max(0,e),6)),C8={kernelName:Co,backendName:"cpu",kernelFunc:y_};function pm(e,t,n,a,r){if(n==="linear")return pr({inputs:{x:t},backend:e});if(n==="relu")return b_({inputs:{x:t},backend:e});if(n==="elu")return m_({inputs:{x:t},backend:e});if(n==="relu6")return y_({inputs:{x:t},backend:e});if(n==="prelu")return g_({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return f_({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return r_({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function xt(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,i),l=w.sizeFromShape(o);w.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let u=n.data.get(r.dataId);if(u.complexTensorInfos!=null){let p=u.complexTensorInfos.real,d=u.complexTensorInfos.imag;p.shape=o,d.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var E8={kernelName:Ru,backendName:"cpu",kernelFunc:xt};function x_(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;ge([r,s],"matMul");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],d=o?s.shape[u-1]:s.shape[u-2],c=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=w.sizeFromShape(m),b=w.sizeFromShape(f),y=Ju.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([c,h]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,p,c]:[g,c,p],v=o?[b,h,d]:[b,d,h],I=xt({inputs:{x:r},backend:n,attrs:{shape:x}}),N=xt({inputs:{x:s},backend:n,attrs:{shape:v}}),C=i?I.shape[1]:I.shape[2],_=i?I.shape[2]:I.shape[1],F=o?N.shape[1]:N.shape[2],D=Math.max(g,b),$=n.data.get(I.dataId).values,S=n.data.get(N.dataId).values,M=w.computeStrides(I.shape),B=w.computeStrides(N.shape),[U,H,j]=i?[M[0],1,M[1]]:[M[0],M[1],1],[K,Z,J]=o?[1,B[1],B[0]]:[B[1],1,B[0]],ee=_*F,ae=Oe([D,_,F],I.dtype),te=ae.values,se=n.blockSize;for(let ie=0;ie<D;ie++){let xe=ie%g,ue=ie%b;for(let ye=0;ye<_;ye+=se){let ke=Math.min(ye+se,_);for(let Se=0;Se<F;Se+=se){let Le=Math.min(Se+se,F);for(let Ue=0;Ue<C;Ue+=se){let mt=Math.min(Ue+se,C);for(let st=ye;st<ke;st++)for(let tt=Se;tt<Le;tt++){let nt=0;for(let Re=Ue;Re<mt;Re++){let gt=$[xe*U+st*H+Re*j],Gn=S[Re*K+tt*Z+ue*J];nt+=gt*Gn}te[ie*ee+(st*F+tt)]+=nt}}}}}return n.disposeIntermediateTensorInfo(I),n.disposeIntermediateTensorInfo(N),n.makeTensorInfo(y,ae.dtype,ae.values)}var _8={kernelName:Ri,backendName:"cpu",kernelFunc:x_};function A8(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a,c,h,m,f=[];c=x_({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:u},backend:n}),i&&(h=ql({inputs:{a:c,b:i},backend:n}),f.push(c),c=h),p&&(m=pm(n,c,p,o,d),f.push(c),c=m);for(let g of f)n.disposeIntermediateTensorInfo(g);return c}var F8={kernelName:si,backendName:"cpu",kernelFunc:A8},$8=lt(Ni,e=>Math.acos(e)),D8={kernelName:Ni,backendName:"cpu",kernelFunc:$8},R8=lt(Ti,e=>Math.acosh(e)),M8={kernelName:Ti,backendName:"cpu",kernelFunc:R8};function O8(e){let{inputs:t,backend:n}=e,a=t;ge(t,"addN");let r=a.map(o=>n.data.get(o.dataId).values),s=Oe(a[0].shape,a[0].dtype),i=s.values;for(let o=0;o<a.length;o++){let l=r[o];for(let u=0;u<i.length;u++)i[u]+=l[u]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}var P8={kernelName:Ci,backendName:"cpu",kernelFunc:O8};function L8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"all");let o=w.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Bn({inputs:{x:r},backend:n,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("all",l,p.shape.length);let[d,c]=T.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];x=x&&I}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=T.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var z8={kernelName:Zl,backendName:"cpu",kernelFunc:L8};function W8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"any");let o=w.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Bn({inputs:{x:r},backend:n,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("any",l,p.shape.length);let[d,c]=T.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];x=x||I}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=T.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var B8={kernelName:Jl,backendName:"cpu",kernelFunc:W8};function V8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ge(r,"argMax");let i=w.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Bn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],T.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[p,d]=T.computeOutAndReduceShapes(l.shape,i),c=w.sizeFromShape(p),h=w.makeZerosTypedArray(c,"int32"),m=w.sizeFromShape(d),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let b=g*m,y=f[b],x=0;for(let v=0;v<m;++v){let I=f[b+v];I>y&&(y=I,x=v)}h[g]=x}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(p,"int32",h)}var U8={kernelName:Ql,backendName:"cpu",kernelFunc:V8};function G8(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;ge(r,"argMin");let i=w.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Bn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],T.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[p,d]=T.computeOutAndReduceShapes(l.shape,i),c=w.sizeFromShape(p),h=w.makeZerosTypedArray(c,"int32"),m=w.sizeFromShape(d),f=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let b=g*m,y=f[b],x=0;for(let v=0;v<m;++v){let I=f[b+v];I<y&&(y=I,x=v)}h[g]=x}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(p,"int32",h)}var H8={kernelName:eu,backendName:"cpu",kernelFunc:G8},q8=lt(Ei,e=>Math.asin(e)),j8={kernelName:Ei,backendName:"cpu",kernelFunc:q8},K8=lt(_i,e=>Math.asinh(e)),X8={kernelName:_i,backendName:"cpu",kernelFunc:K8},Y8=lt(Ai,e=>Math.atan(e)),Z8={kernelName:Ai,backendName:"cpu",kernelFunc:Y8},J8=Mt((e,t)=>Math.atan2(e,t)),Q8=Zt($i,J8),eX={kernelName:$i,backendName:"cpu",kernelFunc:Q8},tX=lt(Fi,e=>Math.atanh(e)),nX={kernelName:Fi,backendName:"cpu",kernelFunc:tX};function K1(e,t,n,a,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,p=r.effectiveFilterHeight,d=r.effectiveFilterWidth,c=r.padInfo.top,h=r.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=Oe(r.outShape,n),g=f.values,b=r.outShape[1]*r.outShape[2]*r.outShape[3],y=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let v=0;v<r.batchSize;++v){let I=v*b,N=v*a[0];for(let C=0;C<r.inChannels;++C)for(let _=0;_<r.outHeight;++_){let F=_*i-c,D=Math.max(0,F),$=Math.min(r.inHeight,p+F),S=I+_*y;for(let M=0;M<r.outWidth;++M){let B=M*o-h,U=Math.max(0,B),H=Math.min(r.inWidth,d+B),j=m,K=0,Z=0;for(let ee=D;ee<$;ee+=l){let ae=N+ee*a[1];for(let te=U;te<H;te+=u){let se=ae+te*a[2],ie=e[se+C];s==="max"&&ie>j?j=ie:s==="avg"&&(K+=ie,Z++)}if(isNaN(j))break}let J=S+M*x+C;g[J]=s==="avg"?K/Z:j}}}return f}function v_(e,t,n,a,r=!1,s=!1){let i=Oe(a.outShape,"int32"),o=a.strideHeight,l=a.strideWidth,u=a.dilationHeight,p=a.dilationWidth,d=a.effectiveFilterHeight,c=a.effectiveFilterWidth,h=a.padInfo.top,m=a.padInfo.left,f=Oe(t,n,e);for(let g=0;g<a.batchSize;++g)for(let b=0;b<a.inChannels;++b)for(let y=0;y<a.outHeight;++y){let x=y*o-h,v=x;for(;v<0;)v+=u;let I=Math.min(a.inHeight,d+x);for(let N=0;N<a.outWidth;++N){let C=N*l-m,_=C;for(;_<0;)_+=p;let F=Math.min(a.inWidth,c+C),D=Number.NEGATIVE_INFINITY,$=-1;for(let S=v;S<I;S+=u){let M=S-x;for(let B=_;B<F;B+=p){let U=B-C,H=f.get(g,S,B,b);H>D&&(D=H,r?$=s?((g*a.inHeight+S)*a.inWidth+B)*a.inChannels+b:(S*a.inWidth+B)*a.inChannels+b:$=M*c+U)}}i.set($,g,y,N,b)}}return i}function w_(e,t,n,a,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,p=r.dilationHeight,d=r.dilationWidth,c=r.effectiveFilterDepth,h=r.effectiveFilterHeight,m=r.effectiveFilterWidth,f=r.padInfo.front,g=r.padInfo.top,b=r.padInfo.left,y=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Oe(r.outShape,n),v=x.values,I=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],N=r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[3]*r.outShape[4],_=r.outShape[4];for(let F=0;F<r.batchSize;++F){let D=F*I,$=F*a[0];for(let S=0;S<r.inChannels;++S)for(let M=0;M<r.outDepth;++M){let B=M*i-f,U=B;for(;U<0;)U+=u;let H=Math.min(r.inDepth,c+B),j=D+M*N;for(let K=0;K<r.outHeight;++K){let Z=K*o-g,J=Z;for(;J<0;)J+=p;let ee=Math.min(r.inHeight,h+Z),ae=j+K*C;for(let te=0;te<r.outWidth;++te){let se=te*l-b,ie=se;for(;ie<0;)ie+=d;let xe=Math.min(r.inWidth,m+se),ue=ae+te*_,ye=y,ke=0,Se=0;for(let Ue=U;Ue<H;Ue+=u){let mt=$+Ue*a[1];for(let st=J;st<ee;st+=p){let tt=mt+st*a[2];for(let nt=ie;nt<xe;nt+=d){let Re=tt+nt*a[3],gt=e[Re+S];if(s==="max"&>>ye?ye=gt:s==="avg"&&(ke+=gt,Se++),isNaN(ye))break}if(isNaN(ye))break}if(isNaN(ye))break}let Le=ue+S;v[Le]=s==="avg"?ke/Math.max(Se,1):ye}}}}return x}function aX(e,t){let n=Oe(t.outShape,"int32"),a=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,p=t.effectiveFilterHeight,d=t.effectiveFilterWidth,c=t.padInfo.front,h=t.padInfo.top,m=t.padInfo.left;for(let f=0;f<t.batchSize;++f)for(let g=0;g<t.inChannels;++g)for(let b=0;b<t.outDepth;++b){let y=b*a-c,x=y;for(;x<0;)x+=i;let v=Math.min(t.inDepth,u+y);for(let I=0;I<t.outHeight;++I){let N=I*r-h,C=N;for(;C<0;)C+=o;let _=Math.min(t.inHeight,p+N);for(let F=0;F<t.outWidth;++F){let D=F*s-m,$=D;for(;$<0;)$+=l;let S=Math.min(t.inWidth,d+D),M=Number.NEGATIVE_INFINITY,B=-1;for(let U=x;U<v;U+=i){let H=U-y;for(let j=C;j<_;j+=o){let K=j-N;for(let Z=$;Z<S;Z+=l){let J=Z-D,ee=e.get(f,U,j,Z,g);ee>=M&&(M=ee,B=H*p*d+K*p+J)}}}n.set(B,f,b,I,F,g)}}}return n}function rX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ge(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l),d;if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))d=pr({inputs:{x:r},backend:n});else{let c=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=K1(c,r.shape,r.dtype,h,p,"avg");d=n.makeTensorInfo(p.outShape,r.dtype,m.values)}return d}var sX={kernelName:Di,backendName:"cpu",kernelFunc:rX};function iX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;ge(r,"avgPool3d");let p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.data.get(r.dataId).values,c=w_(d,r.shape,r.dtype,w.computeStrides(r.shape),p,"avg");return n.makeTensorInfo(c.shape,"float32",c.values)}var oX={kernelName:tu,backendName:"cpu",kernelFunc:iX};function lX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;ge([r,s],"avgPool3DGrad");let p=T.computePool3DInfo(s.shape,i,o,1,l,u),d=p.strideDepth,c=p.strideHeight,h=p.strideWidth,m=p.filterDepth,f=p.filterHeight,g=p.filterWidth,b=p.dilationDepth,y=p.dilationHeight,x=p.dilationWidth,v=p.effectiveFilterDepth,I=p.effectiveFilterHeight,N=p.effectiveFilterWidth,C=v-1-p.padInfo.front,_=N-1-p.padInfo.left,F=I-1-p.padInfo.top,D=Oe(s.shape,"float32"),$=1/(m*f*g),S=n.bufferSync(r);for(let M=0;M<p.batchSize;++M)for(let B=0;B<p.inChannels;++B)for(let U=0;U<p.inDepth;++U)for(let H=0;H<p.inHeight;++H)for(let j=0;j<p.inWidth;++j){let K=U-C,Z=H-F,J=j-_,ee=0;for(let ae=0;ae<v;ae+=b){let te=(K+ae)/d;if(!(te<0||te>=p.outDepth||Math.floor(te)!==te))for(let se=0;se<I;se+=y){let ie=(Z+se)/c;if(!(ie<0||ie>=p.outHeight||Math.floor(ie)!==ie))for(let xe=0;xe<N;xe+=x){let ue=(J+xe)/h;if(ue<0||ue>=p.outWidth||Math.floor(ue)!==ue)continue;let ye=S.get(M,te,ie,ue,B);ee+=ye}}}D.set(ee*$,M,U,H,j,B)}return n.makeTensorInfo(D.shape,D.dtype,D.values)}var uX={kernelName:Rc,backendName:"cpu",kernelFunc:lX};function pX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;ge([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,p=T.computePool2DInfo(i.shape,o,l,1,u),d=p.strideHeight,c=p.strideWidth,h=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,b=p.effectiveFilterHeight,y=p.effectiveFilterWidth,x=y-1-p.padInfo.left,v=b-1-p.padInfo.top,I=Oe(i.shape,"float32"),N=1/(h*m),C=n.data.get(r.dataId).values,_=Oe(r.shape,"float32",C);for(let F=0;F<p.batchSize;++F)for(let D=0;D<p.inChannels;++D)for(let $=0;$<p.inHeight;++$)for(let S=0;S<p.inWidth;++S){let M=$-v,B=S-x,U=0;for(let H=0;H<b;H+=f){let j=(M+H)/d;if(!(j<0||j>=p.outHeight||Math.floor(j)!==j))for(let K=0;K<y;K+=g){let Z=(B+K)/c;if(Z<0||Z>=p.outWidth||Math.floor(Z)!==Z)continue;let J=_.get(F,j,Z,D);U+=J}}I.set(U*N,F,$,S,D)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}var cX={kernelName:Dc,backendName:"cpu",kernelFunc:pX};function dX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,scale:s,offset:i,mean:o,variance:l}=t;w.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ge([r,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=a;u==null&&(u=.001);let p=n.data.get(r.dataId).values,d=n.data.get(o.dataId).values,c=n.data.get(l.dataId).values,h=s?n.data.get(s.dataId).values:new Float32Array([1]),m=i?n.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(p.length),g=m.length,b=h.length,y=c.length,x=d.length,v=0,I=0,N=0,C=0;for(let _=0;_<p.length;++_)f[_]=m[v++]+(p[_]-d[I++])*h[N++]/Math.sqrt(c[C++]+u),v>=g&&(v=0),I>=x&&(I=0),N>=b&&(N=0),C>=y&&(C=0);return n.makeTensorInfo(r.shape,r.dtype,f)}var hX={kernelName:Ji,backendName:"cpu",kernelFunc:dX};function mX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;ge([r],"batchToSpaceND");let o=s.reduce((b,y)=>b*y),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),d=T.getSliceBeginCoords(i,s.length),c=T.getSliceSize(p,i,s.length),h=xt({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Bn({inputs:{x:h},backend:n,attrs:{perm:u}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:p}}),g=xi({inputs:{x:f},backend:n,attrs:{begin:d,size:c}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var fX={kernelName:nu,backendName:"cpu",kernelFunc:mX};function gX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=P1(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var bX={kernelName:au,backendName:"cpu",kernelFunc:gX};function yX(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var xX={kernelName:Mc,backendName:"cpu",kernelFunc:yX},vX=lt(vs,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),wX={kernelName:vs,backendName:"cpu",kernelFunc:vX},kX=e=>{let{x:t}=e.inputs,n=e.backend,a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId),s=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values;for(let u=0;u<o.length;u++){let p=o[u],d=l[u];a[u]=Math.hypot(p,d)}return n.makeOutput(a,t.shape,"float32")},IX={kernelName:Oc,backendName:"cpu",kernelFunc:kX};function jl(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.imag,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var SX={kernelName:_m,backendName:"cpu",kernelFunc:jl};function Kl(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=t.map(f=>f.shape);T.assertParamsConsistent(i,s);let o=T.computeOutShape(t.map(f=>f.shape),s);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(f=>w.sizeFromShape(f.shape)>0);if(l.length===1)return pr({inputs:{x:l[0]},backend:n});if(l[0].dtype==="complex64"){let f=l.map(v=>yi({inputs:{input:v},backend:n})),g=l.map(v=>jl({inputs:{input:v},backend:n})),b=Kl({inputs:f,backend:n,attrs:{axis:s}}),y=Kl({inputs:g,backend:n,attrs:{axis:s}}),x=Yn({inputs:{real:b,imag:y},backend:n});return f.forEach(v=>n.disposeIntermediateTensorInfo(v)),g.forEach(v=>n.disposeIntermediateTensorInfo(v)),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),x}let u=l.map(f=>{let g=[-1,w.sizeFromShape(f.shape.slice(s))];return xt({inputs:{x:f},backend:n,attrs:{shape:g}})}),p=u.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));o=T.computeOutShape(u.map(f=>f.shape),1);let d=u[0].shape[0]===1,c=L1(p,o,t[0].dtype,d),h=T.computeOutShape(l.map(f=>f.shape),s),m=n.makeTensorInfo(h,t[0].dtype,c);return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var NX={kernelName:su,backendName:"cpu",kernelFunc:Kl};function k_(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a;ge([r,s],"conv2d");let d=T.convertConv2DDataFormat(l),c=T.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,d),h=c.filterHeight,m=c.filterWidth,f=c.dilationHeight,g=c.dilationWidth,b=c.padInfo.left,y=c.padInfo.top,x=c.dataFormat==="channelsLast",v=new Wt(c.outShape,r.dtype),I=w.computeStrides(r.shape),N=w.computeStrides(s.shape),C=I[0],_=x?I[1]:I[2],F=x?I[2]:1,D=x?1:I[1],$=v.strides[0],S=x?v.strides[1]:v.strides[2],M=x?v.strides[2]:1,B=x?1:v.strides[1],U=n.data.get(r.dataId).values,H=n.data.get(s.dataId).values,j=v.values;for(let K=0;K<c.batchSize;++K){let Z=K*C,J=K*$;for(let ee=0;ee<c.outHeight;++ee){let ae=J+ee*S,te=ee*c.strideHeight-y;for(let se=0;se<h;++se){let ie=te+se*f;if(ie<0||ie>=c.inHeight)continue;let xe=se*N[0],ue=Z+ie*_;for(let ye=0;ye<c.outWidth;++ye){let ke=ae+ye*M,Se=ye*c.strideWidth-b;for(let Le=0;Le<m;++Le){let Ue=Se+Le*g;if(Ue<0||Ue>=c.inWidth)continue;let mt=xe+Le*N[1],st=ue+Ue*F,tt=mt;for(let nt=0;nt<c.inChannels;++nt){let Re=U[st+nt*D];for(let gt=0;gt<c.outChannels;++gt)j[ke+gt*B]+=Re*H[tt+gt];tt+=c.outChannels}}}}}}return n.makeTensorInfo(v.shape,v.dtype,j)}var TX={kernelName:Pi,backendName:"cpu",kernelFunc:k_};function CX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=a;ge([r,s],"conv2dBackpropFilter");let d=T.convertConv2DDataFormat(l),c=T.computeConv2DInfo(r.shape,p,i,1,o,u,!1,d),{strideHeight:h,strideWidth:m,filterHeight:f,filterWidth:g}=c,b=c.dataFormat==="channelsLast",y=new Wt(c.filterShape,"float32"),x=c.padInfo.left,v=c.padInfo.top,I=n.data.get(r.dataId).values,N=n.data.get(s.dataId).values,C=new Wt(r.shape,r.dtype,I),_=new Wt(s.shape,s.dtype,N);for(let F=0;F<f;++F){let D=Math.max(0,Math.ceil((v-F)/h)),$=Math.min(c.outHeight,(c.inHeight+v-F)/h);for(let S=0;S<g;++S){let M=Math.max(0,Math.ceil((x-S)/m)),B=Math.min(c.outWidth,(c.inWidth+x-S)/m);for(let U=0;U<c.inChannels;++U)for(let H=0;H<c.outChannels;++H){let j=0;for(let K=0;K<c.batchSize;++K)for(let Z=D;Z<$;++Z){let J=F+Z*h-v;for(let ee=M;ee<B;++ee){let ae=S+ee*m-x;b?j+=C.get(K,J,ae,U)*_.get(K,Z,ee,H):j+=C.get(K,U,J,ae)*_.get(K,H,Z,ee)}}y.set(j,F,S,U,H)}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var EX={kernelName:km,backendName:"cpu",kernelFunc:CX};function _X(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=a;ge([r,s],"conv2dBackpropInput");let d=w.computeStrides(s.shape),c=w.computeStrides(r.shape),h=T.convertConv2DDataFormat(u),m=T.computeConv2DInfo(i,s.shape,o,1,l,p,!1,h),f=new Wt(m.inShape,"float32"),g=f.values,b=n.data.get(r.dataId).values,y=n.data.get(s.dataId).values,[x,v,I]=d,{batchSize:N,filterHeight:C,filterWidth:_,inChannels:F,inHeight:D,inWidth:$,outChannels:S,outHeight:M,outWidth:B,strideHeight:U,strideWidth:H}=m;h=m.dataFormat;let j=C-1-m.padInfo.top,K=_-1-m.padInfo.left,Z=h==="channelsLast",J=f.strides[0],ee=Z?f.strides[1]:f.strides[2],ae=Z?f.strides[2]:1,te=Z?1:f.strides[1],se=c[0],ie=Z?c[1]:c[2],xe=Z?c[2]:1,ue=Z?1:c[1];for(let ye=0;ye<N;++ye)for(let ke=0;ke<F;++ke)for(let Se=0;Se<D;++Se){let Le=Se-j,Ue=Math.max(0,Math.ceil(Le/U)),mt=Math.min(M,(C+Le)/U);for(let st=0;st<$;++st){let tt=st-K,nt=Math.max(0,Math.ceil(tt/H)),Re=Math.min(B,(_+tt)/H),gt=0;for(let Ot=Ue;Ot<mt;++Ot){let ia=Ot*U-Le;for(let ln=nt;ln<Re;++ln){let An=ln*H-tt,oa=se*ye+ie*Ot+xe*ln,Fn=x*(C-1-ia)+v*(_-1-An)+I*ke;for(let ut=0;ut<S;++ut){let $n=b[oa+ue*ut],Hn=y[Fn+ut];gt+=$n*Hn}}}let Gn=J*ye+ee*Se+ae*st+te*ke;g[Gn]=gt}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var AX={kernelName:Li,backendName:"cpu",kernelFunc:_X};function FX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;ge([r,s],"conv3d");let u=T.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:p,filterHeight:d,filterWidth:c,dilationDepth:h,dilationHeight:m,dilationWidth:f,padInfo:g}=u,b=g.front,y=g.left,x=g.top,v=new Wt(u.outShape,r.dtype),I=n.data.get(r.dataId).values,N=n.data.get(s.dataId).values,C=v.values,_=w.computeStrides(r.shape),F=w.computeStrides(s.shape);for(let D=0;D<u.batchSize;++D){let $=D*_[0],S=D*v.strides[0];for(let M=0;M<u.outDepth;++M){let B=S+M*v.strides[1],U=M*u.strideDepth-b;for(let H=0;H<p;++H){let j=U+H*h;if(j<0||j>=u.inDepth)continue;let K=H*F[0],Z=$+j*_[1];for(let J=0;J<u.outHeight;++J){let ee=B+J*v.strides[2],ae=J*u.strideHeight-x;for(let te=0;te<d;++te){let se=ae+te*m;if(se<0||se>=u.inHeight)continue;let ie=K+te*F[1],xe=Z+se*_[2];for(let ue=0;ue<u.outWidth;++ue){let ye=ee+ue*u.outChannels,ke=ue*u.strideWidth-y;for(let Se=0;Se<c;++Se){let Le=ke+Se*f;if(Le<0||Le>=u.inWidth)continue;let Ue=ie+Se*F[2],mt=xe+Le*u.inChannels,st=Ue;for(let tt=0;tt<u.inChannels;++tt){let nt=I[mt+tt];for(let Re=0;Re<u.outChannels;++Re)C[ye+Re]+=nt*N[st+Re];st+=u.outChannels}}}}}}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}var $X={kernelName:zi,backendName:"cpu",kernelFunc:FX};function DX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;ge([r,s],"conv3dBackpropFilterV2");let u=w.computeStrides(r.shape),p=w.computeStrides(s.shape),d=T.computeConv3DInfo(r.shape,l,i,1,o),c=d.strideDepth,h=d.strideHeight,m=d.strideWidth,f=d.filterDepth,g=d.filterHeight,b=d.filterWidth,y=new Wt(d.filterShape,"float32"),x=y.values,[v,I,N,C]=y.strides,_=n.data.get(s.dataId).values,[F,D,$,S]=p,M=n.data.get(r.dataId).values,[B,U,H,j]=u,K=d.padInfo.front,Z=d.padInfo.left,J=d.padInfo.top;for(let ee=0;ee<f;++ee){let ae=Math.max(0,Math.ceil((K-ee)/c)),te=Math.min(d.outDepth,(d.inDepth+K-ee)/c),se=ee*v;for(let ie=0;ie<g;++ie){let xe=Math.max(0,Math.ceil((J-ie)/h)),ue=Math.min(d.outHeight,(d.inHeight+J-ie)/h),ye=ie*I+se;for(let ke=0;ke<b;++ke){let Se=Math.max(0,Math.ceil((Z-ke)/m)),Le=Math.min(d.outWidth,(d.inWidth+Z-ke)/m),Ue=ke*N+ye;for(let mt=0;mt<d.inChannels;++mt){let st=mt*C+Ue;for(let tt=0;tt<d.outChannels;++tt){let nt=0;for(let Re=0;Re<d.batchSize;++Re){let gt=Re*B,Gn=Re*F;for(let Ot=ae;Ot<te;++Ot){let ia=(ee+Ot*c-K)*U+gt,ln=Ot*D+Gn;for(let An=xe;An<ue;++An){let oa=(ie+An*h-J)*H+ia,Fn=An*$+ln;for(let ut=Se;ut<Le;++ut){let $n=(ke+ut*m-Z)*j+oa,Hn=ut*S+Fn;nt+=M[$n+mt]*_[Hn+tt]}}}}x[st+tt]=nt}}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var RX={kernelName:iu,backendName:"cpu",kernelFunc:DX};function MX(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;ge([r],"conv3dBackpropInputV2");let u=w.computeStrides(r.shape),p=w.computeStrides(s.shape),d=T.computeConv3DInfo(l,s.shape,o,1,i),c=new Wt(d.inShape,"float32"),h=c.values,[m,f,g,b]=c.strides,y=n.data.get(r.dataId).values,[x,v,I,N]=u,C=n.data.get(s.dataId).values,[_,F,D,$]=p,{batchSize:S,filterDepth:M,filterHeight:B,filterWidth:U,inChannels:H,inDepth:j,inHeight:K,inWidth:Z,outChannels:J,outDepth:ee,outHeight:ae,outWidth:te,strideDepth:se,strideHeight:ie,strideWidth:xe}=d,ue=M-1-d.padInfo.front,ye=B-1-d.padInfo.top,ke=U-1-d.padInfo.left;for(let Se=0;Se<S;++Se)for(let Le=0;Le<H;++Le)for(let Ue=0;Ue<j;++Ue){let mt=Ue-ue,st=Math.max(0,Math.ceil(mt/se)),tt=Math.min(ee,(M+mt)/se);for(let nt=0;nt<K;++nt){let Re=nt-ye,gt=Math.max(0,Math.ceil(Re/ie)),Gn=Math.min(ae,(B+Re)/ie);for(let Ot=0;Ot<Z;++Ot){let ia=Ot-ke,ln=Math.max(0,Math.ceil(ia/xe)),An=Math.min(te,(U+ia)/xe),oa=0;for(let Fn=st;Fn<tt;++Fn){let ut=Fn*se-mt;for(let $n=gt;$n<Gn;++$n){let Hn=$n*ie-Re;for(let yr=ln;yr<An;++yr){let ml=yr*xe-ia,Za=x*Se+v*Fn+I*$n+N*yr,Wp=_*(M-1-ut)+F*(B-1-Hn)+D*(U-1-ml)+$*Le;for(let Ia=0;Ia<J;++Ia){let Ur=y[Za+Ia],Jt=C[Wp+Ia];oa+=Ur*Jt}}}}h[m*Se+f*Ue+g*nt+b*Ot+Le]=oa}}}return n.makeTensorInfo(c.shape,c.dtype,c.values)}var OX={kernelName:ou,backendName:"cpu",kernelFunc:MX},PX=lt(Wi,e=>Math.cos(e)),LX={kernelName:Wi,backendName:"cpu",kernelFunc:PX},zX=lt(Bi,e=>Math.cosh(e)),WX={kernelName:Bi,backendName:"cpu",kernelFunc:zX};function BX(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,[p,d,c,h]=r.shape,m=s.shape[0],[f,g]=o,b=Oe([m,f,g,h],"float32"),y=n.data.get(s.dataId).values,x=n.data.get(i.dataId).values,v=n.data.get(r.dataId).values,I=w.computeStrides(r.shape),N=w.computeStrides(b.shape);for(let C=0;C<m;C++){let _=C*4,F=y[_],D=y[_+1],$=y[_+2],S=y[_+3],M=x[C];if(M>=p)continue;let B=f>1?($-F)*(d-1)/(f-1):0,U=g>1?(S-D)*(c-1)/(g-1):0;for(let H=0;H<f;H++){let j=f>1?F*(d-1)+H*B:.5*(F+$)*(d-1);if(j<0||j>d-1){for(let K=0;K<g;K++)for(let Z=0;Z<h;Z++){let J=Z+K*N[2]+H*N[1]+C*N[0];b.values[J]=u}continue}if(l==="bilinear"){let K=Math.floor(j),Z=Math.ceil(j),J=j-K;for(let ee=0;ee<g;ee++){let ae=g>1?D*(c-1)+ee*U:.5*(D+S)*(c-1);if(ae<0||ae>c-1){for(let xe=0;xe<h;xe++){let ue=xe+ee*N[2]+H*N[1]+C*N[0];b.values[ue]=u}continue}let te=Math.floor(ae),se=Math.ceil(ae),ie=ae-te;for(let xe=0;xe<h;xe++){let ue=xe+te*I[2]+K*I[1]+M*I[0],ye=v[ue];ue=xe+se*I[2]+K*I[1]+M*I[0];let ke=v[ue];ue=xe+te*I[2]+Z*I[1]+M*I[0];let Se=v[ue];ue=xe+se*I[2]+Z*I[1]+M*I[0];let Le=v[ue],Ue=ye+(ke-ye)*ie,mt=Se+(Le-Se)*ie;ue=xe+ee*N[2]+H*N[1]+C*N[0],b.values[ue]=Ue+(mt-Ue)*J}}}else for(let K=0;K<g;++K){let Z=g>1?D*(c-1)+K*U:.5*(D+S)*(c-1);if(Z<0||Z>c-1){for(let ae=0;ae<h;ae++){let te=ae+K*N[2]+H*N[1]+C*N[0];b.values[te]=u}continue}let J=Math.round(Z),ee=Math.round(j);for(let ae=0;ae<h;ae++){let te=ae+J*I[2]+ee*I[1]+M*I[0],se=ae+K*N[2]+H*N[1]+C*N[0];b.values[se]=v[te]}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var VX={kernelName:uu,backendName:"cpu",kernelFunc:BX};function UX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;ge(r,"cumprod");let l=T.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Bn({inputs:{x:r},backend:n,attrs:{perm:l}}));let p=T.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let d=fa(u.dtype,"int32"),c=w.makeOnesTypedArray(w.sizeFromShape(u.shape),d),h=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(b,y)=>b+m-y-1:(b,y)=>b+y;for(let b=0;b<h.length;b+=m)for(let y=0;y<m;y++){let x=f(b,y);if(y===0)c[x]=i?1:h[x];else{let v=f(b,y-1);c[x]=i?h[v]*c[v]:h[x]*c[v]}}let g=n.makeTensorInfo(u.shape,d,c);if(l!=null){let b=T.getUndoAxesPermutation(l),y=Bn({inputs:{x:g},backend:n,attrs:{perm:b}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),y}return g}var GX={kernelName:lu,backendName:"cpu",kernelFunc:UX};function HX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;ge(r,"cumsum");let l=T.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Bn({inputs:{x:r},backend:n,attrs:{perm:l}}));let p=T.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let d=fa(u.dtype,"int32"),c=w.makeZerosTypedArray(w.sizeFromShape(u.shape),d),h=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(b,y)=>b+m-y-1:(b,y)=>b+y;for(let b=0;b<h.length;b+=m)for(let y=0;y<m;y++){let x=f(b,y);if(y===0)c[x]=i?0:h[x];else{let v=f(b,y-1);c[x]=i?h[v]+c[v]:h[x]+c[v]}}let g=n.makeTensorInfo(u.shape,d,c);if(l!=null){let b=T.getUndoAxesPermutation(l),y=Bn({inputs:{x:g},backend:n,attrs:{perm:b}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),y}return g}var qX={kernelName:Vi,backendName:"cpu",kernelFunc:HX};function jX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=P1(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),p=AE(l,u,i,o);return n.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var KX={kernelName:Pc,backendName:"cpu",kernelFunc:jX};function XX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;w.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=r.shape[0],l=r.shape[1],u=r.shape[2],p=r.shape[3],d=l*s,c=u*s,h=p/(s*s),m=n.data.get(r.dataId).values,f=new Float32Array(o*d*c*h),g=0;for(let b=0;b<o;++b)for(let y=0;y<d;++y){let x=Math.floor(y/s),v=y%s;for(let I=0;I<c;++I){let N=Math.floor(I/s),C=I%s,_=(v*s+C)*h;for(let F=0;F<h;++F){let D=F+_+p*(N+u*(x+l*b));f[g++]=m[D]}}}return n.makeTensorInfo([o,d,c,h],r.dtype,f)}var YX={kernelName:pu,backendName:"cpu",kernelFunc:XX};function I_(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=a;ge([r,s],"depthwiseConv2DNative");let p=w.computeStrides(r.shape),d=w.computeStrides(s.shape),c=l;c==null&&(c=[1,1]),w.assert(T.eitherStridesOrDilationsAreOne(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let h=T.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:b,padInfo:y}=h,x=y.left,v=y.top,I=h.outChannels/h.inChannels,N=new Wt(h.outShape,r.dtype),C=n.data.get(r.dataId).values,_=n.data.get(s.dataId).values,F=N.values;for(let D=0;D<h.batchSize;++D){let $=D*p[0],S=D*N.strides[0];for(let M=0;M<h.outHeight;++M){let B=S+M*N.strides[1],U=M*h.strideHeight-v;for(let H=0;H<m;++H){let j=U+H*g;if(j<0||j>=h.inHeight)continue;let K=H*d[0],Z=$+j*p[1];for(let J=0;J<h.outWidth;++J){let ee=B+J*N.strides[2],ae=J*h.strideWidth-x;for(let te=0;te<f;++te){let se=ae+te*b;if(se<0||se>=h.inWidth)continue;let ie=K+te*d[1],xe=Z+se*h.inChannels,ue=ee,ye=ie;for(let ke=0;ke<h.inChannels;++ke){let Se=C[xe+ke];for(let Le=0;Le<I;++Le)F[ue+Le]+=Se*_[ye+Le];ue+=I,ye+=I}}}}}}return n.makeTensorInfo(N.shape,N.dtype,N.values)}var ZX={kernelName:Ui,backendName:"cpu",kernelFunc:I_};function JX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=a;ge([r,s],"depthwiseConv2dNativeBackpropFilter");let d=T.computeConv2DInfo(r.shape,p,i,o,l,u,!0),{strideHeight:c,strideWidth:h,filterHeight:m,filterWidth:f}=d,g=new Wt(d.filterShape,"float32"),b=d.padInfo.left,y=d.padInfo.top,x=d.outChannels/d.inChannels,v=n.data.get(r.dataId).values,I=new Wt(r.shape,r.dtype,v),N=n.data.get(s.dataId).values,C=new Wt(s.shape,s.dtype,N);for(let _=0;_<m;++_){let F=Math.max(0,Math.ceil((y-_)/c)),D=Math.min(d.outHeight,(d.inHeight+y-_)/c);for(let $=0;$<f;++$){let S=Math.max(0,Math.ceil((b-$)/h)),M=Math.min(d.outWidth,(d.inWidth+b-$)/h);for(let B=0;B<d.outChannels;++B){let U=Math.trunc(B/x),H=B%x,j=0;for(let K=0;K<d.batchSize;++K)for(let Z=F;Z<D;++Z){let J=_+Z*c-y;for(let ee=S;ee<M;++ee){let ae=$+ee*h-b;j+=I.get(K,J,ae,U)*C.get(K,Z,ee,B)}}g.set(j,_,$,U,H)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var QX={kernelName:Im,backendName:"cpu",kernelFunc:JX};function eY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=a;ge([r,s],"depthwiseConv2DNativeBackpropInput");let d=w.computeStrides(r.shape),c=w.computeStrides(s.shape),h=T.computeConv2DInfo(p,s.shape,i,o,l,u,!0),m=new Wt(h.inShape,"float32"),f=m.values,[g,b,y]=m.strides,x=n.data.get(r.dataId).values,[v,I,N]=d,C=n.data.get(s.dataId).values,[_,F,D]=c,{batchSize:$,filterHeight:S,filterWidth:M,inChannels:B,inHeight:U,inWidth:H,outChannels:j,outHeight:K,outWidth:Z,strideHeight:J,strideWidth:ee}=h,ae=S-1-h.padInfo.top,te=M-1-h.padInfo.left,se=j/B;for(let ie=0;ie<$;++ie)for(let xe=0;xe<B;++xe)for(let ue=0;ue<U;++ue){let ye=ue-ae,ke=Math.max(0,Math.ceil(ye/J)),Se=Math.min(K,(S+ye)/J);for(let Le=0;Le<H;++Le){let Ue=Le-te,mt=Math.max(0,Math.ceil(Ue/ee)),st=Math.min(Z,(M+Ue)/ee),tt=0;for(let nt=ke;nt<Se;++nt){let Re=nt*J-ye;for(let gt=mt;gt<st;++gt){let Gn=gt*ee-Ue,Ot=v*ie+I*nt+N*gt,ia=_*(S-1-Re)+F*(M-1-Gn)+D*xe;for(let ln=0;ln<se;++ln){let An=xe*se+ln,oa=x[Ot+An],Fn=C[ia+ln];tt+=oa*Fn}}}f[g*ie+b*ue+y*Le+xe]=tt}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var tY={kernelName:Sm,backendName:"cpu",kernelFunc:eY};function nY(e){let{inputs:t,backend:n}=e,{x:a}=t,r=w.sizeFromShape(a.shape),s=n.data.get(a.dataId).values,i=Oe([r,r],a.dtype),o=i.values;for(let u=0;u<s.length;u++)o[u*r+u]=s[u];let l=[...a.shape,...a.shape];return n.makeTensorInfo(l,i.dtype,i.values)}var aY={kernelName:Lc,backendName:"cpu",kernelFunc:nY},rY={kernelName:Gi,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r}=e,{strides:s,pad:i,dilations:o}=n,l=t,u=l.data.get(a.dataId).values,p=a.shape.length,d=l.data.get(r.dataId).values,c=r.shape.length,{batchSize:h,inHeight:m,inWidth:f,inChannels:g,outHeight:b,outWidth:y,padInfo:x,strideHeight:v,strideWidth:I,filterHeight:N,filterWidth:C,dilationHeight:_,dilationWidth:F,outShape:D}=T.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),$=w.sizeFromShape(D),S=D.length,M=w.getArrayFromDType(a.dtype,$);for(let B=0;B<h;++B)for(let U=0;U<b;++U){let H=U*v-x.top;for(let j=0;j<y;++j){let K=j*I-x.left;for(let Z=0;Z<g;++Z){let J=Number.MIN_SAFE_INTEGER;for(let ae=0;ae<N;++ae){let te=H+ae*_;if(te>=0&&te<m)for(let se=0;se<C;++se){let ie=K+se*F;if(ie>=0&&ie<f){let xe=w.locToIndex([B,te,ie,Z],p,w.computeStrides(a.shape)),ue=w.locToIndex([ae,se,Z],c,w.computeStrides(r.shape)),ye=u[xe]+d[ue];ye>J&&(J=ye)}}}let ee=w.locToIndex([B,U,j,Z],S,w.computeStrides(D));M[ee]=J}}}return{dataId:l.write(w.toTypedArray(M,a.dtype),D,a.dtype),shape:D,dtype:a.dtype}}},sY={kernelName:Rl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,p=w.toNestedArray(a.shape,u.data.get(a.dataId).values),d=w.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:c,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:b,padInfo:y,strideHeight:x,strideWidth:v,filterHeight:I,filterWidth:N,dilationHeight:C,dilationWidth:_,outShape:F}=T.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===F.length,()=>`Error in ${Rl}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let D=w.toNestedArray(F,u.data.get(s.dataId).values),$=w.makeZerosNestedTypedArray(r.shape,r.dtype);for(let S=0;S<c;++S)for(let M=0;M<g;++M){let B=M*x-y.top;for(let U=0;U<b;++U){let H=U*v-y.left;for(let j=0;j<f;++j){let K=Number.MIN_SAFE_INTEGER,Z=0,J=0;for(let ee=0;ee<I;++ee){let ae=B+ee*C;if(ae>=0&&ae<h)for(let te=0;te<N;++te){let se=H+te*_;if(se>=0&&se<m){let ie=p[S][ae][se][j]+d[ee][te][j];ie>K&&(K=ie,Z=ee,J=te)}}}$[Z][J][j]+=D[S][M][U][j]}}}return{dataId:u.write(w.toTypedArray($,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},iY={kernelName:Dl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,p=w.toNestedArray(a.shape,u.data.get(a.dataId).values),d=w.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:c,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:b,padInfo:y,strideHeight:x,strideWidth:v,filterHeight:I,filterWidth:N,dilationHeight:C,dilationWidth:_,outShape:F}=T.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);w.assert(s.rank===F.length,()=>`Error in ${Dl}, dy must have the same rank as output ${F.length}, but got ${s.rank}`);let D=w.toNestedArray(F,u.data.get(s.dataId).values),$=w.makeZerosNestedTypedArray(a.shape,a.dtype);for(let S=0;S<c;++S)for(let M=0;M<g;++M){let B=M*x-y.top;for(let U=0;U<b;++U){let H=U*v-y.left;for(let j=0;j<f;++j){let K=Number.MIN_SAFE_INTEGER,Z=B<0?0:B,J=H<0?0:H;for(let ee=0;ee<I;++ee){let ae=B+ee*C;if(ae>=0&&ae<h)for(let te=0;te<N;++te){let se=H+te*_;if(se>=0&&se<m){let ie=p[S][ae][se][j]+d[ee][te][j];ie>K&&(K=ie,Z=ae,J=se)}}}$[S][Z][J][j]+=D[S][M][U][j]}}}return{dataId:u.write(w.toTypedArray($,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function oY(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{canvas:s,options:i}=a,{contextOptions:o,imageOptions:l}=i||{},u=(l==null?void 0:l.alpha)||1,p=(o==null?void 0:o.contextType)||"2d";if(p!=="2d")throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);let d=s.getContext(p,(o==null?void 0:o.contextAttributes)||{});if(d==null)throw new Error(`Could not get the context with ${p} type.`);let[c,h]=r.shape.slice(0,2),m=r.shape.length===2?1:r.shape[2],f=n.data.get(r.dataId).values,g=r.dtype==="float32"?255:1,b=new Uint8ClampedArray(h*c*4);for(let x=0;x<c*h;++x){let v=[0,0,0,255*u];for(let N=0;N<m;N++){let C=f[x*m+N];if(r.dtype==="float32"){if(C<0||C>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${C}.`)}else if(r.dtype==="int32"&&(C<0||C>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${C}.`);m===1?(v[0]=C*g,v[1]=C*g,v[2]=C*g):v[N]=C*g}let I=x*4;b[I+0]=Math.round(v[0]),b[I+1]=Math.round(v[1]),b[I+2]=Math.round(v[2]),b[I+3]=Math.round(v[3])}s.width=h,s.height=c;let y=new ImageData(b,h,c);return d.putImageData(y,0,0),r}var lY={kernelName:Nm,backendName:"cpu",kernelFunc:oY};function Ed(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"sum");let o;r.dtype==="bool"?o=gs({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=pr({inputs:{x:r},backend:n});let l=o.shape.length,u=w.parseAxisParam(s,o.shape),p=T.getAxesPermutation(u,l),d=u,c=o;p!=null&&(c=Bn({inputs:{x:o},backend:n,attrs:{perm:p}}),d=T.getInnerMostAxes(d.length,l)),T.assertAxesAreInnerMostDims("sum",d,c.shape.length);let[h,m]=T.computeOutAndReduceShapes(c.shape,d),f=T.upcastType(c.dtype,"int32"),g=lm(n,h,f),b=w.sizeFromShape(m),y=n.data.get(g.dataId).values,x=n.data.get(c.dataId).values;for(let v=0;v<y.length;++v){let I=v*b,N=0;for(let C=0;C<b;++C)N+=x[I+C];y[v]=N}if(i){let v=T.expandShapeToKeepDim(g.shape,u),I=g;g=xt({inputs:{x:g},backend:n,attrs:{shape:v}}),n.disposeIntermediateTensorInfo(I)}return n.disposeIntermediateTensorInfo(o),p!=null&&n.disposeIntermediateTensorInfo(c),g}var uY={kernelName:Lo,backendName:"cpu",kernelFunc:Ed};function pY(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=T.decodeEinsumEquation(r,s.length);T.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=T.getEinsumComputePath(o,l),d=p.length,c=null,h=i.length,m=[];for(let f=0;f<d;++f){for(let g of p[f]){let{permutationIndices:b,expandDims:y}=T.getEinsumPermutation(h,l[g]),x;T.isIdentityPermutation(b)?x=s[g]:(x=Bn({inputs:{x:s[g]},backend:n,attrs:{perm:b}}),m.push(x));let v=x.shape.slice();for(let I=0;I<y.length;++I)v.splice(y[I],0,1);w.arraysEqual(x.shape,v)||(x=xt({inputs:{x},backend:n,attrs:{shape:v}}),m.push(x)),c===null?c=x:(c=Lf({inputs:{a:x,b:c},backend:n}),m.push(c))}f<d-1&&(u[f]>=0&&(c=Ed({inputs:{x:c},backend:n,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(c)),h--)}for(let f of m)f!==c&&n.disposeIntermediateTensorInfo(f);return c}var cY={kernelName:Tm,backendName:"cpu",kernelFunc:pY};function dY(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;ge([a,r],"eluGrad");let s=new Float32Array(w.sizeFromShape(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=0?s[l]=o[l]:s[l]=o[l]*(u+1)}return n.makeTensorInfo(r.shape,"float32",s)}var hY={kernelName:cu,backendName:"cpu",kernelFunc:dY},mY=T.ERF_P,fY=T.ERF_A1,gY=T.ERF_A2,bY=T.ERF_A3,yY=T.ERF_A4,xY=T.ERF_A5,vY=lt(ji,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+mY*n);return t*(1-((((xY*a+yY)*a+bY)*a+gY)*a+fY)*a*Math.exp(-n*n))}),wY={kernelName:ji,backendName:"cpu",kernelFunc:vY};function cm(e){let{inputs:t,backend:n,attrs:a}=e,{input:r}=t,{dim:s}=a,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),xt({inputs:{x:r},backend:n,attrs:{shape:o}})}var kY={kernelName:hu,backendName:"cpu",kernelFunc:cm},IY=Mt((e,t)=>e/t),X1=Zt(Hi,IY),ov={kernelName:Hi,backendName:"cpu",kernelFunc:X1};function S_(e,t,n){let a=e.shape,r=a[0],s=a[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,s],p=w.sizeFromShape(u),d=w.getTypedArrayFromDType("float32",p),c=w.getTypedArrayFromDType("float32",p);for(let g=0;g<r;g++){let b=xi({inputs:{x:o},backend:n,attrs:{begin:[g,0],size:[1,s]}}),y=xi({inputs:{x:l},backend:n,attrs:{begin:[g,0],size:[1,s]}}),x=Yn({inputs:{real:b,imag:y},backend:n}),{real:v,imag:I}=SY(x,t,n),N=T.mergeRealAndImagArrays(v,I);for(let C=0;C<s;C++){let _=T.getComplexWithIndex(N,C);d[g*s+C]=_.real,c[g*s+C]=_.imag}n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(x)}let h=n.makeTensorInfo(u,"float32",d),m=n.makeTensorInfo(u,"float32",c),f=Yn({inputs:{real:h,imag:m},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}function SY(e,t,n){let a=w.sizeFromShape(e.shape),r=n.data.get(e.dataId),s=n.data.get(r.complexTensorInfos.real.dataId).values,i=n.data.get(r.complexTensorInfos.imag.dataId).values;if(NY(a)){let o=lv(s,i,a,t,n),l=[e.shape[0],e.shape[1]];if(t){let u=n.makeTensorInfo(l,"float32",o.real),p=n.makeTensorInfo(l,"float32",o.imag),d=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),c=pr({inputs:{x:d},backend:n}),h=ov.kernelFunc({inputs:{a:u,b:d},backend:n}),m=ov.kernelFunc({inputs:{a:p,b:c},backend:n}),f=n.data.get(h.dataId).values,g=n.data.get(m.dataId).values;return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=T.mergeRealAndImagArrays(s,i),l=TY(o,a,t);return T.splitRealAndImagArrays(l)}}function NY(e){return(e&e-1)===0}function lv(e,t,n,a,r){if(n===1)return{real:e,imag:t};let s=T.mergeRealAndImagArrays(e,t),i=n/2,o=T.complexWithEvenIndex(s),l=o.real,u=o.imag,p=[l.length],d=r.makeTensorInfo(p,"float32",l),c=r.makeTensorInfo(p,"float32",u),h=Yn({inputs:{real:d,imag:c},backend:r}),m=T.complexWithOddIndex(s),f=m.real,g=m.imag,b=[f.length],y=r.makeTensorInfo(b,"float32",f),x=r.makeTensorInfo(b,"float32",g),v=Yn({inputs:{real:y,imag:x},backend:r}),I=lv(l,u,i,a,r),N=I.real,C=I.imag,_=[N.length],F=r.makeTensorInfo(_,"float32",N),D=r.makeTensorInfo(_,"float32",C),$=Yn({inputs:{real:F,imag:D},backend:r}),S=lv(f,g,i,a,r),M=S.real,B=S.imag,U=[M.length],H=r.makeTensorInfo(U,"float32",M),j=r.makeTensorInfo(U,"float32",B),K=Yn({inputs:{real:H,imag:j},backend:r}),Z=T.exponents(n,a),J=[Z.real.length],ee=r.makeTensorInfo(J,"float32",Z.real),ae=r.makeTensorInfo(J,"float32",Z.imag),te=Yn({inputs:{real:ee,imag:ae},backend:r}),se=Lf({inputs:{a:te,b:K},backend:r}),ie=ql({inputs:{a:$,b:se},backend:r}),xe=q1({inputs:{a:$,b:se},backend:r}),ue=yi({inputs:{input:ie},backend:r}),ye=yi({inputs:{input:xe},backend:r}),ke=jl({inputs:{input:ie},backend:r}),Se=jl({inputs:{input:xe},backend:r}),Le=Kl({inputs:[ue,ye],backend:r,attrs:{axis:0}}),Ue=Kl({inputs:[ke,Se],backend:r,attrs:{axis:0}}),mt=r.data.get(Le.dataId).values,st=r.data.get(Ue.dataId).values;return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(D),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(H),r.disposeIntermediateTensorInfo(j),r.disposeIntermediateTensorInfo(K),r.disposeIntermediateTensorInfo(ee),r.disposeIntermediateTensorInfo(ae),r.disposeIntermediateTensorInfo(te),r.disposeIntermediateTensorInfo(se),r.disposeIntermediateTensorInfo(ie),r.disposeIntermediateTensorInfo(xe),r.disposeIntermediateTensorInfo(ue),r.disposeIntermediateTensorInfo(ke),r.disposeIntermediateTensorInfo(ye),r.disposeIntermediateTensorInfo(Se),r.disposeIntermediateTensorInfo(Le),r.disposeIntermediateTensorInfo(Ue),{real:mt,imag:st}}function TY(e,t,n){let a=new Float32Array(t*2);for(let r=0;r<t;r++){let s=0,i=0;for(let o=0;o<t;o++){let l=T.exponent(r*o,t,n),u=T.getComplexWithIndex(e,o);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}n&&(s/=t,i/=t),T.assignToTypedArray(a,s,i,r)}return a}function CY(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=xt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=S_(o,!1,n),u=xt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var EY={kernelName:Cm,backendName:"cpu",kernelFunc:CY};function Y1(e){let{backend:t,attrs:n}=e,{shape:a,value:r,dtype:s}=n,i=s||w.inferDtype(r),o=w.getArrayFromDType(i,w.sizeFromShape(a));return AY(o,r,i),t.makeTensorInfo(a,i,o)}var _Y={kernelName:zc,backendName:"cpu",kernelFunc:Y1};function AY(e,t,n){e.fill(t)}var FY={kernelName:mu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,r=n,s=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[i,o,l,u]=a.shape,p=r.data.get(a.dataId).values;for(let d=0;d<i;d++){let c=d*l*o*u;for(let h=0;h<o;h++){let m=h*(l*u);for(let f=0;f<l;f++){let g=f*u;for(let b=0;b<u;b++){let y=Math.round(l-f-1),x=c+m+g+b,v=p[x];if(y>=0&&y<l){let I=y*u,N=c+m+I+b;v=p[N]}s[x]=v}}}}return{dataId:r.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function $Y(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=k_({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c}});if(i){let g=f;if(p==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let b=xt({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});f=ql({inputs:{a:f,b},backend:n}),n.disposeIntermediateTensorInfo(b)}else f=ql({inputs:{a:f,b:i},backend:n});n.disposeIntermediateTensorInfo(g)}if(h){let g=f;if(p==="NCHW"&&h==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let b=xt({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});f=pm(n,f,h,b,m),n.disposeIntermediateTensorInfo(b)}else f=pm(n,f,h,o,m);n.disposeIntermediateTensorInfo(g)}return f}var DY={kernelName:ii,backendName:"cpu",kernelFunc:$Y};function RY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=I_({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c}});if(i){let g=f;f=ql({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=pm(n,f,h,o,m),n.disposeIntermediateTensorInfo(g)}return f}var MY={kernelName:oi,backendName:"cpu",kernelFunc:RY};function OY(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=w.sizeFromShape(a.shape),i=r.shape,o=i[i.length-1],[l,u,p,d]=T.prepareAndValidate(a,r);if(u===0)return n.makeTensorInfo(l,a.dtype,[]);let c=n.data.get(r.dataId).values,h=n.bufferSync(a),m=WE(c,h,a.dtype,u,o,p,d,a.shape,s);return n.makeTensorInfo(l,a.dtype,m.values)}var PY={kernelName:gu,backendName:"cpu",kernelFunc:OY};function LY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;ge([r,s],"gatherV2");let l=w.parseAxisParam(i,r.shape)[0],u=n.data.get(s.dataId).values,p=r.shape[l];for(let v=0;v<u.length;++v){let I=u[v];w.assert(I<=p-1&&I>=0,()=>`GatherV2: the index value ${I} is not in [0, ${p-1}]`)}let d=o;o==null&&(d=0);let c=w.sizeFromShape(s.shape),h=T.segment_util.collectGatherOpShapeInfo(r,s,l,d),m=xt({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),f=xt({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,c/h.batchSize]}}),g=[h.batchSize,h.outerSize,c/h.batchSize,h.sliceSize],b=n.bufferSync(f),y=n.bufferSync(m),x=BE(y,b,g);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.makeTensorInfo(h.outputShape,x.dtype,x.values)}var zY={kernelName:fu,backendName:"cpu",kernelFunc:LY};function WY(e){let{inputs:t,backend:n}=e,{input:a}=t,r=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=xt({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=S_(o,!0,n),u=xt({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var BY={kernelName:Em,backendName:"cpu",kernelFunc:WY},VY=lt(to,e=>Number.isFinite(e)?1:0,"bool"),UY={kernelName:to,backendName:"cpu",kernelFunc:VY},GY=lt(no,e=>Math.abs(e)===1/0?1:0,"bool"),HY={kernelName:no,backendName:"cpu",kernelFunc:GY},qY=lt(ao,e=>Number.isNaN(e)?1:0,"bool"),jY={kernelName:ao,backendName:"cpu",kernelFunc:qY};function KY(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=qE(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var XY={kernelName:vu,backendName:"cpu",kernelFunc:KY},YY=lt(io,e=>Math.log1p(e)),ZY={kernelName:io,backendName:"cpu",kernelFunc:YY},JY=Mt((e,t)=>e&&t),QY=Zt(wu,JY,null,"bool"),e7={kernelName:wu,backendName:"cpu",kernelFunc:QY},t7=lt(ku,e=>e?0:1,"bool"),n7={kernelName:ku,backendName:"cpu",kernelFunc:t7},a7=Mt((e,t)=>e||t),r7=Zt(Iu,a7,null,"bool"),s7={kernelName:Iu,backendName:"cpu",kernelFunc:r7};function i7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;ge(r,"LRN");let u=r.shape[3],p=u-1,d=n.data.get(r.dataId).values,c=w.sizeFromShape(r.shape),h=new Float32Array(c);function m(f){let g=f%u,b=f-g+Math.max(0,g-s),y=f-g+Math.min(g+s,p),x=0;for(;b<=y;b++){let v=d[b];x+=v*v}return x}for(let f=0;f<c;f++){let g=m(f),b=d[f]*Math.pow(i+o*g,-l);h[f]=b}return n.makeTensorInfo(r.shape,r.dtype,h)}var o7={kernelName:oo,backendName:"cpu",kernelFunc:i7};function l7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a;ge(i,"LRNGrad");let d=w.sizeFromShape(i.shape),c=i.shape[3],h=n.data.get(i.dataId).values,m=n.data.get(r.dataId).values,f=n.data.get(s.dataId).values,g=new Float32Array(d),b=d;for(let y=0;y<b;y++){let x=y%c,v=y-x+Math.max(0,x-o),I=y-x+Math.min(c,x+o+1),N=0;for(let C=v;C<I;C++)N+=Math.pow(m[C],2);N=u*N+l;for(let C=v;C<I;C++){let _=-2*u*p*m[C]*f[y]/N;y===C&&(_+=Math.pow(N,-p)),_*=h[y],g[C]+=_}}return n.makeTensorInfo(i.shape,r.dtype,g)}var u7={kernelName:Su,backendName:"cpu",kernelFunc:l7};function N_(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=n,l=r.shape,u=l.length,p=w.parseAxisParam(s,l),d=p,c=T.getAxesPermutation(d,u),h=o.data.get(r.dataId).values;if(c!=null){let v=new Array(u);for(let I=0;I<v.length;I++)v[I]=l[c[I]];h=W1(h,l,r.dtype,c,v),d=T.getInnerMostAxes(d.length,u),l=v}ge(r,"max"),T.assertAxesAreInnerMostDims("max",d,u);let[m,f]=T.computeOutAndReduceShapes(l,d),g=w.sizeFromShape(f),b=KE(h,g,m,r.dtype),y=o.write(b,m,r.dtype),x=m;return i&&(x=T.expandShapeToKeepDim(m,p)),{dataId:y,shape:x,dtype:r.dtype}}var p7={kernelName:lo,backendName:"cpu",kernelFunc:N_};function c7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;ge(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l),d;if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))d=pr({inputs:{x:r},backend:n});else{let c=n.data.get(r.dataId).values,h=w.computeStrides(r.shape),m=K1(c,r.shape,r.dtype,h,p,"max");d=n.makeTensorInfo(p.outShape,r.dtype,m.values)}return d}var d7={kernelName:po,backendName:"cpu",kernelFunc:c7};function h7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;ge(r,"maxPool3d");let p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.data.get(r.dataId).values,c=w_(d,r.shape,r.dtype,w.computeStrides(r.shape),p,"max");return n.makeTensorInfo(c.shape,"float32",c.values)}var m7={kernelName:Nu,backendName:"cpu",kernelFunc:h7};function f7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;ge([r,s],"maxPool3DGrad");let p=T.computePool3DInfo(s.shape,i,o,1,l,u),d=n.bufferSync(s),c=aX(d,p),h=p.strideDepth,m=p.strideHeight,f=p.strideWidth,g=p.dilationDepth,b=p.dilationHeight,y=p.dilationWidth,x=p.effectiveFilterDepth,v=p.effectiveFilterHeight,I=p.effectiveFilterWidth,N=x-1-p.padInfo.front,C=I-1-p.padInfo.left,_=v-1-p.padInfo.top,F=Oe(s.shape,"float32"),D=n.bufferSync(r);for(let $=0;$<p.batchSize;++$)for(let S=0;S<p.inChannels;++S)for(let M=0;M<p.inDepth;++M)for(let B=0;B<p.inHeight;++B)for(let U=0;U<p.inWidth;++U){let H=M-N,j=B-_,K=U-C,Z=0;for(let J=0;J<x;J+=g){let ee=(H+J)/h;if(!(ee<0||ee>=p.outDepth||Math.floor(ee)!==ee))for(let ae=0;ae<v;ae+=b){let te=(j+ae)/m;if(!(te<0||te>=p.outHeight||Math.floor(te)!==te))for(let se=0;se<I;se+=y){let ie=(K+se)/f;if(ie<0||ie>=p.outWidth||Math.floor(ie)!==ie)continue;let xe=x*v*I-1-c.get($,ee,te,ie,S),ue=J*v*I+ae*I+se,ye=xe===ue?1:0;if(ye===0)continue;let ke=D.get($,ee,te,ie,S);Z+=ke*ye}}}F.set(Z,$,M,B,U,S)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}var g7={kernelName:Bc,backendName:"cpu",kernelFunc:f7};function b7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;ge([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:d}=a,c=T.computePool2DInfo(o.shape,l,u,1,p,d),h=n.data.get(o.dataId).values,m=Oe(c.outShape,o.dtype,v_(h,o.shape,o.dtype,c).values),f=c.strideHeight,g=c.strideWidth,b=c.dilationHeight,y=c.dilationWidth,x=c.effectiveFilterHeight,v=c.effectiveFilterWidth,I=v-1-c.padInfo.left,N=x-1-c.padInfo.top,C=Oe(o.shape,"float32"),_=n.data.get(r.dataId).values,F=Oe(r.shape,"float32",_);for(let D=0;D<c.batchSize;++D)for(let $=0;$<c.inChannels;++$)for(let S=0;S<c.inHeight;++S)for(let M=0;M<c.inWidth;++M){let B=S-N,U=M-I,H=0;for(let j=0;j<x;j+=b){let K=(B+j)/f;if(!(K<0||K>=c.outHeight||Math.floor(K)!==K))for(let Z=0;Z<v;Z+=y){let J=(U+Z)/g;if(J<0||J>=c.outWidth||Math.floor(J)!==J)continue;let ee=x*v-1-m.get(D,K,J,$),ae=j*v+Z,te=ee===ae?1:0;if(te===0)continue;let se=F.get(D,K,J,$);H+=se*te}}C.set(H,D,S,M,$)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var y7={kernelName:Wc,backendName:"cpu",kernelFunc:b7};function x7(e,t,n,a,r){let s=w.computeStrides(t),i=K1(e,t,n,s,r,"max"),o=v_(e,t,n,r,!0,a);return[i.values,o.values]}var v7={kernelName:Vc,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;ge(a,"MaxPoolWithArgmax");let u=l.data.get(a.dataId).values,p=T.computePool2DInfo(a.shape,r,s,[1,1],i),[d,c]=x7(u,a.shape,a.dtype,o,p),h=l.write(d,p.outShape,a.dtype),m=l.write(c,p.outShape,a.dtype);return[{dataId:h,shape:p.outShape,dtype:a.dtype},{dataId:m,shape:p.outShape,dtype:"int32"}]}};function w7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=w.parseAxisParam(s,r.shape),l=T.computeOutAndReduceShapes(r.shape,o)[1],u=w.sizeFromShape(l),p=[],d=n.makeTensorInfo([],"float32",new Float32Array([u]));p.push(d);let c=gs({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});p.push(c);let h=X1({inputs:{a:c,b:d},backend:n});p.push(h);let m=Ed({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var k7={kernelName:co,backendName:"cpu",kernelFunc:w7};function I7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;ge(r,"min");let o=w.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=Bn({inputs:{x:r},backend:n,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("min",l,p.shape.length);let[d,c]=T.computeOutAndReduceShapes(p.shape,l),h=w.sizeFromShape(c),m=w.makeZerosTypedArray(w.sizeFromShape(d),p.dtype),f=n.data.get(p.dataId).values;for(let b=0;b<m.length;++b){let y=b*h,x=f[y];for(let v=0;v<h;++v){let I=f[y+v];(Number.isNaN(I)||I<x)&&(x=I)}m[b]=x}u!=null&&n.disposeIntermediateTensorInfo(p);let g=n.makeTensorInfo(d,p.dtype,m);if(i){let b=T.expandShapeToKeepDim(d,o),y=xt({inputs:{x:g},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(g),y}return g}var S7={kernelName:ho,backendName:"cpu",kernelFunc:I7};function N7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,mode:i}=a;ge(r,"mirrorPad");let o=s.map((y,x)=>y[0]+r.shape[x]+y[1]),l=s.map(y=>y[0]),u=s.map((y,x)=>y[0]+r.shape[x]),p=i==="reflect"?0:1,d=n.data.get(r.dataId).values,c=r.shape.length,h=w.computeStrides(r.shape),m=w.sizeFromShape(o),f=o.length,g=w.computeStrides(o),b=w.getTypedArrayFromDType(r.dtype,m);for(let y=0;y<m;y++){let x=w.indexToLoc(y,f,g);for(let I=0;I<f;I++)x[I]<l[I]?x[I]=l[I]*2-x[I]-p:x[I]>=u[I]&&(x[I]=(u[I]-1)*2-x[I]+p);x=x.map((I,N)=>I-l[N]);let v=w.locToIndex(x,c,h);b[y]=d[v]}return{dataId:n.write(b,o,r.dtype),shape:o,dtype:r.dtype}}var T7={kernelName:fo,backendName:"cpu",kernelFunc:N7},C7=Mt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),E7=Zt(go,C7),_7={kernelName:go,backendName:"cpu",kernelFunc:E7},A7=ys(bm());function T_(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=r.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=w.parseAxisParam([o],r.shape),u=N_({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),p=T.expandShapeToKeepDim(u.shape,l),d=xt({inputs:{x:u},backend:n,attrs:{shape:p}}),c=q1({inputs:{a:r,b:d},backend:n}),h=OE({inputs:{x:c},backend:n}),m=Ed({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:p}}),g=X1({inputs:{a:h,b:f},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var F7={kernelName:zo,backendName:"cpu",kernelFunc:T_};function $7(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;ge(r,"multinomial");let l=o?r:T_({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],p=l.shape[1],d=n.data.get(l.dataId).values,c=[u,s],h=w.makeZerosTypedArray(w.sizeFromShape(c),"int32");for(let m=0;m<u;++m){let f=m*p,g=new Float32Array(p-1);g[0]=d[f];for(let x=1;x<g.length;++x)g[x]=g[x-1]+d[f+x];let b=A7.alea(i.toString()),y=m*s;for(let x=0;x<s;++x){let v=b();h[y+x]=g.length;for(let I=0;I<g.length;I++)if(v<g[I]){h[y+x]=I;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(c,"int32",h)}var D7={kernelName:Tu,backendName:"cpu",kernelFunc:$7},R7=hr.nonMaxSuppressionV3Impl;function M7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;ge(r,"NonMaxSuppression");let u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,{selectedIndices:d}=R7(u,p,i,o,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var O7={kernelName:_u,backendName:"cpu",kernelFunc:M7},P7=hr.nonMaxSuppressionV4Impl;function L7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a;ge(r,"NonMaxSuppressionPadded");let p=n.data.get(r.dataId).values,d=n.data.get(s.dataId).values,{selectedIndices:c,validOutputs:h}=P7(p,d,i,o,l,u);return[n.makeTensorInfo([c.length],"int32",new Int32Array(c)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var z7={kernelName:Au,backendName:"cpu",kernelFunc:L7},W7=hr.nonMaxSuppressionV5Impl;function B7(e){let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a;ge(r,"NonMaxSuppressionWithScore");let p=n.data.get(r.dataId).values,d=n.data.get(s.dataId).values,c=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:b}=W7(p,d,c,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var V7={kernelName:Fu,backendName:"cpu",kernelFunc:B7};function U7(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a;ge(r,"oneHot");let u=w.sizeFromShape(r.shape),p=new Float32Array(u*i);p.fill(l);let d=n.data.get(r.dataId).values;for(let c=0;c<u;++c)d[c]>=0&&d[c]<i&&(p[c*i+d[c]]=o);return n.makeTensorInfo([...r.shape,i],s,p)}var G7={kernelName:yo,backendName:"cpu",kernelFunc:U7};function dm(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(a.dtype==="complex64"){let r=yi({inputs:{input:a},backend:n}),s=dm({inputs:{x:r},backend:n}),i=jl({inputs:{input:a},backend:n}),o=dm({inputs:{x:i},backend:n}),l=Yn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Y1({backend:n,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var H7={kernelName:Yu,backendName:"cpu",kernelFunc:dm};function C_(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(a.dtype==="complex64"){let r=yi({inputs:{input:a},backend:n}),s=C_({inputs:{x:r},backend:n}),i=jl({inputs:{input:a},backend:n}),o=dm({inputs:{x:i},backend:n}),l=Yn({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return Y1({backend:n,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var q7={kernelName:$u,backendName:"cpu",kernelFunc:C_};function E_(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return cm({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=cm({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=Kl({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var j7={kernelName:Du,backendName:"cpu",kernelFunc:E_};function K7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;ge(r,"pad");let o=s.map((b,y)=>b[0]+r.shape[y]+b[1]),l=s.map(b=>b[0]),u=n.data.get(r.dataId).values,p=w.sizeFromShape(r.shape),d=r.shape.length,c=w.computeStrides(r.shape),h=w.sizeFromShape(o),m=o.length,f=w.computeStrides(o),g=w.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let b=0;b<p;b++){let y=w.indexToLoc(b,d,c).map((v,I)=>v+l[I]),x=w.locToIndex(y,m,f);g[x]=u[b]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var __={kernelName:xo,backendName:"cpu",kernelFunc:K7},X7=Mt((e,t)=>Math.pow(e,t)),Y7=Zt(vo,X7),Z7={kernelName:vo,backendName:"cpu",kernelFunc:Y7};function J7(e){let{inputs:t,backend:n,attrs:a}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=a,l=r.map(b=>n.data.get(b.dataId).values),u=r.map(b=>b.shape),p=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,[c,h,m]=e_(l,u,p,s.shape,s.dtype,d,i.shape,o),f=c.map(b=>n.makeTensorInfo([b.length],"int32",b)),g=n.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var Q7={kernelName:Am,backendName:"cpu",kernelFunc:J7};function eZ(e){let{inputs:t,backend:n}=e,{starts:a,limits:r,deltas:s}=t,i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=t_(i,a.shape,a.dtype,o,r.shape,l,s.shape),d=n.makeTensorInfo([u.length],"int32",u),c=n.makeTensorInfo([p.length],a.dtype,p);return[d,c]}var tZ={kernelName:Fm,backendName:"cpu",kernelFunc:eZ};function nZ(e){let{inputs:t,backend:n,attrs:a}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=a,u=n.data.get(r.dataId).values,p=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,c=o.map(g=>n.data.get(g.dataId).values),h=o.map(g=>g.shape),[m,f]=n_(u,r.shape,p,s.shape,s.dtype,d,i.shape,c,h,l);return n.makeTensorInfo(m,s.dtype,f)}var aZ={kernelName:$m,backendName:"cpu",kernelFunc:nZ};function rZ(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=B1(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var sZ={kernelName:Uc,backendName:"cpu",kernelFunc:rZ},iZ=lt(Io,e=>1/e),oZ={kernelName:Io,backendName:"cpu",kernelFunc:iZ};function lZ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ge(r,"resizeBilinear");let l=w.computeStrides(r.shape),[u,p]=o,[d,c,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(w.sizeFromShape([d,u,p,m])),b=[s&&u>1?c-1:c,s&&p>1?h-1:h],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],x=0,v=b[0]/y[0],I=b[1]/y[1];for(let N=0;N<d;N++)for(let C=0;C<u;C++){let _;i?_=v*(C+.5)-.5:_=v*C;let F=Math.max(0,Math.floor(_)),D=_-F,$=Math.min(c-1,Math.ceil(_)),S=N*l[0]+F*l[1],M=N*l[0]+$*l[1];for(let B=0;B<p;B++){let U;i?U=I*(B+.5)-.5:U=I*B;let H=Math.max(0,Math.floor(U)),j=U-H,K=Math.min(h-1,Math.ceil(U)),Z=S+H*l[2],J=M+H*l[2],ee=S+K*l[2],ae=M+K*l[2];for(let te=0;te<m;te++){let se=f[Z+te],ie=f[J+te],xe=f[ee+te],ue=f[ae+te],ye=se+(xe-se)*j,ke=ie+(ue-ie)*j,Se=ye+(ke-ye)*D;g[x++]=Se}}}return n.makeTensorInfo([d,u,p,m],"float32",g)}var uZ={kernelName:To,backendName:"cpu",kernelFunc:lZ};function pZ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ge([s,r],"resizeBilinearGrad");let o=w.computeStrides(r.shape),[l,u,p,d]=r.shape,[,c,h]=s.shape,m=new Float32Array(l*u*p*d),f=[i&&c>1?u-1:u,i&&h>1?p-1:p],g=[i&&c>1?c-1:c,i&&h>1?h-1:h],b=f[0]/g[0],y=f[1]/g[1],x=n.data.get(s.dataId).values,v=0;for(let I=0;I<l;I++){let N=I*o[0];for(let C=0;C<c;C++){let _=C*b,F=Math.floor(_),D=Math.min(Math.ceil(_),u-1),$=N+F*o[1],S=N+D*o[1],M=_-F,B=1-M;for(let U=0;U<h;U++){let H=U*y,j=Math.floor(H),K=Math.min(Math.ceil(H),p-1),Z=H-j,J=1-Z,ee=$+j*o[2],ae=$+K*o[2],te=S+j*o[2],se=S+K*o[2],ie=B*J,xe=B*Z,ue=M*J,ye=M*Z;for(let ke=0;ke<d;ke++){let Se=x[v++];m[ee+ke]+=Se*ie,m[ae+ke]+=Se*xe,m[te+ke]+=Se*ue,m[se+ke]+=Se*ye}}}}return n.makeTensorInfo([l,p,u,d],"float32",m)}var cZ={kernelName:Ou,backendName:"cpu",kernelFunc:pZ};function dZ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;ge(r,"resizeNearestNeighbor");let l=w.computeStrides(r.shape),[u,p]=o,[d,c,h,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(d*u*p*m),b=[s&&u>1?c-1:c,s&&p>1?h-1:h],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],x=b[0]/y[0],v=b[1]/y[1],I=0;for(let N=0;N<d;N++){let C=N*l[0];for(let _=0;_<u;_++){let F=i?x*(_+.5):x*_,D=Math.min(c-1,s?Math.round(F):Math.floor(F));i&&(D=Math.max(0,D));let $=C+D*l[1];for(let S=0;S<p;S++){let M=i?v*(S+.5):v*S,B=Math.min(h-1,s?Math.round(M):Math.floor(M));i&&(B=Math.max(0,B));let U=$+B*l[2];for(let H=0;H<m;H++){let j=f[U+H];g[I++]=j}}}}return n.makeTensorInfo([d,u,p,m],r.dtype,g)}var hZ={kernelName:No,backendName:"cpu",kernelFunc:dZ};function mZ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a;ge([s,r],"resizeNearestNeighborGrad");let o=w.computeStrides(r.shape),l=w.computeStrides(s.shape),[u,p,d,c]=r.shape,[,h,m]=s.shape,f=new Float32Array(u*p*d*c),g=n.data.get(s.dataId).values,b=[i&&h>1?p-1:p,i&&m>1?d-1:d],y=[i&&h>1?h-1:h,i&&m>1?m-1:m],x=b[0]/y[0],v=b[1]/y[1],I=1/x,N=1/v,C=Math.ceil(I)*2+2,_=Math.ceil(N)*2+2;for(let F=0;F<u;F++){let D=F*o[0];for(let $=0;$<p;$++){let S=D+$*o[1],M=Math.floor($*I),B=Math.floor(M-C/2);for(let U=0;U<d;U++){let H=S+U*o[2],j=Math.floor(U*N),K=Math.floor(j-_/2);for(let Z=0;Z<c;Z++){let J=0;for(let ee=0;ee<C;ee++){let ae=ee+B;if(ae<0||ae>=h)continue;let te=D+ae*l[1],se=ae*x,ie=Math.min(p-1,i?Math.round(se):Math.floor(se));if($===ie)for(let xe=0;xe<_;xe++){let ue=xe+K;if(ue<0||ue>=m)continue;let ye=te+ue*l[2],ke=ue*v,Se=Math.min(d-1,i?Math.round(ke):Math.floor(ke));U===Se&&(J+=g[ye+Z])}}f[H+Z]=J}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var fZ={kernelName:Mu,backendName:"cpu",kernelFunc:mZ};function gZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;ge(r,"reverse");let i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return pr({inputs:{x:r},backend:n});let l=new Wt(r.shape,r.dtype),u=n.bufferSync(r);for(let p=0;p<l.size;p++){let d=l.indexToLoc(p),c=d.slice();o.forEach(h=>c[h]=r.shape[h]-1-c[h]),l.set(u.get(...c),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var bZ={kernelName:Eo,backendName:"cpu",kernelFunc:gZ},yZ={kernelName:Zu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[u,p,d,c]=a.shape,[h,m]=T.getImageCenter(i,p,d),f=255,g=Math.sin(r),b=Math.cos(r),y=o.data.get(a.dataId).values;for(let x=0;x<u;x++){let v=x*d*p*c;for(let I=0;I<p;I++){let N=I*(d*c);for(let C=0;C<d;C++){let _=C*c;for(let F=0;F<c;F++){let D=[u,I,C,F],$=D[2],S=D[1],M=($-h)*b-(S-m)*g,B=($-h)*g+(S-m)*b;M=Math.round(M+h),B=Math.round(B+m);let U=s;if(typeof s!="number"&&(F===3?U=f:U=s[F]),M>=0&&M<d&&B>=0&&B<p){let j=B*(d*c),K=M*c,Z=v+j+K+F;U=y[Z]}let H=v+N+_+F;l[H]=U}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},xZ=lt(_o,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}),vZ={kernelName:_o,backendName:"cpu",kernelFunc:xZ};function wZ(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=T.calculateShapes(s,r,i),c=!0,h=n.bufferSync(r),m=n.bufferSync(s),f=ti(h,m,i,d,u,l,o,p,0,c);return n.makeTensorInfo(i,f.dtype,f.values)}var kZ={kernelName:Pu,backendName:"cpu",kernelFunc:wZ};function IZ(e,t){let n=0,a=e.length,r=0;for(;n<a;)r=Math.floor((n+a)/2),e[r]<t?n=r+1:a=r;return a}function SZ(e,t){let n=0,a=e.length,r=0;for(;n<a;)r=Math.floor((n+a)/2),e[r]<=t?n=r+1:a=r;return a}function NZ(e,t,n,a,r,s){let i=w.getArrayFromDType("int32",n*r);for(let o=0;o<n;++o){let l=e.slice(o*a,(o+1)*a),u=o*r;for(let p=0;p<r;++p)i[u+p]=s==="left"?IZ(l,t[p+u]):SZ(l,t[p+u])}return i}function TZ(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=NZ(o,l,r.shape[0],r.shape[1],s.shape[1],i);return n.makeTensorInfo(s.shape,"int32",u)}var CZ={kernelName:zu,backendName:"cpu",kernelFunc:TZ};function EZ(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t;ge([a,r,s],"select");let i=a.shape.length,o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=fa(r.dtype,s.dtype),d=w.makeZerosTypedArray(w.sizeFromShape(r.shape),p),c=0,h=i===0||i>1||r.shape.length===1?1:w.sizeFromShape(r.shape.slice(1));for(let m=0;m<o.length;m++)for(let f=0;f<h;f++)o[m]===1?d[c++]=l[m]:d[c++]=u[m];return n.makeTensorInfo(r.shape,p,d)}var _Z={kernelName:Wu,backendName:"cpu",kernelFunc:EZ},AZ=T.SELU_SCALEALPHA,FZ=T.SELU_SCALE,$Z=lt(Fo,e=>e>=0?FZ*e:AZ*(Math.exp(e)-1)),DZ={kernelName:Fo,backendName:"cpu",kernelFunc:$Z},RZ=lt(Ro,e=>e<0?-1:e>0?1:0),MZ={kernelName:Ro,backendName:"cpu",kernelFunc:RZ},OZ=lt($o,e=>Math.sin(e)),PZ={kernelName:$o,backendName:"cpu",kernelFunc:OZ},LZ=lt(Do,e=>Math.sinh(e)),zZ={kernelName:Do,backendName:"cpu",kernelFunc:LZ},WZ=11920928955078125e-23,eS=Math.log(WZ)+2,BZ=lt(Oo,e=>{let t=e>-eS,n=e<eS,a=Math.exp(e),r;return n?r=a:t?r=e:r=Math.log(1+a),r}),VZ={kernelName:Oo,backendName:"cpu",kernelFunc:BZ};function UZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;ge([r],"spaceToBatchND");let o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=__.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=T.getReshaped(u.shape,s,o,!1),d=T.getPermuted(p.length,s.length,!1),c=T.getReshapedPermuted(u.shape,s,o,!1),h=xt({inputs:{x:u},backend:n,attrs:{shape:p}}),m=Bn({inputs:{x:h},backend:n,attrs:{perm:d}}),f=xt({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),f}var GZ={kernelName:Vu,backendName:"cpu",kernelFunc:UZ};function HZ(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${a.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=n.data.get(i.dataId).values[0],[d,c,h,m,f]=s_(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var qZ={kernelName:Gc,backendName:"cpu",kernelFunc:HZ};function jZ(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.data.get(r.dataId).values),o=n.data.get(a.dataId).values,l=Array.from(n.data.get(s.dataId).values),[u,p,d]=i_(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var KZ={kernelName:Gu,backendName:"cpu",kernelFunc:jZ};function XZ(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=V1(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var YZ={kernelName:Hc,backendName:"cpu",kernelFunc:XZ};function ZZ(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=V1(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var JZ={kernelName:qc,backendName:"cpu",kernelFunc:ZZ};function QZ(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=T.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f;switch(s.dtype){case"bool":{let g=n.bufferSync(s),b=!!n.data.get(i.dataId).values[0];f=ti(m,g,o,c,p,u,l,d,b,h);break}case"float32":{let g=n.bufferSync(s),b=n.data.get(i.dataId).values[0];f=ti(m,g,o,c,p,u,l,d,b,h);break}case"int32":{let g=n.bufferSync(s),b=n.data.get(i.dataId).values[0];f=ti(m,g,o,c,p,u,l,d,b,h);break}case"string":{let g=n.bufferSync(s),b=w.decodeString(n.data.get(i.dataId).values[0]);f=ti(m,g,o,c,p,u,l,d,b,h);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return n.makeTensorInfo(o,f.dtype,f.values)}var eJ={kernelName:Hu,backendName:"cpu",kernelFunc:QZ};function tJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=xi({inputs:{x:r},backend:n,attrs:{begin:u,size:c}});return u[o]+=d,h})}var nJ={kernelName:Uu,backendName:"cpu",kernelFunc:tJ},aJ={kernelName:jc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;ge(n,"square");let r=a.data.get(n.dataId).values,s=new Float32Array(r.length);for(let i=0;i<r.length;++i){let o=r[i];s[i]=o*o}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},rJ=lt(ks,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),sJ={kernelName:ks,backendName:"cpu",kernelFunc:rJ};function iJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a;ge(r,"stridedSlice");let{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=xt({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let N=Kt.computeOutShape(y,x,v),C=xi({inputs:{x:r},backend:n,attrs:{begin:y,size:N}});I=xt({inputs:{x:C},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(C)}else{let N=n.bufferSync(r),C=u_(h,N,v,y);I=n.makeTensorInfo(m,C.dtype,C.values)}return I}var oJ={kernelName:qu,backendName:"cpu",kernelFunc:iJ};function lJ(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.data.get(p.dataId).values,h=n.data.get(d.dataId).values,[m,f]=U1(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var uJ={kernelName:Xc,backendName:"cpu",kernelFunc:lJ};function pJ(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values[0],[u,p,d]=G1(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var cJ={kernelName:Yc,backendName:"cpu",kernelFunc:pJ};function dJ(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.data.get(s.dataId).values,o=H1(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var hJ={kernelName:Zc,backendName:"cpu",kernelFunc:dJ},mJ=lt(Vo,e=>Math.tan(e)),fJ={kernelName:Vo,backendName:"cpu",kernelFunc:mJ},gJ=lt(Uo,e=>Math.tanh(e)),bJ={kernelName:Uo,backendName:"cpu",kernelFunc:gJ};function yJ(e){let{inputs:t,backend:n}=e,{tensor:a,indices:r,updates:s}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:u,outputSize:p}=T.calculateShapes(s,r,a.shape),d=!1,c=n.bufferSync(r),h=n.bufferSync(s),m=n.bufferSync(a),f=ti(c,h,a.shape,p,l,o,i,u,m,d);return n.makeTensorInfo(a.shape,f.dtype,f.values)}var xJ={kernelName:Lu,backendName:"cpu",kernelFunc:yJ};function vJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;ge(r,"tile");let i=c_(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var wJ={kernelName:ws,backendName:"cpu",kernelFunc:vJ};function kJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;ge(r,"topk");let o=n.data.get(r.dataId).values,[l,u]=h_(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var IJ={kernelName:ju,backendName:"cpu",kernelFunc:kJ};function SJ(e){let{inputs:t,attrs:n,backend:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=w.computeStrides(r.shape),y=b[0],x=b[1],v=b[2],I=w.computeStrides(g),N=I[0],C=I[1],_=I[2],F=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(g));F.fill(l);let D=a.data.get(r.dataId).values,$=a.data.get(s.dataId).values;for(let S=0;S<p;++S){let M=s.shape[0]===1?$:$.subarray(S*8,S*8+8);for(let B=0;B<m;++B)for(let U=0;U<f;++U)for(let H=0;H<h;++H){let j,K=M[6]*U+M[7]*B+1;if(K===0)continue;let Z=(M[0]*U+M[1]*B+M[2])/K,J=(M[3]*U+M[4]*B+M[5])/K,ee=tS(Z,c,o),ae=tS(J,d,o);switch(i){case"nearest":j=AJ(D,d,c,y,x,v,S,ae,ee,H,l);break;case"bilinear":j=FJ(D,d,c,y,x,v,S,ae,ee,H,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let te=S*N+B*C+U*_+H;F[te]=j}return a.makeTensorInfo(g,r.dtype,F)}return{dataId:a.write(F,g,r.dtype),shape:r.shape,dtype:r.dtype}}var NJ={kernelName:Ku,backendName:"cpu",kernelFunc:SJ};function tS(e,t,n){switch(n){case"reflect":return TJ(e,t);case"wrap":return CJ(e,t);case"nearest":return _J(e,t);case"constant":default:return EJ(e,t)}}function TJ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let a=2*t;n<a&&(n=a*Math.trunc(-n/a)+n),n=n<-t?n+a:-n-1}else if(n>t-1)if(t<=1)n=0;else{let a=2*t;n-=a*Math.trunc(n/a),n>=t&&(n=a-n-1)}return w.clamp(0,n,t-1)}function CJ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let a=t-1;n+=t*(Math.trunc(-n/a)+1)}else if(n>t-1)if(t<=1)n=0;else{let a=t-1;n-=t*Math.trunc(n/a)}return w.clamp(0,n,t-1)}function EJ(e,t){return e}function _J(e,t){return w.clamp(0,e,t-1)}function ac(e,t,n,a,r,s,i,o,l,u,p){let d=i*a+o*r+l*s+u;return 0<=o&&o<t&&0<=l&&l<n?e[d]:p}function AJ(e,t,n,a,r,s,i,o,l,u,p){let d=Math.round(o),c=Math.round(l);return ac(e,t,n,a,r,s,i,d,c,u,p)}function FJ(e,t,n,a,r,s,i,o,l,u,p){let d=Math.floor(o),c=Math.floor(l),h=d+1,m=c+1,f=(m-l)*ac(e,t,n,a,r,s,i,d,c,u,p)+(l-c)*ac(e,t,n,a,r,s,i,d,m,u,p),g=(m-l)*ac(e,t,n,a,r,s,i,h,c,u,p)+(l-c)*ac(e,t,n,a,r,s,i,h,m,u,p);return(h-o)*f+(o-d)*g}function $J(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;ge(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=j1(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var DJ={kernelName:Jc,backendName:"cpu",kernelFunc:$J};function RJ(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r.shape.length,o=r.shape[s],l=new Array(i-1),u=0;for(let h=0;h<i;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i).fill(0),d=r.shape.slice();d[s]=1;let c=new Array(o);for(let h=0;h<c.length;h++){p[s]=h;let m=xi({inputs:{x:r},backend:n,attrs:{begin:p,size:d}});c[h]=xt({inputs:{x:m},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(m)}return c}var MJ={kernelName:Xu,backendName:"cpu",kernelFunc:RJ};function OJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a;ge(r,"unsortedSegmentSum");let o=r.shape.length,l=s.shape.length,u=[],p=[],d=o-l,c=s;for(let m=0;m<d;++m){let f=cm({inputs:{input:c},backend:n,attrs:{dim:m+1}});c=f,p.push(f)}for(let m=0;m<i;++m){let f=w.createScalarValue(m,"int32"),g=n.makeTensorInfo([],"int32",f),b=RE({inputs:{a:g,b:c},backend:n}),y=gs({inputs:{x:b},backend:n,attrs:{dtype:"float32"}}),x=Lf({inputs:{a:y,b:r},backend:n}),v=Ed({inputs:{x},backend:n,attrs:{axis:0,keepDims:!1}});u.push(v),p.push(g),p.push(b),p.push(y),p.push(x),p.push(v)}let h=E_({inputs:u,backend:n,attrs:{axis:0}});return p.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var PJ={kernelName:Qc,backendName:"cpu",kernelFunc:OJ},LJ=[F8,pK,D8,M8,gK,P8,z8,B8,U8,H8,j8,X8,Z8,eX,nX,sX,oX,uX,cX,_8,hX,fX,bX,yK,xX,mK,vK,wX,cK,IX,NX,TX,EX,AX,$X,RX,OX,LX,WX,VX,GX,qX,KX,YX,ZX,QX,tY,aY,rY,sY,iY,lY,cY,k8,hY,wK,wY,kK,kY,SK,EY,_Y,FY,TK,EK,DY,MY,PY,zY,AK,$K,dK,BY,SX,UY,HY,jY,I8,RK,OK,XY,LK,ZY,e7,n7,s7,o7,u7,p7,WK,d7,m7,g7,y7,v7,k7,S7,VK,T7,_7,D7,GK,qK,O7,z7,V7,KK,G7,q7,j7,__,Z7,N8,ZK,Q7,tZ,aZ,sZ,hK,ov,oZ,T8,C8,E8,uZ,cZ,hZ,fZ,bZ,yZ,vZ,i8,kZ,CZ,_Z,DZ,l8,MZ,PZ,zZ,u8,F7,VZ,GZ,qZ,KZ,YZ,JZ,eJ,nJ,d8,aJ,m8,g8,sJ,oJ,uJ,cJ,hJ,v8,uY,fJ,bJ,xJ,wJ,IJ,NJ,XK,DJ,MJ,PJ,H7];for(let e of LJ)ed(e);var A_={};_e(A_,{assertNotComplex:()=>lp,bindCanvasToFramebuffer:()=>XJ,bindColorTextureToFramebuffer:()=>Ph,bindTextureToProgramUniformSampler:()=>q_,bindTextureUnit:()=>U_,bindVertexBufferToProgramAttribute:()=>uv,callAndCheck:()=>de,canBeRepresented:()=>$_,createFragmentShader:()=>M_,createFramebuffer:()=>V_,createProgram:()=>O_,createStaticIndexBuffer:()=>z_,createStaticVertexBuffer:()=>L_,createTexture:()=>W_,createVertexShader:()=>R_,getBatchDim:()=>vi,getExtensionOrThrow:()=>rc,getFramebufferErrorMessage:()=>j_,getMaxTexturesInShader:()=>Z_,getNumChannels:()=>jJ,getProgramUniformLocation:()=>H_,getProgramUniformLocationOrThrow:()=>G_,getRowsCols:()=>wi,getShapeAs3D:()=>ic,getTextureShapeFromLogicalShape:()=>X_,getWebGLDisjointQueryTimerVersion:()=>J_,getWebGLErrorMessage:()=>D_,getWebGLMaxTextureSize:()=>Y_,hasExtension:()=>da,isCapableOfRenderingToFloatTexture:()=>Q_,isDownloadFloatTextureEnabled:()=>eA,isReshapeFree:()=>Tc,isWebGLFenceEnabled:()=>tA,isWebGLVersionEnabled:()=>cv,linkProgram:()=>P_,logShaderSourceAndInfoLog:()=>J1,resetMaxTextureSize:()=>YJ,resetMaxTexturesInShader:()=>ZJ,unbindColorTextureFromFramebuffer:()=>pv,unbindTextureUnit:()=>KJ,validateFramebuffer:()=>sc,validateProgram:()=>Oh,validateTextureSize:()=>B_});var Qs={},_h={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function F_(e,t){Qs[e]=t}function qa(e,t){if(!(e in Qs)||t!=null){let a=WJ(e,t);if(a!==null)Qs[e]=a;else return console.log("Could not get context for WebGL version",e),null}let n=Qs[e];return n==null||n.isContextLost()?(delete Qs[e],qa(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),Qs[e])}function zJ(e){if(!G().getBool("IS_SAFARI")&&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 WJ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let n=t==null?zJ(e):t;return n.addEventListener("webglcontextlost",a=>{a.preventDefault(),delete Qs[e]},!1),G().getBool("SOFTWARE_WEBGL_ENABLED")&&(_h.failIfMajorPerformanceCaveat=!1),e===1?n.getContext("webgl",_h)||n.getContext("experimental-webgl",_h):n.getContext("webgl2",_h)}var Nc;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(Nc||(Nc={}));var ca;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(ca||(ca={}));var pn;(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"})(pn||(pn={}));function _d(e,t){return[t,e]}function BJ(e,t){return e*t}function Ah(e){let t=w.sizeFromShape(e),n=Math.ceil(t/4);return w.sizeToSquarishShape(n)}function op(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function VJ(e,t){let[n,a]=op(e,t);return n*a*4}function Z1(e,t){let n=e,a,r,s,i,o,l,u,p,d,c;return G().getNumber("WEBGL_VERSION")===2?(a=n.R32F,r=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,p=1,d=n.HALF_FLOAT,c=n.FLOAT,l=n.RGBA8):(a=e.RGBA,r=e.RGBA,s=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,p=4,d=t!=null?t.HALF_FLOAT_OES:null,c=e.FLOAT,l=e.RGBA),{internalFormatFloat:a,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:p,textureTypeHalfFloat:d,textureTypeFloat:c}}function de(e,t){let n=t();return G().getBool("DEBUG")&&UJ(e),n}function UJ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+D_(e,t))}var GJ=596e-10,HJ=65504;function $_(e){return!!(G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||GJ<Math.abs(e)&&Math.abs(e)<HJ)}function D_(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 rc(e,t){return Or(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function R_(e,t){let n=Or(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(de(e,()=>e.shaderSource(n,t)),de(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 M_(e,t){let n=Or(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(de(e,()=>e.shaderSource(n,t)),de(e,()=>e.compileShader(n)),G().get("ENGINE_COMPILE_ONLY"))return n;if(e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw J1(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var qJ=/ERROR: [0-9]+:([0-9]+):/g;function J1(e,t){let n=qJ.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let a=+n[1],r=e.split(`
|
|
`),s=r.length.toString().length+2,i=r.map((d,c)=>w.rightPad((c+1).toString(),s)+d),o=0;for(let d=0;d<i.length;d++)o=Math.max(i[d].length,o);let l=i.slice(0,a-1),u=i.slice(a-1,a),p=i.slice(a);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${w.rightPad(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
|
|
`))}function O_(e){return Or(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function P_(e,t){if(de(e,()=>e.linkProgram(t)),!G().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Oh(e,t){if(de(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function L_(e,t){let n=Or(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),de(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function z_(e,t){let n=Or(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return de(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),de(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function jJ(){return G().getNumber("WEBGL_VERSION")===2?1:4}function W_(e){return Or(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function B_(e,t){let n=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a=`[${e}x${t}]`;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function V_(e){return Or(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function uv(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),de(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),de(e,()=>e.enableVertexAttribArray(o)),!0)}function U_(e,t,n){K_(e,n),de(e,()=>e.activeTexture(e.TEXTURE0+n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function KJ(e,t){K_(e,t),de(e,()=>e.activeTexture(e.TEXTURE0+t)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function G_(e,t,n){return Or(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function H_(e,t,n){return e.getUniformLocation(t,n)}function q_(e,t,n,a){de(e,()=>U_(e,t,a)),de(e,()=>e.uniform1i(n,a))}function XJ(e){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),de(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),de(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Ph(e,t,n){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),de(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function pv(e,t){de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),de(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function sc(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+j_(e,t))}function j_(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 Or(e,t,n){let a=de(e,()=>t());if(a==null)throw new Error(n);return a}function K_(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>n){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function vi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function wi(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 ic(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[vi(e),...wi(e)]),t}function X_(e,t=!1){let n=G().getNumber("WEBGL_MAX_TEXTURE_SIZE"),a=G().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");a===1/0&&G().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(a=n/2),t&&(n=n*2,a=a*2,e=e.map((o,l)=>l>=e.length-2?w.nearestLargerEven(e[l]):e[l]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.sizeFromShape(e),s=null;e.length<=1&&r<=n?s=[1,r]:e.length===2&&e[0]<=n&&e[1]<=n?s=e:e.length===3&&e[0]*e[1]<=n&&e[2]<=n?s=[e[0]*e[1],e[2]]:e.length===3&&e[0]<=n&&e[1]*e[2]<=n?s=[e[0],e[1]*e[2]]:e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n?s=[e[0]*e[1]*e[2],e[3]]:e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(s=[e[0],e[1]*e[2]*e[3]]);let i=s!=null&&Math.max(...s)>a&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(s==null||i)if(t){let o=vi(e),l=2,u=2;e.length&&([l,u]=wi(e)),r=o*(l/2)*(u/2),s=w.sizeToSquarishShape(r).map(p=>p*2)}else s=w.sizeToSquarishShape(r);return s}function Fh(e){return e%2===0}function Tc(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[e.length-1],a=t[t.length-1];if(n===a||Fh(n)&&Fh(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Fh(e[0])&&Fh(t[0])}var Lh,zh;function Y_(e){if(Lh==null){let t=qa(e);Lh=t.getParameter(t.MAX_TEXTURE_SIZE)}return Lh}function YJ(){Lh=null}function ZJ(){zh=null}function Z_(e){if(zh==null){let t=qa(e);zh=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,zh)}function J_(e){if(e===0)return 0;let t,n=qa(e);return da(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:da(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function da(e,t){return e.getExtension(t)!=null}function cv(e){try{if(qa(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function Q_(e){if(e===0)return!1;let t=qa(e);if(e===1){if(!da(t,"OES_texture_float"))return!1}else if(!da(t,"EXT_color_buffer_float"))return!1;return dv(t)}function eA(e){if(e===0)return!1;let t=qa(e);if(e===1){if(!da(t,"OES_texture_float")||!da(t,"WEBGL_color_buffer_float"))return!1}else{if(da(t,"EXT_color_buffer_float"))return dv(t);let n="EXT_color_buffer_half_float";if(da(t,n)){let a=t.getExtension(n);return JJ(t,a)}return!1}return dv(t)}function dv(e){let t=Z1(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,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 r=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),r}function JJ(e,t){let n=Z1(e,t),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(r),s}function tA(e){return e!==2?!1:qa(e).fenceSync!=null}function lp(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 be=G();be.registerFlag("HAS_WEBGL",()=>be.getNumber("WEBGL_VERSION")>0);be.registerFlag("WEBGL_VERSION",()=>cv(2)?2:cv(1)?1:0);be.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);be.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>be.get("WEBGL_VERSION")===2);be.registerFlag("WEBGL_CPU_FORWARD",()=>!0);be.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);be.registerFlag("WEBGL_PACK",()=>be.getBool("HAS_WEBGL"));be.registerFlag("WEBGL_PACK_NORMALIZATION",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_CLIP",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_REDUCE",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_LAZILY_UNPACK",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_CONV_IM2COL",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>be.getBool("WEBGL_PACK"));be.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>Y_(be.getNumber("WEBGL_VERSION")));be.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>Z_(be.getNumber("WEBGL_VERSION")));be.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=be.getNumber("WEBGL_VERSION");return e===0?0:J_(e)});be.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>be.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ad.isMobile());be.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>Q_(be.getNumber("WEBGL_VERSION")));be.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>be.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:be.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));be.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>eA(be.getNumber("WEBGL_VERSION")));be.registerFlag("WEBGL_FENCE_API_ENABLED",()=>tA(be.getNumber("WEBGL_VERSION")));be.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>be.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);be.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${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}.`)});be.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>ad.isMobile()?1:-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${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}.`)});be.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);be.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);be.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);be.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);be.registerFlag("WEBGL_EXP_CONV",()=>!1);be.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>be.getBool("IS_TEST"));be.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);be.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);be.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);be.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function Cn(){let e,t,n,a,r,s,i,o,l,u;return G().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",a="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=G().getBool("WEBGL2_ISNAN_CUSTOM")?`
|
|
bool isnan_custom(float val) {
|
|
uint floatToUint = floatBitsToUint(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`:"",l="",u=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",n="varying",a="varying",r="texture2D",s="gl_FragColor",i="",o=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,l=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,u=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Zo(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i=`int ${e[s]} = ${n} / ${r}`,o=s===a.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r}`:`index -= ${e[s]} * ${r}`;return`${i}; ${o};`}).join("")}function zf(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i=`int ${e[s]} = ${n} / outShapeStrides[${s}]`,o=s===a.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function QJ(e,t){let n=e.length,a=e.map(s=>`${t}[${s}]`),r=new Array(n-1);r[n-2]=a[n-1];for(let s=n-3;s>=0;--s)r[s]=`(${r[s+1]} * ${a[s+1]})`;return r}function e9(e,t,n="index"){let a=e.map((s,i)=>i),r=QJ(a,t);return r.map((s,i)=>{let o=`int ${e[i]} = ${n} / ${r[i]}`,l=i===r.length-1?`int ${e[i+1]} = ${n} - ${e[i]} * ${r[i]}`:`index -= ${e[i]} * ${r[i]}`;return`${o}; ${l};`}).join("")}function Q1(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 ek(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var nA=`
|
|
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:aA}=T;function t9(e,t,n){let a=[];if(e.forEach(c=>{let h=w.sizeFromShape(c.shapeInfo.logicalShape);if(c.shapeInfo.isUniform?a.push(`uniform float ${c.name}${h>1?`[${h}]`:""};`):(a.push(`uniform sampler2D ${c.name};`),a.push(`uniform int offset${c.name};`)),n.enableShapeUniforms){let{uniformShape:m}=tk(n.packedInputs,c.shapeInfo.logicalShape,c.shapeInfo.texShape);switch(m.length){case 1:a.push(`uniform int ${c.name}Shape;`);break;case 2:a.push(`uniform ivec2 ${c.name}Shape;`);break;case 3:a.push(`uniform ivec3 ${c.name}Shape;`);break;case 4:a.push(`uniform ivec4 ${c.name}Shape;`);break;default:break}a.push(`uniform ivec2 ${c.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:a.push("uniform int outShape;");break;case 2:a.push("uniform ivec2 outShape;"),a.push("uniform int outShapeStrides;");break;case 3:a.push("uniform ivec3 outShape;"),a.push("uniform ivec2 outShapeStrides;");break;case 4:a.push("uniform ivec4 outShape;"),a.push("uniform ivec3 outShapeStrides;");break;default:break}a.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(c=>{a.push(`uniform ${c.type} ${c.name}${c.arrayIndex?`[${c.arrayIndex}]`:""};`)});let r=a.join(`
|
|
`),s=e.map(c=>n9(c,t,n.packedInputs,n.enableShapeUniforms)).join(`
|
|
`),i=t.texShape,o=Cn(),l=s9(o),u,p,d=l9(o);return t.isPacked?(u=a9(t.logicalShape,i,n.enableShapeUniforms),p=o9(o)):(u=r9(t.logicalShape,i,n.enableShapeUniforms),p=i9(o)),n.packedInputs&&(d+=d9),[d,l,p,r,u,s,n.userCode].join(`
|
|
`)}function up(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return S9(e,t);case 1:return T9(e,t);case 2:return E9(e,t);case 3:return A9(e,t);case 4:return $9(e,t);case 5:return D9(e);case 6:return R9(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function rA(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return I9(e);case 1:return N9(e,t);case 2:return C9(e,t);case 3:return _9(e,t);default:return F9(e,t)}}function n9(e,t,n=!1,a){let r="";n?r+=rA(e,a):r+=up(e,a);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(n?r+=M9(e,t):r+=O9(e,t)),r}function a9(e,t,n){switch(e.length){case 0:return sA();case 1:return h9(e,t,n);case 2:return w9(e,t,n);case 3:return f9(e,t,n);default:return b9(e,t,n)}}function r9(e,t,n){switch(e.length){case 0:return sA();case 1:return m9(e,t,n);case 2:return k9(e,t,n);case 3:return g9(e,t,n);case 4:return y9(e,t,n);case 5:return x9(e,t);case 6:return v9(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function s9(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function i9(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function o9(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function l9(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);
|
|
}
|
|
|
|
${u9}
|
|
${p9}
|
|
${c9}
|
|
`}var u9=`
|
|
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);
|
|
}
|
|
`,p9=`
|
|
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);
|
|
}
|
|
`,c9=`
|
|
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);
|
|
}
|
|
`,d9=`
|
|
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 sA(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function h9(e,t,n){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return a[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${a[1]}.0);
|
|
}
|
|
`:a[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${a[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(${a[0]}, ${a[1]}));
|
|
return 2 * (resTexRC.x * ${a[1]} + resTexRC.y);
|
|
}
|
|
`}function m9(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 f9(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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),s=r*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${a[0]}, ${a[1]}));
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function g9(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;
|
|
${zf(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let a=Zo(["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;
|
|
${a}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function b9(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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),s=r*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o=`
|
|
int b${u} = index / ${i};
|
|
index -= b${u} * ${i};
|
|
`+o,l=`b${u}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${a[0]}, ${a[1]}));
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
|
|
${o}
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function y9(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;
|
|
${zf(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let a=Zo(["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;
|
|
${a}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function x9(e,t){let n=Zo(["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 v9(e,t){let n=Zo(["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 w9(e,t,n){let a=[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(${a[0]}, ${a[1]}));
|
|
}
|
|
`;let r=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(${a[0]}, ${a[1]}));
|
|
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function k9(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 Jo(e){return`offset${e}`}function I9(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=Cn();return`
|
|
vec4 ${n}() {
|
|
return ${a.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function S9(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${a}() {return ${n};}`;let[r,s]=e.shapeInfo.texShape;if(r===1&&s===1)return`
|
|
float ${a}() {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let i=Jo(n);if(t)return`
|
|
float ${a}() {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let[o,l]=e.shapeInfo.texShape;return`
|
|
float ${a}() {
|
|
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function N9(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=Cn();if(t)return`
|
|
vec4 ${a}(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 ${s.texture2D}(${n}, uv);
|
|
}
|
|
`;let i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`
|
|
vec4 ${a}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${i[0]}, ${i[1]}, index);
|
|
return ${s.texture2D}(${n}, uv);
|
|
}
|
|
`}function T9(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int index) {
|
|
${pp(e)}
|
|
}
|
|
`;let r=e.shapeInfo.texShape,s=r[0],i=r[1];if(i===1&&s===1)return`
|
|
float ${a}(int index) {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let o=Jo(n);return i===1?t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:s===1?t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function C9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Cn();if(s!=null&&w.arraysEqual(n,s))return t?`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
|
|
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${r}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${a}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],p=Math.ceil(n[1]/2);return`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${p}, ${u[0]}, ${u[1]}, row, col);
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`}function E9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape;if(s!=null&&w.arraysEqual(n,s)){if(t)return`
|
|
float ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let c=s[0],h=s[1];return`
|
|
float ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${c}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}let{newShape:i,keptDims:o}=w.squeezeShape(n),l=i;if(l.length<n.length){let c=cp(e,l),h=["row","col"];return`
|
|
${up(c,t)}
|
|
float ${r}(int row, int col) {
|
|
return ${r}(${dp(h,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
|
|
${pp(e)}
|
|
}
|
|
`;let u=s[0],p=s[1],d=Jo(a);return p===1?t?`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${a}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${a}TexShape[0]));
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:u===1?t?`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${a}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${a}TexShape[1]), 0.5);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:t?`
|
|
float ${r}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a}Shape[1] + col + ${d};
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n[1]} + col + ${d};
|
|
vec2 uv = uvFromFlat(${u}, ${p}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function _9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(n[0]===1){let c=n.slice(1),h=[1,2],m=cp(e,c),f=["b","row","col"];return`
|
|
${rA(m,t)}
|
|
vec4 ${r}(int b, int row, int col) {
|
|
return ${r}(${dp(f,h)});
|
|
}
|
|
`}let o=Cn();if(t)return`
|
|
vec4 ${r}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${a}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${a}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${o.texture2D}(${a}, uv);
|
|
}
|
|
`;let l=i[0],u=i[1],p=Math.ceil(n[2]/2),d=p*Math.ceil(n[1]/2);return`
|
|
vec4 ${r}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${u}, ${d}, ${p}, b, row, col);
|
|
return ${o.texture2D}(${a}, uv);
|
|
}
|
|
`}function A9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[1]*n[2],i=n[2],{newShape:o,keptDims:l}=w.squeezeShape(n),u=o;if(u.length<n.length){let f=cp(e,u),g=["row","col","depth"];return`
|
|
${up(f,t)}
|
|
float ${r}(int row, int col, int depth) {
|
|
return ${r}(${dp(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${s}, ${i}, 1)));
|
|
${pp(e)}
|
|
}
|
|
`;let p=e.shapeInfo.texShape,d=p[0],c=p[1],h=e.shapeInfo.flatOffset;if(c===s&&h==null)return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
int stride1 = ${a}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${i}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${d}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(c===i&&h==null)return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${a}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(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(${c}.0, ${d}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let m=Jo(a);return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${a}Shape[1] * ${a}Shape[2];
|
|
int stride1 = ${a}Shape[2];
|
|
int index = row * stride0 + col * stride1 + depth + ${m};
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${s} + col * ${i} + depth + ${m};
|
|
vec2 uv = uvFromFlat(${d}, ${c}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function F9(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=Cn();if(t)return`
|
|
vec4 ${a}(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 ${r.texture2D}(${n}, uv);
|
|
}
|
|
`;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],p=l[1],d=Math.ceil(s[i-1]/2),c=d*Math.ceil(s[i-2]/2),h="int b, int row, int col",m=`b * ${c} + (row / 2) * ${d} + (col / 2)`;for(let f=2;f<i-1;f++)h=`int b${f}, `+h,c*=s[i-f-1],m=`b${f} * ${c} + `+m;return`
|
|
vec4 ${a}(${h}) {
|
|
int index = ${m};
|
|
int texR = index / ${p};
|
|
int texC = index - texR * ${p};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${u});
|
|
return ${r.texture2D}(${n}, uv);
|
|
}
|
|
`}function $9(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[3],i=n[2]*s,o=n[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(n);if(l.length<n.length){let y=cp(e,l),x=["row","col","depth","depth2"];return`
|
|
${up(y,t)}
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
return ${r}(${dp(x,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, 1)));
|
|
${pp(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1],m=`int stride2 = ${a}Shape[3];`,f=`int stride1 = ${a}Shape[2] * stride2;`,g=`int stride0 = ${a}Shape[1] * stride1;`;if(h===o&&p==null)return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
${m}
|
|
${f}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${i}, ${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${c}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(h===s&&p==null)return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${a}Shape[1] * ${a}Shape[2], ${a}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(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, ${c}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let b=Jo(a);return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${m}
|
|
${f}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index + ${b});
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} +
|
|
depth * ${s} + depth2;
|
|
vec2 uv = uvFromFlat(${c}, ${h}, index + ${b});
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function D9(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(t);if(l.length<t.length){let f=cp(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${up(f)}
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${a}(${dp(g,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, ${r})) +
|
|
depth3;
|
|
${pp(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1];if(h===o&&p==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${c}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===r&&p==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${c}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=Jo(n);return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} + depth * ${s} +
|
|
depth2 * ${r} + depth3 + ${m};
|
|
vec2 uv = uvFromFlat(${c}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function R9(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=w.squeezeShape(t);if(r.length<t.length){let g=cp(e,r),b=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${up(g)}
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${a}(${dp(b,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,p=t[1]*u;if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${p}, ${u}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${pp(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,h=c[0],m=c[1];if(m===p&&d==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${u}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(m===i&&d==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=Jo(n);return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${p} + col * ${u} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
|
|
vec2 uv = uvFromFlat(${h}, ${m}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function pp(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 M9(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=aA(e.shapeInfo.logicalShape,t.logicalShape),l=ht(i),u=i-s,p,d=["x","y","z","w","u","v"];s===0?p="":i<2&&o.length>=1?p="coords = 0;":p=o.map(g=>`coords.${d[g+u]} = 0;`).join(`
|
|
`);let c="";i<2&&s>0?c="coords":c=e.shapeInfo.logicalShape.map((g,b)=>`coords.${d[b+u]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,f=w.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!f)i===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(o.length){let g=s-2,b=s-1;o.indexOf(g)>-1&&o.indexOf(b)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(b)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${r}() {
|
|
${l} coords = getOutputCoords();
|
|
${p}
|
|
vec4 outputValue = get${a}(${c});
|
|
${h}
|
|
}
|
|
`}function O9(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&w.arraysEqual(i,s))return`
|
|
float ${r}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;let u=ht(l),p=aA(e.shapeInfo.logicalShape,t.logicalShape),d=l-o,c,h=["x","y","z","w","u","v"];o===0?c="":l<2&&p.length>=1?c="coords = 0;":c=p.map(f=>`coords.${h[f+d]} = 0;`).join(`
|
|
`);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${h[g+d]}`).join(", "),`
|
|
float ${r}() {
|
|
${u} coords = getOutputCoords();
|
|
${c}
|
|
return get${a}(${m});
|
|
}
|
|
`}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 tk(e,t,n){let{newShape:a,keptDims:r}=w.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):a,l=!e&&s>1&&!w.arraysEqual(t,n)&&a.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function cp(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function dp(e,t){return t.map(n=>e[n]).join(", ")}function P9(e,t,n,a){let r=n.map((p,d)=>{let c={logicalShape:p.shape,texShape:p.isUniform?null:p.texData.texShape,isUniform:p.isUniform,isPacked:p.isUniform?!1:p.texData.isPacked,flatOffset:null};return p.texData!=null&&p.texData.slice!=null&&p.texData.slice.flatOffset>0&&(c.flatOffset=p.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:c}}),s=r.map(p=>p.shapeInfo),i={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},o=t9(r,i,t),l=M_(e.gl,o),u=e.createProgram(l);return G().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(u),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i},iA(e,t,u)))}function iA(e,t,n){let a=[],r=[],s,i,o,l=null,u=null;u=e.getUniformLocation(n,"NAN",!1),G().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(n,"INFINITY",!1));let p=!1;for(let d of t.variableNames){let c={name:d,uniform:e.getUniformLocation(n,d,p),offset:e.getUniformLocation(n,`offset${d}`,p)};t.enableShapeUniforms&&(c.shape=e.getUniformLocation(n,`${d}Shape`,p),c.texShape=e.getUniformLocation(n,`${d}TexShape`,p)),a.push(c)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(n,"outShape",p),o=e.getUniformLocation(n,"outShapeStrides",p),i=e.getUniformLocation(n,"outTexShape",p)),t.customUniforms)for(let d of t.customUniforms)r.push(e.getUniformLocation(n,d.name,p));return{variablesLocations:a,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}}function nS(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,a)=>{let r=n.logicalShape,s=t[a],i=s.shape;if(!w.arraysEqual(r,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${i} must match`);if(n.isUniform&&s.isUniform)return;let o=n.texShape,l=s.isUniform?null:s.texData.texShape;if(!w.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function L9(e,t,n,a,r){t.program.enableShapeUniforms||(nS(t.inShapeInfos,n),nS([t.outShapeInfo],[a]));let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),G().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN);for(let l=0;l<n.length;++l){let u=n[l],{uniform:p,offset:d,shape:c,texShape:h}=t.variablesLocations[l];if(c){let{uniformShape:m}=tk(t.program.packedInputs,u.shape,u.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(c,new Int32Array(m));break;case 2:e.gl.uniform2iv(c,new Int32Array(m));break;case 3:e.gl.uniform3iv(c,new Int32Array(m));break;case 4:e.gl.uniform4iv(c,new Int32Array(m));break;default:break}}if(h&&e.gl.uniform2i(h,u.texData.texShape[0],u.texData.texShape[1]),p!=null){if(u.isUniform){if(w.sizeFromShape(u.shape)<2)e.gl.uniform1f(p,u.uniformValues[0]);else{let m=u.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(p,m)}continue}u.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,u.texData.slice.flatOffset),e.setInputMatrixTexture(u.texData.texture.texture,p,l)}}let o=t.outShapeLocation;if(o)switch(a.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(a.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(a.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(a.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(a.shape));break;default:break}if(t.outShapeStridesLocation){let l=w.computeStrides(a.shape);switch(a.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,a.texData.texShape[0],a.texData.texShape[1]),t.program.customUniforms&&r)for(let l=0;l<t.program.customUniforms.length;++l){let u=t.program.customUniforms[l],p=t.customUniformLocations[l],d=r[l];if(u.type==="float")e.gl.uniform1fv(p,d);else if(u.type==="vec2")e.gl.uniform2fv(p,d);else if(u.type==="vec3")e.gl.uniform3fv(p,d);else if(u.type==="vec4")e.gl.uniform4fv(p,d);else if(u.type==="int")e.gl.uniform1iv(p,d);else if(u.type==="ivec2")e.gl.uniform2iv(p,d);else if(u.type==="ivec3")e.gl.uniform3iv(p,d);else if(u.type==="ivec4")e.gl.uniform4iv(p,d);else throw Error(`uniform type ${u.type} is not supported yet.`)}e.executeProgram()}function z9(e,t,n){let a="";t.concat(n).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!i.isUniform){let l=i.texData.texShape,{useSqueezeShape:u,uniformShape:p,keptDims:d}=tk(e.packedInputs,i.shape,l),c="",h="",m="";if(p.length===1&&e.packedInputs){let I=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];c=`${I[0]>1}_${I[1]>1}`}else if(p.length===2&&!e.packedInputs)h=`${p[0]>1}_${p[1]>1}`;else if(p.length>2&&!e.packedInputs){let I=w.computeStrides(p);m=`${I[0]===l[1]}_${I[I.length-1]===l[1]}`}let f=i.shape.length,g=p.length===2&&w.arraysEqual(i.shape,l),b=w.sizeFromShape(i.shape)===1,y=T.getBroadcastDims(i.shape,n.shape),x=!e.packedInputs&&f===n.shape.length&&w.arraysEqual(l,n.texData.texShape),v=e.packedInputs||p.length>2?"":`${l[0]>1}_${l[1]>1}`;a+=`${f}_${x}_${u?d:""}_${p.length}_${b}_${y}_${g}_${c}_${h}_${m}_${v}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;a+=`${i.shape}_${l}_${o}`}});let r=e.userCode,s=e.constructor.name;return s+="_"+a+"_"+r+`${G().getNumber("WEBGL_VERSION")}`,s}function xn(e){return G().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var W9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Nc.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Cn();this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?zf(["r","c","d"],e):Zo(["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;
|
|
}
|
|
`}},B9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Nc.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Cn();this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?zf(["r","c","d"],e):Zo(["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;
|
|
}
|
|
`}},V9=class{constructor(e){this.variableNames=["A"],this.outTexUsage=ca.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode=`
|
|
${nA}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},U9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ca.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode=`
|
|
${nA}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},G9={R:0,G:1,B:2,A:3},aS=class{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let a=Cn();this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)");let s="";for(let i=0;i<n.length;i++){let o=n[i];s+=`
|
|
if(offset == ${i}) {
|
|
result = values[${G9[o]}];
|
|
}`}this.userCode=`
|
|
${this.enableShapeUniforms?ek():Q1(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int flatIndex = getFlatIndex(coords);
|
|
float result = 0.;
|
|
int offset = imod(flatIndex, ${n.length});
|
|
|
|
flatIndex = idiv(flatIndex, ${n.length}, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
if (r < texShape[0]) {
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${a.texture2D}(A, uv);
|
|
${s}
|
|
}
|
|
${a.output} = vec4(${r}, 0., 0., 0.);
|
|
}
|
|
`}},H9=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Cn();this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length);let a="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;a+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${i};
|
|
if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${s};
|
|
|
|
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[${o}] = values[0];
|
|
} else if (offset == 1) {
|
|
result[${o}] = values[1];
|
|
} else if (offset == 2) {
|
|
result[${o}] = values[2];
|
|
} else {
|
|
result[${o}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${this.enableShapeUniforms?ek():Q1(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${a}
|
|
|
|
${n.output} = ${r};
|
|
}
|
|
`}},oA={};_e(oA,{bindVertexProgramAttributeStreams:()=>gA,createBufferFromOutputTexture:()=>xA,createFloat16MatrixTexture:()=>dA,createFloat16PackedMatrixTexture:()=>fA,createFloat32MatrixTexture:()=>cA,createIndexBuffer:()=>pA,createPackedMatrixTexture:()=>mA,createUnsignedBytesMatrixTexture:()=>hA,createVertexBuffer:()=>uA,createVertexShader:()=>lA,downloadByteEncodedFloatMatrixFromOutputTexture:()=>wA,downloadFloat32MatrixFromBuffer:()=>vA,downloadMatrixFromPackedOutputTexture:()=>IA,downloadPackedMatrixFromBuffer:()=>kA,getInternalFormatForFloat16MatrixTexture:()=>ak,getInternalFormatForFloat16PackedMatrixTexture:()=>ik,getInternalFormatForFloat32MatrixTexture:()=>nk,getInternalFormatForPackedMatrixTexture:()=>sk,getInternalFormatForUnsignedBytesMatrixTexture:()=>rk,uploadDenseMatrixToTexture:()=>bA,uploadPixelDataToTexture:()=>yA});function lA(e){let t=Cn(),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 R_(e,n)}function uA(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 L_(e,t)}function pA(e){let t=new Uint16Array([0,1,2,2,1,3]);return z_(e,t)}function Ad(e,t,n,a,r,s){B_(t,n);let i=W_(e),o=e.TEXTURE_2D;return de(e,()=>e.bindTexture(o,i)),de(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),de(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),de(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),de(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),G().getNumber("WEBGL_VERSION")===1?de(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)):de(e,()=>e.texStorage2D(o,1,a,t,n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[n,t]}}function nk(e){return e.internalFormatFloat}function cA(e,t,n,a){let[r,s]=_d(t,n);return Ad(e,r,s,nk(a),a.textureFormatFloat,e.FLOAT)}function ak(e){return e.internalFormatHalfFloat}function dA(e,t,n,a){let[r,s]=_d(t,n);return Ad(e,r,s,ak(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function rk(e){return e.downloadTextureFormat}function hA(e,t,n,a){let[r,s]=_d(t,n);return Ad(e,r,s,rk(a),e.RGBA,e.UNSIGNED_BYTE)}function sk(e){return e.internalFormatPackedFloat}function mA(e,t,n,a){let[r,s]=op(t,n);return Ad(e,r,s,sk(a),e.RGBA,e.FLOAT)}function ik(e){return e.internalFormatPackedHalfFloat}function fA(e,t,n,a){let[r,s]=op(t,n);return Ad(e,r,s,ik(a),e.RGBA,a.textureTypeHalfFloat)}function gA(e,t,n){return de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),uv(e,t,"clipSpacePos",n,3,20,0)&&uv(e,t,"uv",n,2,20,12)}function bA(e,t,n,a,r,s){de(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(n*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA,o,i)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function yA(e,t,n){de(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):G().getNumber("WEBGL_VERSION")===2?de(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):de(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),de(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function xA(e,t,n,a){let r=e.createBuffer();de(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return de(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),de(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),de(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function vA(e,t,n){let a=e,r=new Float32Array(n);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),r}function wA(e,t,n,a){let[r,s]=_d(t,n),i=4,o=new Uint8Array(BJ(t*n,i));return de(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function kA(e,t,n,a,r,s,i,o){let l=e,u=new Float32Array(VJ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function IA(e,t,n){let a=new Float32Array(t*n*4);return de(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var Wh=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=G().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,F_(t,e)):this.gl=qa(t),e=this.gl,G().getNumber("WEBGL_VERSION")===2){let r=e;this.createVertexArray=()=>de(r,()=>r.createVertexArray()),this.bindVertexArray=s=>de(r,()=>r.bindVertexArray(s)),this.deleteVertexArray=s=>de(r,()=>r.deleteVertexArray(s)),this.getVertexArray=()=>de(r,()=>r.getParameter(r.VERTEX_ARRAY_BINDING))}else if(e!=null){let r=e.getExtension("OES_vertex_array_object");if(r==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>de(e,()=>r.createVertexArrayOES()),this.bindVertexArray=s=>de(e,()=>r.bindVertexArrayOES(s)),this.deleteVertexArray=s=>de(e,()=>r.deleteVertexArrayOES(s)),this.getVertexArray=()=>de(e,()=>e.getParameter(r.VERTEX_ARRAY_BINDING_OES))}let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),G().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=rc(this.gl,r),da(this.gl,s))this.textureHalfFloatExtension=rc(this.gl,s);else if(G().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),da(this.gl,a))this.colorBufferHalfFloatExtension=rc(this.gl,a);else if(G().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",da(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(da(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=uA(this.gl),this.indexBuffer=pA(this.gl),this.framebuffer=V_(this.gl),this.textureConfig=Z1(this.gl,this.textureHalfFloatExtension)}get debug(){return G().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;de(e,()=>e.finish()),de(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),de(e,()=>e.deleteFramebuffer(this.framebuffer)),de(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),de(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),de(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),cA(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),dA(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),hA(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),yA(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),bA(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),fA(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),mA(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(pv(this.gl,this.framebuffer),this.outputTexture=null),de(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>wA(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return kA(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return vA(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=xA(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),a}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(G().getBool("WEBGL_FENCE_API_ENABLED")){let a=e,r=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let s=a.clientWaitSync(r,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},t=r}else G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>IA(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=lA(t));let n=O_(t);de(t,()=>t.attachShader(n,this.vertexShader)),de(t,()=>t.attachShader(n,e)),P_(t,n);let a=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&Oh(t,a),a}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);let t=this.gl;de(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),gA(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(de(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Oh(this.gl,this.program),de(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?G_(this.gl,e,t):H_(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),de(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(),q_(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=op(t,n);this.setOutputMatrixTextureDriver(e,a,r)}setOutputMatrixWriteRegion(e,t,n,a){this.setOutputMatrixWriteRegionDriver(n,e,a,t)}setOutputPackedMatrixWriteRegion(e,t,n,a){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Oh(this.gl,this.program),sc(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;if(this.debug){let t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}de(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),de(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=rc(this.gl,G().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(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(a.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(G().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,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),a=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=q9(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){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in G().platform&&(n=G().platform.setTimeoutCustom.bind(G().platform)),w.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Ph(this.gl,e,this.framebuffer),this.debug&&sc(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Ph(this.gl,this.outputTexture,this.framebuffer),this.debug&&sc(this.gl)):pv(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let a=this.gl;Ph(a,e,this.framebuffer),this.debug&&sc(a),this.outputTexture=e,de(a,()=>a.viewport(0,0,t,n)),de(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),de(this.gl,()=>this.gl.scissor(e,t,n,a))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function q9(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:j9,bincountImpl:SA,bincountReduceImpl:K9,bitwiseAndImpl:X9,castImpl:Y9,ceilImpl:Z9,concatImpl:J9,equalImpl:Q9,expImpl:eQ,expm1Impl:tQ,floorImpl:nQ,gatherNdImpl:aQ,gatherV2Impl:rQ,greaterImpl:sQ,greaterEqualImpl:iQ,lessImpl:oQ,lessEqualImpl:lQ,linSpaceImpl:uQ,logImpl:pQ,maxImpl:cQ,maximumImpl:dQ,minimumImpl:hQ,multiplyImpl:mQ,negImpl:fQ,notEqualImpl:gQ,prodImpl:bQ,raggedGatherImpl:yQ,raggedRangeImpl:xQ,raggedTensorToTensorImpl:vQ,rangeImpl:wQ,rsqrtImpl:kQ,scatterImpl:IQ,sigmoidImpl:SQ,simpleAbsImpl:NA,sliceImpl:NQ,sparseFillEmptyRowsImpl:TQ,sparseReshapeImpl:CQ,sparseSegmentReductionImpl:TA,sqrtImpl:EQ,staticRegexReplaceImpl:_Q,stridedSliceImpl:AQ,stringNGramsImpl:FQ,stringSplitImpl:$Q,stringToHashBucketFastImpl:DQ,subImpl:RQ,tileImpl:MQ,topKImpl:OQ,transposeImpl:ok,uniqueImpl:PQ}=M1;function CA(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function kn(e,t){return t===1?[e]:CA(e,t)}function LQ(e,t){if(e===1)return"rc";let n="";for(let a=0;a<e;a++)n+=t[a],a<e-1&&(n+=",");return n}var zQ=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=xn(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=kn("rc",this.rank),n=ht(this.rank),a=this.getOutOfBoundsCondition(t),r=this.getSetup(t),s=this.getOutput(t);this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
|
|
if(${a}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${r}
|
|
|
|
setOutput(vec4(${s}));
|
|
}
|
|
}
|
|
`}}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let a=0;a<=1;a++){let r=`${n===0?"r":"rp1"}, ${a===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)r=`${e[e.length-1-s]},`+r;t.push(r)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],a=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
|
|
int r = ${t[0]};
|
|
int c = ${t[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${n};
|
|
bool rEdge = rp1 >= ${a};
|
|
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
|
|
cEdge ? 0. : getA(${t[1]}),
|
|
rEdge ? 0. : getA(${t[2]}),
|
|
rEdge || cEdge ? 0. : getA(${t[3]})`}},EA=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length);let n="";for(let a=0;a<4;a++){let r="thisRC = rc;";a%2===1&&(r+="thisRC.z += 1;"),a>1&&(r+="thisRC.y += 1;"),n+=`
|
|
${r}
|
|
${a>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[${a}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${a>0?"}":""}
|
|
`}this.userCode=`
|
|
${WQ(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?ek():Q1(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 WQ(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?e9(["r","c","d"],"inputShape"):Zo(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var BQ=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){let a=sS(t,n),r=iS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=rS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].pop();return this.usedTextures[r].push(o),o}let i;return a===pn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===pn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===pn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===pn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===pn.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,a){if(this.freeTextures==null)return;let r=sS(n,a),s=iS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=rS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=G().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l&&l.indexOf(e);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),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.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function VQ(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F||t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function rS(e,t,n,a,r){let s=UQ(t,a),i;if(r){let[l,u]=op(e[0],e[1]);i=l*u}else{let[l,u]=_d(e[0],e[1]);i=l*u}let o=VQ(n,s);return i*o}function UQ(e,t){switch(e){case pn.PACKED_2X2_FLOAT32:return sk(t);case pn.PACKED_2X2_FLOAT16:return ik(t);case pn.UNPACKED_FLOAT32:return nk(t);case pn.UNPACKED_FLOAT16:return ak(t);case pn.PACKED_4X1_UNSIGNED_BYTE:return rk(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function GQ(e){return G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?pn.PACKED_2X2_FLOAT32:pn.UNPACKED_FLOAT32:e?pn.PACKED_2X2_FLOAT16:pn.UNPACKED_FLOAT16}function sS(e,t){if(e===ca.UPLOAD)return pn.PACKED_2X2_FLOAT32;if(e===ca.RENDER||e==null)return GQ(t);if(e===ca.DOWNLOAD||e===ca.PIXELS)return pn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function iS(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var rr=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Da="if (isnan(x)) return x;",HQ="return x;",oS="return abs(x);",qQ="return (x >= 0.0) ? x : (exp(x) - 1.0);",jQ=Da+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,KQ=Da+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Yr="return x;",XQ="return 1.0 / (1.0 + exp(-1.0 * x));",YQ="return x;",ZQ=`
|
|
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;
|
|
`,JQ=`
|
|
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;
|
|
`,QQ=`
|
|
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;
|
|
`,eee="return 1.0 / (1.0 + exp(-1.0 * x));",ts=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},tee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=xn(this.outputShape.length);let t=e.length,n=kn("rc",t),a=ht(t),r=LQ(t,n),s=n.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${r});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}},nee=hr.whereImpl,aee=1e-7,ree=1e-4,bx={};function see(e){return e in bx||(bx[e]={}),bx[e]}var iee=G().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),oee=600;function lee(){return G().global.screen==null?1024:G().global.screen.height*G().global.screen.width*window.devicePixelRatio*oee/1024/1024}var lk=class _A extends Fc{nextDataId(){return _A.nextDataId++}constructor(t){if(super(),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,!G().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let n;if(t!=null){if(t instanceof Wh)n=t;else{let a=qa(G().getNumber("WEBGL_VERSION"),t);n=new Wh(a)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let a=qa(G().getNumber("WEBGL_VERSION"));n=new Wh(a),this.binaryCache=see(G().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=n,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new BQ(this.gpgpu),this.numMBBeforeWarning=lee(),this.texData=new ym(this,Ta())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,n,a,r,s,i){let o=this.makeTensorInfo(n,a),l=this.texData.get(o.dataId);l.isPacked=!1,l.texture={texture:t,texShape:[r,s]},l.texShape=[r,s];let u=ic(n),p=new aS(u,!1,i),d=this.runWebGLProgram(p,[o],a,[[r,s]]);return d.shape=n,l.texture=null,this.disposeIntermediateTensorInfo(o),d.dataId}write(t,n,a){if((G().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||G().getBool("DEBUG"))&&this.checkNumericalProblems(t),a==="complex64"&&t!=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:n,dtype:a,values:t,usage:ca.UPLOAD,refCount:1}),r}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let n=this.texData.get(t);n.refCount++}decRef(t){if(this.texData.has(t)){let n=this.texData.get(t);n.refCount--}}move(t,n,a,r,s){if(G().getBool("DEBUG")&&this.checkNumericalProblems(n),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:a,dtype:r,values:n,usage:ca.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let n=this.texData.get(t),{values:a,dtype:r,complexTensorInfos:s,slice:i,shape:o,isPacked:l}=n;if(i!=null){let c;l?c=new ts(o,Yr):c=new rr(o,Yr);let h=this.runWebGLProgram(c,[{dataId:t,shape:o,dtype:r}],r),m=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),m}if(a!=null)return this.convertAndCacheOnCPU(t);if(r==="string")return a;let u=this.activeTimers!=null,p;u&&(p=w.now());let d;if(r==="complex64"){let c=this.readSync(s.real.dataId),h=this.readSync(s.imag.dataId);d=T.mergeRealAndImagArrays(c,h)}else d=this.getValuesFromTexture(t);return u&&(this.downloadWaitMs+=w.now()-p),this.convertAndCacheOnCPU(t,d)}async read(t){if(this.pendingRead.has(t)){let m=this.pendingRead.get(t);return new Promise(f=>m.push(f))}let n=this.texData.get(t),{values:a,shape:r,slice:s,dtype:i,complexTensorInfos:o,isPacked:l}=n;if(s!=null){let m;l?m=new ts(r,Yr):m=new rr(r,Yr);let f=this.runWebGLProgram(m,[{dataId:t,shape:r,dtype:i}],i),g=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),g}if(a!=null)return this.convertAndCacheOnCPU(t);if(G().getBool("DEBUG")&&!G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&G().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,p;if(i!=="complex64"&&G().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(t);let m=this.texData.get(p.dataId);u=this.gpgpu.createBufferFromTexture(m.texture.texture,...Ah(r))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(i==="complex64"){let m=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=m[0],g=m[1];d=T.mergeRealAndImagArrays(f,g)}else if(u==null)d=this.getValuesFromTexture(t);else{let m=w.sizeFromShape(r);d=this.gpgpu.downloadFloat32MatrixFromBuffer(u,m)}if(p!=null&&this.disposeIntermediateTensorInfo(p),u!=null){let m=this.gpgpu.gl;de(m,()=>m.deleteBuffer(u))}let c=this.convertAndCacheOnCPU(t,d),h=this.pendingRead.get(t);return this.pendingRead.delete(t),h.forEach(m=>m(c)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&Ta().removeDataId(t,this),this.pendingDeletes--),c}readToGPU(t,n={}){let a=this.texData.get(t),{values:r,shape:s,slice:i,dtype:o,isPacked:l,texture:u}=a;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let h;l?h=new ts(s,Yr):h=new rr(s,Yr);let m=this.runWebGLProgram(h,[{dataId:t,shape:s,dtype:o}],o),f=this.readToGPU(m,n);return this.disposeIntermediateTensorInfo(m),f}if(u==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let p=this.decode(t,n.customTexShape),d=Ta().makeTensorFromTensorInfo(p),c=this.texData.get(p.dataId);return Object.assign({tensorRef:d},c.texture)}bufferSync(t){let n=this.readSync(t.dataId);if(t.dtype==="string")try{let a=n.map(r=>w.decodeString(r));return Oe(t.shape,t.dtype,a)}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Oe(t.shape,t.dtype,n)}checkNumericalProblems(t){if(t!=null)for(let n=0;n<t.length;n++){let a=t[n];if(!$_(a))throw G().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${a} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${a} cannot be represented on this device.`)}}getValuesFromTexture(t){let{shape:n,dtype:a,isPacked:r}=this.texData.get(t),s=w.sizeFromShape(n);if(G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let c=this.decode(t),h=this.texData.get(c.dataId),m=this.gpgpu.downloadMatrixFromPackedTexture(h.texture.texture,...Ah(n)).subarray(0,s);return this.disposeIntermediateTensorInfo(c),m}let i=G().getBool("WEBGL_PACK")&&r===!0,o=i?ic(n):n,l=i?new U9(o):new V9(o),u=this.runWebGLProgram(l,[{shape:o,dtype:a,dataId:t}],"float32"),p=this.texData.get(u.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(p.texture.texture,p.texShape[0],p.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),d}timerAvailable(){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(t){let n=this.activeTimers,a=[],r=!1;this.programTimersStack==null?(this.programTimersStack=a,r=!0):this.activeTimers.push(a),this.activeTimers=a,t();let s=w.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),i=w.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=n,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);o.kernelMs=w.sum(l),o.getExtraProfileInfo=()=>l.map((u,p)=>({name:i[p],ms:u})).map(u=>`${u.name}: ${u.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 G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:w.now(),endMs:null}}endTimer(t){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=w.now(),t)}async getQueryTime(t){if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);let n=t;return n.endMs-n.startMs}disposeData(t,n=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(n?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!n&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);let{complexTensorInfos:a}=this.texData.get(t);return a!=null&&(this.disposeData(a.real.dataId,n),this.disposeData(a.imag.dataId,n)),this.texData.delete(t),!0}releaseGPUData(t){let{texture:n,dtype:a,texShape:r,usage:s,isPacked:i,slice:o}=this.texData.get(t),l=o&&o.origDataId||t,u=this.dataRefCount.get(l);u>1?this.dataRefCount.set(l,u-1):(this.dataRefCount.delete(l),n!=null&&(this.numBytesInGPU-=this.computeBytes(r,a),this.textureManager.releaseTexture(n,r,s,i)));let p=this.texData.get(t);p.texture=null,p.texShape=null,p.isPacked=!1,p.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,n=iee){return G().getBool("WEBGL_CPU_FORWARD")&&t.every(a=>this.texData.get(a.dataId).texture==null&&w.sizeFromShape(a.shape)<n)}getGPGPUContext(){return this.gpgpu}where(t){T.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let n=t.dataSync();return nee(t.shape,n)}packedUnaryOp(t,n,a){let r=new ts(t.shape,n),s=this.compileAndRun(r,[t],a);return Ta().makeTensorFromTensorInfo(s)}abs(t){if(this.shouldExecuteOnCPU([t])&&t.dtype!=="complex64"){let r=NA(this.texData.get(t.dataId).values);return this.makeOutput(t.shape,t.dtype,r)}if(G().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,oS,t.dtype);let n=new rr(t.shape,oS),a=this.compileAndRun(n,[t]);return Ta().makeTensorFromTensorInfo(a)}makeTensorInfo(t,n,a){let r;if(n==="string"&&a!=null&&a.length>0&&w.isString(a[0])){let s=a.map(i=>w.encodeString(i));r=this.write(s,t,n)}else r=this.write(a,t,n);return this.texData.get(r).usage=null,{dataId:r,shape:t,dtype:n}}makeOutput(t,n,a){return Ta().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,a),this)}unpackTensor(t){let n=new tee(t.shape);return this.runWebGLProgram(n,[t],t.dtype)}packTensor(t){let n=new zQ(t.shape);return this.runWebGLProgram(n,[t],t.dtype,null,!0)}packedReshape(t,n){let a=[vi(t.shape),...wi(t.shape)],r={dtype:t.dtype,shape:a,dataId:t.dataId},s=[vi(n),...wi(n)],i=new EA(s,a),o=!0,l=[a],u=this.runWebGLProgram(i,[r],t.dtype,l,o);return{dataId:u.dataId,shape:n,dtype:u.dtype}}decode(t,n){let a=this.texData.get(t),{isPacked:r,shape:s,dtype:i}=a;if(n!=null){let c=w.sizeFromShape(s),h=n[0]*n[1]*4;w.assert(c<=h,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let o=ic(s),l;r?l=new B9(o):l=new W9(o);let u=!0,p=[n!=null?n:Ah(o)],d=this.runWebGLProgram(l,[{shape:o,dtype:i,dataId:t}],i,p,u,n);return{dtype:i,shape:s,dataId:d.dataId}}runWebGLProgram(t,n,a,r,s=!1,i){let o=this.makeTensorInfo(t.outputShape,a),l=this.texData.get(o.dataId);if(t.packedOutput&&(l.isPacked=!0),t.outPackingScheme===Nc.DENSE){let b=i!=null?i:Ah(t.outputShape);l.texShape=b.map(y=>y*2)}if(t.outTexUsage!=null&&(l.usage=t.outTexUsage),w.sizeFromShape(o.shape)===0)return l.values=w.getTypedArrayFromDType(o.dtype,0),o;let u=[],p=n.map(b=>{if(b.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(b.dataId);if(y.texture==null){if(!t.packedInputs&&w.sizeFromShape(b.shape)<=G().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:b.shape,texData:null,isUniform:!0,uniformValues:y.values};t.packedInputs&&(y.isPacked=!0,y.shape=b.shape)}if(this.uploadToGPU(b.dataId),!!y.isPacked!=!!t.packedInputs)b=y.isPacked?this.unpackTensor(b):this.packTensor(b),u.push(b),y=this.texData.get(b.dataId);else if(y.isPacked&&!Tc(y.shape,b.shape)){let x=b,v=b.shape;b.shape=y.shape,b=this.packedReshape(b,v),u.push(b),y=this.texData.get(b.dataId),x.shape=v}return{shape:b.shape,texData:y,isUniform:!1}});this.uploadToGPU(o.dataId);let d={shape:o.shape,texData:l,isUniform:!1},c=z9(t,p,d),h=this.getAndSaveBinary(c,()=>P9(this.gpgpu,t,p,d)),m=this.activeTimers!=null,f;m&&(f=this.startTimer()),G().get("ENGINE_COMPILE_ONLY")||L9(this.gpgpu,h,p,d,r),u.forEach(b=>this.disposeIntermediateTensorInfo(b)),m&&(f=this.endTimer(f),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(f)}));let g=G().getNumber("WEBGL_FLUSH_THRESHOLD");if(g>0){let b=w.now();b-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=b)}if(!G().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&s===!1){let b=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),b}return o}compileAndRun(t,n,a,r,s=!1){return a=a||n[0].dtype,this.runWebGLProgram(t,n,a,r,s)}getAndSaveBinary(t,n){return t in this.binaryCache||(this.binaryCache[t]=n()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(G().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=O(()=>{if(!G().get("WEBGL_RENDER_FLOAT32_ENABLED")){let t=G().getBool("DEBUG");G().set("DEBUG",!1);let n=this.abs(ve(1e-8)).dataSync()[0];if(G().set("DEBUG",t),n>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?aee:ree}uploadToGPU(t){let n=this.texData.get(t),{shape:a,dtype:r,values:s,texture:i,usage:o,isPacked:l}=n;if(i!=null)return;let u=this.activeTimers!=null,p;u&&(p=w.now());let d=n.texShape;if(d==null&&(d=X_(a,l),n.texShape=d),s!=null){let c=ic(a),h,m=d[1],f=d[0],g=s instanceof Uint8Array||s instanceof Uint8ClampedArray;(l||!g)&&([m,f]=op(d[0],d[1])),l?h=new H9(c,g):h=new aS(c,g);let b=g?[f,m]:d,y=this.makeTensorInfo(b,r),x=this.texData.get(y.dataId);g?x.usage=ca.PIXELS:x.usage=ca.UPLOAD,x.texShape=b,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),m,f,s);let v=[[f,m]],I=this.runWebGLProgram(h,[y],r,v,!0),N=this.texData.get(I.dataId);n.texShape=N.texShape,n.isPacked=N.isPacked,n.usage=N.usage,G().get("ENGINE_COMPILE_ONLY")?this.disposeData(I.dataId):(n.texture=N.texture,n.values=null,this.texData.delete(I.dataId)),this.disposeIntermediateTensorInfo(y),u&&(this.uploadWaitMs+=w.now()-p)}else{let c=this.acquireTexture(d,o,r,l);n.texture=c}}convertAndCacheOnCPU(t,n){let a=this.texData.get(t),{dtype:r}=a;return n!=null&&(a.values=uee(n,r)),a.values}acquireTexture(t,n,a,r){if(this.numBytesInGPU+=this.computeBytes(t,a),!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(t,n,r)}computeBytes(t,n){return t[0]*t[1]*w.bytesPerElement(n)}checkCompileCompletion(){for(let[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){let t=[];if(this.gpgpu.parallelCompilationExtension){for(let[,n]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(n));return Promise.all(t)}else{for(let[,n]of Object.entries(this.binaryCache)){let a=new Promise(r=>{try{this.checkCompletion_(n),r(!0)}catch(s){throw s}});t.push(a)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await Zw(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(J1(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);let{variablesLocations:n,customUniformLocations:a,infLoc:r,nanLoc:s,outShapeLocation:i,outShapeStridesLocation:o,outTexShapeLocation:l}=iA(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=n,t.customUniformLocations=a,t.infLoc=r,t.nanLoc=s,t.outShapeLocation=i,t.outShapeStridesLocation=o,t.outTexShapeLocation=l}}createTensorFromGPUData(t,n,a){t.channels=t.channels||"RGBA";let{texture:r,height:s,width:i,channels:o}=t,l=Ta().backend;if(!l.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");let u=l.writeTexture(r,n,a,s,i,o);return Ta().makeTensorFromDataId(u,n,a,l)}};lk.nextDataId=0;function uee(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let a=0;a<n.length;++a)n[a]=Math.round(e[a]);return n}else throw new Error(`Unknown dtype ${t}`)}var pee="4.16.0";function AA(){G().set("WEBGL_FORCE_F16_TEXTURES",!0)}ad.isBrowser()&&Om("webgl",()=>new lk,2);var cee={forceHalfFloat:AA},uk=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,ki=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=T.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=xn(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Qo=`
|
|
result.r = isNaN.r ? NAN : result.r;
|
|
result.g = isNaN.g ? NAN : result.g;
|
|
result.b = isNaN.b ? NAN : result.b;
|
|
result.a = isNaN.a ? NAN : result.a;
|
|
`,hp=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=T.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=xn(r);let s="";if(a)if(r===0||w.sizeFromShape(this.outputShape)===1)s=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(s=`
|
|
${ht(r)} coords = getOutputCoords();
|
|
`,r===1)this.enableShapeUniforms?s+=`
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`:s+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let i=kn("coords",r);this.enableShapeUniforms?s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[r-2]} + 1) >= outShape[${r} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[r-1]} + 1) >= outShape[${r} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[r-2]} + 1) >= ${this.outputShape[r-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[r-1]} + 1) >= ${this.outputShape[r-1]};
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
${s}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function ta(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var dee={kernelName:eo,backendName:"webgl",kernelFunc:ta};function Fs(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.makeTensorInfo(a.shape,"complex64"),i=n.texData.get(s.dataId),o=ta({inputs:{x:a},backend:n}),l=ta({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var hee={kernelName:wm,backendName:"webgl",kernelFunc:Fs},FA="return (a < 0.) ? b * a : a;",$A=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function mee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp($A,r.shape,i.shape):new ki(FA,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}var fee={kernelName:ro,backendName:"webgl",kernelFunc:mee},DA="return (a < 0.) ? b * a : a;",RA=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function gee(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp(RA,a.shape,r.shape):new ki(DA,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],"float32")}var bee={kernelName:wo,backendName:"webgl",kernelFunc:gee},mp="if (isnan(x)) return x;";function Ze({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let d=o.texData.get(i.dataId),c=n(d.values,l);return o.makeTensorInfo(i.shape,l,c)}let u=G().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,p;return u?p=new ts(i.shape,t):p=new rr(i.shape,e),o.runWebGLProgram(p,[i],l)}}function hn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,p=o;if(a&&l.dtype==="complex64"){let m=p.texData.get(l.dataId),f=p.texData.get(u.dataId),[g,b]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[v,I]=x,N={dataId:v.dataId,dtype:v.dtype,shape:l.shape},C={dataId:I.dataId,dtype:I.dtype,shape:u.shape},_=new ki(e,l.shape,u.shape);return p.runWebGLProgram(_,[N,C],fa(v.dtype,I.dtype))}),y=Fs({inputs:{real:g,imag:b},backend:p});return p.disposeIntermediateTensorInfo(g),p.disposeIntermediateTensorInfo(b),y}let d=s||fa(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||p.shouldExecuteOnCPU([l,u]))&&r!=null){let m=p.texData.get(l.dataId).values,f=p.texData.get(u.dataId).values,g=l.dtype==="string"?T.fromUint8ToStringArray(m):m,b=l.dtype==="string"?T.fromUint8ToStringArray(f):f,[y,x]=r(l.shape,u.shape,g,b,d),v=p.makeTensorInfo(x,d),I=p.texData.get(v.dataId);return I.values=y,v}let c=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return c?h=new hp(t,l.shape,u.shape,n):h=new ki(e,l.shape,u.shape),p.runWebGLProgram(h,[l,u],d)}}function Cc(e,t=!1){if(e==="linear")return t?YQ:HQ;if(e==="relu")return t?JQ:jQ;if(e==="elu")return t?ZQ:qQ;if(e==="relu6")return t?QQ:KQ;if(e==="prelu")return t?RA:DA;if(e==="leakyrelu")return t?$A:FA;if(e==="sigmoid")return t?eee:XQ;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var MA=class{constructor(e,t,n,a=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=xn(this.outputShape.length);let u=a?e[1]:e[2],p=Math.ceil(u/2),d=a?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",h=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:l?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:f=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,g="result = activation(result);");let b=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let y="rc.x",x="rc.x";e[0]<t[0]?y=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`
|
|
${f}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${p}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
int batchA = ${y};
|
|
int batchB = ${x};
|
|
for (int i = 0; i < ${p}; i++) {
|
|
vec4 a = getMatrixA(batchA, ${d});
|
|
vec4 b = getMatrixB(batchB, ${c});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${m[0]});
|
|
result += (${h[1]} * ${m[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${b}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},lS={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},uS=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=T.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));
|
|
}
|
|
`}},pS="return a * b;";function pk(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=T.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),u=new uS(lS.REAL,a.shape,r.shape),p=new uS(lS.IMAG,a.shape,r.shape),d=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Fs({inputs:{real:c,imag:h},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}if(n.shouldExecuteOnCPU([a,r])){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),[u,p]=mQ(a.shape,r.shape,o.values,l.values,s),d=n.makeTensorInfo(p,s),c=n.texData.get(d.dataId);return c.values=u,d}let i;return G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new hp(pS,a.shape,r.shape):i=new ki(pS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var yee={kernelName:bo,backendName:"webgl",kernelFunc:pk};function xee(e,t,n){let a=[vi(e.shape),...wi(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[vi(t),...wi(t)],i=new EA(s,a),o=!0,l=[a],u=n.runWebGLProgram(i,[r],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function ce(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=w.sizeFromShape(r.shape),l=w.inferFromImplicitShape(s,o),u=w.sizeFromShape(l);w.assert(o===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let p=i.texData.get(r.dataId);return p.isPacked&&!Tc(r.shape,l)&&!(p.texture!==null&&Tc(p.shape,l))?xee(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var vee={kernelName:Ru,backendName:"webgl",kernelFunc:ce},cS=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(n/4)*4,o=n%4,l="sumValue += dot(values, ones);";if(t!=null){let p=1/t;l=`sumValue += dot(values * ${w.isInt(p)?p.toPrecision(2):p}, ones);`}let u="";r%n>0&&(u=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${u}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${i}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${l}
|
|
}
|
|
|
|
int inIdx = inOffset + ${i};
|
|
if (${o===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${o===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${o===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${l}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}},wee=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(n/4)*4,p=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 = ${o}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${o}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,c="vec4";t==="all"?(i="1.0",d=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,c="bvec4"):t==="any"&&(i="0.0",d=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,c="bvec4");let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
vec4 minMaxValue = vec4(${i});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${c} values = ${c}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${p===1}) {
|
|
${c} values = ${c}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${p===2}) {
|
|
${c} values = ${c}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${p===3}) {
|
|
${c} values = ${c}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function kee(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=T.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function el(e,t,n,a){let r=kee(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:u}=r[i],p,d;n==="mean"?p=i===0?new cS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new cS({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):p=new wee({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},n),d=s,s=a.runWebGLProgram(p,[s],t),d.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(d)}return s}var Iee=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;let a=ht(this.rank),r=See(t);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function See(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let r=0;r<e.length;r++)a[e[r]]=n[r];return a.join()}var Nee=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let a=ht(this.rank),r=CA("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=r[u];let i=`vec2(${s.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${o}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${r[this.rank-1]};
|
|
if(++${r[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${o}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Wf(e,t,n){let a=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Nee(e.shape,t):new Iee(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function Tee(e,t,n,a){let r=t,s=e.shape.length,i=w.parseAxisParam(r,e.shape),o=i,l=T.getAxesPermutation(o,s),u=l!=null,p=e;u&&(p=Wf(e,l,a),o=T.getInnerMostAxes(o.length,s)),T.assertAxesAreInnerMostDims("sum",o,s);let[d,c]=T.computeOutAndReduceShapes(p.shape,o),h=d;n&&(h=T.expandShapeToKeepDim(d,i));let m=w.sizeFromShape(c),f=w.sizeFromShape(e.shape)/m,g=ce({inputs:{x:p},attrs:{shape:[f,m]},backend:a}),b=Mm(e.dtype),y=el(g,b,"sum",a),x=ce({inputs:{x:y},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(y),u&&a.disposeIntermediateTensorInfo(p),x}function Bf(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return Tee(r,s,i,n)}var Cee={kernelName:Lo,backendName:"webgl",kernelFunc:Bf};function In(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{perm:s}=a,i=n,o=r.shape.length,l=new Array(o);for(let p=0;p<l.length;p++)l[p]=r.shape[s[p]];let u;if(i.shouldExecuteOnCPU([r])){let p=i.texData.get(r.dataId).values,d=ok(p,r.shape,r.dtype,s,l);u=i.makeTensorInfo(l,r.dtype);let c=i.texData.get(u.dataId);c.values=d}else u=Wf(r,s,i);return u}var Eee={kernelName:Tr,backendName:"webgl",kernelFunc:In},OA=1e3;function hm({a:e,b:t,transposeA:n,transposeB:a,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,p=t.shape.length,d=n?e.shape[u-2]:e.shape[u-1],c=a?t.shape[p-1]:t.shape[p-2],h=n?e.shape[u-1]:e.shape[u-2],m=a?t.shape[p-2]:t.shape[p-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(f),y=w.sizeFromShape(g),x=Ju.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,m]);w.assert(d===c,()=>`Error in matMul: inner shapes (${d}) and (${c}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`);let v=n?[b,d,h]:[b,h,d],I=a?[y,m,c]:[y,c,m],N=ce({inputs:{x:e},backend:r,attrs:{shape:v}}),C=ce({inputs:{x:t},backend:r,attrs:{shape:I}}),_=[N,C],F=Math.max(b,y),D=n?N.shape[1]:N.shape[2],$=s!=null,S=i!=null,M=l==="leakyrelu",B=l!=null?Cc(l,!0):null,U=$||S||M||B!=null,H;if((h===1||m===1)&&D>OA&&U===!1){let K=N,Z=C;n&&(K=In({inputs:{x:N},backend:r,attrs:{perm:[0,2,1]}}),_.push(K)),a&&(Z=In({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),_.push(Z));let J=m!==1,ee=m===1,ae=K;J&&(ae=ce({inputs:{x:K},backend:r,attrs:{shape:[F,D,1]}}),_.push(ae));let te=m===1?2:1,se=Z;ee&&(se=ce({inputs:{x:Z},backend:r,attrs:{shape:[F,1,D]}}),_.push(se));let ie=pk({inputs:{a:ae,b:se},backend:r});H=Bf({inputs:{x:ie},backend:r,attrs:{axis:te,keepDims:!0}}),_.push(ie)}else{let K=fa(e.dtype,t.dtype),Z=new MA(v,I,[F,h,m],n,a,$,B,S,M),J=[N,C];if(s!=null&&J.push(s),S&&J.push(i),M){let ee=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));J.push(ee),_.push(ee)}H=r.runWebGLProgram(Z,J,K)}let j=ce({inputs:{x:H},backend:r,attrs:{shape:x}});_.push(H);for(let K of _)r.disposeIntermediateTensorInfo(K);return j}function _ee(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a;return hm({a:r,b:s,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:d,activation:p})}var Aee={kernelName:si,backendName:"webgl",kernelFunc:_ee},dS="return abs(x);";function Fee(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=n.texData.get(a.dataId),i=NA(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new ts(a.shape,dS):r=new rr(a.shape,dS),n.runWebGLProgram(r,[a],a.dtype)}var $ee={kernelName:Yl,backendName:"webgl",kernelFunc:Fee},Dee=Da+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,Ree=Ze({opSnippet:Dee}),Mee={kernelName:Ni,backendName:"webgl",kernelFunc:Ree},Oee=Da+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,Pee=Ze({opSnippet:Oee}),Lee={kernelName:Ti,backendName:"webgl",kernelFunc:Pee},hS="return a + b;",zee=hn({opSnippet:hS,packedOpSnippet:hS,supportsComplex:!0,cpuKernelImpl:j9}),Wee={kernelName:xs,backendName:"webgl",kernelFunc:zee},Bee=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`float v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
float result = ${a};
|
|
setOutput(result);
|
|
}
|
|
`}},Vee=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`vec4 v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
vec4 result = ${a};
|
|
setOutput(result);
|
|
}
|
|
`}};function Bh(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return ta({inputs:{x:a[0]},backend:n});if(a.length>G().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=Bh({inputs:a.slice(0,o),backend:n}),u=Bh({inputs:a.slice(o),backend:n});return Bh({inputs:[l,u],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>fa(o,l)),s=a.map(o=>o.shape),i=G().getBool("WEBGL_PACK")?new Vee(a[0].shape,s):new Bee(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var Uee={kernelName:Ci,backendName:"webgl",kernelFunc:Bh};function Gee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),d=r;p!=null&&(d=In({inputs:{x:r},backend:n,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,o)),T.assertAxesAreInnerMostDims("all",u,o);let[c,h]=T.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=el(f,f.dtype,"all",n),b;if(i){let y=T.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var Hee={kernelName:Zl,backendName:"webgl",kernelFunc:Gee};function qee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),d=r;p!=null&&(d=In({inputs:{x:r},backend:n,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,o)),T.assertAxesAreInnerMostDims("any",u,o);let[c,h]=T.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=el(f,f.dtype,"any",n),b;if(i){let y=T.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var jee={kernelName:Jl,backendName:"webgl",kernelFunc:qee},Kee=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:a,batchSize:r,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${a};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${a}; i++) {
|
|
int inIdx = ${o};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},Xee=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=ht(o),u=kn("coords",o),p,d;if(s===1){d=o+1;let C=ht(d);p=`
|
|
${C} sourceLocR = ${C}(${u.join()}, 0);
|
|
++${u[o-1]};
|
|
${C} sourceLocG = ${C}(${u.join()}, 0);
|
|
++${u[o-2]};
|
|
${C} sourceLocA = ${C}(${u.join()}, 0);
|
|
--${u[o-1]};
|
|
${C} sourceLocB = ${C}(${u.join()}, 0);
|
|
--${u[o-2]};`}else d=o,p=`
|
|
${l} sourceLocR = coords;
|
|
++${u[o-1]};
|
|
${l} sourceLocG = coords;
|
|
++${u[o-2]};
|
|
${l} sourceLocA = coords;
|
|
--${u[o-1]};
|
|
${l} sourceLocB = coords;
|
|
--${u[o-2]};`;let c=["x","y","z","w","u","v"].slice(0,d),h="."+c[d-1],m=c.map(C=>"int "+C),f=kn("sourceLocR",d-1).concat("inIdx.r"),g=kn("sourceLocG",d-1).concat("inIdx.g"),b=kn("sourceLocB",d-1).concat("inIdx.b"),y=kn("sourceLocA",d-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",v=a?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${y.join()})));`,I=`vec4(
|
|
getAChannel(${f.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,N=a?"":`
|
|
float getBestIndicesAChannel(${m.join()}) {
|
|
return getChannel(getBestIndicesA(${c.join()}),
|
|
vec2(${c.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${m.join()}) {
|
|
return getChannel(getA(${c.join()}),
|
|
vec2(${c.slice(-2).join()}));
|
|
}
|
|
${N}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};
|
|
bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};
|
|
${p}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${I};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${v}
|
|
vec4 candidate = ${I};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function PA(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=T.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new Kee(o,n,a==null),u=[t];a!=null&&u.push(a);let p=e.runWebGLProgram(l,u,"int32");if(p.shape[1]===1)return p;let d=PA(e,t,n,p);return e.disposeIntermediateTensorInfo(p),d}function LA(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=T.computeOptimalWindowSize(s),o=new Xee(r,i,n,a==null),l=a==null?[t]:[t,a],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let p=LA(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}return u}function zA(e,t,n,a){let r=[n];if(T.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!G().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[u,p]=T.computeOutAndReduceShapes(l.shape,r),d=w.sizeFromShape(p),c=ce({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});s.push(c);let h=PA(e,c,a);s.push(h);let m=ce({inputs:{x:h},backend:e,attrs:{shape:u}});return s.forEach(f=>e.disposeIntermediateTensorInfo(f)),m}return LA(e,t,a)}function Yee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=In({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=zA(n,l,i[0],"max");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var Zee={kernelName:Ql,backendName:"webgl",kernelFunc:Yee};function Jee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=In({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=zA(n,l,i[0],"min");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var Qee={kernelName:eu,backendName:"webgl",kernelFunc:Jee},ete=Da+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,tte=Ze({opSnippet:ete}),nte={kernelName:Ei,backendName:"webgl",kernelFunc:tte},ate=Da+"return log(x + sqrt(x * x + 1.0));",rte=Ze({opSnippet:ate}),ste={kernelName:_i,backendName:"webgl",kernelFunc:rte},ite=Da+`
|
|
return atan(x);
|
|
`,ote=Ze({opSnippet:ite}),lte={kernelName:Ai,backendName:"webgl",kernelFunc:ote},ute=uk+`
|
|
return atan(a, b);
|
|
`,pte=`
|
|
vec4 result = atan(a, b);
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
`+Qo+`
|
|
return result;
|
|
`,cte=hn({opSnippet:ute,packedOpSnippet:pte}),dte={kernelName:$i,backendName:"webgl",kernelFunc:cte},hte=Da+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,mte=Ze({opSnippet:hte}),fte={kernelName:Fi,backendName:"webgl",kernelFunc:mte},Ec=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,c=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(m||(b="-1.0 / 1e-20"),n){let C=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${c}, ${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 < ${p};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${u}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${C} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?r?f:g:`wR * ${d} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let y="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / max(count, 1.0)");let v=Math.floor(s/4)*4,I=s%4,N=`
|
|
if (${m}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${y}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${c}, ${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 < ${p};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${v}; wC += 4) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
getValue(batch, xR, xC + 3 * ${u}, d)
|
|
);
|
|
|
|
${N}
|
|
}
|
|
|
|
int xC = xCCorner + ${v};
|
|
if (${I===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${I===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${I===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
}
|
|
}
|
|
setOutput(${x});
|
|
}
|
|
`}},ck=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,p=e.dilationHeight,d=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",x="0.0";if(y||(x="-1.0 / 1e-20"),n){let F=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${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 < ${c};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
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 ${F} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${m} +
|
|
wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let v="max",I=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(I="avgValue / max(count, 1.0)");let N=Math.floor(s/4)*4,C=s%4,_=`
|
|
if (${y}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${v}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${b});
|
|
const float initializationValue = ${x};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${x});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${c};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${N}; 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)
|
|
);
|
|
|
|
${_}
|
|
}
|
|
|
|
int xC = xCCorner + ${N};
|
|
if (${C===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${_}
|
|
} else if (${C===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${_}
|
|
} else if (${C===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
|
|
);
|
|
|
|
${_}
|
|
}
|
|
}
|
|
}
|
|
setOutput(${I});
|
|
}
|
|
`}};function gte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;lp(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return ta({inputs:{x:r},backend:n});let d=new Ec(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var bte={kernelName:Di,backendName:"webgl",kernelFunc:gte};function yte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=[1,1,1],d=T.computePool3DInfo(r.shape,s,i,p,o,l,u),c=new ck(d,"avg",!1);return n.runWebGLProgram(c,[r],"float32")}var xte={kernelName:tu,backendName:"webgl",kernelFunc:yte},vte=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,p=l-1-e.padInfo.left,d=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${u}, ${p});
|
|
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 < ${o};
|
|
wR += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC+= ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},wte=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,c=e.effectiveFilterWidth,h=p-1-e.padInfo.front,m=d-1-e.padInfo.top,f=c-1-e.padInfo.left,g=1/(t*n*a);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${m}, ${f});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${o}) {
|
|
float dyD = float(dyDCorner + wD) / ${r}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${c};
|
|
wC += ${u}) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function kte(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=T.computePool3DInfo(i.shape,o,l,d,u,p),h=new wte(c);return n.runWebGLProgram(h,[r],i.dtype)}var Ite={kernelName:Rc,backendName:"webgl",kernelFunc:kte};function Ste(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;lp([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,p=T.computePool2DInfo(i.shape,o,l,1,u),d=new vte(p);return n.runWebGLProgram(d,[r],i.dtype)}var Nte={kernelName:Dc,backendName:"webgl",kernelFunc:Ste};function Tte(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return hm({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var Cte={kernelName:Ri,backendName:"webgl",kernelFunc:Tte},Ete=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(T.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(T.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${i};
|
|
float scale = ${o};
|
|
float inv = scale * inversesqrt(variance + float(${s}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},_te=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(T.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(T.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${i};
|
|
vec4 scale = ${o};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${s}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},Ate=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;w.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let u=[a,r,s],p=null;i!=null&&(p=i.shape,u.push(i));let d=null;o!=null&&(d=o.shape,u.push(o));let c=G().getBool("WEBGL_PACK_NORMALIZATION")?new _te(a.shape,r.shape,s.shape,p,d,l):new Ete(a.shape,r.shape,s.shape,p,d,l);return t.runWebGLProgram(c,u,u[0].dtype)},Fte={kernelName:Ji,backendName:"webgl",kernelFunc:Ate},$te=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=Dte(this.rank),a,r=e.map((s,i)=>`sourceLoc.${hv[i]} = start[${i}] + coords.${hv[i]};`);a=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${r.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${a}
|
|
setOutput(getSource(${n}));
|
|
}
|
|
`}},hv=["x","y","z","w","u","v"];function Dte(e){if(e===1)return"sourceLoc";if(e<=6)return hv.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var Rte=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=kn("coords",this.rank),a=kn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${a.slice(-2).join()})`,s=`getChannel(getSource(${a.join()}), ${r})`,i=`
|
|
result.x = ${s};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${a[this.rank-1]};
|
|
result.y = ${s};
|
|
--${a[this.rank-1]};
|
|
}
|
|
`,o=this.rank===1?"":`
|
|
--${n[this.rank-1]};
|
|
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${a[this.rank-2]};
|
|
result.z = ${s};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${a[this.rank-1]};
|
|
result.w = ${s};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((u,p)=>`start[${p}]`).join()});`:e.map((u,p)=>`${a[p]} = ${n[p]} + start[${p}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${o}
|
|
setOutput(result);
|
|
}
|
|
`}};function Mte(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Kt.computeFlatOffset(t,w.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function fp(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=Kt.parseSliceParams(r,s,i);if(Kt.assertParamsValid(r,o,l),w.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.texData.get(r.dataId),c=NQ(d.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,c)}let{isPacked:u}=n.texData.get(r.dataId),p=Kt.isSliceContinous(r.shape,o,l);if(u||!p){let d=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Rte(l):new $te(l),c=[o];return n.runWebGLProgram(d,[r],r.dtype,c)}return n.uploadToGPU(r.dataId),Mte(r,o,l,n)}var Ote={kernelName:Bu,backendName:"webgl",kernelFunc:fp},Pte=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;w.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,x)=>y*x),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),d=T.getSliceBeginCoords(i,s.length),c=T.getSliceSize(p,i,s.length),h=[],m=ce({inputs:{x:r},backend:n,attrs:{shape:l}}),f=In({inputs:{x:m},backend:n,attrs:{perm:u}}),g=ce({inputs:{x:f},backend:n,attrs:{shape:p}}),b=fp({inputs:{x:g},backend:n,attrs:{begin:d,size:c}});return h.push(m),h.push(f),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},Lte={kernelName:nu,backendName:"webgl",kernelFunc:Pte};function zte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.readSync(r.dataId),l=n.readSync(s.dataId),u=SA(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var Wte={kernelName:au,backendName:"webgl",kernelFunc:zte},Bte=`
|
|
int r = int(a.r) & int(b.r);
|
|
int g = int(a.g) & int(b.g);
|
|
int rb = int(a.b) & int(b.b);
|
|
int ra = int(a.a) & int(b.a);
|
|
return vec4(r, g, rb, ra);
|
|
`,Vte=`
|
|
return float(int(a.r) & int(b.r));
|
|
`;function Ute(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=G().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([a,r])||i===1){let l=n.texData.get(a.dataId).values,u=n.texData.get(r.dataId).values,[p,d]=X9(a.shape,r.shape,l,u,a.dtype),c=n.makeTensorInfo(d,a.dtype),h=n.texData.get(c.dataId);return h.values=p,c}let o;return s?o=new hp(Bte,a.shape,r.shape,!1):o=new ki(Vte,a.shape,r.shape),n.runWebGLProgram(o,[a,r],a.dtype)}var Gte={kernelName:ru,backendName:"webgl",kernelFunc:Ute};function Hte(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.readSync(a.dataId),i=n.readSync(r.dataId),o=T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var qte={kernelName:Mc,backendName:"webgl",kernelFunc:Hte},jte="return float(a != b);",WA=hn({opSnippet:jte,cpuKernelImpl:gQ,dtype:"bool"}),Kte={kernelName:Eu,backendName:"webgl",kernelFunc:WA};function Fd(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return ta({inputs:{x:r.complexTensorInfos.real},backend:n})}var Xte={kernelName:Dm,backendName:"webgl",kernelFunc:Fd},Yte="return float(int(x));";function Zte(e,t){let n=new rr(e.shape,Yte),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function mv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return ta({inputs:{x:r},backend:n});let i=It(r.shape),o=mv({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Fs({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Fd({inputs:{input:r},backend:n}),o=mv({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(r.dtype,s)){let i=ta({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(n.shouldExecuteOnCPU([r])){let i=n.texData.get(r.dataId).values,[o,l,u]=Y9(i,r.shape,r.dtype,s);return n.makeTensorInfo(o,l,u)}if(s==="int32")return Zte(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=WA({inputs:{a:r,b:i},backend:n});return n.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var Jte={kernelName:Mi,backendName:"webgl",kernelFunc:mv},mS="return ceil(x);",Qte=Ze({opSnippet:mS,packedOpSnippet:mS,cpuKernelImpl:Z9}),ene={kernelName:Oi,backendName:"webgl",kernelFunc:Qte},tne=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));
|
|
}
|
|
`}},nne=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 ane(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;G().getBool("WEBGL_PACK_CLIP")?o=new nne(r.shape):o=new tne(r.shape);let l=[[s],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}var rne={kernelName:vs,backendName:"webgl",kernelFunc:ane},sne=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 fS(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function ine(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new sne(a.shape),i=[fS(a,r.complexTensorInfos.real),fS(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var one={kernelName:Oc,backendName:"webgl",kernelFunc:ine},lne=class{constructor(e){this.outputShape=[],this.outputShape=T.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];n.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let a=t.length,r=t[t.length-1];n.push(`else setOutput(getT${a}(yR, yC-${r}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},une=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=T.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=ht(a),s=kn("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((m,f)=>`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],u=i.slice(-2),p=i.join(),d=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${p}), vec2(${u.join()}));
|
|
}`;for(let m=1;m<o.length;m++){let f=o[m-1];d+=`
|
|
if (${l} < ${o[m]} && ${l} >= ${o[m-1]}) {
|
|
return getChannel(
|
|
getT${m}(${$h(i,l,f)}),
|
|
vec2(${$h(u,l,f)}));
|
|
}`}let c=o.length,h=o[o.length-1];d+=`
|
|
return getChannel(
|
|
getT${c}(${$h(i,l,h)}),
|
|
vec2(${$h(u,l,h)}));`,this.userCode=`
|
|
float getValue(${i.map(m=>"int "+m)}) {
|
|
${d}
|
|
}
|
|
|
|
void main() {
|
|
${r} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
|
|
|
|
${s[a-1]} = ${s[a-1]} + 1;
|
|
if (${s[a-1]} < ${n[a-1]}) {
|
|
result.g = getValue(${s});
|
|
}
|
|
|
|
${s[a-2]} = ${s[a-2]} + 1;
|
|
if (${s[a-2]} < ${n[a-2]}) {
|
|
result.a = getValue(${s});
|
|
}
|
|
|
|
${s[a-1]} = ${s[a-1]} - 1;
|
|
if (${s[a-2]} < ${n[a-2]} &&
|
|
${s[a-1]} < ${n[a-1]}) {
|
|
result.b = getValue(${s});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function $h(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function Vf(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return ta({inputs:{x:r.complexTensorInfos.imag},backend:n})}var pne={kernelName:_m,backendName:"webgl",kernelFunc:Vf};function oc(e,t,n){let a=e[0].dtype;if(a==="complex64"){let h=e.map(y=>Fd({inputs:{input:y},backend:n})),m=e.map(y=>Vf({inputs:{input:y},backend:n})),f=oc(h,t,n),g=oc(m,t,n),b=Fs({inputs:{real:f,imag:g},backend:n});return h.forEach(y=>n.disposeIntermediateTensorInfo(y)),m.forEach(y=>n.disposeIntermediateTensorInfo(y)),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),b}let r=n.shouldExecuteOnCPU(e);if(a==="string"&&(r=!0),r){let h=e.map(v=>{let I=[-1,w.sizeFromShape(v.shape.slice(t))];return ce({inputs:{x:v},backend:n,attrs:{shape:I}})}),m=h.map(v=>({vals:n.readSync(v.dataId),shape:v.shape})),f=T.computeOutShape(h.map(v=>v.shape),1),g=h[0].shape[0]===1,b=J9(m,f,a,g),y=T.computeOutShape(e.map(v=>v.shape),t),x=n.makeTensorInfo(y,a,b);return h.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}let s=e.filter(h=>w.sizeFromShape(h.shape)>0),i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let h=i?new rr(e[0].shape,Yr):new ts(e[0].shape,Yr);return n.runWebGLProgram(h,e,a)}let o=G().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){let h=[];for(let f=0;f<s.length;f+=o){let g=s.slice(f,f+o);h.push(oc(g,t,n))}let m=oc(h,t,n);for(let f of h)n.disposeIntermediateTensorInfo(f);return m}if(i){let h=new une(s.map(m=>m.shape),t);return n.runWebGLProgram(h,s,a)}let{tensors2D:l,outShape:u}=cne(s,t,n),p=new lne(l.map(h=>h.shape)),d=n.runWebGLProgram(p,l,a);l.forEach(h=>n.disposeIntermediateTensorInfo(h));let c=ce({inputs:{x:d},attrs:{shape:u},backend:n});return n.disposeIntermediateTensorInfo(d),c}function cne(e,t,n){let a=T.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ce({inputs:{x:r},attrs:{shape:[-1,w.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function BA(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=t.map(u=>u.shape);T.assertParamsConsistent(i,s);let o=T.computeOutShape(t.map(u=>u.shape),s);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(u=>w.sizeFromShape(u.shape)>0);return l.length===1?ta({inputs:{x:l[0]},backend:n}):oc(l,s,n)}var dne={kernelName:su,backendName:"webgl",kernelFunc:BA},VA=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,b=f?2:3,y=f?3:1,x="",v="";n&&(a?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,v="result = activation(result);");let I=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${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 * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${c}; wC++) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${m===1}) {
|
|
|
|
if (${f}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${h}) *
|
|
getW(wR, wC, ${h}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${h}, xR, xC) *
|
|
getW(wR, wC, ${h}, d2);
|
|
}
|
|
|
|
} else if (${m===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${m===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1),
|
|
getX(batch, xR, xC, ${h} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC),
|
|
getX(batch, ${h} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${I}
|
|
${v}
|
|
setOutput(result);
|
|
}
|
|
`}},hne=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,a=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.filterDepth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${r}, ${s}, ${i});
|
|
const ivec3 pads = ivec3(${t}, ${n}, ${a});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${p}; wF++) {
|
|
int xF = xFCorner + wF * ${o};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${c}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${m===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${m===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${m===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1),
|
|
getX(batch, xF, xR, xC, ${h} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2),
|
|
getW(wF, wR, wC, ${h} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},UA=class{constructor(e,t=!1,n=null,a=!1,r=!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=xn(this.outputShape.length);let s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,p=u,d=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let f=0;f<u;f++)d+=`
|
|
vec4 xTexelC${f*2};
|
|
int xTexelC${f*2}Ready;
|
|
vec4 xTexelC${f*2+1};
|
|
int xTexelC${f*2+1}Ready;
|
|
vec4 xC${f};`;d+=`
|
|
for (int r = 0; r < ${l}; r++) {
|
|
for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
|
|
`;for(let f=0;f<u;f++)d+=`
|
|
xTexelC${f*2} = vec4(0.0);
|
|
xTexelC${f*2}Ready = 0;
|
|
xTexelC${f*2+1} = vec4(0.0);
|
|
xTexelC${f*2+1}Ready = 0;
|
|
xC${f} = vec4(0.0);`;d+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let f=0;f<(p+1)/2;f++){let g=f*2;if(d+=`
|
|
xC = xCCorner + ${g*o};
|
|
`,i===1){if(g<u&&(s%2===1?(d+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
|
|
xTexelC${g} = 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${g}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g}Ready = 1;
|
|
}
|
|
`,o===1&&g>0?d+=`
|
|
xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.xy);
|
|
`:d+=`
|
|
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${g} = vec4(previous.zw, xTexelC${g}.xy);
|
|
} else {
|
|
xC${g} = vec4(0.0, 0.0, xTexelC${g}.xy);
|
|
}
|
|
`):d+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
|
|
xTexelC${g} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${g}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g}Ready = 1;
|
|
}
|
|
|
|
xC${g} = xTexelC${g};
|
|
`,g+1<u)){let b=s%2===0?w.nearestLargerEven(o):o;o%2===0&&s%2===1||o%2!==0&&s%2!==1?(d+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${b};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
|
|
xTexelC${g+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${g+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g+1}Ready = 1;
|
|
}
|
|
`,o>1?d+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
xC${g+1} = vec4(previous.zw, xTexelC${g+1}.xy);
|
|
} else {
|
|
xC${g+1} = vec4(0.0, 0.0, xTexelC${g+1}.xy);
|
|
}
|
|
`:d+=`
|
|
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy);
|
|
`):b===1?d+=`
|
|
xC${g+1} = xTexelC${g};
|
|
`:d+=`
|
|
xCOffset = xC + ${b};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
|
|
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${g+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g+1}Ready = 1;
|
|
}
|
|
|
|
xC${g+1} = xTexelC${g+1};
|
|
`}}else g<u&&(s%2===1?(d+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
|
|
xTexelC${g} = 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${g}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${g+1}Ready == 0) {
|
|
xTexelC${g+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${g+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g+1}Ready = 1;
|
|
}
|
|
|
|
xC${g} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
|
|
`,g+1<u&&(d+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy);
|
|
`)):(d+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
|
|
xTexelC${g} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${g}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
|
|
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${g+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${g+1}Ready = 1;
|
|
}
|
|
|
|
xC${g} = vec4(
|
|
xTexelC${g}.xy, xTexelC${g+1}.xy);
|
|
`,g+1<u&&(d+=`
|
|
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
|
|
`)));g<u&&(d+=`
|
|
wTexel = getW(r, ${g}, d1, d2);
|
|
dotProd += xC${g}.xxzz * vec4(wTexel.xy, wTexel.xy);
|
|
if(d1 + 1 < ${e.inChannels}) {
|
|
dotProd += xC${g}.yyww * vec4(wTexel.zw, wTexel.zw);
|
|
}
|
|
`,g+1<u&&(d+=`
|
|
wTexel = getW(r, ${g+1}, d1, d2);
|
|
dotProd += xC${g+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
|
|
if(d1 + 1 < ${e.inChannels}) {
|
|
dotProd += xC${g+1}.yyww * vec4(wTexel.zw, wTexel.zw);
|
|
}
|
|
`))}d+=`
|
|
}
|
|
`,d+=`
|
|
}
|
|
`,d+=`
|
|
}
|
|
`;let c="",h="";n&&(a?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:c=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,h="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&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 xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${d}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},mne=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{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=xn(this.outputShape.length);let{dataFormat:n}=t,a=Cn(),r=n==="channelsLast",s=r?1:2,i=r?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,l="";for(let u=0;u<=1;u++)for(let p=0;p<=1;p++)l+=`
|
|
blockIndex = rc.z + ${p};
|
|
pos = rc.y + ${u};
|
|
|
|
${o}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${s}] && 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[${i}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${r}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${u*2+p}] = getChannel(
|
|
getA(rc.x, d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${u*2+p}] = getChannel(
|
|
getA(rc.x, ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${l}
|
|
|
|
${a.output} = result;
|
|
}
|
|
`}};function mm(e,t){let n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&n===1&&e[0]>1?[e[0],1]:null}function GA({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=a.texData.get(e.dataId),p=n.inChannels,d=l[0]*l[1]*l[2],c=n.outChannels,h=n.dataFormat==="channelsLast",m=!1,f=!1,g,b=[];if(s!=null){let y=mm(s.shape,h);y!=null&&(s=ce({inputs:{x:s},backend:a,attrs:{shape:y}}),b.push(s))}if(r!=null){let y=mm(r.shape,h);y!=null&&(r=ce({inputs:{x:r},backend:a,attrs:{shape:y}}),b.push(r))}if(!((d===1||c===1)&&p>OA)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&w.arraysEqual(u.shape.slice(-3),l.slice(-3))){let y=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,y,n.inChannels],dtype:e.dtype},v=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(Tc(u.shape,x.shape),()=>`packed reshape ${u.shape} to ${x.shape} isn't free`);let I=ce({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(I);let N=hm({a:x,b:I,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),C=a.texData.get(N.dataId);w.assert(C.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=v,C.shape=n.outShape,g=ta({inputs:{x:N},backend:a}),g.shape=n.outShape,b.push(N)}else{let y=n.outHeight*n.outWidth,x=ce({inputs:{x:e},backend:a,attrs:{shape:h?[n.batchSize,y,n.inChannels]:[n.batchSize,n.inChannels,y]}}),v=ce({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),I=hm({a:h?x:v,b:h?v:x,transposeA:!h,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ce({inputs:{x:I},backend:a,attrs:{shape:n.outShape}}),b.push(x),b.push(v),b.push(I)}for(let y of b)a.disposeIntermediateTensorInfo(y);return g}function HA({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:p,outWidth:d,outHeight:c,dataFormat:h}=n,m=h==="channelsLast",f=l*u*p,g=c*d,b=[n.batchSize,f,g],y=!0,x=!1,v=[];if(s!=null){let K=mm(s.shape,m);K!=null&&(s=ce({inputs:{x:s},backend:a,attrs:{shape:K}}),v.push(s))}if(r!=null){let K=mm(r.shape,m);K!=null&&(r=ce({inputs:{x:r},backend:a,attrs:{shape:K}}),v.push(r))}let I=ce({inputs:{x:t},backend:a,attrs:{shape:[1,f,w.sizeFromShape(t.shape)/f]}});v.push(I);let N=new mne(b,n),C=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],_=a.runWebGLProgram(N,[e],"float32",C),F=ce({inputs:{x:_},backend:a,attrs:{shape:b}});v.push(_),v.push(F);let D=r!=null,$=s!=null,S=o==="leakyrelu",M=o?Cc(o,!0):null,B=new MA(m?F.shape:I.shape,m?I.shape:F.shape,m?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],y,x,D,M,$,S),U=m?[F,I]:[I,F];if(r&&U.push(r),$&&U.push(s),S){let K=a.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));U.push(K),v.push(K)}let H=a.runWebGLProgram(B,U,"float32"),j=ce({inputs:{x:H},backend:a,attrs:{shape:n.outShape}});v.push(H);for(let K of v)a.disposeIntermediateTensorInfo(K);return j}function fne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a,d=T.convertConv2DDataFormat(l),c=T.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,d),h;if(c.filterHeight===1&&c.filterWidth===1&&c.dilationHeight===1&&c.dilationWidth===1&&c.strideHeight===1&&c.strideWidth===1&&(c.padInfo.type==="SAME"||c.padInfo.type==="VALID"))h=GA({x:r,filter:s,convInfo:c,backend:n});else if(c.strideWidth<=2&&d==="channelsLast"&&G().getBool("WEBGL_EXP_CONV")){let f=new UA(c),g=[[c.padInfo.top,c.padInfo.left],[c.strideHeight,c.strideWidth],[c.dilationHeight,c.dilationWidth],[c.inHeight,c.inWidth]];h=n.runWebGLProgram(f,[r,s],"float32",g)}else if(G().getBool("WEBGL_CONV_IM2COL"))h=HA({x:r,filter:s,convInfo:c,backend:n});else{let f=new VA(c);h=n.runWebGLProgram(f,[r,s],"float32")}let m=ce({inputs:{x:h},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(h),m}var gne={kernelName:Pi,backendName:"webgl",kernelFunc:fne},bne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${r};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
${s?`float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);`}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},yne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=s?1:2,u=s?2:3,p=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${p}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${s}) {
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
} else {
|
|
float xValue = getDy(batch, d2, idyR, idyC);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},xne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yF = 0; yF < ${e.outDepth}; yF++) {
|
|
int xF = wF + yF * ${t} - ${r};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${n} - ${s};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${a} - ${i};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},vne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=a-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${o}, ${l}, ${u});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${r}.0;
|
|
|
|
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = ${t} - 1 - wF;
|
|
|
|
for (int wR = 0; wR < ${n}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${n} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${a}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${a} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function wne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=a,d=T.convertConv2DDataFormat(l),c=T.computeConv2DInfo(r.shape,p,i,1,o,u,!1,d),h=new bne(c);return n.runWebGLProgram(h,[r,s],"float32")}var kne={kernelName:km,backendName:"webgl",kernelFunc:wne},Ine=class{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=xn(this.outputShape.length);let t=e.filterHeight,n=e.filterWidth,a=t-1-e.padInfo.top,r=n-1-e.padInfo.left;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${r});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
|
|
ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
vec4 result = vec4(0.);
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / strides[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++) {
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
float dyC = float(dyCCorner + wC) / strides[1];
|
|
bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
|
|
&& (fract(dyC) == 0.0);
|
|
int idyC = int(dyC);
|
|
|
|
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
|
|
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
|
|
&& (fract(dyC2) == 0.0);
|
|
int idyC2 = int(dyC2);
|
|
|
|
if (idyCVal && idyCVal2) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
|
|
dySample : getDy(batch, idyR, idyC2, d2);
|
|
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
|
|
dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample2.xy : dySample2.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal2) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC2, d2);
|
|
vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Sne(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=a,d=T.convertConv2DDataFormat(u),c=T.computeConv2DInfo(i,s.shape,o,1,l,p,!1,d);if(G().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&d==="channelsLast"){let h=[[c.strideHeight,c.strideWidth]],m=new Ine(c);return n.runWebGLProgram(m,[r,s],"float32",h)}else{let h=new yne(c);return n.runWebGLProgram(h,[r,s],"float32")}}var Nne={kernelName:Li,backendName:"webgl",kernelFunc:Sne};function Tne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=T.computeConv3DInfo(r.shape,s.shape,i,l,o),p=new hne(u);return n.runWebGLProgram(p,[r,s],"float32")}var Cne={kernelName:zi,backendName:"webgl",kernelFunc:Tne};function Ene(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,u=T.computeConv3DInfo(r.shape,l,i,1,o),p=new xne(u);return n.runWebGLProgram(p,[r,s],"float32")}var _ne={kernelName:iu,backendName:"webgl",kernelFunc:Ene};function Ane(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,u=T.computeConv3DInfo(l,s.shape,o,1,i),p=new vne(u);return n.runWebGLProgram(p,[r,s],"float32")}var Fne={kernelName:ou,backendName:"webgl",kernelFunc:Ane},$ne=mp+`
|
|
return cos(x);
|
|
`,Dne=`
|
|
vec4 result = cos(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${Qo}
|
|
return result;
|
|
`,Rne=Ze({opSnippet:$ne,packedOpSnippet:Dne}),Mne={kernelName:Wi,backendName:"webgl",kernelFunc:Rne},One=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Pne=Ze({opSnippet:One}),Lne={kernelName:Bi,backendName:"webgl",kernelFunc:Pne},zne=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[p,d]=n;this.outputShape=[u,p,d,l];let c=a==="bilinear"?1:0,[h,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,b]=p>1?[`${(i-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,x,v]=d>1?[`${(o-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
|
|
const float height_ratio = float(${f});
|
|
const float width_ratio = float(${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 >= ${s}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${x};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
float in_x = ${v};
|
|
if( in_x < 0.0 || in_x > ${m} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${c} == 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);
|
|
}
|
|
}
|
|
`}},Wne=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,p=new zne(r.shape,s.shape,o,l,u);return n.runWebGLProgram(p,[r,s,i],"float32")},Bne={kernelName:uu,backendName:"webgl",kernelFunc:Wne},_c;(function(e){e.Prod="*",e.Sum="+"})(_c||(_c={}));var gS=class{constructor(e,t,n,a){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let r=this.outputShape.length,s=this.op===_c.Prod?"1.0":"0.0",i=n?s:`getX(${bS(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1],l="",u="";n?(l=a?`end != ${o-1}`:"end != 0",u=a?"end + 1":"end - 1"):(l=a?`end + pow2 < ${o}`:"end >= pow2",u=a?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${ht(r)} coords = getOutputCoords();
|
|
int end = ${yS(r,"coords",this.op)};
|
|
float val = ${i};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${l}) {
|
|
int idx = ${u};
|
|
${yS(r,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${bS(r,"coords",this.op)});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function bS(e,t,n){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 new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function yS(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function qA(e,t,n,a,r,s){let i=t.shape.length,o=T.getAxesPermutation([a],i),l=t;o!=null&&(l=In({inputs:{x:t},backend:n,attrs:{perm:o}}));let u=T.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${a}`);let p=l.shape[u],d=ta({inputs:{x:l},backend:n});for(let c=0;c<=Math.ceil(Math.log2(p))-1;c++){let h=new gS(e,l.shape,!1,s),m=[[c]],f=d;d=n.runWebGLProgram(h,[d],d.dtype,m),n.disposeIntermediateTensorInfo(f)}if(r){let c=new gS(e,l.shape,r,s),h=d;d=n.runWebGLProgram(c,[d],d.dtype),n.disposeIntermediateTensorInfo(h)}if(o!=null){let c=T.getUndoAxesPermutation(o),h=In({inputs:{x:d},backend:n,attrs:{perm:c}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(l),h}return d}function Vne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return qA(_c.Prod,r,n,s,i,o)}var Une={kernelName:lu,backendName:"webgl",kernelFunc:Vne};function Gne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return qA(_c.Sum,r,n,s,i,o)}var Hne={kernelName:Vi,backendName:"webgl",kernelFunc:Gne};function qne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=SA(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),p=K9(l,u,i,o);return n.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var jne={kernelName:Pc,backendName:"webgl",kernelFunc:qne},Kne=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 Xne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],d=l*s,c=u*s,h=p/(s*s),m=i==="NHWC"?[o,d,c,h]:[o,h,d,c],f=new Kne(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var Yne={kernelName:pu,backendName:"webgl",kernelFunc:Xne},jA=class{constructor(e,t=!1,n=null,a=!1,r=!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=xn(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";n&&(a?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,u="result = activation(result);");let p=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${l}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${o};
|
|
int q = d2 - d1 * ${o};
|
|
|
|
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 < ${s}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${i}; 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;
|
|
${p}
|
|
${u}
|
|
setOutput(result);
|
|
}
|
|
`}},KA=class{constructor(e,t=!1,n=null,a=!1,r=!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=xn(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,p=e.filterWidth,d=p,c=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<p;g++)c+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;c+=`
|
|
for (int r = 0; r < ${u}; r++) {
|
|
`;for(let g=0;g<p;g++)c+=`
|
|
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);`;c+=`
|
|
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(c+=`
|
|
xC = xCCorner + ${b*l};
|
|
`,o===1){if(b<p&&(i%2===1?(c+=`
|
|
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;
|
|
}
|
|
`,l===1&&b>0?c+=`
|
|
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
|
|
`:c+=`
|
|
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);
|
|
}
|
|
`):c+=`
|
|
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<p)){let y=i%2===0?w.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(c+=`
|
|
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;
|
|
}
|
|
`,l>1?c+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy);
|
|
} else {
|
|
xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy);
|
|
}
|
|
`:c+=`
|
|
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
|
|
`):y===1?c+=`
|
|
xC${b+1} = xTexelC${b};
|
|
`:c+=`
|
|
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<p&&(i%2===1?(c+=`
|
|
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<p&&(c+=`
|
|
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);
|
|
`)):(c+=`
|
|
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<p&&(c+=`
|
|
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
|
|
`)));b<p&&(c+=`
|
|
wTexel = getW(r, ${b}, d1, q);
|
|
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
|
|
`,b+1<p&&(c+=`
|
|
wTexel = getW(r, ${b+1}, d1, q);
|
|
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}c+=`
|
|
}
|
|
`,c+=`
|
|
}
|
|
`;let h="",m="";n&&(a?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:h=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,m="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&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 / ${s};
|
|
int q = d2 - d1 * ${s};
|
|
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);
|
|
|
|
${c}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${f}
|
|
${m}
|
|
setOutput(result);
|
|
}
|
|
`}};function Zne(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=a,p=l;p==null&&(p=[1,1]),w.assert(T.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let d=T.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),c;G().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?c=new KA(d):c=new jA(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(c,[r,s],"float32",h)}var Jne={kernelName:Ui,backendName:"webgl",kernelFunc:Zne},Qne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * ${s} + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${r};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},eae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${o}; dm++) {
|
|
int d2 = d1 * ${o} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function tae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=a,d=T.computeConv2DInfo(r.shape,p,i,o,l,u,!0),c=new Qne(d);return n.runWebGLProgram(c,[r,s],"float32")}var nae={kernelName:Im,backendName:"webgl",kernelFunc:tae};function aae(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=a,d=T.computeConv2DInfo(p,s.shape,i,o,l,u,!0),c=new eae(d);return n.runWebGLProgram(c,[r,s],"float32")}var rae={kernelName:Sm,backendName:"webgl",kernelFunc:aae},sae=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 iae(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=w.sizeFromShape(a.shape),i=ce({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new sae(s),l=n.runWebGLProgram(o,[i],i.dtype),u=ce({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var oae={kernelName:Lc,backendName:"webgl",kernelFunc:iae},lae=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:a,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:p,left:d}=a;this.userCode=`
|
|
const ivec2 strides = ivec2(${r}, ${s});
|
|
const ivec2 pads = ivec2(${p}, ${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 < ${i}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${o}; w++) {
|
|
int wIn = wBeg + w * ${u};
|
|
|
|
if (wIn >= 0 && wIn < ${n}) {
|
|
float xVal = getX(batch, hIn, wIn, d1);
|
|
float wVal = getW(h, w, d1);
|
|
|
|
float val = xVal + wVal;
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = curVal;
|
|
setOutput(result);
|
|
}
|
|
`}};function uae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=T.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p,d=new lae(u);p=n.runWebGLProgram(d,[r,s],"float32");let c=ce({inputs:{x:p},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(p),c}var pae={kernelName:Gi,backendName:"webgl",kernelFunc:uae};function cae(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=T.decodeEinsumEquation(r,s.length);T.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=T.getEinsumComputePath(o,l),d=p.length,c=null,h=i.length,m=[];for(let f=0;f<d;++f){for(let g of p[f]){let{permutationIndices:b,expandDims:y}=T.getEinsumPermutation(h,l[g]),x;T.isIdentityPermutation(b)?x=s[g]:(x=In({inputs:{x:s[g]},backend:n,attrs:{perm:b}}),m.push(x));let v=x.shape.slice();for(let I=0;I<y.length;++I)v.splice(y[I],0,1);w.arraysEqual(x.shape,v)||(x=ce({inputs:{x},backend:n,attrs:{shape:v}}),m.push(x)),c===null?c=x:(c=pk({inputs:{a:x,b:c},backend:n}),m.push(c))}f<d-1&&(u[f]>=0&&(c=Bf({inputs:{x:c},backend:n,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(c)),h--)}for(let f of m)f!==c&&n.disposeIntermediateTensorInfo(f);return c}var dae={kernelName:Tm,backendName:"webgl",kernelFunc:cae},hae="return (x >= 0.0) ? x : (exp(x) - 1.0);",mae=`
|
|
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;
|
|
`,fae=Ze({opSnippet:hae,packedOpSnippet:mae}),gae={kernelName:qi,backendName:"webgl",kernelFunc:fae},bae="return (b >= 0.0) ? a : a * (b + 1.0);",yae=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,xae=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp(yae,a.shape,r.shape):new ki(bae,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},vae={kernelName:cu,backendName:"webgl",kernelFunc:xae},wae=`
|
|
return vec4(equal(a, b));
|
|
`,kae="return float(a == b);",Iae=hn({opSnippet:kae,packedOpSnippet:wae,dtype:"bool",cpuKernelImpl:Q9}),Sae={kernelName:du,backendName:"webgl",kernelFunc:Iae},Nae=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${T.ERF_P};
|
|
float a1 = ${T.ERF_A1};
|
|
float a2 = ${T.ERF_A2};
|
|
float a3 = ${T.ERF_A3};
|
|
float a4 = ${T.ERF_A4};
|
|
float a5 = ${T.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));
|
|
`,Tae=Ze({opSnippet:Nae}),Cae={kernelName:ji,backendName:"webgl",kernelFunc:Tae},Eae=mp+`
|
|
return exp(x);
|
|
`,_ae=`
|
|
vec4 result = exp(x);
|
|
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;
|
|
`,XA=Ze({opSnippet:Eae,packedOpSnippet:_ae,cpuKernelImpl:eQ,dtype:"float32"}),Aae={kernelName:Ki,backendName:"webgl",kernelFunc:XA};function fv(e){let{inputs:t,attrs:n,backend:a}=e,{dim:r}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(w.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),ce({inputs:{x:s},backend:a,attrs:{shape:o}})}var Fae={kernelName:hu,backendName:"webgl",kernelFunc:fv},xS="return exp(x) - 1.0;",$ae=Ze({opSnippet:xS,packedOpSnippet:xS,cpuKernelImpl:tQ}),Dae={kernelName:Xi,backendName:"webgl",kernelFunc:$ae},vS=class{constructor(e,t,n){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=n?`${a}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${r};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${i}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${a});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${a}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${s};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function YA(e,t,n){let a=n.texData.get(e.dataId),r=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=ce({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,u=new vS("real",l,t),p=new vS("imag",l,t),d=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Fs({inputs:{real:c,imag:h},backend:n});n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h);let f=ce({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function Rae(e){let{inputs:t,backend:n}=e,{input:a}=t;return YA(a,!1,n)}var Mae={kernelName:Cm,backendName:"webgl",kernelFunc:Rae},Oae=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 $d(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||w.inferDtype(r),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new Oae(a,r),o=[[r]];return t.runWebGLProgram(i,[],s,o)}}var Pae={kernelName:zc,backendName:"webgl",kernelFunc:$d},Lae=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);
|
|
}
|
|
`}},zae={kernelName:mu,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new Lae(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},wS="return floor(x);",Wae=Ze({opSnippet:wS,packedOpSnippet:wS,cpuKernelImpl:nQ}),Bae={kernelName:Yi,backendName:"webgl",kernelFunc:Wae},Vae=`
|
|
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;
|
|
}
|
|
`,Uae=`
|
|
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);
|
|
`,Gae=hn({opSnippet:Vae,packedOpSnippet:Uae,dtype:"int32"}),Hae={kernelName:Zi,backendName:"webgl",kernelFunc:Gae},qae=class{constructor(e){this.variableNames=["A"];let t=Cn(),[n,a]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}.0, ${n}.0);
|
|
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`}},jae=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Cn(),[n,a]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}.0, ${n}.0);
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},Kae={kernelName:Hh,backendName:"webgl",kernelFunc:Xae},Il,yx=G().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Xae(e){let{inputs:t,backend:n,attrs:a}=e,{pixels:r}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,l],d=[u,l,s];if(o||i){let f=G().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Il==null||f!==yx)&&(yx=f,Il=document.createElement("canvas").getContext("2d",{willReadFrequently:yx})),Il.canvas.width=l,Il.canvas.height=u,Il.drawImage(r,0,0,l,u),r=Il.canvas}let c=n.makeTensorInfo(p,"int32");n.texData.get(c.dataId).usage=ca.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(c.dataId),r);let h=G().getBool("WEBGL_PACK")?new jae(d):new qae(d),m=n.runWebGLProgram(h,[c],"int32");return n.disposeData(c.dataId),m}function Yae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=T.convertConv2DDataFormat(p),g=T.computeConv2DInfo(r.shape,s.shape,l,d,u,c,!1,f),b,y=[],x=i!=null,v=o!=null,I=h==="leakyrelu",N=()=>{let _=[r,s],F=(D,$)=>{if($==="NCHW"&&D.shape.length===1&&D.shape[0]!==1){let S=ce({inputs:{x:D},backend:n,attrs:{shape:[D.shape[0],1,1]}});return y.push(S),S}return D};if(x&&_.push(F(i,p)),v&&_.push(F(o,p)),I){let D=n.makeTensorInfo([],"float32",w.createScalarValue(m,"float32"));_.push(D),y.push(D)}return _};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=GA({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(g.strideWidth<=2&&f==="channelsLast"&&G().getBool("WEBGL_EXP_CONV")){let _=h?Cc(h,!0):null,F=new UA(g,x,_,v,I),D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],$=N();b=n.runWebGLProgram(F,$,"float32",D)}else if(G().getBool("WEBGL_CONV_IM2COL"))b=HA({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let _=h?Cc(h,!1):null,F=new VA(g,x,_,v,I),D=N();b=n.runWebGLProgram(F,D,"float32")}let C=ce({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(_=>n.disposeIntermediateTensorInfo(_)),C}var Zae={kernelName:ii,backendName:"webgl",kernelFunc:Yae};function Jae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dimRoundingMode:d,activation:c,leakyreluAlpha:h}=a,m=[],f=p;f==null&&(f=[1,1]),w.assert(T.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=T.computeConv2DInfo(r.shape,s.shape,l,f,u,d,!0),b=G().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,y=c?Cc(c,b):null,x=[r,s],v=i!=null,I=o!=null,N=c==="leakyrelu";if(v&&x.push(i),I&&x.push(o),N){let D=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));x.push(D),m.push(D)}let C;b?C=new KA(g,v,y,I,N):C=new jA(g,v,y,I,N);let _=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=n.runWebGLProgram(C,x,"float32",_);return m.forEach(D=>n.disposeIntermediateTensorInfo(D)),F}var Qae={kernelName:oi,backendName:"webgl",kernelFunc:Jae},ere=class{constructor(e,t,n,a){this.sliceDim=e,this.strides=t,this.paramsShape=a,this.variableNames=["x","indices"],this.outputShape=n;let r=ht(n.length),s=`
|
|
int index;`;for(let i=0;i<this.sliceDim;i++)s+=`
|
|
index = round(getIndices(coords[0], ${i}));
|
|
out_of_bounds = out_of_bounds || index < 0;
|
|
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
|
|
flattenIndex += index * ${this.strides[i]};`;this.userCode=`
|
|
void main() {
|
|
${r} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
bool out_of_bounds = false;
|
|
|
|
${s}
|
|
|
|
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function tre(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],o=w.sizeFromShape(a.shape),[l,u,p,d]=T.prepareAndValidate(a,r),c=ce({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),h=ce({inputs:{x:a},backend:n,attrs:{shape:[w.sizeFromShape(a.shape)/p,p]}});if(n.shouldExecuteOnCPU([a,r])||a.dtype==="string"){let b=n.readSync(r.dataId),y=n.bufferSync(a),x=aQ(b,y,a.dtype,u,i,p,d,a.shape,o);return n.makeTensorInfo(l,a.dtype,x.values)}let m=new ere(i,d,[u,p],a.shape),f=n.runWebGLProgram(m,[h,c],h.dtype),g=ce({inputs:{x:f},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),g}var nre={kernelName:gu,backendName:"webgl",kernelFunc:tre},are=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=ht(this.rank),a=rre(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
int index = int(getIndices(resRC.x, resRC.z));
|
|
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
|
|
setOutput(inBounds * getA(${a}));
|
|
}
|
|
`}};function rre(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;r<e.length;r++)r===2?a.push("index"):a.push(`${n[r]}`);return a.join()}function ZA(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0];if(G().get("DEBUG")){let y=n.readSync(s.dataId),x=r.shape[l];for(let v=0;v<y.length;++v){let I=y[v];w.assert(I<=x-1&&I>=0,()=>`GatherV2: the index value ${I} is not in [0, ${x-1}]`)}}let u=T.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=w.sizeFromShape(s.shape),d=[],c=ce({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=ce({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,p/u.batchSize]}});d.push(c),d.push(h);let m=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let y=n.bufferSync(h),x=n.bufferSync(c),v=rQ(x,y,m);return d.forEach(I=>n.disposeIntermediateTensorInfo(I)),n.makeTensorInfo(u.outputShape,v.dtype,v.values)}let f=new are(c.shape,m),g=n.runWebGLProgram(f,[c,h],c.dtype);d.push(g);let b=ce({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var sre={kernelName:fu,backendName:"webgl",kernelFunc:ZA},ire="return float(a > b);",ore=`
|
|
return vec4(greaterThan(a, b));
|
|
`,lre=hn({opSnippet:ire,packedOpSnippet:ore,cpuKernelImpl:sQ,dtype:"bool"}),ure={kernelName:bu,backendName:"webgl",kernelFunc:lre},pre="return float(a >= b);",cre=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,dre=hn({opSnippet:pre,packedOpSnippet:cre,dtype:"bool",cpuKernelImpl:iQ}),hre={kernelName:Qi,backendName:"webgl",kernelFunc:dre};function mre(e){let{inputs:t,backend:n}=e,{input:a}=t;return YA(a,!0,n)}var fre={kernelName:Em,backendName:"webgl",kernelFunc:mre},gre="return float(!isnan(x) && !isinf(x));",bre=Ze({opSnippet:gre,dtype:"bool"}),yre={kernelName:to,backendName:"webgl",kernelFunc:bre},xre="return float(isinf(x));",vre=Ze({opSnippet:xre,dtype:"bool"}),wre={kernelName:no,backendName:"webgl",kernelFunc:vre},kre="return float(isnan(x));",Ire=Ze({opSnippet:kre,dtype:"bool"}),Sre={kernelName:ao,backendName:"webgl",kernelFunc:Ire},Nre="return float(a < b);",Tre=`
|
|
return vec4(lessThan(a, b));
|
|
`,Cre=hn({opSnippet:Nre,packedOpSnippet:Tre,cpuKernelImpl:oQ,dtype:"bool"}),Ere={kernelName:yu,backendName:"webgl",kernelFunc:Cre},_re="return float(a <= b);",Are=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,Fre=hn({opSnippet:_re,packedOpSnippet:Are,cpuKernelImpl:lQ,dtype:"bool"}),$re={kernelName:xu,backendName:"webgl",kernelFunc:Fre};function Dre(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=uQ(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var Rre={kernelName:vu,backendName:"webgl",kernelFunc:Dre},Mre=mp+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,Ore=`
|
|
vec4 result = log(x);
|
|
bvec4 isNaN = isnan(x);
|
|
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
|
|
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
|
|
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
|
|
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
|
|
return result;
|
|
`,Pre=Ze({opSnippet:Mre,packedOpSnippet:Ore,cpuKernelImpl:pQ}),Lre={kernelName:so,backendName:"webgl",kernelFunc:Pre},zre=mp+`
|
|
return log(1.0 + x);
|
|
`,Wre=Ze({opSnippet:zre}),Bre={kernelName:io,backendName:"webgl",kernelFunc:Wre},Vre="return float(a >= 1.0 && b >= 1.0);",Ure=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,Gre=hn({opSnippet:Vre,packedOpSnippet:Ure,dtype:"bool"}),Hre={kernelName:wu,backendName:"webgl",kernelFunc:Gre},qre="return float(!(x >= 1.0));",jre=Ze({opSnippet:qre}),Kre={kernelName:ku,backendName:"webgl",kernelFunc:jre},Xre="return float(a >= 1.0 || b >= 1.0);",Yre=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,Zre=hn({opSnippet:Xre,packedOpSnippet:Yre,dtype:"bool"}),Jre={kernelName:Iu,backendName:"webgl",kernelFunc:Zre},Qre=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
int d = coords[3];
|
|
float x = getX(b, r, c, d);
|
|
float sum = 0.0;
|
|
for (int j = -${s}; j <= ${s}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${i}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${o};
|
|
setOutput(val);
|
|
}
|
|
`}},ese=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords.x;
|
|
int r = coords.y;
|
|
int c = coords.z;
|
|
int d = coords.w;
|
|
|
|
bool hasNextCol = d < ${this.outputShape[3]};
|
|
bool hasNextRow = c < ${this.outputShape[2]};
|
|
|
|
vec4 sum = vec4(0.);
|
|
vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
|
|
|
vec4 xAtOutputCoords = vec4(
|
|
getChannel(xFragAtOutputCoords, vec2(c, d)),
|
|
hasNextCol ?
|
|
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
|
|
hasNextRow ?
|
|
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
|
|
);
|
|
|
|
int firstChannel = d - ${s};
|
|
vec2 cache = vec2(0.);
|
|
if(firstChannel >= 0){
|
|
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
|
|
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
|
|
if(hasNextRow){
|
|
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
|
|
}
|
|
}
|
|
|
|
ivec2 depth = ivec2(d, d + 1);
|
|
for (int j = - ${s}; j <= ${s}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * ${o};
|
|
setOutput(result);
|
|
}
|
|
`}},tse=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,u=G().getBool("WEBGL_PACK_NORMALIZATION")?new ese(r.shape,s,i,o,l):new Qre(r.shape,s,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)},nse={kernelName:oo,backendName:"webgl",kernelFunc:tse},ase=class{constructor(e,t,n,a,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=a,this.beta=r,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float result = 0.0;
|
|
for (int d = 0; d < ${this.depth}; ++d) {
|
|
int depthBegin = int(max(0.0, float(d - ${t})));
|
|
int depthEnd = int(min(float(${this.depth}),
|
|
float(d + ${t} + 1)));
|
|
|
|
const int MIN_DEPTH_BEGIN = 0;
|
|
const int MAX_DEPTH_END = ${this.depth};
|
|
|
|
float norm = 0.0;
|
|
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd) {
|
|
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
norm = float(${a}) * norm + float(${n});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${a})
|
|
* float(${r})
|
|
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${r});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},rse=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a,d=new ase(r.shape,o,l,u,p);return n.runWebGLProgram(d,[r,s,i],r.dtype)},sse={kernelName:Su,backendName:"webgl",kernelFunc:rse};function ise(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=el(i,e.dtype,"max",a),l=ce({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function JA(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),d=p!=null,c=n.shouldExecuteOnCPU([r]),h=r;if(d){if(c){let y=n.texData.get(h.dataId).values,x=new Array(o);for(let N=0;N<x.length;N++)x[N]=r.shape[p[N]];let v=ok(y,r.shape,r.dtype,p,x);h=n.makeTensorInfo(x,r.dtype);let I=n.texData.get(h.dataId);I.values=v}else h=Wf(r,p,n);u=T.getInnerMostAxes(u.length,o)}T.assertAxesAreInnerMostDims("max",u,o);let[m,f]=T.computeOutAndReduceShapes(h.shape,u),g=m;i&&(g=T.expandShapeToKeepDim(m,l));let b;if(c){let y=n.texData.get(h.dataId).values,x=cQ(y,w.sizeFromShape(f),g,r.dtype);b=n.makeTensorInfo(g,r.dtype);let v=n.texData.get(b.dataId);v.values=x}else b=ise(h,f,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var ose={kernelName:lo,backendName:"webgl",kernelFunc:JA},lse=uk+`
|
|
return max(a, b);
|
|
`,use=`
|
|
vec4 result = vec4(max(a, b));
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
`+Qo+`
|
|
return result;
|
|
`,pse=hn({opSnippet:lse,packedOpSnippet:use,cpuKernelImpl:dQ}),cse={kernelName:uo,backendName:"webgl",kernelFunc:pse};function dse(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;lp(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return ta({inputs:{x:r},backend:n});let d=new Ec(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var hse={kernelName:po,backendName:"webgl",kernelFunc:dse};function mse(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=a,p=[1,1,1],d=T.computePool3DInfo(r.shape,s,i,p,o,u,l),c=new ck(d,"max",!1);return n.runWebGLProgram(c,[r],r.dtype)}var fse={kernelName:Nu,backendName:"webgl",kernelFunc:mse},gse=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,a=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${r};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${s}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * ${s} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},bse=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=o-1-e.padInfo.front,d=l-1-e.padInfo.top,c=u-1-e.padInfo.left,h=o*l*u-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${p}, ${d}, ${c});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${o};
|
|
wD += ${r}) {
|
|
float dyD = float(dyDCorner + wD) / ${t}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${l};
|
|
wR += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${u};
|
|
wC += ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${h} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${u} +
|
|
wR * ${u} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function yse(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=T.computePool3DInfo(i.shape,o,l,d,u,p),h=new ck(c,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new bse(c),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var xse={kernelName:Bc,backendName:"webgl",kernelFunc:yse};function vse(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;lp([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:d}=a,c=T.computePool2DInfo(o.shape,l,u,1,p,d),h=!0,m=new Ec(c,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new gse(c),b=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),b}var wse={kernelName:Wc,backendName:"webgl",kernelFunc:vse};function kse(e,t,n,a){let r=new Ec(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new Ec(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var Ise={kernelName:Vc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;w.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let u=[1,1];w.assert(T.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let p=T.computePool2DInfo(a.shape,r,s,u,i),[d,c]=kse(a,o,p,l);return[d,c]}};function Sse(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=el(i,"float32","mean",a),l=ce({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var Nse={kernelName:co,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{keepDims:r,axis:s}=t,i=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,p=T.getAxesPermutation(u,o),d=p!=null,c=i.shouldExecuteOnCPU([a]),h=[],m=a;if(d){if(c){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let C=0;C<v.length;C++)v[C]=a.shape[p[C]];let I=ok(x,a.shape,a.dtype,p,v);m=i.makeTensorInfo(v,a.dtype);let N=i.texData.get(m.dataId);N.values=I}else m=Wf(a,p,i);h.push(m),u=T.getInnerMostAxes(u.length,o)}T.assertAxesAreInnerMostDims("sum",u,o);let[f,g]=T.computeOutAndReduceShapes(m.shape,u),b=f;r&&(b=T.expandShapeToKeepDim(f,l));let y=Sse(m,g,b,i);for(let x of h)i.disposeIntermediateTensorInfo(x);return y}};function Tse(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),d=r;p!=null&&(d=In({inputs:{x:r},backend:n,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,r.shape.length)),T.assertAxesAreInnerMostDims("min",u,o);let[c,h]=T.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=el(f,f.dtype,"min",n),b;if(i){let y=T.expandShapeToKeepDim(c,l);b=ce({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ce({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),b}var Cse={kernelName:ho,backendName:"webgl",kernelFunc:Tse},Ese=uk+`
|
|
return min(a, b);
|
|
`,_se=`
|
|
vec4 result = vec4(min(a, b));
|
|
bvec4 isNaNA = isnan(a);
|
|
bvec4 isNaNB = isnan(b);
|
|
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
|
|
`+Qo+`
|
|
return result;
|
|
`,Ase=hn({opSnippet:Ese,packedOpSnippet:_se,cpuKernelImpl:hQ}),Fse={kernelName:mo,backendName:"webgl",kernelFunc:Ase},$se=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);let a=e.length,r=ht(a),s=t.map(u=>u[0]).join(","),i=t.map((u,p)=>u[0]+e[p]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=n==="reflect"?0:1;if(a===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${l};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${l};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${r} start = ${r}(${s});
|
|
${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outC = getOutputCoords();
|
|
for (int i = 0; i < ${a}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${l};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
|
|
}
|
|
}
|
|
${r} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}},Dse=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let a=e.length,r=ht(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=kn("rc",a),l=kn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,p=a===1?"source":`vec2(${l.slice(-2).join()})`,d=n==="reflect"?0:1,c="";if(a===1){let h=`
|
|
${r} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${d};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${d};
|
|
}
|
|
source -= start;
|
|
`;c=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${p});
|
|
${o[a-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${p});
|
|
}
|
|
`}else{let h=`
|
|
${r} source = rc;
|
|
${r} lt = ${r}(lessThan(source, start));
|
|
${r} gte = ${r}(greaterThanEqual(source, end));
|
|
${r} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${d}) +
|
|
gte * ((end - 1) * 2 - source + ${d});
|
|
source -= start;
|
|
`;c=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${p});
|
|
${o[a-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${p});
|
|
}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${l.join()}), ${p});
|
|
${o[a-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${l.join()}), ${p});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${r} start = ${r}(${s});
|
|
const ${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${c}
|
|
setOutput(result);
|
|
}
|
|
`}},Rse=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Dse(a.shape,r,s):new $se(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},Mse={kernelName:fo,backendName:"webgl",kernelFunc:Rse},Ose=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,Pse=`
|
|
vec4 result = mod(a, b);
|
|
bvec4 isNaN = equal(b, vec4(0.0));
|
|
`+Qo+`
|
|
return result;
|
|
`,Lse=hn({opSnippet:Ose,packedOpSnippet:Pse}),zse={kernelName:go,backendName:"webgl",kernelFunc:Lse},Wse=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}));
|
|
}
|
|
`}},Bse=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,Vse=`
|
|
// 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;
|
|
`,QA=hn({opSnippet:Bse,packedOpSnippet:Vse,checkOutOfBounds:!0}),Use={kernelName:Hi,backendName:"webgl",kernelFunc:QA},kS="return a - b;",eF=hn({opSnippet:kS,packedOpSnippet:kS,supportsComplex:!0,cpuKernelImpl:RQ}),Gse={kernelName:Bo,backendName:"webgl",kernelFunc:eF};function tF(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=w.parseAxisParam([s],r.shape),o=JA({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=T.expandShapeToKeepDim(o.shape,i),u=ce({inputs:{x:o},backend:n,attrs:{shape:l}}),p=eF({inputs:{a:r,b:u},backend:n}),d=XA({inputs:{x:p},backend:n}),c=Bf({inputs:{x:d},backend:n,attrs:{axis:i,keepDims:!1}}),h=ce({inputs:{x:c},backend:n,attrs:{shape:l}}),m=QA({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}var Hse={kernelName:zo,backendName:"webgl",kernelFunc:tF};function qse(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:tF({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],p=l.shape[1],d=new Wse(u,p,s),c=[[i]],h=n.runWebGLProgram(d,[l],"int32",c);return o||n.disposeIntermediateTensorInfo(l),h}var jse={kernelName:Tu,backendName:"webgl",kernelFunc:qse},Kse=Da+`
|
|
return -x;
|
|
`,Xse=`
|
|
vec4 result = -x;
|
|
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;
|
|
`;function Yse(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=fQ(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new ts(a.shape,Xse):r=new rr(a.shape,Kse),n.runWebGLProgram(r,[a],a.dtype)}var Zse={kernelName:Cu,backendName:"webgl",kernelFunc:Yse},Jse=hr.nonMaxSuppressionV3Impl;function Qse(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),{selectedIndices:d}=Jse(u,p,i,o,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var eie={kernelName:_u,backendName:"webgl",kernelFunc:Qse},tie=hr.nonMaxSuppressionV4Impl;function nie(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),{selectedIndices:c,validOutputs:h}=tie(p,d,i,o,l,u);return[n.makeTensorInfo([c.length],"int32",new Int32Array(c)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var aie={kernelName:Au,backendName:"webgl",kernelFunc:nie},rie=hr.nonMaxSuppressionV5Impl;function sie(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),c=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:b}=rie(p,d,c,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var iie={kernelName:Fu,backendName:"webgl",kernelFunc:sie},oie=class{constructor(e,t,n,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${a}), float(${n}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},lie=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a,u=w.sizeFromShape(r.shape),p=new oie(u,i,o,l),d=ce({inputs:{x:r},backend:n,attrs:{shape:[u]}}),c=n.runWebGLProgram(p,[d],s);n.disposeIntermediateTensorInfo(d);let h=[...r.shape,i],m=ce({inputs:{x:c},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(c),m},uie={kernelName:yo,backendName:"webgl",kernelFunc:lie};function fm(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=Fd({inputs:{input:a},backend:n}),s=fm({inputs:{x:r},backend:n}),i=Vf({inputs:{input:a},backend:n}),o=fm({inputs:{x:i},backend:n}),l=Fs({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return $d({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var pie={kernelName:Yu,backendName:"webgl",kernelFunc:fm};function nF(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let r=Fd({inputs:{input:a},backend:n}),s=nF({inputs:{x:r},backend:n}),i=Vf({inputs:{input:a},backend:n}),o=fm({inputs:{x:i},backend:n}),l=Fs({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return $d({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var cie={kernelName:$u,backendName:"webgl",kernelFunc:nF};function die(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return fv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=fv({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=BA({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var hie={kernelName:Du,backendName:"webgl",kernelFunc:die},mie=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let a=e.length,r=ht(a),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${r} start = ${r}(${s});
|
|
${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${r} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
}
|
|
`}},fie=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let a=e.length,r=ht(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=kn("rc",a),l=kn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,p=a===1?"source":`vec2(${l.slice(-2).join()})`,d=[`${r} rc = outputLoc;`,`${o[a-1]} += 1;
|
|
if(${u}) {
|
|
`,a===1?"":`}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {`,a===1?"":` ${o[a-1]} += 1;
|
|
if(${u}) {`],c=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=a===1?2:4;m<f;m++)h+=`
|
|
${d[m]}
|
|
if (${c}) {
|
|
result[${m}] = float(value);
|
|
} else {
|
|
${r} source = rc - start;
|
|
result[${m}] = getChannel(getX(${l.join()}), ${p});
|
|
}
|
|
`;h+=a===1?"} ":"}}",this.userCode=`
|
|
const ${r} start = ${r}(${s});
|
|
const ${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},aF=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;if(w.sizeFromShape(r.shape)===0){let u=s.map((p,d)=>p[0]+r.shape[d]+p[1]);return $d({backend:n,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fie(r.shape,s,i):new mie(r.shape,s,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},gie={kernelName:xo,backendName:"webgl",kernelFunc:aF},bie=`
|
|
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);
|
|
`,yie=`
|
|
// 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;
|
|
|
|
bvec4 isNaN1 = lessThan(a, vec4(0.0));
|
|
bvec4 isNaN2 = lessThan(floor(b), b);
|
|
bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
|
|
`+Qo+`
|
|
return result;
|
|
`,xie=hn({opSnippet:bie,packedOpSnippet:yie}),vie={kernelName:vo,backendName:"webgl",kernelFunc:xie};function wie(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],u=w.parseAxisParam(s,r.shape),p=u,d=T.getAxesPermutation(p,o),c=r;d!=null&&(c=In({inputs:{x:r},backend:n,attrs:{perm:d}}),p=T.getInnerMostAxes(p.length,o),l.push(c)),T.assertAxesAreInnerMostDims("prod",p,o);let h;if(n.shouldExecuteOnCPU([c])){let m=n.texData.get(c.dataId).values,{outVals:f,outShape:g,outDtype:b}=bQ(c.shape,c.dtype,m,p);h=n.makeTensorInfo(g,b,f)}else{let[m,f]=T.computeOutAndReduceShapes(c.shape,p),g=w.sizeFromShape(f),b=ce({inputs:{x:c},backend:n,attrs:{shape:[-1,g]}}),y=Mm(r.dtype),x=el(b,y,"prod",n);h=ce({inputs:{x},backend:n,attrs:{shape:m}}),l.push(b),l.push(x)}if(i){l.push(h);let m=T.expandShapeToKeepDim(h.shape,u);h=ce({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var kie={kernelName:ko,backendName:"webgl",kernelFunc:wie};function Iie(e){let{inputs:t,backend:n,attrs:a}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=a,l=r.map(b=>n.readSync(b.dataId)),u=r.map(b=>b.shape),p=n.readSync(s.dataId),d=n.readSync(i.dataId),[c,h,m]=yQ(l,u,p,s.shape,s.dtype,d,i.shape,o),f=c.map(b=>n.makeTensorInfo([b.length],"int32",b)),g=n.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var Sie={kernelName:Am,backendName:"webgl",kernelFunc:Iie};function Nie(e){let{inputs:t,backend:n}=e,{starts:a,limits:r,deltas:s}=t,i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=xQ(i,a.shape,a.dtype,o,r.shape,l,s.shape),d=n.makeTensorInfo([u.length],"int32",u),c=n.makeTensorInfo([p.length],a.dtype,p);return[d,c]}var Tie={kernelName:Fm,backendName:"webgl",kernelFunc:Nie};function Cie(e){let{inputs:t,backend:n,attrs:a}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),d=n.readSync(i.dataId),c=o.map(g=>n.readSync(g.dataId)),h=o.map(g=>g.shape),[m,f]=vQ(u,r.shape,p,s.shape,s.dtype,d,i.shape,c,h,l);return n.makeTensorInfo(m,s.dtype,f)}var Eie={kernelName:$m,backendName:"webgl",kernelFunc:Cie},rF=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=wQ(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},_ie={kernelName:Uc,backendName:"webgl",kernelFunc:rF},Aie="return 1.0 / x;",Fie=Ze({opSnippet:Aie}),$ie={kernelName:Io,backendName:"webgl",kernelFunc:Fie},Die=Da+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Rie=`
|
|
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;
|
|
`,Mie=Ze({opSnippet:Die,packedOpSnippet:Rie}),Oie={kernelName:So,backendName:"webgl",kernelFunc:Mie},Pie=Da+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Lie=`
|
|
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;
|
|
`,zie=Ze({opSnippet:Pie,packedOpSnippet:Lie}),Wie={kernelName:Co,backendName:"webgl",kernelFunc:zie},Bie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/p[0]},
|
|
${u[1]/p[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the 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);
|
|
}
|
|
`}},Vie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/p[0]},
|
|
${u[1]/p[1]},
|
|
${u[1]/p[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${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 < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
// In parallel, construct four corners for all four components in
|
|
// packed 2x2 cell.
|
|
vec4 topLeft = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomLeft = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 topRight = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomRight = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
|
|
|
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
|
|
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
|
|
vec4 newValue = mix(top, bottom, fracRC.x);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function Uie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Vie(r.shape,l,u,s,i):new Bie(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],"float32")}var Gie={kernelName:To,backendName:"webgl",kernelFunc:Uie},Hie=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${p});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${c});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${a-1}.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0));
|
|
float dxCLerp = dxC - float(leftDxCIndex);
|
|
float inverseDxCLerp = 1.0 - dxCLerp;
|
|
|
|
if (r == topDxRIndex && c == leftDxCIndex) {
|
|
// topLeft
|
|
accumulator +=
|
|
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == topDxRIndex && c == rightDxCIndex) {
|
|
// topRight
|
|
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == leftDxCIndex) {
|
|
// bottomLeft
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == rightDxCIndex) {
|
|
// bottomRight
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function qie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new Hie(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var jie={kernelName:Ou,backendName:"webgl",kernelFunc:qie},Kie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":c="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/p[0]},
|
|
${u[1]/p[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${c};
|
|
|
|
// 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);
|
|
}
|
|
`}},Xie=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":c="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/p[0]},
|
|
${u[1]/p[1]},
|
|
${u[1]/p[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${c};
|
|
|
|
// 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 < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function Yie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Xie(r.shape,l,u,s,i):new Kie(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],r.dtype)}var Zie={kernelName:No,backendName:"webgl",kernelFunc:Yie},Jie=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${p});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${c});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${o[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${o[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${a}) - 1),
|
|
${n} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${r}) - 1),
|
|
${n} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function Qie(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new Jie(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var eoe={kernelName:Mu,backendName:"webgl",kernelFunc:Qie},toe=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let a=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,r=e.map((i,o)=>a(o)).join(","),s=ht(n);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},noe=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let a=kn("rc",n),r=`${a[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${a[n-2]} + 1 < ${this.outputShape[n-2]}`,i=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(${r}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${i} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${o(a.slice())};
|
|
if(${r}){
|
|
result.g = ${l(a.slice())};
|
|
}
|
|
if(${s}) {
|
|
result.b = ${u(a.slice())};
|
|
if(${r}) {
|
|
result.a = ${p(a.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function o(h){return d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function p(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let m=e.map((b,y)=>c(y,h)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function c(h,m){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${m[h]} - 1`:`${m[h]}`}}};function aoe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return ta({inputs:{x:r},backend:n});let l=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new noe(r.shape,o):new toe(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var roe={kernelName:Eo,backendName:"webgl",kernelFunc:aoe},soe=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],a=e[2];this.outputShape=e;let r="";typeof t=="number"?r=`float outputValue = ${t.toFixed(2)};`:r=`
|
|
vec3 fill = vec3(${t.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${r}
|
|
if(coordX >= 0 && coordX < ${a} && coordY >= 0 && coordY < ${n}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},ioe={kernelName:Zu,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new soe(a.shape,s),[u,p]=T.getImageCenter(i,a.shape[1],a.shape[2]),d=[[u,p,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[a],a.dtype,d)}},ooe=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,loe=Ze({opSnippet:ooe}),uoe={kernelName:_o,backendName:"webgl",kernelFunc:loe},poe="return inversesqrt(x);",coe=Ze({opSnippet:poe,cpuKernelImpl:kQ}),doe={kernelName:Ao,backendName:"webgl",kernelFunc:coe},dk=class{constructor(e,t,n,a,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let l=ht(r.length),u=ht(s.length),p="";n===1?p="i":n===2&&(p="i, j");let d=`getIndices(${p})`,c="";a===1?c="i":a===2&&(c="i, coords[1]");let h=`getUpdates(${c})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${r});
|
|
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${d});
|
|
flattenedIndex += index * ${g};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${h};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(${f}, sum, float(found)));
|
|
}
|
|
`}},hoe=class{constructor(e,t,n,a,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;let l=ht(r.length),u=ht(s.length),p="";n===1?p="i":n===2&&(p="i, j");let d=`getIndices(${p})`,c="";a===1?c="i":a===2&&(c="i, coords[1]");let h=`getUpdates(${c})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides",b=t>1?"strides[j + 1]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${r});
|
|
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
vec4 sum = vec4(0.);
|
|
vec4 found = vec4(0.);
|
|
for (int i = 0; i < ${e}; i+=2) {
|
|
ivec2 flattenedIndex = ivec2(0);
|
|
for (int j = 0; j < ${t}; j+=2) {
|
|
ivec4 index = round(${d});
|
|
flattenedIndex += index.xz * ${g};
|
|
if (j + 1 < ${t}) {
|
|
flattenedIndex += index.yw * ${b};
|
|
}
|
|
}
|
|
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
|
|
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
|
|
vec4 updVals = ${h};
|
|
if (flattenedIndex[0] == coords[0]) {
|
|
sum.xy += updVals.xy;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[0] == coords[0] + 1) {
|
|
sum.zw += updVals.xy;
|
|
found.zw = vec2(1.);
|
|
}
|
|
if (flattenedIndex[1] == coords[0]) {
|
|
sum.xy += updVals.zw;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[1] == coords[0] + 1) {
|
|
sum.zw += updVals.zw;
|
|
found.zw = vec2(1.);
|
|
}
|
|
}
|
|
}
|
|
setOutput(mix(${f}, sum, found));
|
|
}
|
|
`}};function moe(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=T.calculateShapes(s,r,i),c=[d/u,u];if(d===0)return n.makeTensorInfo(i,r.dtype);let h=ce({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=ce({inputs:{x:s},backend:n,attrs:{shape:[l,u]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g;G().getBool("WEBGL_PACK")?g=new hoe(l,o,h.shape.length,m.shape.length,p,c):g=new dk(l,o,h.shape.length,m.shape.length,p,c);let b=n.runWebGLProgram(g,[m,h,f],m.dtype),y=ce({inputs:{x:b},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(f),y}var foe={kernelName:Pu,backendName:"webgl",kernelFunc:moe},goe=class{constructor(e,t,n,a){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];let r="while (left < right) {",s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=G().getNumber("WEBGL_VERSION")===2?r:s,o=a==="left"?"<":"<=";this.userCode=`
|
|
int findBound(int batch, float value) {
|
|
int left = 0;
|
|
int right = numInputs;
|
|
int mid;
|
|
${i}
|
|
mid = (left + right) / 2;
|
|
if (getSortedSequence(batch, mid) ${o} value) {
|
|
left = mid + 1;
|
|
} else {
|
|
right = mid;
|
|
}
|
|
}
|
|
return right;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int valueIndex = coords[1];
|
|
|
|
float value = getValues(batch, valueIndex);
|
|
|
|
setOutput(float(findBound(batch, value)));
|
|
}
|
|
`}};function boe(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a,o=new goe(r.shape[0],r.shape[1],s.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,s],"int32",l)}var yoe={kernelName:zu,backendName:"webgl",kernelFunc:boe},xoe=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let a,r;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)r="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push(`${i[u]}`),u<e&&o.push(`${i[u]}`);a=o.join(),r=l.join()}let s=ht(n);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${a});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function voe(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new xoe(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],fa(r.dtype,s.dtype))}var woe={kernelName:Wu,backendName:"webgl",kernelFunc:voe},koe=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${T.SELU_SCALEALPHA};
|
|
float scale = ${T.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Ioe=Ze({opSnippet:koe}),Soe={kernelName:Fo,backendName:"webgl",kernelFunc:Ioe},Noe=mp+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,Toe=`
|
|
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
|
|
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;
|
|
`,Coe=Ze({opSnippet:Noe,packedOpSnippet:Toe,cpuKernelImpl:SQ}),Eoe={kernelName:Mo,backendName:"webgl",kernelFunc:Coe},_oe=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,Aoe=Ze({opSnippet:_oe}),Foe={kernelName:Ro,backendName:"webgl",kernelFunc:Aoe},$oe=mp+`
|
|
return sin(x);
|
|
`,Doe=`
|
|
vec4 result = sin(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${Qo}
|
|
return result;
|
|
`,Roe=Ze({opSnippet:$oe,packedOpSnippet:Doe}),Moe={kernelName:$o,backendName:"webgl",kernelFunc:Roe},Ooe=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Poe=Ze({opSnippet:Ooe}),Loe={kernelName:Do,backendName:"webgl",kernelFunc:Poe},zoe=`
|
|
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;
|
|
`,Woe=Ze({opSnippet:zoe}),Boe={kernelName:Oo,backendName:"webgl",kernelFunc:Woe},Voe=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;w.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,y)=>b*y),l=[[0,0]];l.push(...i);for(let b=1+s.length;b<r.shape.length;++b)l.push([0,0]);let u=[],p=aF({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),d=T.getReshaped(p.shape,s,o,!1),c=T.getPermuted(d.length,s.length,!1),h=T.getReshapedPermuted(p.shape,s,o,!1),m=ce({inputs:{x:p},backend:n,attrs:{shape:d}}),f=In({inputs:{x:m},backend:n,attrs:{perm:c}}),g=ce({inputs:{x:f},backend:n,attrs:{shape:h}});return u.push(p),u.push(m),u.push(f),u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},Uoe={kernelName:Vu,backendName:"webgl",kernelFunc:Voe};function Goe(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${a.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=n.readSync(a.dataId),l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=n.readSync(i.dataId)[0],[d,c,h,m,f]=TQ(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var Hoe={kernelName:Gc,backendName:"webgl",kernelFunc:Goe};function qoe(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.readSync(r.dataId)),o=n.readSync(a.dataId),l=Array.from(n.readSync(s.dataId)),[u,p,d]=CQ(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var joe={kernelName:Gu,backendName:"webgl",kernelFunc:qoe};function Koe(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=TA(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var Xoe={kernelName:Hc,backendName:"webgl",kernelFunc:Koe};function Yoe(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=TA(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var Zoe={kernelName:qc,backendName:"webgl",kernelFunc:Yoe};function Joe(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=T.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let b=n.bufferSync(r),y=n.bufferSync(s),x=w.decodeString(n.readSync(i.dataId)[0]),v=IQ(b,y,o,c,p,u,l,d,x,h);return n.makeTensorInfo(o,v.dtype,v.values)}let m=new dk(u,l,r.shape.length,s.shape.length,d,[c,1],h),f=n.runWebGLProgram(m,[s,r,i],s.dtype),g=ce({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),g}var Qoe={kernelName:Hu,backendName:"webgl",kernelFunc:Joe};function ele(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=r.shape.length,p=new Array(u).fill(0),d=r.shape.slice();return l.map(c=>{let h=[...d];h[o]=c;let m=fp({inputs:{x:r},backend:n,attrs:{begin:p,size:h}});return p[o]+=c,m})}var tle={kernelName:Uu,backendName:"webgl",kernelFunc:ele},IS="return sqrt(x);",nle=Ze({opSnippet:IS,packedOpSnippet:IS,cpuKernelImpl:EQ}),ale={kernelName:Po,backendName:"webgl",kernelFunc:nle},rle="return x * x;",sle=Ze({opSnippet:rle}),ile={kernelName:jc,backendName:"webgl",kernelFunc:sle},SS="return (a - b) * (a - b);",ole=hn({opSnippet:SS,packedOpSnippet:SS}),lle={kernelName:Wo,backendName:"webgl",kernelFunc:ole};function ule(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");let s=n.readSync(r.dataId),i=T.fromUint8ToStringArray(s),o=_Q(i,"string",a);return n.makeTensorInfo(r.shape,"string",o)}var ple={kernelName:Kc,backendName:"webgl",kernelFunc:ule};function cle({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Da+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new rr(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var dle={kernelName:ks,backendName:"webgl",kernelFunc:cle},hle=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=ht(n.length),s=ht(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,u)=>(o++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
|
|
${r} begin = ${r}(${e});
|
|
${r} strides = ${r}(${t});
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function mle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=ce({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let C=Kt.computeOutShape(y,x,v),_=fp({inputs:{x:r},backend:n,attrs:{begin:y,size:C}});I=ce({inputs:{x:_},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(_)}else if(n.shouldExecuteOnCPU([r])){let C=n.readSync(r.dataId),_=Oe(r.shape,r.dtype,C),F=AQ(h,_,v,y);I=n.makeTensorInfo(m,r.dtype,F.values)}else{let C=new hle(y,v,h);I=n.runWebGLProgram(C,[r],r.dtype)}let N=ce({inputs:{x:I},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(I),N}var fle={kernelName:qu,backendName:"webgl",kernelFunc:mle};function gle(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.readSync(p.dataId),h=n.readSync(d.dataId),[m,f]=FQ(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var ble={kernelName:Xc,backendName:"webgl",kernelFunc:gle};function yle(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=n.readSync(s.dataId),l=n.readSync(i.dataId)[0],[u,p,d]=$Q(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var xle={kernelName:Yc,backendName:"webgl",kernelFunc:yle};function vle(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.readSync(s.dataId),o=DQ(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var wle={kernelName:Zc,backendName:"webgl",kernelFunc:vle},kle="return tan(x);",Ile=Ze({opSnippet:kle}),Sle={kernelName:Vo,backendName:"webgl",kernelFunc:Ile},Nle=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Tle=Ze({opSnippet:Nle}),Cle={kernelName:Uo,backendName:"webgl",kernelFunc:Tle};function Ele(e){let{inputs:t,backend:n,attrs:a}=e,{tensor:r,indices:s,updates:i}=t,{}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=T.calculateShapes(i,s,r.shape),c=[d/u,u];if(d===0)return n.makeTensorInfo(r.shape,s.dtype);let h=ce({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),m=ce({inputs:{x:i},backend:n,attrs:{shape:[l,u]}}),f=ce({inputs:{x:r},backend:n,attrs:{shape:c}}),g=new dk(l,o,h.shape.length,m.shape.length,p,c,!1,!0),b=n.runWebGLProgram(g,[m,h,f],f.dtype),y=ce({inputs:{x:b},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),y}var _le={kernelName:Lu,backendName:"webgl",kernelFunc:Ele},Ale=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;let a=ht(this.rank),r=Fle(e);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function Fle(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],a=[];for(let r=0;r<e.length;r++)a.push(`imod(${n[r]}, ${e[r]})`);return a.join()}function sF(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;if(r.dtype==="string"||r.shape.length>5){let o=n.readSync(r.dataId),l=r.dtype==="string"?o.map(d=>w.decodeString(d)):o,u=Oe(r.shape,r.dtype,l),p=MQ(u,s);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new Ale(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var $le={kernelName:ws,backendName:"webgl",kernelFunc:sF},Dle=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));
|
|
}
|
|
}
|
|
`}},Rle=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 qs(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function NS(e){let t=1;for(;t<e;)t*=2;return t}function Mle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=G().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=G().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,p=u[u.length-1];if(n.shouldExecuteOnCPU([r])||p<o||s>l){let F=n.readSync(r.dataId),[D,$]=OQ(F,u,r.dtype,s,i);return[n.makeTensorInfo(D.shape,D.dtype,D.values),n.makeTensorInfo($.shape,$.dtype,$.values)]}if(s===0)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(p===1)return[r,$d({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),c=d!==null&&d.isPacked,h=c?n.unpackTensor(r):r,m=w.sizeFromShape(u)/p,f=ce({inputs:{x:h},attrs:{shape:[m,p]},backend:n});c&&qs(n,h);let g=NS(s),b=NS(p),y=null,x=()=>y===null?[f,f]:[f,y],v=(F,D,$)=>{let S=x(),M=new Dle($),B=[[p],[y===null?1:0],[Number.NEGATIVE_INFINITY],[F],[D]],U=y;y=n.runWebGLProgram(M,S,"int32",B),qs(n,U)};for(let F=1;F<g;F*=2){let D=F*2;for(let $=F;$>=1;$/=2)v(D,$,[m,b])}for(let F=b;F>g;F/=2){let D=x(),$=new Rle([m,F/2]),S=[[p],[y===null?1:0],[g]],M=y;y=n.runWebGLProgram($,D,"int32",S),qs(n,M);let B=g/2,U=B*2;for(let H=B;H>=1;H/=2)v(U,H,y.shape)}let I=y;y=fp({inputs:{x:y},backend:n,attrs:{begin:0,size:[m,s]}}),qs(n,I);let N=ZA({inputs:{x:f,indices:y},backend:n,attrs:{axis:1,batchDims:1}});qs(n,f);let C=u.slice(0,-1);C.push(s),I=y,y=ce({inputs:{x:y},attrs:{shape:C},backend:n}),qs(n,I);let _=N;return N=ce({inputs:{x:N},attrs:{shape:C},backend:n}),qs(n,_),[N,y]}var Ole={kernelName:ju,backendName:"webgl",kernelFunc:Mle},Ple=class{constructor(e,t,n,a,r,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=n==="nearest"?1:2,o;switch(a){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${o} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${o} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${o} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${r});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${r});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${i} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function Lle(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=new Ple(d,c,i,o,l,g);return n.runWebGLProgram(b,[r,s],"float32")}var zle={kernelName:Ku,backendName:"webgl",kernelFunc:Lle};function Wle(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;lp(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=PQ(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var Ble={kernelName:Jc,backendName:"webgl",kernelFunc:Wle};function Vle(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),p=0;for(let f=0;f<o;f++)f!==s&&(u[p++]=i.shape[f]);let d=[],c=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){c[s]=f;let g=fp({inputs:{x:i},backend:n,attrs:{begin:c,size:h}}),b=ce({inputs:{x:g},backend:n,attrs:{shape:u}});m[f]=b,d.push(g)}return d.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var Ule={kernelName:Xu,backendName:"webgl",kernelFunc:Vle},Gle=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,a=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/n);this.outputShape=[a,i];let o="0.0",l="sumValue",u=Math.floor(n/4)*4,p=n%4,d=`
|
|
sumValue += dot(values, segFilter);
|
|
`,c="";r%n>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`);let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${c}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${s})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${s})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${p===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 (${p===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 (${p===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(${l});
|
|
}
|
|
`}};function Hle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],u=0,p=T.getAxesPermutation([u],o),d=r;p!=null&&(d=In({inputs:{x:r},backend:n,attrs:{perm:p}}),l.push(d),u=T.getInnerMostAxes(1,o)[0]);let c=T.segment_util.computeOutShape(d.shape,u,i),h=w.sizeFromShape([d.shape[u]]),m=ce({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=Mm(r.dtype),g=(v,I,N,C,_)=>{let F=v.shape[0],D=v.shape[1],$=T.segment_util.segOpComputeOptimalWindowSize(D,_),S={windowSize:$,inSize:D,batchSize:F,numSegments:_},M=new Gle(S,I),B=n.compileAndRun(M,[v,N],C);if(l.push(B),B.shape[1]===_)return B;let U=rF({backend:n,attrs:{start:0,stop:_,step:1,dtype:"float32"}}),H=sF({inputs:{x:U},backend:n,attrs:{reps:[D/$]}});return l.push(U),l.push(H),g(B,I,H,C,_)},b=g(m,"unsortedSegmentSum",s,f,i),y=ce({inputs:{x:b},backend:n,attrs:{shape:c}}),x=y;if(p!=null){l.push(y);let v=T.getUndoAxesPermutation(p);x=In({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var qle={kernelName:Qc,backendName:"webgl",kernelFunc:Hle},jle=[Aee,$ee,Mee,Lee,Wee,Uee,Hee,jee,Zee,Qee,nte,ste,lte,dte,fte,bte,xte,Ite,Nte,Cte,Fte,Lte,Wte,Gte,qte,Jte,ene,rne,hee,one,dne,gne,kne,Nne,Cne,_ne,Fne,Mne,Lne,Bne,Une,Hne,jne,Yne,Jne,nae,rae,oae,pae,dae,gae,vae,Sae,Cae,Aae,Fae,Dae,Mae,Pae,zae,Bae,Hae,Kae,Zae,Qae,nre,sre,ure,hre,dee,fre,pne,yre,wre,Sre,fee,Ere,$re,Rre,Lre,Bre,Hre,Kre,Jre,nse,sse,ose,cse,hse,fse,xse,wse,Ise,Nse,Cse,Fse,Mse,zse,jse,yee,Zse,eie,aie,iie,Kte,uie,cie,hie,gie,vie,bee,kie,Sie,Tie,Eie,_ie,Xte,Use,$ie,Oie,Wie,vee,Gie,jie,Zie,eoe,roe,ioe,uoe,doe,foe,yoe,woe,Soe,Eoe,Foe,Moe,Loe,Ote,Hse,Boe,Uoe,Hoe,joe,Xoe,Zoe,Qoe,tle,ale,ile,lle,ple,dle,fle,ble,xle,wle,Gse,Cee,Sle,Cle,_le,$le,Ole,zle,Eee,Ble,Ule,qle,pie];for(let e of jle)ed(e);var Qe;(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"})(Qe||(Qe={}));var Ac;(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"})(Ac||(Ac={}));var iF;function Kle(e){iF=e.wasm.cwrap(si,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Xle(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a,c=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let _=n.dataIdMap.get(i.dataId);if(_.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${_.shape.length}.`);m=_.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=Ac[p];if(g==null)throw new Error(`${p} activation not yet supported for FusedConv2D in the wasm backend.`);let b=l?r.shape[2]:r.shape[1],y=u?s.shape[1]:s.shape[2],x=Ju.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)),v=n.makeOutput([...x,b,y],r.dtype),I=n.dataIdMap.get(v.dataId).id,N=new Uint8Array(new Int32Array(r.shape).buffer),C=new Uint8Array(new Int32Array(s.shape).buffer);return iF(c,N,r.shape.length,h,C,s.shape.length,l,u,g,m,f,d||0,I),v}var Yle={kernelName:si,backendName:"wasm",setupFunc:Kle,kernelFunc:Xle};function Xe(e,t){let n;function a(s){n=s.wasm.cwrap(e,null,["number","number","number"])}function r(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),p=i.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||n(l,Qe[o.dtype],p),u}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:r}}var Zle=Xe(Yl),Jle=Xe(Ni),Qle=Xe(Ti);function Ut(e,t,n){let a;function r(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:p}=l,d=o.dataIdMap.get(u.dataId).id,c=o.dataIdMap.get(p.dataId).id,h=n!=null?n:u.dtype,m=T.assertAndGetBroadcastShape(u.shape,p.shape),f=o.makeOutput(m,h);if(w.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(u.shape).buffer),b=new Uint8Array(new Int32Array(p.shape).buffer),y=o.dataIdMap.get(f.dataId).id;return a(d,g,u.shape.length,c,b,p.shape.length,Qe[u.dtype],y),f}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var eue=!0,tue=Ut(xs,eue),oF;function nue(e){oF=e.wasm.cwrap(Ci,null,["array","number","number","number"])}function aue(e){let{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(a.shape)===0)return a;let r=t.map(o=>n.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(r).buffer),i=n.dataIdMap.get(a.dataId).id;return oF(s,r.length,Qe[a.dtype],i),a}var rue={kernelName:Ci,backendName:"wasm",setupFunc:nue,kernelFunc:aue};function Uf(e){let{inputs:{x:t},backend:n}=e;if(t.dtype==="string")return bn(n.readSync(t.dataId),t.shape,t.dtype);let a=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(r),a}var sue={kernelName:eo,backendName:"wasm",kernelFunc:Uf},lF;function iue(e){lF=e.wasm.cwrap(Tr,null,["number","array","number","number","number","array","number"])}function bs(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=lue(t.x.shape,a.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=oue(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=Uf({inputs:t,backend:n});return m.shape=o,m}let u=n.makeOutput(o,l.dtype),p=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(u.dataId).id,c=new Uint8Array(new Int32Array(s).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return lF(p,h,l.shape.length,Qe[l.dtype],d,c,s.length),u}function oue(e,t){let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];return n}function lue(e,t){let n=[],a=[];for(let r=0;r<e.length;++r)e[r]!==1&&n.push(e[r]),e[t[r]]!==1&&a.push(t[r]);for(let r=0;r<a.length;++r){let s=-1;for(let i=0;i<a.length;++i)a[i]>=r&&(s===-1||a[s]>a[i])&&(s=i);a[s]=r}return[n,a]}var uue={kernelName:Tr,backendName:"wasm",kernelFunc:bs,setupFunc:iue};function $s(e,t,n){let a=e.shape,r=e.shape.length,s=w.parseAxisParam(t,a),i=s,o=T.getAxesPermutation(i,r),l=null,u=!1;if(o!=null){let p=new Array(r);for(let c=0;c<p.length;c++)p[c]=a[o[c]];i=T.getInnerMostAxes(i.length,r),l=bs({inputs:{x:e},attrs:{perm:o},backend:n});let d=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==d&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var uF;function pue(e){uF=e.wasm.cwrap(Zl,null,["number, number, number"])}function cue(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=$s(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;T.assertAxesAreInnerMostDims("all",p,h);let[m,f]=T.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;uF(o,g,y)}if(c&&t.disposeData(u.dataId),s){let y=T.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var due={kernelName:Zl,backendName:"wasm",setupFunc:pue,kernelFunc:cue},pF;function hue(e){pF=e.wasm.cwrap(Jl,null,["number, number, number"])}function mue(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=$s(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;T.assertAxesAreInnerMostDims("any",p,h);let[m,f]=T.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;pF(o,g,y)}if(c&&t.disposeData(u.dataId),s){let y=T.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var fue={kernelName:Jl,backendName:"wasm",setupFunc:hue,kernelFunc:mue};function cF(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number","number","number","number"])}function a(r){let{backend:s,inputs:i,attrs:o}=r,{axis:l}=o,{x:u}=i,p=s.dataIdMap.get(u.dataId).id,d=p,c=u,{transposed:h,axes:m,inputWasTransposed:f}=$s(u,l,s);if(f){let I=s.dataIdMap.get(h.dataId).id;I!==p&&(c=h,d=I)}let g=c.shape.slice(0,-1),b=s.makeOutput(g,"int32"),y=s.dataIdMap.get(b.dataId).id,x=w.sizeFromShape(b.shape),v=c.shape[m[0]];return t(d,Qe[c.dtype],x,v,y),f&&s.disposeData(h.dataId),b}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var gue=cF(Ql),bue=cF(eu),yue=Xe(Ei),xue=Xe(_i),vue=Xe(Ai),wue=Ut($i,!1),kue=Xe(Fi),dF;function Iue(e){dF=e.wasm.cwrap(Di,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Sue(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,p=T.computePool2DInfo(r.shape,i,o,1,l,u),d=p.filterHeight,c=p.filterWidth,h=p.padInfo.top,m=p.padInfo.right,f=p.padInfo.bottom,g=p.padInfo.left,b=p.strideHeight,y=p.strideWidth,x=p.inChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);if(p.dilationWidth!==1||p.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${p.dilationHeight}, ${p.dilationWidth}].`);let v=a.makeOutput(p.outShape,"float32"),I=a.dataIdMap.get(v.dataId).id;return dF(s,r.shape[0],r.shape[1],r.shape[2],d,c,h,m,f,g,b,y,x,I),v}var Nue={kernelName:Di,backendName:"wasm",setupFunc:Iue,kernelFunc:Sue},hF;function Tue(e){hF=e.wasm.cwrap("AvgPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Cue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.makeOutput(p.outShape,r.dtype);return hF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var Eue={kernelName:tu,backendName:"wasm",setupFunc:Tue,kernelFunc:Cue},mF;function _ue(e){mF=e.wasm.cwrap("AvgPool3DGrad",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"])}function Aue(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=T.computePool3DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return mF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left,p.filterDepth,p.filterHeight,p.filterWidth),d}var Fue={kernelName:Rc,backendName:"wasm",setupFunc:_ue,kernelFunc:Aue},fF;function $ue(e){fF=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Due(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l}=a,u=T.computePool2DInfo(s.shape,i,o,1,l),p=n.makeOutput(s.shape,s.dtype);return fF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left,u.filterHeight,u.filterWidth),p}var Rue={kernelName:Dc,backendName:"wasm",setupFunc:$ue,kernelFunc:Due};function Ln(e){let{inputs:t,attrs:n}=e,{x:a}=t,{shape:r}=n,s=w.sizeFromShape(a.shape),i=w.inferFromImplicitShape(r,s);return w.assert(s===w.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var Mue={kernelName:Ru,backendName:"wasm",kernelFunc:Ln},gF;function Oue(e){gF=e.wasm.cwrap(Ri,null,["number","array","number","number","array","number","number","number","number"])}function Pue(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],d=o?s.shape[u-1]:s.shape[u-2],c=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=w.sizeFromShape(m),b=w.sizeFromShape(f),y=Ju.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([c,h]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,p,c]:[g,c,p],v=o?[b,h,d]:[b,d,h],I=Ln({inputs:{x:r},backend:n,attrs:{shape:x}}),N=Ln({inputs:{x:s},backend:n,attrs:{shape:v}}),C=n.dataIdMap.get(I.dataId).id,_=n.dataIdMap.get(N.dataId).id,F=i?I.shape[2]:I.shape[1],D=o?N.shape[1]:N.shape[2],$=Math.max(g,b),S=n.makeOutput([$,F,D],I.dtype),M=n.dataIdMap.get(S.dataId).id,B=new Uint8Array(new Int32Array(I.shape).buffer),U=new Uint8Array(new Int32Array(N.shape).buffer);return gF(C,B,I.shape.length,_,U,N.shape.length,i,o,M),n.disposeData(I.dataId),n.disposeData(N.dataId),S.shape=y,S}var Lue={kernelName:Ri,backendName:"wasm",setupFunc:Oue,kernelFunc:Pue};function Ii(e){let{inputs:{x:t},attrs:{begin:n,size:a},backend:r}=e,[s,i]=Kt.parseSliceParams(t,n,a),o=Kt.isSliceContinous(t.shape,s,i),l=r.readSync(t.dataId),u=r.makeOutput(i,t.dtype),p=w.computeStrides(t.shape),d=r.dataIdMap.get(u.dataId);if(o){let m=Kt.computeFlatOffset(s,p);return t.dtype==="string"?d.stringBytes=l.slice(m,m+w.sizeFromShape(i)):r.typedArrayFromHeap(u).set(l.subarray(m,m+w.sizeFromShape(i))),u}if(t.dtype==="string"){let m=um(l,s,i,t.shape,t.dtype);return d.stringBytes=m,u}let c=r.typedArrayFromHeap(u),h=t.shape.length;if(h===2)zue(l,p[0],c,s,i);else if(h===3)Wue(l,p[0],p[1],c,s,i);else if(h===4)Bue(l,p[0],p[1],p[2],c,s,i);else{let m=um(l,s,i,t.shape,t.dtype);c.set(m)}return u}function zue(e,t,n,a,r){let s=0,i=a[0],o=a[1],l=i+r[0];for(let u=i;u<l;u++){let p=u*t+o;n.set(e.subarray(p,p+r[1]),s),s+=r[1]}}function Wue(e,t,n,a,r,s){let i=0,o=r[0],l=r[1],u=r[2],p=o+s[0],d=l+s[1];for(let c=o;c<p;c++)for(let h=l;h<d;h++){let m=c*t+h*n+u;a.set(e.subarray(m,m+s[2]),i),i+=s[2]}}function Bue(e,t,n,a,r,s,i){let o=0,l=s[0],u=s[1],p=s[2],d=l+i[0],c=u+i[1],h=p+i[2],m=s[3];for(let f=l;f<d;f++)for(let g=u;g<c;g++)for(let b=p;b<h;b++){let y=f*t+g*n+b*a+m;r.set(e.subarray(y,y+i[3]),o),o+=i[3]}}var Vue={kernelName:Bu,backendName:"wasm",kernelFunc:Ii};function Uue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a,o=s.reduce((b,y)=>b*y),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),d=T.getSliceBeginCoords(i,s.length),c=T.getSliceSize(p,i,s.length),h=Ln({inputs:{x:r},backend:n,attrs:{shape:l}}),m=bs({inputs:{x:h},backend:n,attrs:{perm:u}}),f=Ln({inputs:{x:m},backend:n,attrs:{shape:p}}),g=Ii({inputs:{x:f},backend:n,attrs:{begin:d,size:c}});return n.disposeData(h.dataId),n.disposeData(m.dataId),n.disposeData(f.dataId),g}var Gue={kernelName:nu,backendName:"wasm",kernelFunc:Uue},bF;function Hue(e){bF=e.wasm.cwrap(au,null,["number","number","boolean","number","number","number"])}function que(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,weights:s}=n,{size:i}=a,o=s.shape.reduce((d,c)=>d*c,1)!==0,l=r.shape.length===1?[i]:[r.shape[0],i],u=t.makeOutput(l,s.dtype);function p(d){return t.dataIdMap.get(d.dataId).id}return bF(p(r),i,o,p(s),Qe[s.dtype],p(u)),u}var jue={kernelName:au,backendName:"wasm",setupFunc:Hue,kernelFunc:que},Kue=!0,Xue=Ut(ru,Kue);function Yue(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.typedArrayFromHeap(a),i=n.typedArrayFromHeap(r),o=T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeOutput([o.length],"int32",void 0,new Int32Array(o))}var Zue={kernelName:Mc,backendName:"wasm",kernelFunc:Yue};function Ds(e){let{inputs:{x:t},attrs:{dtype:n},backend:a}=e,r=a.makeOutput(t.shape,n),s=a.typedArrayFromHeap(t);return a.typedArrayFromHeap(r).set(s),r}var Jue={kernelName:Mi,backendName:"wasm",kernelFunc:Ds},Que=Xe(Oi),yF;function epe(e){yF=e.wasm.cwrap(vs,null,["number","number","number","number"])}function tpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(l.dataId).id;return yF(o,s,i,u),l}var npe={kernelName:vs,backendName:"wasm",setupFunc:epe,kernelFunc:tpe};function xF(e){let{inputs:t,backend:n}=e,a=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=t.map(h=>h.shape);T.assertParamsConsistent(r,a);let s=T.computeOutShape(t.map(h=>h.shape),a),i=t.filter(h=>w.sizeFromShape(h.shape)>0);if(i.length===1)return Uf({inputs:{x:i[0]},backend:n});let o=n.makeOutput(s,t[0].dtype);if(w.sizeFromShape(s)===0)return o;if(i[0].dtype==="string"){let h=i.map(x=>{let v=[-1,w.sizeFromShape(x.shape.slice(a))];return Ln({inputs:{x},backend:n,attrs:{shape:v}})}),m=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));s=T.computeOutShape(h.map(x=>x.shape),1);let f=h[0].shape[0]===1,g=L1(m,s,t[0].dtype,f),b=T.computeOutShape(i.map(x=>x.shape),a);o.shape=b;let y=n.dataIdMap.get(o.dataId);return y.stringBytes=T.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),o}let l=w.sizeFromShape(i[0].shape.slice(0,a)),u=0,p=i.map(h=>{let m=w.sizeFromShape(h.shape.slice(a));return u+=m,m}),d=i.map(h=>n.typedArrayFromHeap(h)),c=n.typedArrayFromHeap(o);for(let h=0;h<l;h++){let m=h*u;for(let f=0;f<d.length;f++){let g=p[f],b=h*g,y=d[f].subarray(b,b+g);c.set(y,m),m+=g}}return o}var ape={kernelName:su,backendName:"wasm",kernelFunc:xF},vF;function rpe(e){vF=e.wasm.cwrap(Pi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function spe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:d,dataFormat:c}=n,h=T.convertConv2DDataFormat(c),m=T.computeConv2DInfo(r.shape,s.shape,l,u,p,d,!1,h),f=m.filterHeight,g=m.filterWidth,b=m.padInfo.top,y=m.padInfo.right,x=m.padInfo.bottom,v=m.padInfo.left,I=m.dilationHeight,N=m.dilationWidth,C=m.strideHeight,_=m.strideWidth,F=m.inChannels,D=m.outChannels,$=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let S=a.makeOutput(m.outShape,"float32"),M=a.dataIdMap.get(S.dataId).id;return vF(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,b,y,x,v,$,I,N,C,_,F,D,M),S}var ipe={kernelName:Pi,backendName:"wasm",setupFunc:rpe,kernelFunc:spe},wF;function ope(e){wF=e.wasm.cwrap(Li,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 lpe(e){let{backend:t,inputs:n,attrs:a}=e,{dy:r,filter:s}=n,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:p}=a,d=1,c=T.convertConv2DDataFormat(l),h=T.computeConv2DInfo(p,s.shape,i,d,o,u,!1,c),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:b,inHeight:y,inWidth:x,outChannels:v,outHeight:I,outWidth:N,strideHeight:C,strideWidth:_}=h,F=f-1-h.padInfo.top,D=g-1-h.padInfo.left,$=h.dataFormat==="channelsLast",S=w.computeStrides(h.inShape),M=w.computeStrides(r.shape),[B,U,H]=w.computeStrides(s.shape),j=S[0],K=$?S[1]:S[2],Z=$?S[2]:1,J=$?1:S[1],ee=M[0],ae=$?M[1]:M[2],te=$?M[2]:1,se=$?1:M[1],ie=t.makeOutput(h.inShape,"float32"),xe=t.dataIdMap.get(ie.dataId).id,ue=t.dataIdMap.get(r.dataId).id,ye=t.dataIdMap.get(s.dataId).id;return wF(ue,ye,m,f,g,y,x,b,I,N,v,C,_,F,D,B,U,H,j,K,Z,J,ee,ae,te,se,xe),ie}var upe={kernelName:Li,backendName:"wasm",setupFunc:ope,kernelFunc:lpe},kF;function ppe(e){kF=e.wasm.cwrap(zi,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"])}function cpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor x must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=T.computeConv3DInfo(r.shape,s.shape,i,l,o),p=n.makeOutput(u.outShape,r.dtype);return kF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var dpe={kernelName:zi,backendName:"wasm",setupFunc:ppe,kernelFunc:cpe},IF;function hpe(e){IF=e.wasm.cwrap(iu,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"])}function mpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=T.computeConv3DInfo(r.shape,l,i,1,o),p=n.makeOutput(u.filterShape,s.dtype);return IF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var fpe={kernelName:iu,backendName:"wasm",setupFunc:hpe,kernelFunc:mpe},SF;function gpe(e){SF=e.wasm.cwrap(ou,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"])}function bpe(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=T.computeConv3DInfo(l,s.shape,o,1,i),p=n.makeOutput(u.inShape,r.dtype);return SF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(p.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),p}var ype={kernelName:ou,backendName:"wasm",setupFunc:gpe,kernelFunc:bpe},xpe=Xe(Wi),vpe=Xe(Bi),gv;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(gv||(gv={}));var NF;function wpe(e){NF=e.wasm.cwrap(uu,null,["number","number","number","number","array","number","number","number","number","number"])}function kpe(e){let{backend:t,inputs:n,attrs:a}=e,{method:r,extrapolationValue:s,cropSize:i}=a,{image:o,boxes:l,boxInd:u}=n,p=l.shape[0],[d,c]=i,h=[p,d,c,o.shape[3]],m=t.dataIdMap.get(o.dataId),f;o.dtype!=="float32"&&(f=Ds({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));let g=m.id,b=t.dataIdMap.get(l.dataId).id,y=t.dataIdMap.get(u.dataId).id,x=t.makeOutput(h,"float32"),v=t.dataIdMap.get(x.dataId).id,I=new Uint8Array(new Int32Array(o.shape).buffer);return NF(g,b,y,p,I,d,c,gv[r],s,v),f!=null&&t.disposeData(f.dataId),x}var Ipe={kernelName:uu,backendName:"wasm",setupFunc:wpe,kernelFunc:kpe},TF;function Spe(e){TF=e.wasm.cwrap(lu,null,["number","number","number","number","number","number"])}function Npe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;w.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumprod does not support ${r.dtype} tensors in the WASM backend`);let u=T.getAxesPermutation([s],l),p=r;u!==null&&(p=bs({inputs:{x:r},attrs:{perm:u},backend:n}));let d=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumprod",[d],l);let c=n.makeOutput(p.shape,p.dtype),h=p.shape[d],m=n.dataIdMap.get(p.dataId).id,f=n.dataIdMap.get(c.dataId).id;TF(m,i?1:0,o?1:0,h,f,Qe[r.dtype]);let g=c;if(u!==null){let b=T.getUndoAxesPermutation(u);g=bs({inputs:{x:c},attrs:{perm:b},backend:n}),n.disposeData(p.dataId),n.disposeData(c.dataId)}return g}var Tpe={kernelName:lu,backendName:"wasm",setupFunc:Spe,kernelFunc:Npe},CF;function Cpe(e){CF=e.wasm.cwrap(Vi,null,["number","number","number","number","number","number"])}function Epe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length;w.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let u=T.getAxesPermutation([s],l),p=r;u!==null&&(p=bs({inputs:{x:r},attrs:{perm:u},backend:n}));let d=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumsum",[d],l);let c=n.makeOutput(p.shape,p.dtype),h=p.shape[d],m=n.dataIdMap.get(p.dataId).id,f=n.dataIdMap.get(c.dataId).id;CF(m,i?1:0,o?1:0,h,f,Qe[r.dtype]);let g=c;if(u!==null){let b=T.getUndoAxesPermutation(u);g=bs({inputs:{x:c},attrs:{perm:b},backend:n}),n.disposeData(p.dataId),n.disposeData(c.dataId)}return g}var _pe={kernelName:Vi,backendName:"wasm",setupFunc:Cpe,kernelFunc:Epe},EF;function Ape(e){EF=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function Fpe(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,weights:s}=n,{size:i,binaryOutput:o}=a,l=s.shape.reduce((c,h)=>c*h,1)!==0,u=r.shape.length===1?[i]:[r.shape[0],i],p=t.makeOutput(u,s.dtype);function d(c){return t.dataIdMap.get(c.dataId).id}return EF(d(r),new Uint8Array(new Int32Array(r.shape).buffer),r.shape.length,i,l,d(s),Qe[s.dtype],o,d(p)),p}var $pe={kernelName:Pc,backendName:"wasm",setupFunc:Ape,kernelFunc:Fpe},_F;function Dpe(e){_F=e.wasm.cwrap(pu,null,["number","number","number","array","number","array","array","number","number"])}function Rpe(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{blockSize:s,dataFormat:i}=a,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],d=l*s,c=u*s,h=p/(s*s),m=i==="NHWC"?[o,d,c,h]:[o,h,d,c],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(r.dataId).id,b=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),y=new Uint8Array(new Int32Array(m).buffer),x=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer),v=t.dataIdMap.get(f.dataId).id;return _F(g,s,i==="NHWC"?1:0,b,r.shape.length-1,y,x,m.length,v),f}var Mpe={kernelName:pu,backendName:"wasm",setupFunc:Dpe,kernelFunc:Rpe},AF;function Ope(e){AF=e.wasm.cwrap(Ui,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Ppe(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:d}=n,c=u==null?[1,1]:u,h=T.computeConv2DInfo(r.shape,s.shape,l,c,p,d,!0),m=h.filterHeight,f=h.filterWidth,g=h.padInfo.top,b=h.padInfo.right,y=h.padInfo.bottom,x=h.padInfo.left,v=h.dilationHeight,I=h.dilationWidth,N=h.strideHeight,C=h.strideWidth,_=h.inChannels,F=h.outChannels,D=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 $=a.makeOutput(h.outShape,"float32"),S=a.dataIdMap.get($.dataId).id;return AF(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,b,y,x,D,v,I,N,C,_,F,S),$}var Lpe={kernelName:Ui,backendName:"wasm",setupFunc:Ope,kernelFunc:Ppe},FF;function zpe(e){FF=e.wasm.cwrap("Diag",null,["number","number","number","number"])}function Wpe(e){let{inputs:t,backend:n}=e,{x:a}=t,r=w.sizeFromShape(a.shape),s=n.makeOutput([...a.shape,...a.shape],a.dtype);return FF(n.dataIdMap.get(a.dataId).id,Qe[a.dtype],r,n.dataIdMap.get(s.dataId).id),s}var Bpe={kernelName:Lc,backendName:"wasm",setupFunc:zpe,kernelFunc:Wpe},$F;function Vpe(e){$F=e.wasm.cwrap(Gi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Upe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a;if(r.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${r.dtype} and ${s.dtype}`);let u=T.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p=n.makeOutput(u.outShape,r.dtype);return $F(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(p.dataId).id,Qe[r.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),p}var Gpe={kernelName:Gi,backendName:"wasm",setupFunc:Vpe,kernelFunc:Upe},DF;function Hpe(e){DF=e.wasm.cwrap(Rl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function qpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=a;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let p=T.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),d=n.makeOutput(s.shape,s.dtype);return DF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,Qe[r.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),d}var jpe={kernelName:Rl,backendName:"wasm",setupFunc:Hpe,kernelFunc:qpe},RF;function Kpe(e){RF=e.wasm.cwrap(Dl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Xpe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=a;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let p=T.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),d=n.makeOutput(r.shape,r.dtype);return RF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,Qe[r.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),d}var Ype={kernelName:Dl,backendName:"wasm",setupFunc:Kpe,kernelFunc:Xpe},Zpe=Xe(qi),MF;function Jpe(e){MF=e.wasm.cwrap(cu,null,["number","number","number"])}function Qpe(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=n.makeOutput(r.shape,"float32"),i=o=>n.dataIdMap.get(o.dataId).id;return MF(i(r),i(a),i(s)),s}var ece={kernelName:cu,backendName:"wasm",setupFunc:Jpe,kernelFunc:Qpe},tce=!1,nce=Ut(du,tce,"bool"),ace=Xe(ji),rce=Xe(Ki,"float32");function bv(e){let{inputs:t,attrs:n,backend:a}=e,{input:r}=t,{dim:s}=n,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Ln({inputs:{x:r},backend:a,attrs:{shape:o}})}var sce={kernelName:hu,backendName:"wasm",kernelFunc:bv},ice=Xe(Xi,"float32");function OF(e){let{attrs:{shape:t,value:n},backend:a}=e,{attrs:{dtype:r}}=e;r=r||w.inferDtype(n);let s=a.makeOutput(t,r);return a.typedArrayFromHeap(s).fill(n),s}var oce={kernelName:zc,backendName:"wasm",kernelFunc:OF},PF;function lce(e){PF=e.wasm.cwrap(mu,null,["number","number","number","number","number","number"])}function uce(e){let{inputs:t,backend:n}=e,{image:a}=t,r=n.makeOutput(a.shape,a.dtype),s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,[o,l,u,p]=a.shape;return PF(s,o,l,u,p,i),r}var pce={kernelName:mu,backendName:"wasm",kernelFunc:uce,setupFunc:lce},cce=Xe(Yi),dce=!1,hce=Ut(Zi,dce),LF;function mce(e){LF=e.wasm.cwrap(Ji,null,["number","number","number","number","number","number","number"])}function fce(e){let{backend:t,inputs:n,attrs:a}=e,{varianceEpsilon:r}=a,{x:s,mean:i,variance:o,offset:l,scale:u}=n,p=t.dataIdMap.get(s.dataId).id,d=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(o.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,m=u!=null?t.dataIdMap.get(u.dataId).id:0,f=t.makeOutput(s.shape,s.dtype);if(w.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return LF(p,d,c,h,m,r,g),f}var gce={kernelName:Ji,backendName:"wasm",setupFunc:mce,kernelFunc:fce},zF;function bce(e){zF=e.wasm.cwrap(ii,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 yce(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=n,f=T.computeConv2DInfo(r.shape,s.shape,l,p,u,c),g=Ac[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let b=a.dataIdMap.get(r.dataId).id,y=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let I=f.filterHeight,N=f.filterWidth,C=f.padInfo.top,_=f.padInfo.right,F=f.padInfo.bottom,D=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,M=f.strideHeight,B=f.strideWidth,U=f.inChannels,H=f.padInfo.type==="SAME"?1:0,j=f.batchSize,K=f.inHeight,Z=f.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(J.dataId).id,ae=o==null?0:a.dataIdMap.get(o.dataId).id;return zF(b,j,K,Z,y,I,N,v,C,_,F,D,H,$,S,M,B,U,x,g,ae,m||0,ee),J}var xce={kernelName:ii,backendName:"wasm",setupFunc:bce,kernelFunc:yce},WF;function vce(e){WF=e.wasm.cwrap(oi,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 wce(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=n,f=T.computeConv2DInfo(r.shape,s.shape,l,p,u,c,!0),g=Ac[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let b=a.dataIdMap.get(r.dataId).id,y=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let I=f.filterHeight,N=f.filterWidth,C=f.padInfo.top,_=f.padInfo.right,F=f.padInfo.bottom,D=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,M=f.strideHeight,B=f.strideWidth,U=f.inChannels,H=f.padInfo.type==="SAME"?1:0,j=f.batchSize,K=f.inHeight,Z=f.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=a.makeOutput(f.outShape,"float32"),ee=a.dataIdMap.get(J.dataId).id,ae=o==null?0:a.dataIdMap.get(o.dataId).id;return WF(b,j,K,Z,y,I,N,v,C,_,F,D,H,$,S,M,B,U,x,g,ae,m||0,ee),J}var kce={kernelName:oi,backendName:"wasm",setupFunc:vce,kernelFunc:wce},BF;function Ice(e){BF=e.wasm.cwrap(gu,null,["number","number","number","number","number","number","array","number"])}function Sce(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=Yw.prepareAndValidate(a,r),u=t.makeOutput(s,a.dtype);if(i===0)return u;let p=r.shape,d=p[p.length-1],c=t.dataIdMap.get(a.dataId).id,h=t.dataIdMap.get(r.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(u.dataId).id;return BF(c,Qe[a.dtype],h,i,d,o,m,f),u}var Nce={kernelName:gu,backendName:"wasm",setupFunc:Ice,kernelFunc:Sce},VF;function Tce(e){VF=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Cce(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,indices:s}=n,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0],u=t.readSync(s.dataId),p=r.shape[l];for(let C=0;C<u.length;++C){let _=u[C];w.assert(_<=p-1&&_>=0,()=>`GatherV2: the index value ${_} is not in [0, ${p-1}]`)}let d=T.segment_util.collectGatherOpShapeInfo(r,s,l,o),c=Ln({inputs:{x:r},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=w.sizeFromShape(s.shape),m=Ln({inputs:{x:s},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),f=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(f,r.dtype);if(w.sizeFromShape(r.shape)===0)return g;let b=c.shape.length-1,y=t.dataIdMap.get(c.dataId).id,x=t.dataIdMap.get(m.dataId).id,v=t.dataIdMap.get(g.dataId).id,I=new Uint8Array(new Int32Array(w.computeStrides(c.shape)).buffer),N=new Uint8Array(new Int32Array(w.computeStrides(f)).buffer);return VF(y,Qe[r.dtype],I,b,x,d.batchSize,N,v),t.disposeData(c.dataId),t.disposeData(m.dataId),g.shape=d.outputShape,g}var Ece={kernelName:fu,backendName:"wasm",setupFunc:Tce,kernelFunc:Cce},_ce=!1,Ace=Ut(bu,_ce,"bool"),Fce=!1,$ce=Ut(Qi,Fce,"bool"),Dce=Xe(to,"bool"),Rce=Xe(no,"bool"),Mce=Xe(ao,"bool"),UF;function Oce(e){UF=e.wasm.cwrap(ro,null,["number","number","number","number"])}function Pce(e){let{inputs:{x:t},attrs:{alpha:n},backend:a}=e,r=a.dataIdMap.get(t.dataId).id,s=a.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let i=a.dataIdMap.get(s.dataId).id;UF(r,Qe[t.dtype],n,i)}return s}var Lce={kernelName:ro,backendName:"wasm",setupFunc:Oce,kernelFunc:Pce},zce=!1,Wce=Ut(yu,zce,"bool"),Bce=!1,Vce=Ut(xu,Bce,"bool"),GF;function Uce(e){GF=e.wasm.cwrap(vu,null,["number","number","number","number"])}function Gce(e){let{attrs:t,backend:n}=e,{start:a,stop:r,num:s}=t,i=Math.floor(s),o=n.makeOutput([i],"float32");return GF(n.dataIdMap.get(o.dataId).id,a,r,i),o}var Hce={kernelName:vu,backendName:"wasm",setupFunc:Uce,kernelFunc:Gce},qce=Xe(so),jce=Xe(io),Kce=!1,Xce=Ut(wu,Kce,"bool"),Yce=Xe(ku),Zce=!1,Jce=Ut(Iu,Zce,"bool"),Qce=!1,ede=Ut(qS,Qce,"bool"),HF;function tde(e){HF=e.wasm.cwrap(oo,null,["number","number","number","number","number","number","number"])}function nde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;if(r.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");let u=n.makeOutput(r.shape,r.dtype);return HF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(u.dataId).id,r.shape[3],s,i,o,l),u}var ade={kernelName:oo,backendName:"wasm",setupFunc:tde,kernelFunc:nde},qF;function rde(e){qF=e.wasm.cwrap(Su,null,["number","number","number","number","number","number","number","number","number"])}function sde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a;if(r.dtype!=="float32"||s.dtype!=="float32"||i.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");let d=n.makeOutput(r.shape,r.dtype);return qF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,i.shape[3],o,l,u,p),d}var ide={kernelName:Su,backendName:"wasm",setupFunc:rde,kernelFunc:sde},jF;function ode(e){jF=e.wasm.cwrap(lo,null,["number","number","number","number"])}function lde(e){let{backend:t,inputs:n,attrs:a}=e,{reductionIndices:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:d,inputWasTransposed:c}=$s(i,r,t);if(c){let y=t.dataIdMap.get(u.dataId).id;l=u,o=y}let h=l.shape.length;T.assertAxesAreInnerMostDims("max",p,h);let[m,f]=T.computeOutAndReduceShapes(l.shape,p),g=w.sizeFromShape(f),b=t.makeOutput(m,i.dtype);if(w.sizeFromShape(l.shape)!==0){let y=t.dataIdMap.get(b.dataId).id;jF(o,Qe[i.dtype],g,y)}if(c&&t.disposeData(u.dataId),s){let y=T.expandShapeToKeepDim(b.shape,d);b.shape=y}return b}var ude={kernelName:lo,backendName:"wasm",setupFunc:ode,kernelFunc:lde},pde=!1,cde=Ut(uo,pde),KF;function dde(e){KF=e.wasm.cwrap(po,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function hde(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id;w.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,p=T.computePool2DInfo(r.shape,i,o,1,l,u),d=p.filterHeight,c=p.filterWidth,h=p.padInfo.top,m=p.padInfo.right,f=p.padInfo.bottom,g=p.padInfo.left,b=p.dilationHeight,y=p.dilationWidth,x=p.strideHeight,v=p.strideWidth,I=p.inChannels,N=p.outChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);let C=a.makeOutput(p.outShape,"float32"),_=a.dataIdMap.get(C.dataId).id;return KF(s,r.shape[0],r.shape[1],r.shape[2],d,c,h,m,f,g,b,y,x,v,I,N,_),C}var mde={kernelName:po,backendName:"wasm",setupFunc:dde,kernelFunc:hde},XF;function fde(e){XF=e.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function gde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),d=n.makeOutput(p.outShape,r.dtype);return XF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var bde={kernelName:Nu,backendName:"wasm",setupFunc:fde,kernelFunc:gde},YF;function yde(e){YF=e.wasm.cwrap("MaxPool3DGrad",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 xde(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=T.computePool3DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return YF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inDepth,p.inHeight,p.inWidth,p.outDepth,p.outHeight,p.outWidth,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),d}var vde={kernelName:Bc,backendName:"wasm",setupFunc:yde,kernelFunc:xde},ZF;function wde(e){ZF=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function kde(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=T.computePool2DInfo(s.shape,i,o,1,l,u),d=n.makeOutput(s.shape,s.dtype);return ZF(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left),d}var Ide={kernelName:Wc,backendName:"wasm",setupFunc:wde,kernelFunc:kde},JF;function Sde(e){JF=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Nde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,includeBatchInIndex:l}=a;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];w.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,[1,1],o),d=n.makeOutput(p.outShape,r.dtype),c=n.makeOutput(p.outShape,"int32");return JF(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(d.dataId).id,n.dataIdMap.get(c.dataId).id,Qe[r.dtype],l,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left),[d,c]}var Tde={kernelName:Vc,backendName:"wasm",setupFunc:Sde,kernelFunc:Nde},QF;function Cde(e){QF=e.wasm.cwrap(co,null,["number, number, number"])}function Ede(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=$s(i,r,t),m=d;if(h){let v=t.dataIdMap.get(p.dataId).id;v!==o&&(u=p,l=v,m=T.getInnerMostAxes(m.length,u.shape.length))}T.assertAxesAreInnerMostDims("mean",m,u.shape.length);let[f,g]=T.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=u;u.dtype!=="float32"&&(y=Ds({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(y.dataId).id);let x=t.makeOutput(f,"float32");if(w.sizeFromShape(u.shape)!==0){let v=t.dataIdMap.get(x.dataId).id;QF(l,b,v)}if(h&&t.disposeData(p.dataId),s){let v=T.expandShapeToKeepDim(x.shape,c);x.shape=v}return u.dtype!=="float32"&&t.disposeData(y.dataId),x}var _de={kernelName:co,backendName:"wasm",setupFunc:Cde,kernelFunc:Ede},e$;function Ade(e){e$=e.wasm.cwrap(ho,null,["number","number","number","number"])}function Fde(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=$s(i,r,t);if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x)}let m=u.shape.length;T.assertAxesAreInnerMostDims("min",d,m);let[f,g]=T.computeOutAndReduceShapes(u.shape,d),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;e$(l,Qe[i.dtype],b,x)}if(h&&t.disposeData(p.dataId),s){let x=T.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var $de={kernelName:ho,backendName:"wasm",setupFunc:Ade,kernelFunc:Fde},Dde=!1,Rde=Ut(mo,Dde),yv;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(yv||(yv={}));var t$;function Mde(e){t$=e.wasm.cwrap(fo,null,["number","array","number","number","array","array","number","number"])}function Ode(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,mode:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]),i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map(m=>m[0]),d=a.map(m=>m[1]),c=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(d).buffer);return t$(i,u,t.shape.length,Qe[t.dtype],c,h,yv[r],l),o}var Pde={kernelName:fo,backendName:"wasm",kernelFunc:Ode,setupFunc:Mde},n$;function Lde(e){n$=e.wasm.cwrap(zo,null,["number","number","number","number"])}function a$(e){let{backend:t,inputs:{logits:n},attrs:{dim:a}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),i=t.dataIdMap.get(s.dataId).id,o=n.shape[a],l=w.sizeFromShape(n.shape)/o;return w.sizeFromShape(s.shape)===0||n$(r,i,o,l),s}var zde={kernelName:zo,backendName:"wasm",setupFunc:Lde,kernelFunc:a$},r$;function Wde(e){r$=e.wasm.cwrap(Tu,null,["number","number","number","number","number","number"])}function Bde(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;if(r.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${r.dtype}`);let l=o?r:a$({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),[u,p]=l.shape,d=n.makeOutput([u,s],"int32");return r$(n.dataIdMap.get(l.dataId).id,u,p,s,i,n.dataIdMap.get(d.dataId).id),o||n.disposeData(l.dataId),d}var Vde={kernelName:Tu,backendName:"wasm",setupFunc:Wde,kernelFunc:Bde},Ude=Ut(go,!0),Gde=!0,Hde=Ut(bo,Gde),qde=Xe(Cu);function hk(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),a=n[0],r=n[1],s=n[2],i=n[3];return e.wasm._free(t),{pSelectedIndices:a,selectedSize:r,pSelectedScores:s,pValidOutputs:i}}var s$;function jde(e){s$=e.wasm.cwrap(_u,"number",["number","number","number","number","number"])}function Kde(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i}=a,{boxes:o,scores:l}=n,u=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(l.dataId).id,d=s$(u,p,s,r,i),{pSelectedIndices:c,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=hk(t,d);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",c)}var Xde={kernelName:_u,backendName:"wasm",setupFunc:jde,kernelFunc:Kde},i$;function Yde(e){i$=e.wasm.cwrap(Au,"number",["number","number","number","number","number","bool"])}function Zde(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=a,{boxes:l,scores:u}=n,p=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(u.dataId).id,c=i$(p,d,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=hk(t,c);t.wasm._free(f);let b=t.makeOutput([m],"int32",h),y=t.makeOutput([],"int32",g);return[b,y]}var Jde={kernelName:Au,backendName:"wasm",setupFunc:Yde,kernelFunc:Zde},o$;function Qde(e){o$=e.wasm.cwrap(Fu,"number",["number","number","number","number","number","number"])}function ehe(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=a,{boxes:l,scores:u}=n,p=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(u.dataId).id,c=o$(p,d,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=hk(t,c);t.wasm._free(g);let b=t.makeOutput([m],"int32",h),y=t.makeOutput([m],"float32",f);return[b,y]}var the={kernelName:Fu,backendName:"wasm",setupFunc:Qde,kernelFunc:ehe},nhe=!1,ahe=Ut(Eu,nhe,"bool"),l$;function rhe(e){l$=e.wasm.cwrap(yo,null,["number","number","number","number","number"])}function she(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=a,u=n.makeOutput([...r.shape,i],s),p=n.dataIdMap.get(u.dataId).id,d=n.dataIdMap.get(r.dataId).id;return l$(d,i,o,l,p),u}var ihe={kernelName:yo,backendName:"wasm",setupFunc:rhe,kernelFunc:she};function ohe(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var lhe={kernelName:$u,backendName:"wasm",kernelFunc:ohe};function uhe(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return bv({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=bv({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=xF({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeData(p.dataId)),u}var phe={kernelName:Du,backendName:"wasm",kernelFunc:uhe},u$;function che(e){u$=e.wasm.cwrap(xo,null,["number","array","number","number","array","array","number","number"])}function dhe(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,constantValue:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]);if(w.sizeFromShape(t.shape)===0)return OF({backend:n,attrs:{shape:s,value:r,dtype:t.dtype}});let i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map(m=>m[0]),d=a.map(m=>m[1]),c=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(d).buffer);return u$(i,u,t.shape.length,Qe[t.dtype],c,h,r,l),o}var p$={kernelName:xo,backendName:"wasm",kernelFunc:dhe,setupFunc:che},hhe=!1,mhe=Ut(vo,hhe),c$;function fhe(e){c$=e.wasm.cwrap(wo,null,["number","number","number"])}function ghe(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,o=s,l=a,u=l;l.dtype!=="float32"&&(u=Ds({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),o=n.dataIdMap.get(u.dataId).id);let p=n.makeOutput(a.shape,"float32"),d=n.dataIdMap.get(p.dataId).id;return c$(o,i,d),l.dtype!=="float32"&&n.disposeData(u.dataId),p}var bhe={kernelName:wo,backendName:"wasm",setupFunc:fhe,kernelFunc:ghe},d$;function yhe(e){d$=e.wasm.cwrap(ko,null,["number","number","number","number"])}function xhe(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=$s(i,r,t),m=d;if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x,m=T.getInnerMostAxes(m.length,u.shape.length))}T.assertAxesAreInnerMostDims("prod",m,u.shape.length);let[f,g]=T.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;d$(l,b,Qe[y.dtype],x)}if(h&&t.disposeData(p.dataId),s){let x=T.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var vhe={kernelName:ko,backendName:"wasm",setupFunc:yhe,kernelFunc:xhe},whe=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=B1(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},khe={kernelName:Uc,backendName:"wasm",kernelFunc:whe},Ihe=!0,She=Ut(Hi,Ihe),Nhe=Xe(Io),The=Xe(So),Che=Xe(Co),h$;function Ehe(e){h$=e.wasm.cwrap(To,null,["number","number","number","number","number","number","number","number","number","number"])}function _he(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,[p,d,c,h]=r.shape,m=[p,l,u,h],f=t.dataIdMap.get(r.dataId),g;f.dtype!=="float32"&&(g=Ds({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let b=f.id,y=t.makeOutput(m,"float32");if(w.sizeFromShape(r.shape)===0)return y;let x=t.dataIdMap.get(y.dataId).id;return h$(b,p,d,c,h,l,u,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),y}var Ahe={kernelName:To,backendName:"wasm",setupFunc:Ehe,kernelFunc:_he},m$;function Fhe(e){m$=e.wasm.cwrap(Ou,null,["number","number","number","array","array","boolean"])}function $he(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=n.makeOutput(r.shape,"float32"),l=n.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Ds({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),m$(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&n.disposeData(u.dataId),o}var Dhe={kernelName:Ou,backendName:"wasm",setupFunc:Fhe,kernelFunc:$he},f$;function Rhe(e){f$=e.wasm.cwrap(No,null,["number","number","number","number","number","number","number","number","number","number"])}function Mhe(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,[p,d,c,h]=r.shape,m=[p,l,u,h],f=t.makeOutput(m,"float32");if(w.sizeFromShape(r.shape)===0)return f;let g=t.dataIdMap.get(r.dataId),b;g.dtype!=="float32"&&(b=Ds({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(b.dataId));let y=g.id,x=t.dataIdMap.get(f.dataId).id;return f$(y,p,d,c,h,l,u,s?1:0,i?1:0,x),b!=null&&t.disposeData(b.dataId),f}var Ohe={kernelName:No,backendName:"wasm",setupFunc:Rhe,kernelFunc:Mhe},g$;function Phe(e){g$=e.wasm.cwrap(Mu,null,["number","number","number","array","array","boolean"])}function Lhe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=n.makeOutput(r.shape,"float32"),l=n.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Ds({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),g$(n.dataIdMap.get(r.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&n.disposeData(u.dataId),o}var zhe={kernelName:Mu,backendName:"wasm",setupFunc:Phe,kernelFunc:Lhe},b$;function Whe(e){b$=e.wasm.cwrap(Eo,null,["number","array","number","array","number","number"])}function Bhe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=w.parseAxisParam(s,r.shape);if(r.shape.length===0)return Uf({inputs:{x:r},backend:n});let o=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(i).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);b$(l,p,i.length,d,r.shape.length,u);let c=Ln({inputs:{x:o},attrs:{shape:r.shape},backend:n});return n.disposeData(o.dataId),c}var Vhe={kernelName:Eo,backendName:"wasm",kernelFunc:Bhe,setupFunc:Whe},y$;function Uhe(e){y$=e.wasm.cwrap(Zu,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Ghe(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{radians:s,fillValue:i,center:o}=a,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(r.dataId).id,p=n.dataIdMap.get(l.dataId).id,[d,c,h,m]=r.shape,[f,g]=T.getImageCenter(o,c,h),b=i===0,y=255,x=typeof i=="number"?[i,i,i,b?0:y]:[...i,y],v=new Uint8Array(new Int32Array(x).buffer);return y$(u,d,c,h,m,s,f,g,v,x.length,p),l}var Hhe={kernelName:Zu,backendName:"wasm",kernelFunc:Ghe,setupFunc:Uhe},qhe=Xe(_o),jhe=Xe(Ao),x$;function Khe(e){x$=e.wasm.cwrap(Pu,null,["number","number","number","number","number","number","array","number","number"])}function Xhe(e){let{backend:t,inputs:n,attrs:a}=e,{indices:r,updates:s}=n,{shape:i}=a,o=t.makeOutput(i,s.dtype);if(w.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=rf.calculateShapes(s,r,i),h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(d).buffer),g=t.dataIdMap.get(o.dataId).id;return x$(h,m,Qe[s.dtype],l,u,p,f,c,g),o}var Yhe={kernelName:Pu,backendName:"wasm",setupFunc:Khe,kernelFunc:Xhe},v$;function Zhe(e){v$=e.wasm.cwrap(zu,null,["number","number","number","number","number","number","bool","number"])}function Jhe(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a;if(r.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${r.dtype} and ${s.dtype}`);let o=n.makeOutput(s.shape,"int32");function l(u){return n.dataIdMap.get(u.dataId).id}return v$(l(r),l(s),r.shape[0],r.shape[1],s.shape[1],Qe[r.dtype],i==="left",l(o)),o}var Qhe={kernelName:zu,backendName:"wasm",setupFunc:Zhe,kernelFunc:Jhe},w$;function eme(e){w$=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function tme(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(s.dataId).id,u=n.makeOutput(r.shape,r.dtype),p=n.dataIdMap.get(u.dataId).id,d=a.shape.length,c=r.shape.length,h=d===0||d>1||c===1?1:w.sizeFromShape(r.shape.slice(1));return w$(i,o,l,h,p),u}var nme={kernelName:Wu,backendName:"wasm",kernelFunc:tme,setupFunc:eme},ame=Xe(Fo),k$;function rme(e){k$=e.wasm.cwrap(Mo,null,["number","number"])}function sme(e){let{backend:t,inputs:{x:n}}=e,a=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(r.dataId).id;return w.sizeFromShape(r.shape)===0||k$(a,s),r}var ime={kernelName:"Sigmoid",backendName:"wasm",setupFunc:rme,kernelFunc:sme},ome=Xe(Ro),lme=Xe($o),ume=Xe(Do),pme=Xe(Oo);function cme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a,o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=p$.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=T.getReshaped(u.shape,s,o,!1),d=T.getPermuted(p.length,s.length,!1),c=T.getReshapedPermuted(u.shape,s,o,!1),h=Ln({inputs:{x:u},backend:n,attrs:{shape:p}}),m=bs({inputs:{x:h},backend:n,attrs:{perm:d}}),f=Ln({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeData(u.dataId),n.disposeData(h.dataId),n.disposeData(m.dataId),f}var dme={kernelName:Vu,backendName:"wasm",kernelFunc:cme},I$;function hme(e){I$=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function mme(e){let{backend:t,inputs:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=n,o=a.shape[0],l=a.shape[1],u=t.readSync(s.dataId)[0],p=[o+u,l],d=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(i.dataId).id,m=t.makeOutput(p,a.dtype),f=t.dataIdMap.get(m.dataId).id,g=t.makeOutput(p.slice(0,1),r.dtype),b=t.dataIdMap.get(g.dataId).id,y=t.makeOutput([u],"bool"),x=t.dataIdMap.get(y.dataId).id,v=t.makeOutput([o],a.dtype),I=t.dataIdMap.get(v.dataId).id,N=t.makeOutput([4],"int32"),C=t.dataIdMap.get(N.dataId).id,_=I$(d,c,Qe[r.dtype],o,u,l,h,f,b,x,I,C),F=t.readSync(N.dataId),D;switch(F[0]){case 1:{D=T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(F[1]);break}case 2:{D=T.getSparseFillEmptyRowsNegativeIndexErrorMessage(F[1],F[2]);break}case 3:D=T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(F[1],F[2],F[3]);break;default:D=""}if(t.disposeData(N.dataId),D)throw t.disposeData(m.dataId),t.disposeData(g.dataId),t.disposeData(y.dataId),t.disposeData(v.dataId),new Error(D);let $=m,S=g;return _!==p[0]&&($=Ii({inputs:{x:m},attrs:{begin:0,size:[_,l]},backend:t}),S=Ii({inputs:{x:g},attrs:{begin:0,size:_},backend:t}),t.disposeData(m.dataId),t.disposeData(g.dataId)),[$,S,y,v]}var fme={kernelName:Gc,backendName:"wasm",setupFunc:hme,kernelFunc:mme},S$;function gme(e){S$=e.wasm.cwrap(Gu,null,["number","number","number","number","number","number","number"])}function bme(e){let{backend:t,inputs:n}=e,{inputIndices:a,inputShape:r,newShape:s}=n;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(a.dataId).id,o=t.dataIdMap.get(r.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=a.shape[0],p=w.sizeFromShape(s.shape),d=t.makeOutput([u,p],a.dtype),c=t.dataIdMap.get(d.dataId).id,h=t.makeOutput([p],s.dtype),m=t.dataIdMap.get(h.dataId).id,f=t.makeOutput([3],"int32"),g=t.dataIdMap.get(f.dataId).id;S$(i,o,l,u,c,m,g);let b=t.readSync(f.dataId),y;switch(b[0]){case 0:{y=T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break}case 1:{y=T.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break}case 2:y=T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));y=T.getSparseReshapeInputOutputMultipleErrorMessage(x,v);break}case 4:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));y=T.getSparseReshapeInputOutputMismatchErrorMessage(x,v);break}default:y=""}if(t.disposeData(f.dataId),y)throw t.disposeData(d.dataId),t.disposeData(h.dataId),new Error(y);return[d,h]}var yme={kernelName:Gu,backendName:"wasm",setupFunc:gme,kernelFunc:bme},N$;function T$(e){N$=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function C$(e,t){let{backend:n,inputs:a}=e,{data:r,indices:s,segmentIds:i}=a,o=s.shape[0],l=n.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=r.shape.slice();p[0]=u;let d=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(i.dataId).id,m=n.makeOutput(p,r.dtype),f=n.dataIdMap.get(m.dataId).id,g=n.makeOutput([4],"int32"),b=n.dataIdMap.get(g.dataId).id;N$(d,Qe[r.dtype],r.shape[0],c,h,f,b,t,0);let y=n.readSync(g.dataId),x;switch(y[0]){case 0:{x=T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y[1],y[2]);break;case 3:x=T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(y[1],y[2],y[3]);break;default:x=""}if(n.disposeData(g.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function xme(e){return C$(e,!0)}var vme={kernelName:Hc,backendName:"wasm",setupFunc:T$,kernelFunc:xme};function wme(e){return C$(e,!1)}var kme={kernelName:qc,backendName:"wasm",setupFunc:T$,kernelFunc:wme},E$;function Ime(e){E$=e.wasm.cwrap(Hu,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Sme(e){let{backend:t,inputs:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=n,{outputShape:o}=a,l=t.makeOutput(o,i.dtype);if(w.sizeFromShape(o)===0)return l;let{sliceRank:u,numUpdates:p,sliceSize:d,strides:c,outputSize:h}=T.calculateShapes(s,r,o),m=t.dataIdMap.get(r.dataId).id,f=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,b=new Uint8Array(new Int32Array(c).buffer),y=t.dataIdMap.get(l.dataId).id;return E$(m,f,s.shape.length,g,Qe[i.dtype],u,p,d,b,h,y),l}var Nme={kernelName:Hu,backendName:"wasm",setupFunc:Ime,kernelFunc:Sme};function Tme(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=Ii({inputs:{x:r},attrs:{begin:u,size:c},backend:a});return u[o]+=d,h})}var Cme={kernelName:Uu,backendName:"wasm",kernelFunc:Tme},Eme=Xe(Po),_me=Xe(jc),Ame=!0,Fme=Ut(Wo,Ame),_$;function $me(e){_$=e.wasm.cwrap(ks,null,["number","number","number","number"])}function Dme(e){let{backend:t,inputs:n,attrs:a}=e,{alpha:r}=a,{x:s}=n,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return _$(i,r,Qe[s.dtype],l),o}var Rme={kernelName:ks,backendName:"wasm",setupFunc:$me,kernelFunc:Dme},A$;function Mme(e){A$=e.wasm.cwrap(qu,null,["number","array","number","array","array","array","array","array","number","number"])}function Ome(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:b,begin:y,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),I;if(f)I=Ln({inputs:{x:r},backend:t,attrs:{shape:m}});else if(g||b){w.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let N=Kt.computeOutShape(y,x,v),C=Ii({inputs:{x:r},backend:t,attrs:{begin:y,size:N}});I=Ln({inputs:{x:C},backend:t,attrs:{shape:m}}),t.disposeData(C.dataId)}else{let N=t.makeOutput(h,"float32"),C=t.dataIdMap.get(r.dataId).id,_=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),F=new Uint8Array(new Int32Array(y).buffer),D=new Uint8Array(new Int32Array(x).buffer),$=new Uint8Array(new Int32Array(v).buffer),S=new Uint8Array(new Int32Array(h).buffer),M=new Uint8Array(new Int32Array(w.computeStrides(h)).buffer),B=t.dataIdMap.get(N.dataId).id;A$(C,_,r.shape.length,F,D,$,S,M,h.length,B),I=Ln({inputs:{x:N},backend:t,attrs:{shape:m}}),t.disposeData(N.dataId)}return I}var Pme={kernelName:qu,backendName:"wasm",setupFunc:Mme,kernelFunc:Ome};function Lme(e){let{backend:t,inputs:n,attrs:a}=e,{data:r,dataSplits:s}=n,{separator:i,nGramWidths:o,leftPad:l,rightPad:u,padWidth:p,preserveShortSequences:d}=a,c=t.readSync(r.dataId),h=t.readSync(s.dataId),[m,f]=U1(c,h,i,o,l,u,p,d),g=t.makeOutput([m.length],"string"),b=t.dataIdMap.get(g.dataId);b.stringBytes=m;let y=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(y).set(f),[g,y]}var zme={kernelName:Xc,backendName:"wasm",kernelFunc:Lme};function Wme(e){let{backend:t,inputs:n,attrs:a}=e,{input:r,delimiter:s}=n,{skipEmpty:i}=a,o=t.readSync(r.dataId),l=t.readSync(s.dataId),[u,p,d]=G1(o,l[0],i),c=p.length,h=t.makeOutput([c,2],"int32");t.typedArrayFromHeap(h).set(u);let m=t.makeOutput([c],"string"),f=t.dataIdMap.get(m.dataId);f.stringBytes=p;let g=t.makeOutput([2],"int32");return t.typedArrayFromHeap(g).set(d),[h,m,g]}var Bme={kernelName:Yc,backendName:"wasm",kernelFunc:Wme};function Vme(e){let{backend:t,inputs:n,attrs:a}=e,{input:r}=n,{numBuckets:s}=a,i=t.readSync(r.dataId),o=H1(i,s),l=t.makeOutput(r.shape,"int32");return t.typedArrayFromHeap(l).set(o),l}var Ume={kernelName:Zc,backendName:"wasm",kernelFunc:Vme},Gme=!0,Hme=Ut(Bo,Gme),F$;function qme(e){F$=e.wasm.cwrap(Lo,null,["number","number","number","number"])}function jme(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:d,originalAxes:c,inputWasTransposed:h}=$s(i,r,t),m=d;if(h){let x=t.dataIdMap.get(p.dataId).id;x!==o&&(u=p,l=x,m=T.getInnerMostAxes(m.length,u.shape.length))}T.assertAxesAreInnerMostDims("sum",m,u.shape.length);let[f,g]=T.computeOutAndReduceShapes(u.shape,m),b=w.sizeFromShape(g),y=t.makeOutput(f,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;F$(l,b,Qe[y.dtype],x)}if(h&&t.disposeData(p.dataId),s){let x=T.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var Kme={kernelName:Lo,backendName:"wasm",setupFunc:qme,kernelFunc:jme},Xme=Xe(Vo),Yme=Xe(Uo),$$;function Zme(e){$$=e.wasm.cwrap(Lu,null,["number","number","number","number","number","number","array","number","number","number"])}function Jme(e){let{backend:t,inputs:n,attrs:a}=e,{tensor:r,indices:s,updates:i}=n,{}=a,o=t.makeOutput(r.shape,r.dtype);if(w.sizeFromShape(r.shape)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=rf.calculateShapes(i,s,r.shape),h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(i.dataId).id,f=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(d).buffer),b=t.dataIdMap.get(o.dataId).id;return $$(h,m,Qe[i.dtype],l,u,p,g,c,b,f),o}var Qme={kernelName:Lu,backendName:"wasm",setupFunc:Zme,kernelFunc:Jme},D$;function efe(e){D$=e.wasm.cwrap(ws,null,["number","array","number","array","number","number"])}function tfe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,s=n.dataIdMap.get(r.dataId).id,{reps:i}=a,o=new Array(r.shape.length);for(let c=0;c<o.length;c++)o[c]=r.shape[c]*i[c];let l=new Uint8Array(new Int32Array(r.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),p=n.makeOutput(o,r.dtype),d=n.dataIdMap.get(p.dataId).id;return D$(s,l,r.shape.length,u,o.length,Qe[p.dtype],d),p}var nfe={kernelName:ws,backendName:"wasm",setupFunc:efe,kernelFunc:tfe},R$;function afe(e){R$=e.wasm.cwrap(ju,null,["number","array","number","number","number","bool","number","number"])}var rfe=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{k:r,sorted:s}=n,i=t.dataIdMap.get(a.dataId).id,o=new Uint8Array(new Int32Array(a.shape).buffer),l=a.shape.slice();l[l.length-1]=r;let u=t.makeOutput(l,a.dtype),p=t.dataIdMap.get(u.dataId).id,d=t.makeOutput(l,"int32"),c=t.dataIdMap.get(d.dataId).id;return R$(i,o,a.shape.length,Qe[a.dtype],r,s,p,c),[u,d]},sfe={kernelName:ju,backendName:"wasm",setupFunc:afe,kernelFunc:rfe},M$;function ife(e){M$=e.wasm.cwrap(Ku,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function ofe(e){let{backend:t,inputs:n,attrs:a}=e,{image:r,transforms:s}=n,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],b=new Uint8Array(new Int32Array(w.computeStrides(r.shape)).buffer),y=new Uint8Array(new Int32Array(w.computeStrides(g)).buffer),x=t.makeOutput(g,r.dtype),v=t.dataIdMap.get(x.dataId).id,I=t.dataIdMap.get(r.dataId).id,N=t.dataIdMap.get(s.dataId).id,C=i==="nearest"?1:2,_;switch(o){case"constant":_=1;break;case"reflect":_=2;break;case"wrap":_=3;break;case"nearest":_=4;break;default:_=1;break}return M$(I,N,s.shape[0]>1,p,m,f,h,c,d,b,r.shape.length-1,y,g.length-1,C,_,l,v),x}var lfe={kernelName:Ku,backendName:"wasm",setupFunc:ife,kernelFunc:ofe};function ufe(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t,{outputValues:i,outputShape:o,indices:l}=j1(a.readSync(s.dataId),r,s.shape,s.dtype);return[a.makeOutput(o,s.dtype,void 0,i),a.makeOutput([l.length],"int32",void 0,l)]}var pfe={kernelName:Jc,backendName:"wasm",kernelFunc:ufe};function cfe(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r.shape[s],o=r.shape.length,l=new Array(o-1),u=0;for(let h=0;h<o;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i),d=new Array(o).fill(0),c=r.shape.slice();c[s]=1;for(let h=0;h<p.length;h++)d[s]=h,p[h]=Ii({inputs:{x:r},attrs:{begin:d,size:c},backend:n});return p.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var dfe={kernelName:Xu,backendName:"wasm",kernelFunc:cfe};function hfe(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var mfe={kernelName:Yu,backendName:"wasm",kernelFunc:hfe},ffe=[Yle,Zle,Jle,Qle,tue,rue,due,fue,gue,bue,yue,xue,vue,wue,kue,Nue,Rue,Eue,Fue,Lue,Gue,jue,Xue,Zue,Jue,Que,npe,ape,ipe,upe,dpe,fpe,ype,xpe,vpe,Ipe,Tpe,_pe,$pe,Mpe,Lpe,Bpe,Gpe,jpe,Ype,Zpe,ece,nce,ace,rce,sce,ice,oce,pce,cce,hce,gce,xce,kce,Nce,Ece,Ace,$ce,sue,Dce,Rce,Mce,Lce,Wce,Vce,Hce,jce,qce,Xce,Yce,Jce,ede,ade,ide,ude,cde,mde,bde,vde,Ide,Tde,_de,$de,Rde,Pde,Vde,Ude,Hde,qde,Xde,Jde,the,ahe,ihe,lhe,phe,p$,mhe,bhe,vhe,khe,She,Nhe,The,Che,Mue,Ahe,Dhe,Ohe,zhe,Vhe,Hhe,qhe,jhe,Yhe,Qhe,nme,ame,ime,ome,lme,ume,Vue,zde,pme,dme,fme,yme,vme,kme,Nme,Cme,Eme,_me,Fme,Rme,Pme,zme,Bme,Ume,Hme,Kme,Xme,Yme,Qme,nfe,sfe,lfe,uue,pfe,dfe,mfe];for(let e of ffe)ed(e);var xv=G();xv.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>{try{return 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]))}catch(e){return!1}});xv.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(xv.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 TS=ys(WR()),gfe=ys(BR()),CS=ys(VR()),ES=TS.default||TS,bfe=CS.default||CS,O$=class extends Fc{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(P$),vv=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new ym(this,Ta())}write(e,t,n){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,n,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,a,r){let s=this.dataIdNextNumber++;if(a==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:n,dtype:a,memoryOffset:null,refCount:r});return}let i=w.sizeFromShape(n),o=i*w.bytesPerElement(a),l=this.wasm._malloc(o)>>>0;this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:n,dtype:a,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,n){let{memoryOffset:a,dtype:r,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(r==="string")return(t==null||t===0)&&(n==null||n>=i.length)?i:i.slice(t,n);t=t||0,n=n||w.sizeFromShape(s);let o=w.bytesPerElement(r),l=this.wasm.HEAPU8.slice(a+t*o,a+n*o);return vfe(l.buffer,r)}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,a){let r;if(n==null)r=this.write(a!=null?a: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 i=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,i,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let a=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),s=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(a,r,s);case"int32":return new Int32Array(a,r,s);case"bool":return new Uint8Array(a,r,s);default:throw new Error(`Unknown dtype ${t}`)}}};function yfe(e){return(t,n)=>(w.fetch(e,{credentials:"same-origin"}).then(a=>{a.ok||t.env.a(`failed to load wasm binary file at '${e}'`),a.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(s=>{n(s.instance,s.module)})})}),{})}function _S(e,t,n){if(gm!=null)return gm;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),cc!=null&&cc[a]!=null?cc[a]:n+a}async function xfe(){let[e,t]=await Promise.all([G().getAsync("WASM_HAS_SIMD_SUPPORT"),G().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=gfe.wasmWorkerContents.replace(/\n/g,"\\n"),p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return o.endsWith(".wasm")?_S(e,t,lc!=null?lc:l):l+o},mk&&(r.instantiateWasm=yfe(_S(e,t,lc!=null?lc:"")));let s=!1;r.onAbort=()=>{s||dc||(dc=!0,a({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&gm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+ES.toString()],{type:"text/javascript"}),i=ES(r)):i=bfe(r),i.then(o=>{s=!0,dc=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),initWithThreadsCount:o.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:o.cwrap("get_threads_count","number",[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},n({wasm:o})}).catch(a)})}function vfe(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 wfe=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],gm=null,lc=null,cc={},dc=!1,mk=!1;function kfe(e,t=!1){if(Fv("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),dc)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");gm=e,mk=t}function Ife(e,t=!1){if(dc)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")lc=e;else{cc=e;let n=wfe.filter(a=>cc[a]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}mk=t}var P$=-1,vv=-1;function Sfe(e){P$=e}function Nfe(){if(vv===-1)throw new Error("WASM backend not initialized.");return vv}var Tfe="4.16.0",Cfe=2;Om("wasm",async()=>{let{wasm:e}=await xfe();return new O$(e)},Cfe);var AS="4.16.0",Efe="4.16.0",_fe="4.16.0",Afe="4.16.0",Ffe="4.16.0",$fe={tfjs:AS,"tfjs-core":AS,"tfjs-converter":Efe,"tfjs-backend-cpu":_fe,"tfjs-backend-webgl":Afe,"tfjs-backend-wasm":Ffe};var rD={};nx(rD,{AnchorPosition:()=>Ik,DrawBox:()=>Od,DrawBoxOptions:()=>Kf,DrawFaceLandmarks:()=>ig,DrawFaceLandmarksOptions:()=>sg,DrawTextField:()=>sl,DrawTextFieldOptions:()=>Ip,drawContour:()=>Pr,drawDetections:()=>zfe,drawFaceExpressions:()=>Wfe,drawFaceLandmarks:()=>Vfe});function Pr(e,t,n=!1){if(e.beginPath(),t.slice(1).forEach(({x:a,y:r},s)=>{let i=t[s];e.moveTo(i.x,i.y),e.lineTo(a,r)}),n){let a=t[t.length-1],r=t[0];if(!a||!r)return;e.moveTo(a.x,a.y),e.lineTo(r.x,r.y)}e.stroke()}var L$={};nx(L$,{computeReshapedDimensions:()=>bk,getCenterPoint:()=>al,isDimensions:()=>Hf,isEven:()=>Gf,isFloat:()=>gk,isTensor:()=>tl,isTensor1D:()=>Dfe,isTensor2D:()=>fk,isTensor3D:()=>Lr,isTensor4D:()=>wa,isValidNumber:()=>Xa,isValidProbablitiy:()=>gp,range:()=>fr,round:()=>nl});var aa=class e{constructor(t,n){if(!Xa(t)||!Xa(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 e(1/this.width,1/this.height)}};function tl(e,t){return e instanceof Ce&&e.shape.length===t}function Dfe(e){return tl(e,1)}function fk(e){return tl(e,2)}function Lr(e){return tl(e,3)}function wa(e){return tl(e,4)}function gk(e){return e%1!==0}function Gf(e){return e%2===0}function nl(e,t=2){let n=10**t;return Math.floor(e*n)/n}function Hf(e){return e&&e.width&&e.height}function bk({width:e,height:t},n){let a=n/Math.max(t,e);return new aa(Math.round(e*a),Math.round(t*a))}function al(e){return e.reduce((t,n)=>t.add(n),new He(0,0)).div(new He(e.length,e.length))}function fr(e,t,n){return Array(e).fill(0).map((a,r)=>t+r*n)}function Xa(e){return!!e&&e!==1/0&&e!==-1/0&&!Number.isNaN(e)||e===0}function gp(e){return Xa(e)&&e>=0&&e<=1}var He=class e{constructor(t,n){this._x=t,this._y=n}get x(){return this._x}get y(){return this._y}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t.x,this.y*t.y)}div(t){return new e(this.x/t.x,this.y/t.y)}abs(){return new e(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new e(Math.floor(this.x),Math.floor(this.y))}};var mn=class e{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(Xa)}static assertIsValidBox(t,n,a=!1){if(!e.isRect(t))throw new Error(`${n} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!a&&(t.width<0||t.height<0))throw new Error(`${n} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,n=!0){let a=t||{},r=[a.left,a.top,a.right,a.bottom].every(Xa),s=[a.x,a.y,a.width,a.height].every(Xa);if(!s&&!r)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(a)}`);let[i,o,l,u]=s?[a.x,a.y,a.width,a.height]:[a.left,a.top,a.right-a.left,a.bottom-a.top];e.assertIsValidBox({x:i,y:o,width:l,height:u},"Box.constructor",n),this._x=i,this._y=o,this._width=l,this._height=u}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 He(this.left,this.top)}get topRight(){return new He(this.right,this.top)}get bottomLeft(){return new He(this.left,this.bottom)}get bottomRight(){return new He(this.right,this.bottom)}round(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.round(s));return new e({x:t,y:n,width:a,height:r})}floor(){let[t,n,a,r]=[this.x,this.y,this.width,this.height].map(s=>Math.floor(s));return new e({x:t,y:n,width:a,height:r})}toSquare(){let{x:t,y:n,width:a,height:r}=this,s=Math.abs(a-r);return a<r&&(t-=s/2,a+=s),r<a&&(n-=s/2,r+=s),new e({x:t,y:n,width:a,height:r})}rescale(t){let n=Hf(t)?t.width:t,a=Hf(t)?t.height:t;return new e({x:this.x*n,y:this.y*a,width:this.width*n,height:this.height*a})}pad(t,n){let[a,r,s,i]=[this.x-t/2,this.y-n/2,this.width+t,this.height+n];return new e({x:a,y:r,width:s,height:i})}clipAtImageBorders(t,n){let{x:a,y:r,right:s,bottom:i}=this,o=Math.max(a,0),l=Math.max(r,0),u=s-o,p=i-l,d=Math.min(u,t-o),c=Math.min(p,n-l);return new e({x:o,y:l,width:d,height:c}).floor()}shift(t,n){let{width:a,height:r}=this,s=this.x+t,i=this.y+n;return new e({x:s,y:i,width:a,height:r})}padAtBorders(t,n){let a=this.width+1,r=this.height+1,s=1,i=1,o=a,l=r,u=this.left,p=this.top,d=this.right,c=this.bottom;return d>n&&(o=-d+n+a,d=n),c>t&&(l=-c+t+r,c=t),u<1&&(l=2-u,u=1),p<1&&(l=2-p,p=1),{dy:i,edy:l,dx:s,edx:o,y:p,ey:c,x:u,ex:d,w:a,h:r}}calibrate(t){return new e({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 bp=class extends mn{constructor(t,n,a,r,s=!1){super({left:t,top:n,right:a,bottom:r},s)}};var yp=class e{constructor(t,n,a,r,s){this._imageDims=new aa(s.width,s.height),this._score=t,this._classScore=n,this._className=a,this._box=new mn(r).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new mn(this._box).rescale(this.imageDims.reverse())}forSize(t,n){return new e(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:n})}};var Ft=class e extends yp{constructor(t,n,a){super(t,t,"",n,a)}forSize(t,n){let{score:a,relativeBox:r,imageDims:s}=super.forSize(t,n);return new e(a,r,s)}};function z$(e,t,n=!0){let a=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),r=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=a*r;return n?s/(e.area+t.area-s):s/Math.min(e.area,t.area)}function W$(e){let t=e.map(o=>o.x),n=e.map(o=>o.y),a=t.reduce((o,l)=>l<o?l:o,1/0),r=n.reduce((o,l)=>l<o?l:o,1/0),s=t.reduce((o,l)=>o<l?l:o,0),i=n.reduce((o,l)=>o<l?l:o,0);return new bp(a,r,s,i)}function B$(e,t,n,a=!0){let r=t.map((i,o)=>({score:i,boxIndex:o})).sort((i,o)=>i.score-o.score).map(i=>i.boxIndex),s=[];for(;r.length>0;){let i=r.pop();s.push(i);let o=r,l=[];for(let u=0;u<o.length;u++){let p=o[u],d=e[i],c=e[p];l.push(z$(d,c,a))}r=r.filter((u,p)=>l[p]<=n)}return s}function gr(e,t){return O(()=>{let[n,a,r]=t,s=yn([...e.shape.slice(0,3),1],n,"float32"),i=yn([...e.shape.slice(0,3),1],a,"float32"),o=yn([...e.shape.slice(0,3),1],r,"float32"),l=et([s,i,o],3);return pe(e,l)})}function V$(e,t=!1){return O(()=>{let[n,a]=e.shape.slice(1);if(n===a)return e;let r=Math.abs(n-a),s=Math.round(r*(t?.5:1)),i=n>a?2:1,o=c=>{let h=e.shape.slice();return h[i]=c,yn(h,0,"float32")},l=o(s),u=r-l.shape[i],d=[t&&u?o(u):null,e,l].filter(c=>!!c).map(c=>re(c,"float32"));return et(d,i)})}function d0e(e){let t=e.slice();for(let n=t.length-1;n>0;n--){let a=Math.floor(Math.random()*(n+1)),r=t[n];t[n]=t[a],t[a]=r}return t}function qf(e){return 1/(1+Math.exp(-e))}function m0e(e){return Math.log(e/(1-e))}var xp=class extends mn{constructor(t,n,a,r,s=!1){super({x:t,y:n,width:a,height:r},s)}};var Rfe=.5,Mfe=.43,Ofe=.45,ka=class{constructor(t,n,a=new He(0,0)){let{width:r,height:s}=n;this._imgDims=new aa(r,s),this._shift=a,this._positions=t.map(i=>i.mul(new He(r,s)).add(a))}get shift(){return new He(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 He(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 He(t,n))}shiftByPoint(t){return this.shiftBy(t.x,t.y)}align(t,n={}){if(t){let s=t instanceof Ft?t.box.floor():new mn(t);return this.shiftBy(s.x,s.y).align(null,n)}let{useDlibAlignment:a,minBoxPadding:r}={useDlibAlignment:!1,minBoxPadding:.2,...n};return a?this.alignDlib():this.alignMinBbox(r)}alignDlib(){let t=this.getRefPointsForAlignment(),[n,a,r]=t,s=d=>r.sub(d).magnitude(),i=(s(n)+s(a))/2,o=Math.floor(i/Ofe),l=al(t),u=Math.floor(Math.max(0,l.x-Rfe*o)),p=Math.floor(Math.max(0,l.y-Mfe*o));return new xp(u,p,Math.min(o,this.imageWidth+u),Math.min(o,this.imageHeight+p))}alignMinBbox(t){let n=W$(this.positions);return n.pad(n.width*t,n.height*t)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}};var U$=class extends ka{getRefPointsForAlignment(){let t=this.positions;return[t[0],t[1],al([t[3],t[4]])]}};var vp=class extends ka{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(al)}};var Dd=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?` (${nl(this.distance)})`:""}`}};var Rd=class extends mn{static assertIsValidLabeledBox(t,n){if(mn.assertIsValidBox(t,n),!Xa(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 rl=class e{constructor(t,n){if(typeof t!="string")throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(n)||n.some(a=>!(a instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=t,this._descriptors=n}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(t=>Array.from(t))}}static fromJSON(t){let n=t.descriptors.map(a=>new Float32Array(a));return new e(t.label,n)}};var G$=class extends Rd{static assertIsValidPredictedBox(t,n){if(Rd.assertIsValidLabeledBox(t,n),!gp(t.score)||!gp(t.classScore))throw new Error(`${n} - expected properties score (${t.score}) and (${t.classScore}) to be a number between [0, 1]`)}constructor(t,n,a,r){super(t,n),this._score=a,this._classScore=r}get score(){return this._score}get classScore(){return this._classScore}};function zr(e){return e.detection instanceof Ft}function wp(e,t){return{...e,...{detection:t}}}function yk(){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 Md(){return typeof global=="object"&&typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null}function jf(e){let t="";if(!e&&Md())try{e=xR("fs")}catch(a){t=a.toString()}return{readFile:e?a=>new Promise((r,s)=>{e.readFile(a,(i,o)=>i?s(i):r(o))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function xk(){let e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,n=global.Video||global.HTMLVideoElement,a=()=>{if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},r=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},s=()=>{if(n)return new n;throw new Error("createVideoElement - missing Video implementation for nodejs environment")},i=global.fetch,o=jf();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:a,createImageElement:r,createVideoElement:s,fetch:i,...o}}function vk(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}var on;function Pfe(){if(!on)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return on}function wk(e){on=e}function kk(){return vk()?wk(yk()):Md()?wk(xk()):null}function Lfe(e){if(on||kk(),!on)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=on.Canvas,Image:n=on.Image}=e;on.Canvas=t,on.Image=n,on.createCanvasElement=e.createCanvasElement||(()=>new t),on.createImageElement=e.createImageElement||(()=>new n),on.ImageData=e.ImageData||on.ImageData,on.Video=e.Video||on.Video,on.fetch=e.fetch||on.fetch,on.readFile=e.readFile||on.readFile}var at={getEnv:Pfe,setEnv:wk,initialize:kk,createBrowserEnv:yk,createFileSystem:jf,createNodejsEnv:xk,monkeyPatch:Lfe,isBrowser:vk,isNodejs:Md};kk();function kp(e){return!at.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function ra(e){let{Canvas:t,CanvasRenderingContext2D:n}=at.getEnv();if(e instanceof n)return e;let a=kp(e);if(!(a instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let r=a.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("resolveContext2d - canvas 2d context is null");return r}var Ik=(r=>(r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT",r))(Ik||{}),Ip=class{constructor(t={}){let{anchorPosition:n,backgroundColor:a,fontColor:r,fontSize:s,fontStyle:i,padding:o}=t;this.anchorPosition=n||"TOP_LEFT",this.backgroundColor=a||"rgba(0, 0, 0, 0.5)",this.fontColor=r||"rgba(255, 255, 255, 1)",this.fontSize=s||14,this.fontStyle=i||"Georgia",this.padding=o||4}},sl=class e{constructor(t,n,a={}){this.text=typeof t=="string"?[t]:t instanceof e?t.text:t,this.anchor=n,this.options=new Ip(a)}measureWidth(t){let{padding:n}=this.options;return this.text.map(a=>t.measureText(a).width).reduce((a,r)=>a<r?r:a,0)+2*n}measureHeight(){let{fontSize:t,padding:n}=this.options;return this.text.length*t+2*n}getUpperLeft(t,n){let{anchorPosition:a}=this.options,r=a==="BOTTOM_RIGHT"||a==="TOP_RIGHT",s=a==="BOTTOM_LEFT"||a==="BOTTOM_RIGHT",i=this.measureWidth(t),o=this.measureHeight(),l=r?this.anchor.x-i:this.anchor.x,u=s?this.anchor.y-o:this.anchor.y;if(n){let{width:p,height:d}=n,c=Math.max(Math.min(l,p-i),0),h=Math.max(Math.min(u,d-o),0);return{x:c,y:h}}return{x:l,y:u}}draw(t){let n=kp(t),a=ra(n),{backgroundColor:r,fontColor:s,fontSize:i,fontStyle:o,padding:l}=this.options;a.font=`${i}px ${o}`;let u=this.measureWidth(a),p=this.measureHeight();a.fillStyle=r;let d=this.getUpperLeft(a,n);a.fillRect(d.x,d.y,u,p),a.fillStyle=s,this.text.forEach((c,h)=>{let m=l+d.x,f=l+d.y+(h+1)*i;a.fillText(c,m,f)})}};var Kf=class{constructor(t={}){let{boxColor:n,lineWidth:a,label:r,drawLabelOptions:s}=t;this.boxColor=n||"rgba(0, 0, 255, 1)",this.lineWidth=a||2,this.label=r;let i={anchorPosition:"BOTTOM_LEFT",backgroundColor:this.boxColor};this.drawLabelOptions=new Ip({...i,...s})}},Od=class{constructor(t,n={}){this.box=new mn(t),this.options=new Kf(n)}draw(t){let n=ra(t),{boxColor:a,lineWidth:r}=this.options,{x:s,y:i,width:o,height:l}=this.box;n.strokeStyle=a,n.lineWidth=r,n.strokeRect(s,i,o,l);let{label:u}=this.options;u&&new sl([u],{x:s-r/2,y:i},this.options.drawLabelOptions).draw(t)}};function zfe(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof Ft?a.score:zr(a)?a.detection.score:void 0,s=a instanceof Ft?a.box:zr(a)?a.detection.box:new mn(a),i=r?`${nl(r)}`:void 0;new Od(s,{label:i}).draw(e)})}function Xf(e){let{Image:t,Video:n}=at.getEnv();return e instanceof t&&e.complete||e instanceof n&&e.readyState>=3}function H$(e){return new Promise((t,n)=>{(e instanceof at.getEnv().Canvas||Xf(e))&&t(null);function a(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),n(s))}function r(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",r),s.currentTarget.removeEventListener("error",a),t(s))}e.addEventListener("load",r),e.addEventListener("error",a)})}function q$(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToImage - expected buf to be of type: Blob"));let a=new FileReader;a.onload=()=>{typeof a.result!="string"&&n(new Error("bufferToImage - expected reader.result to be a string, in onload"));let r=at.getEnv().createImageElement();r.onload=()=>t(r),r.onerror=n,r.src=a.result},a.onerror=n,a.readAsDataURL(e)})}function Sp(e){let{Image:t,Video:n}=at.getEnv();return e instanceof t?new aa(e.naturalWidth,e.naturalHeight):e instanceof n?new aa(e.videoWidth,e.videoHeight):new aa(e.width,e.height)}function Np({width:e,height:t}){let{createCanvasElement:n}=at.getEnv(),a=n();return a.width=e,a.height=t,a}function Yf(e,t){let{ImageData:n}=at.getEnv();if(!(e instanceof n)&&!Xf(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:a,height:r}=t||Sp(e),s=Np({width:a,height:r});return e instanceof n?ra(s).putImageData(e,0,0):ra(s).drawImage(e,0,0,a,r),s}async function j$(e,t){let n=t||at.getEnv().createCanvasElement(),[a,r,s]=e.shape.slice(wa(e)?1:0),i=O(()=>e.as3D(a,r,s).toInt());return await jo.toPixels(i,n),i.dispose(),n}function Sk(e){let{Image:t,Canvas:n,Video:a}=at.getEnv();return e instanceof t||e instanceof n||e instanceof a}function K$(e,t,n=!1){let{Image:a,Canvas:r}=at.getEnv();if(!(e instanceof a||e instanceof r))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return Np({width:1,height:1});let s=Sp(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,u=Np({width:t,height:t}),p=e instanceof r?e:Yf(e),d=Math.abs(o-l)/2,c=n&&o<l?d:0,h=n&&l<o?d:0;return p.width>0&&p.height>0&&ra(u).drawImage(p,c,h,o,l),u}var Wr=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((a,r)=>{if(Lr(a)){this._imageTensors[r]=a,this._inputDimensions[r]=a.shape;return}if(wa(a)){let i=a.shape[0];if(i!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${i} passed, but not supported in input array`);this._imageTensors[r]=a,this._inputDimensions[r]=a.shape.slice(1);return}let s=a instanceof at.getEnv().Canvas?a:Yf(a);this._canvases[r]=s,this._inputDimensions[r]=[s.height,s.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return fr(this.batchSize,0,1).map((t,n)=>this.getReshapedInputDimensions(n))}getInput(t){return this.canvases[t]||this.imageTensors[t]}getInputDimensions(t){return this._inputDimensions[t]}getInputHeight(t){return this._inputDimensions[t][0]}getInputWidth(t){return this._inputDimensions[t][1]}getReshapedInputDimensions(t){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let n=this.getInputWidth(t),a=this.getInputHeight(t);return bk({width:n,height:a},this.inputSize)}toBatchTensor(t,n=!0){return this._inputSize=t,O(()=>{let a=fr(this.batchSize,0,1).map(s=>{let i=this.getInput(s);if(i instanceof Ce){let o=wa(i)?i:Gt(i);return o=V$(o,n),(o.shape[1]!==t||o.shape[2]!==t)&&(o=Zn.resizeBilinear(o,[t,t],!1,!1)),o.as3D(t,t,3)}if(i instanceof at.getEnv().Canvas)return jo.fromPixels(K$(i,t,n));throw new Error(`toBatchTensor - at batchIdx ${s}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${i}`)});return At(a.map(s=>re(s,"float32"))).as4D(this.batchSize,t,t,3)})}};async function vt(e){if(e instanceof Wr)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");let n=r=>Array.isArray(e)?` at input index ${r}:`:"",a=t.map(kp);return a.forEach((r,s)=>{if(!Sk(r)&&!Lr(r)&&!wa(r))throw typeof t[s]=="string"?new Error(`toNetInput -${n(s)} string passed, but could not resolve HTMLElement for element id ${t[s]}`):new Error(`toNetInput -${n(s)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(wa(r)){let i=r.shape[0];if(i!==1)throw new Error(`toNetInput -${n(s)} tf.Tensor4D with batchSize ${i} passed, but not supported in input array`)}}),await Promise.all(a.map(r=>Sk(r)&&H$(r))),new Wr(a,Array.isArray(e))}async function Pd(e,t){let{Canvas:n}=at.getEnv(),a=e;if(!(e instanceof n)){let i=await vt(e);if(i.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let o=i.getInput(0);a=o instanceof n?o:await j$(o)}let r=ra(a);return t.map(i=>i instanceof Ft?i.forSize(a.width,a.height).box.floor():i).map(i=>i.clipAtImageBorders(a.width,a.height)).map(({x:i,y:o,width:l,height:u})=>{let p=Np({width:l,height:u});return l>0&&u>0&&ra(p).putImageData(r.getImageData(i,o,l,u),0,0),p})}async function Ld(e,t){if(!Lr(e)&&!wa(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(wa(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return O(()=>{let[n,a,r]=e.shape.slice(wa(e)?1:0);return t.map(o=>o instanceof Ft?o.forSize(a,n).box:o).map(o=>o.clipAtImageBorders(a,n)).filter(o=>o.width>0&&o.height>0).map(({x:o,y:l,width:u,height:p})=>Ho(e.as3D(n,a,r),[l,o,0],[p,u,r]))})}async function Rs(e,t){let{fetch:n}=at.getEnv(),a=await n(e,t);if(!(a.status<400))throw new Error(`failed to fetch: (${a.status}) ${a.statusText}, from url: ${a.url}`);return a}async function Qke(e){let t=await Rs(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 q$(n)}async function X$(e){return(await Rs(e)).json()}async function rIe(e){return new Float32Array(await(await Rs(e)).arrayBuffer())}function Y$(e){return new Promise((t,n)=>{e instanceof Blob||n(new Error("bufferToVideo - expected buf to be of type: Blob"));let a=at.getEnv().createVideoElement();a.oncanplay=()=>t(a),a.onerror=n,a.playsInline=!0,a.muted=!0,a.src=URL.createObjectURL(e),a.play()})}async function pIe(e){let t=await Rs(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 Y$(n)}function Zf(e,t){let n=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:n};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${n}`};let a=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(a,"");let r=e.split("/").filter(o=>o),s=e.endsWith(".json")?r[r.length-1]:n,i=a+(e.endsWith(".json")?r.slice(0,r.length-1):r).join("/");return i=e.startsWith("/")?`/${i}`:i,{modelBaseUri:i,manifestUri:i==="/"?`/${s}`:`${i}/${s}`}}async function Z$(e,t){let{manifestUri:n,modelBaseUri:a}=Zf(e,t),r=await X$(n);return qt.loadWeights(r,a)}function bIe(e,t,n=!1){let{width:a,height:r}=n?Sp(t):t;return e.width=a,e.height=r,{width:a,height:r}}var fn=class{constructor(t){this._params=void 0;this._paramMappings=[];this._name=t}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(t){let{obj:n,objProp:a}=this.traversePropertyPath(t);return n[a]}reassignParamFromPath(t,n){let{obj:a,objProp:r}=this.traversePropertyPath(t);a[r].dispose(),a[r]=n}getParamList(){return this._paramMappings.map(({paramPath:t})=>({path:t,tensor:this.getParamFromPath(t)}))}getTrainableParams(){return this.getParamList().filter(t=>t.tensor instanceof os)}getFrozenParams(){return this.getParamList().filter(t=>!(t.tensor instanceof os))}variable(){this.getFrozenParams().forEach(({path:t,tensor:n})=>{this.reassignParamFromPath(t,n.variable())})}freeze(){this.getTrainableParams().forEach(({path:t,tensor:n})=>{let a=bn(n.dataSync());n.dispose(),this.reassignParamFromPath(t,a)})}dispose(t=!0){this.getParamList().forEach(n=>{if(t&&n.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${n.path}`);n.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:t})=>Array.from(t.dataSync())).reduce((t,n)=>t.concat(n)))}async load(t){if(t instanceof Float32Array){this.extractWeights(t);return}await this.loadFromUri(t)}async loadFromUri(t){if(t&&typeof t!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);let n=await Z$(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}=at.getEnv(),{manifestUri:a,modelBaseUri:r}=Zf(t,this.getDefaultModelName()),s=u=>Promise.all(u.map(p=>n(p).then(d=>typeof d=="string"?Buffer.from(d):d.buffer))),i=qt.weightsLoaderFactory(s),o=JSON.parse((await n(a)).toString()),l=await i(o,r);this.loadFromWeightMap(l)}loadFromWeightMap(t){let{paramMappings:n,params:a}=this.extractParamsFromWeightMap(t);this._paramMappings=n,this._params=a}extractWeights(t){let{paramMappings:n,params:a}=this.extractParams(t);this._paramMappings=n,this._params=a}traversePropertyPath(t){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let n=t.split("/").reduce((s,i)=>{if(!s.nextObj.hasOwnProperty(i))throw new Error(`traversePropertyPath - object does not have property ${i}, for path ${t}`);return{obj:s.nextObj,objProp:i,nextObj:s.nextObj[i]}},{nextObj:this.params}),{obj:a,objProp:r}=n;if(!a||!r||!(a[r]instanceof Ce))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${t}`);return{obj:a,objProp:r}}};function Un(e,t,n){return O(()=>{let a=Es(e,t.depthwise_filter,t.pointwise_filter,n,"same");return a=X(a,t.bias),a})}function Jf(e,t,n=!1){return O(()=>{let a=Ke(n?X($t(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Un(e,t.conv0,[2,2])),r=Un(a,t.conv1,[1,1]),s=Ke(X(a,r)),i=Un(s,t.conv2,[1,1]);return Ke(X(a,X(r,i)))})}function zd(e,t,n=!1,a=!0){return O(()=>{let r=Ke(n?X($t(e,t.conv0.filters,a?[2,2]:[1,1],"same"),t.conv0.bias):Un(e,t.conv0,a?[2,2]:[1,1])),s=Un(r,t.conv1,[1,1]),i=Ke(X(r,s)),o=Un(i,t.conv2,[1,1]),l=Ke(X(r,X(s,o))),u=Un(l,t.conv3,[1,1]);return Ke(X(r,X(s,X(o,u))))})}function il(e,t,n="same",a=!1){return O(()=>{let r=X($t(e,t.filters,[1,1],n),t.bias);return a?Ke(r):r})}function En(e,t){Object.keys(e).forEach(n=>{t.some(a=>a.originalPath===n)||e[n].dispose()})}function Tp(e,t){return(n,a,r,s)=>{let i=Fa(e(n*a*r*r),[r,r,n,a]),o=qe(e(a));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function Qf(e,t){return(n,a,r)=>{let s=Ea(e(n*a),[n,a]),i=qe(e(a));return t.push({paramPath:`${r}/weights`},{paramPath:`${r}/bias`}),{weights:s,bias:i}}}var Wd=class{constructor(t,n,a){this.depthwise_filter=t;this.pointwise_filter=n;this.bias=a}};function Cp(e,t){return(n,a,r)=>{let s=Fa(e(9*n),[3,3,n,1]),i=Fa(e(n*a),[1,1,n,a]),o=qe(e(a));return t.push({paramPath:`${r}/depthwise_filter`},{paramPath:`${r}/pointwise_filter`},{paramPath:`${r}/bias`}),new Wd(s,i,o)}}function Ep(e){return t=>{let n=e(`${t}/depthwise_filter`,4),a=e(`${t}/pointwise_filter`,4),r=e(`${t}/bias`,1);return new Wd(n,a,r)}}function sa(e,t){return(n,a,r)=>{let s=e[n];if(!tl(s,a))throw new Error(`expected weightMap[${n}] to be a Tensor${a}D, instead have ${s}`);return t.push({originalPath:n,paramPath:r||n}),s}}function _n(e){let t=e;function n(r){let s=t.slice(0,r);return t=t.slice(r),s}function a(){return t}return{extractWeights:n,getRemainingWeights:a}}function eg(e,t){let n=Tp(e,t),a=Cp(e,t);function r(i,o,l,u=!1){let p=u?n(i,o,3,`${l}/conv0`):a(i,o,`${l}/conv0`),d=a(o,o,`${l}/conv1`),c=a(o,o,`${l}/conv2`);return{conv0:p,conv1:d,conv2:c}}function s(i,o,l,u=!1){let{conv0:p,conv1:d,conv2:c}=r(i,o,l,u),h=a(o,o,`${l}/conv3`);return{conv0:p,conv1:d,conv2:c,conv3:h}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:s}}function J$(e){let t=[],{extractWeights:n,getRemainingWeights:a}=_n(e),{extractDenseBlock4Params:r}=eg(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2"),l=r(128,256,"dense3");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o,dense3:l}}}function tg(e){return t=>{let n=e(`${t}/filters`,4),a=e(`${t}/bias`,1);return{filters:n,bias:a}}}function ng(e,t){let n=sa(e,t),a=tg(n),r=Ep(n);function s(o,l=!1){let u=l?a(`${o}/conv0`):r(`${o}/conv0`),p=r(`${o}/conv1`),d=r(`${o}/conv2`);return{conv0:u,conv1:p,conv2:d}}function i(o,l=!1){let u=l?a(`${o}/conv0`):r(`${o}/conv0`),p=r(`${o}/conv1`),d=r(`${o}/conv2`),c=r(`${o}/conv3`);return{conv0:u,conv1:p,conv2:d,conv3:c}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:i}}function Q$(e){let t=[],{extractDenseBlock4Params:n}=ng(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2"),dense3:n("dense3")};return En(e,t),{params:a,paramMappings:t}}var _p=class extends fn{constructor(){super("FaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceFeatureExtractor - load model before inference");return O(()=>{let a=re(t.toBatchTensor(112,!0),"float32"),s=gr(a,[122.782,117.001,104.298]).div(255),i=zd(s,n.dense0,!0);return i=zd(i,n.dense1),i=zd(i,n.dense2),i=zd(i,n.dense3),i=ya(i,[7,7],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await vt(t))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(t){return Q$(t)}extractParams(t){return J$(t)}};function Bd(e,t){return O(()=>X($e(e,t.weights),t.bias))}function eD(e,t,n){let a=[],{extractWeights:r,getRemainingWeights:s}=_n(e),o=Qf(r,a)(t,n,"fc");if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:a,params:{fc:o}}}function tD(e){let t=[],n=sa(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:a("fc")};return En(e,t),{params:r,paramMappings:t}}function ag(e){let t={},n={};return Object.keys(e).forEach(a=>{let r=a.startsWith("fc")?n:t;r[a]=e[a]}),{featureExtractorMap:t,classifierMap:n}}var Ap=class extends fn{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 O(()=>{let a=t instanceof Wr?this.faceFeatureExtractor.forwardInput(t):t;return Bd(a.as2D(a.shape[0],-1),n.fc)})}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:a}=this.extractClassifierParams(t);this._params=n,this._paramMappings=a}extractClassifierParams(t){return eD(t,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=ag(t);return this.faceFeatureExtractor.loadFromWeightMap(n),tD(a)}extractParams(t){let n=this.getClassifierChannelsIn(),a=this.getClassifierChannelsOut(),r=a*n+a,s=t.slice(0,t.length-r),i=t.slice(t.length-r);return this.faceFeatureExtractor.extractWeights(s),this.extractClassifierParams(i)}};var nD=["neutral","happy","sad","angry","fearful","disgusted","surprised"],Ms=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}`);nD.forEach((n,a)=>{this[n]=t[a]})}asSortedArray(){return nD.map(t=>({expression:t,probability:this[t]})).sort((t,n)=>n.probability-t.probability)}};var rg=class extends Ap{constructor(t=new _p){super("FaceExpressionNet",t)}forwardInput(t){return O(()=>ja(this.runNet(t)))}async forward(t){return this.forwardInput(await vt(t))}async predictExpressions(t){let n=await vt(t),a=await this.forwardInput(n),r=await Promise.all(dt(a).map(async i=>{let o=i.dataSync();return i.dispose(),o}));a.dispose();let s=r.map(i=>new Ms(i));return n.isBatchInput?s:s[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function aD(e){return e.expressions instanceof Ms}function Nk(e,t){return{...e,...{expressions:t}}}function Wfe(e,t,n=.1,a){(Array.isArray(t)?t:[t]).forEach(s=>{let i=s instanceof Ms?s:aD(s)?s.expressions:void 0;if(!i)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let l=i.asSortedArray().filter(d=>d.probability>n),u=zr(s)?s.detection.box.bottomLeft:a||new He(0,0);new sl(l.map(d=>`${d.expression} (${nl(d.probability)})`),u).draw(e)})}function Fp(e){return zr(e)&&e.landmarks instanceof ka&&e.unshiftedLandmarks instanceof ka&&e.alignedRect instanceof Ft}function Bfe(e){let t=l=>l*180/Math.PI,n=(l,u)=>Math.sqrt((l.x-u.x)**2+(l.y-u.y)**2),a={roll:void 0,pitch:void 0,yaw:void 0},r=(l,u,p)=>{let d=Math.floor(l.x-u.x),c=Math.floor(u.x-p.x);return d-c},s=(l,u)=>{let p=Math.hypot(u.x-l.x,u.y-l.y),d=u.y-l.y,c=Math.asin(d/p),h=t(c),m=Math.floor(90-h),f=u.x-l.x<0?-1:1;return m*f},i=(l,u,p)=>{let d=n(l,p),c=new He((l.x+p.x)/2,(l.y+p.y)/2),h=n(u,c),m=Math.atan(h/d),f=Math.floor(t(m)),g=c.y-u.y<0?-1:1;return f*g};if(!e||!e.positions||e.positions.length!==68)return a;let o=e.positions;return a.roll=s(o[27],o[66]),a.pitch=i(o[14],o[30],o[2]),a.yaw=r(o[14],o[33],o[2]),a}function Vd(e,t){let{box:n}=e.detection,a=t.shiftBy(n.x,n.y),r=a.align(),{imageDims:s}=e.detection,i=new Ft(e.detection.score,r.rescale(s.reverse()),s),o=Bfe(t);return{...e,...{landmarks:a,unshiftedLandmarks:t,alignedRect:i,angle:o}}}var sg=class{constructor(t={}){let{drawLines:n=!0,drawPoints:a=!0,lineWidth:r,lineColor:s,pointSize:i,pointColor:o}=t;this.drawLines=n,this.drawPoints=a,this.lineWidth=r||1,this.pointSize=i||2,this.lineColor=s||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}},ig=class{constructor(t,n={}){this.faceLandmarks=t,this.options=new sg(n)}draw(t){let n=ra(t),{drawLines:a,drawPoints:r,lineWidth:s,lineColor:i,pointSize:o,pointColor:l}=this.options;if(a&&this.faceLandmarks instanceof vp&&(n.strokeStyle=i,n.lineWidth=s,Pr(n,this.faceLandmarks.getJawOutline()),Pr(n,this.faceLandmarks.getLeftEyeBrow()),Pr(n,this.faceLandmarks.getRightEyeBrow()),Pr(n,this.faceLandmarks.getNose()),Pr(n,this.faceLandmarks.getLeftEye(),!0),Pr(n,this.faceLandmarks.getRightEye(),!0),Pr(n,this.faceLandmarks.getMouth(),!0)),r){n.strokeStyle=l,n.fillStyle=l;let u=p=>{n.beginPath(),n.arc(p.x,p.y,o,0,2*Math.PI),n.fill()};this.faceLandmarks.positions.forEach(u)}}};function Vfe(e,t){(Array.isArray(t)?t:[t]).forEach(a=>{let r=a instanceof ka?a:Fp(a)?a.landmarks:void 0;if(!r)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new ig(r).draw(e)})}var sD="1.7.13";function Hfe(e,t){let n=Tp(e,t),a=Cp(e,t);function r(i,o,l){let u=a(i,o,`${l}/separable_conv0`),p=a(o,o,`${l}/separable_conv1`),d=n(i,o,1,`${l}/expansion_conv`);return{separable_conv0:u,separable_conv1:p,expansion_conv:d}}function s(i,o){let l=a(i,i,`${o}/separable_conv0`),u=a(i,i,`${o}/separable_conv1`),p=a(i,i,`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:u,separable_conv2:p}}return{extractConvParams:n,extractSeparableConvParams:a,extractReductionBlockParams:r,extractMainBlockParams:s}}function iD(e,t){let n=[],{extractWeights:a,getRemainingWeights:r}=_n(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=Hfe(a,n),u=s(3,32,3,"entry_flow/conv_in"),p=o(32,64,"entry_flow/reduction_block_0"),d=o(64,128,"entry_flow/reduction_block_1"),c={conv_in:u,reduction_block_0:p,reduction_block_1:d},h={};fr(t,0,1).forEach(b=>{h[`main_block_${b}`]=l(128,`middle_flow/main_block_${b}`)});let m=o(128,256,"exit_flow/reduction_block"),f=i(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{entry_flow:c,middle_flow:h,exit_flow:g}}}function qfe(e,t){let n=sa(e,t),a=tg(n),r=Ep(n);function s(o){let l=r(`${o}/separable_conv0`),u=r(`${o}/separable_conv1`),p=a(`${o}/expansion_conv`);return{separable_conv0:l,separable_conv1:u,expansion_conv:p}}function i(o){let l=r(`${o}/separable_conv0`),u=r(`${o}/separable_conv1`),p=r(`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:u,separable_conv2:p}}return{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}}function oD(e,t){let n=[],{extractConvParams:a,extractSeparableConvParams:r,extractReductionBlockParams:s,extractMainBlockParams:i}=qfe(e,n),o=a("entry_flow/conv_in"),l=s("entry_flow/reduction_block_0"),u=s("entry_flow/reduction_block_1"),p={conv_in:o,reduction_block_0:l,reduction_block_1:u},d={};fr(t,0,1).forEach(f=>{d[`main_block_${f}`]=i(`middle_flow/main_block_${f}`)});let c=s("exit_flow/reduction_block"),h=r("exit_flow/separable_conv"),m={reduction_block:c,separable_conv:h};return En(e,n),{params:{entry_flow:p,middle_flow:d,exit_flow:m},paramMappings:n}}function lD(e,t,n){return X($t(e,t.filters,n,"same"),t.bias)}function Tk(e,t,n=!0){let a=n?Ke(e):e;return a=Un(a,t.separable_conv0,[1,1]),a=Un(Ke(a),t.separable_conv1,[1,1]),a=Dt(a,[3,3],[2,2],"same"),a=X(a,lD(e,t.expansion_conv,[2,2])),a}function jfe(e,t){let n=Un(Ke(e),t.separable_conv0,[1,1]);return n=Un(Ke(n),t.separable_conv1,[1,1]),n=Un(Ke(n),t.separable_conv2,[1,1]),n=X(n,e),n}var og=class extends fn{constructor(t){super("TinyXception"),this._numMainBlocks=t}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyXception - load model before inference");return O(()=>{let a=re(t.toBatchTensor(112,!0),"float32"),s=gr(a,[122.782,117.001,104.298]).div(255),i=Ke(lD(s,n.entry_flow.conv_in,[2,2]));return i=Tk(i,n.entry_flow.reduction_block_0,!1),i=Tk(i,n.entry_flow.reduction_block_1),fr(this._numMainBlocks,0,1).forEach(o=>{i=jfe(i,n.middle_flow[`main_block_${o}`])}),i=Tk(i,n.exit_flow.reduction_block),i=Ke(Un(i,n.exit_flow.separable_conv,[1,1])),i})}async forward(t){return this.forwardInput(await vt(t))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(t){return oD(t,this._numMainBlocks)}extractParams(t){return iD(t,this._numMainBlocks)}};function uD(e){let t=[],{extractWeights:n,getRemainingWeights:a}=_n(e),r=Qf(n,t),s=r(512,1,"fc/age"),i=r(512,2,"fc/gender");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{fc:{age:s,gender:i}}}}function pD(e){let t=[],n=sa(e,t);function a(s){let i=n(`${s}/weights`,2),o=n(`${s}/bias`,1);return{weights:i,bias:o}}let r={fc:{age:a("fc/age"),gender:a("fc/gender")}};return En(e,t),{params:r,paramMappings:t}}var Ck=(n=>(n.FEMALE="female",n.MALE="male",n))(Ck||{});var lg=class extends fn{constructor(t=new og(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 O(()=>{let a=t instanceof Wr?this.faceFeatureExtractor.forwardInput(t):t,r=ya(a,[7,7],[2,2],"valid").as2D(a.shape[0],-1),s=Bd(r,n.fc.age).as1D(),i=Bd(r,n.fc.gender);return{age:s,gender:i}})}forwardInput(t){return O(()=>{let{age:n,gender:a}=this.runNet(t);return{age:n,gender:ja(a)}})}async forward(t){return this.forwardInput(await vt(t))}async predictAgeAndGender(t){let n=await vt(t),a=await this.forwardInput(n),r=dt(a.age),s=dt(a.gender),i=r.map((l,u)=>({ageTensor:l,genderTensor:s[u]})),o=await Promise.all(i.map(async({ageTensor:l,genderTensor:u})=>{let p=l.dataSync()[0],d=u.dataSync()[0],c=d>.5,h=c?"male":"female",m=c?d:1-d;return l.dispose(),u.dispose(),{age:p,gender:h,genderProbability:m}}));return a.age.dispose(),a.gender.dispose(),n.isBatchInput?o:o[0]}getDefaultModelName(){return"age_gender_model"}dispose(t=!0){this.faceFeatureExtractor.dispose(t),super.dispose(t)}loadClassifierParams(t){let{params:n,paramMappings:a}=this.extractClassifierParams(t);this._params=n,this._paramMappings=a}extractClassifierParams(t){return uD(t)}extractParamsFromWeightMap(t){let{featureExtractorMap:n,classifierMap:a}=ag(t);return this.faceFeatureExtractor.loadFromWeightMap(n),pD(a)}extractParams(t){let a=t.slice(0,t.length-1539),r=t.slice(t.length-1539);return this.faceFeatureExtractor.extractWeights(a),this.extractClassifierParams(r)}};var $p=class extends Ap{postProcess(t,n,a){let r=a.map(({width:i,height:o})=>{let l=n/Math.max(o,i);return{width:i*l,height:o*l}}),s=r.length;return O(()=>{let i=(d,c)=>At([yn([68],d,"float32"),yn([68],c,"float32")],1).as2D(1,136).as1D(),o=(d,c)=>{let{width:h,height:m}=r[d];return c(h,m)?Math.abs(h-m)/2:0},l=d=>o(d,(c,h)=>c<h),u=d=>o(d,(c,h)=>h<c);return t.mul(yn([s,136],n,"float32")).sub(At(Array.from(Array(s),(d,c)=>i(l(c),u(c))))).div(At(Array.from(Array(s),(d,c)=>i(r[c].width,r[c].height))))})}forwardInput(t){return O(()=>{let n=this.runNet(t);return this.postProcess(n,t.inputSize,t.inputDimensions.map(([a,r])=>({height:a,width:r})))})}async forward(t){return this.forwardInput(await vt(t))}async detectLandmarks(t){let n=await vt(t),a=O(()=>dt(this.forwardInput(n))),r=await Promise.all(a.map(async(s,i)=>{let o=Array.from(s.dataSync()),l=o.filter((p,d)=>Gf(d)),u=o.filter((p,d)=>!Gf(d));return new vp(Array(68).fill(0).map((p,d)=>new He(l[d],u[d])),{height:n.getInputHeight(i),width:n.getInputWidth(i)})}));return a.forEach(s=>s.dispose()),n.isBatchInput?r:r[0]}getClassifierChannelsOut(){return 136}};var Dp=class extends $p{constructor(t=new _p){super("FaceLandmark68Net",t)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function cD(e){let t=[],{extractDenseBlock3Params:n}=ng(e,t),a={dense0:n("dense0",!0),dense1:n("dense1"),dense2:n("dense2")};return En(e,t),{params:a,paramMappings:t}}function dD(e){let t=[],{extractWeights:n,getRemainingWeights:a}=_n(e),{extractDenseBlock3Params:r}=eg(n,t),s=r(3,32,"dense0",!0),i=r(32,64,"dense1"),o=r(64,128,"dense2");if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o}}}var ug=class extends fn{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("TinyFaceFeatureExtractor - load model before inference");return O(()=>{let a=re(t.toBatchTensor(112,!0),"float32"),s=gr(a,[122.782,117.001,104.298]).div(255),i=Jf(s,n.dense0,!0);return i=Jf(i,n.dense1),i=Jf(i,n.dense2),i=ya(i,[14,14],[2,2],"valid"),i})}async forward(t){return this.forwardInput(await vt(t))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(t){return cD(t)}extractParams(t){return dD(t)}};var pg=class extends $p{constructor(t=new ug){super("FaceLandmark68TinyNet",t)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};var hD=class extends Dp{};function mD(e,t){return X(z(e,t.weights),t.biases)}function Ek(e,t,n,a,r="same"){let{filters:s,bias:i}=t.conv,o=$t(e,s,n,r);return o=X(o,i),o=mD(o,t.scale),a?Ke(o):o}function fD(e,t){return Ek(e,t,[1,1],!0)}function _k(e,t){return Ek(e,t,[1,1],!1)}function cg(e,t){return Ek(e,t,[2,2],!0,"valid")}function Kfe(e,t){function n(o,l,u){let p=e(o),d=p.length/(l*u*u);if(gk(d))throw new Error(`depth has to be an integer: ${d}, weights.length: ${p.length}, numFilters: ${l}, filterSize: ${u}`);return O(()=>De(Fa(p,[l,d,u,u]),[2,3,1,0]))}function a(o,l,u,p){let d=n(o,l,u),c=qe(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:d,bias:c}}function r(o,l){let u=qe(e(o)),p=qe(e(o));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:u,biases:p}}function s(o,l,u,p){let d=a(o,l,u,`${p}/conv`),c=r(l,`${p}/scale`);return{conv:d,scale:c}}function i(o,l,u,p,d=!1){let c=s((d?.5:1)*o,l,u,`${p}/conv1`),h=s(o,l,u,`${p}/conv2`);return{conv1:c,conv2:h}}return{extractConvLayerParams:s,extractResidualLayerParams:i}}function gD(e){let{extractWeights:t,getRemainingWeights:n}=_n(e),a=[],{extractConvLayerParams:r,extractResidualLayerParams:s}=Kfe(t,a),i=r(4704,32,7,"conv32_down"),o=s(9216,32,3,"conv32_1"),l=s(9216,32,3,"conv32_2"),u=s(9216,32,3,"conv32_3"),p=s(36864,64,3,"conv64_down",!0),d=s(36864,64,3,"conv64_1"),c=s(36864,64,3,"conv64_2"),h=s(36864,64,3,"conv64_3"),m=s(147456,128,3,"conv128_down",!0),f=s(147456,128,3,"conv128_1"),g=s(147456,128,3,"conv128_2"),b=s(589824,256,3,"conv256_down",!0),y=s(589824,256,3,"conv256_1"),x=s(589824,256,3,"conv256_2"),v=s(589824,256,3,"conv256_down_out"),I=O(()=>De(Ea(t(256*128),[128,256]),[1,0]));if(a.push({paramPath:"fc"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{conv32_down:i,conv32_1:o,conv32_2:l,conv32_3:u,conv64_down:p,conv64_1:d,conv64_2:c,conv64_3:h,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:b,conv256_1:y,conv256_2:x,conv256_down_out:v,fc:I},paramMappings:a}}function Xfe(e,t){let n=sa(e,t);function a(i){let o=n(`${i}/scale/weights`,1),l=n(`${i}/scale/biases`,1);return{weights:o,biases:l}}function r(i){let o=n(`${i}/conv/filters`,4),l=n(`${i}/conv/bias`,1),u=a(i);return{conv:{filters:o,bias:l},scale:u}}function s(i){return{conv1:r(`${i}/conv1`),conv2:r(`${i}/conv2`)}}return{extractConvLayerParams:r,extractResidualLayerParams:s}}function bD(e){let t=[],{extractConvLayerParams:n,extractResidualLayerParams:a}=Xfe(e,t),r=n("conv32_down"),s=a("conv32_1"),i=a("conv32_2"),o=a("conv32_3"),l=a("conv64_down"),u=a("conv64_1"),p=a("conv64_2"),d=a("conv64_3"),c=a("conv128_down"),h=a("conv128_1"),m=a("conv128_2"),f=a("conv256_down"),g=a("conv256_1"),b=a("conv256_2"),y=a("conv256_down_out"),{fc:x}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!fk(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);let v={conv32_down:r,conv32_1:s,conv32_2:i,conv32_3:o,conv64_down:l,conv64_1:u,conv64_2:p,conv64_3:d,conv128_down:c,conv128_1:h,conv128_2:m,conv256_down:f,conv256_1:g,conv256_2:b,conv256_down_out:y,fc:x};return En(e,t),{params:v,paramMappings:t}}function Ya(e,t){let n=fD(e,t.conv1);return n=_k(n,t.conv2),n=X(n,e),n=Ke(n),n}function Ud(e,t){let n=cg(e,t.conv1);n=_k(n,t.conv2);let a=ya(e,2,2,"valid"),r=It(a.shape),s=a.shape[3]!==n.shape[3];if(a.shape[1]!==n.shape[1]||a.shape[2]!==n.shape[2]){let o=[...n.shape];o[1]=1;let l=It(o);n=et([n,l],1);let u=[...n.shape];u[2]=1;let p=It(u);n=et([n,p],2)}return a=s?et([a,r],3):a,n=X(a,n),n=Ke(n),n}var Rp=class extends fn{constructor(){super("FaceRecognitionNet")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("FaceRecognitionNet - load model before inference");return O(()=>{let a=re(t.toBatchTensor(150,!0),"float32"),s=gr(a,[122.782,117.001,104.298]).div(255),i=cg(s,n.conv32_down);i=Dt(i,3,2,"valid"),i=Ya(i,n.conv32_1),i=Ya(i,n.conv32_2),i=Ya(i,n.conv32_3),i=Ud(i,n.conv64_down),i=Ya(i,n.conv64_1),i=Ya(i,n.conv64_2),i=Ya(i,n.conv64_3),i=Ud(i,n.conv128_down),i=Ya(i,n.conv128_1),i=Ya(i,n.conv128_2),i=Ud(i,n.conv256_down),i=Ya(i,n.conv256_1),i=Ya(i,n.conv256_2),i=Ud(i,n.conv256_down_out);let o=i.mean([1,2]);return $e(o,n.fc)})}async forward(t){return this.forwardInput(await vt(t))}async computeFaceDescriptor(t){var s;if((s=t==null?void 0:t.shape)!=null&&s.some(i=>i<=0))return new Float32Array(128);let n=await vt(t),a=O(()=>dt(this.forwardInput(n))),r=await Promise.all(a.map(i=>i.data()));return a.forEach(i=>i.dispose()),n.isBatchInput?r:r[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(t){return bD(t)}extractParams(t){return gD(t)}};function G2e(e){let t=new Rp;return t.extractWeights(e),t}function Ak(e,t){return{...e,...{descriptor:t}}}function K2e(e){return typeof e.age=="number"}function Fk(e,t){return{...e,...{age:t}}}function J2e(e){return(e.gender==="male"||e.gender==="female")&&gp(e.genderProbability)}function $k(e,t,n){return{...e,...{gender:t,genderProbability:n}}}function Yfe(e,t){function n(l,u){let p=Fa(e(9*l),[3,3,l,1]),d=qe(e(l)),c=qe(e(l)),h=qe(e(l)),m=qe(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/batch_norm_scale`},{paramPath:`${u}/batch_norm_offset`},{paramPath:`${u}/batch_norm_mean`},{paramPath:`${u}/batch_norm_variance`}),{filters:p,batch_norm_scale:d,batch_norm_offset:c,batch_norm_mean:h,batch_norm_variance:m}}function a(l,u,p,d,c){let h=Fa(e(l*u*p*p),[p,p,l,u]),m=qe(e(u));return t.push({paramPath:`${d}/filters`},{paramPath:`${d}/${c?"batch_norm_offset":"bias"}`}),{filters:h,bias:m}}function r(l,u,p,d){let{filters:c,bias:h}=a(l,u,p,d,!0);return{filters:c,batch_norm_offset:h}}function s(l,u,p){let d=n(l,`${p}/depthwise_conv`),c=r(l,u,1,`${p}/pointwise_conv`);return{depthwise_conv:d,pointwise_conv:c}}function i(){let l=r(3,32,3,"mobilenetv1/conv_0"),u=s(32,64,"mobilenetv1/conv_1"),p=s(64,128,"mobilenetv1/conv_2"),d=s(128,128,"mobilenetv1/conv_3"),c=s(128,256,"mobilenetv1/conv_4"),h=s(256,256,"mobilenetv1/conv_5"),m=s(256,512,"mobilenetv1/conv_6"),f=s(512,512,"mobilenetv1/conv_7"),g=s(512,512,"mobilenetv1/conv_8"),b=s(512,512,"mobilenetv1/conv_9"),y=s(512,512,"mobilenetv1/conv_10"),x=s(512,512,"mobilenetv1/conv_11"),v=s(512,1024,"mobilenetv1/conv_12"),I=s(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:u,conv_2:p,conv_3:d,conv_4:c,conv_5:h,conv_6:m,conv_7:f,conv_8:g,conv_9:b,conv_10:y,conv_11:x,conv_12:v,conv_13:I}}function o(){let l=r(1024,256,1,"prediction_layer/conv_0"),u=r(256,512,3,"prediction_layer/conv_1"),p=r(512,128,1,"prediction_layer/conv_2"),d=r(128,256,3,"prediction_layer/conv_3"),c=r(256,128,1,"prediction_layer/conv_4"),h=r(128,256,3,"prediction_layer/conv_5"),m=r(256,64,1,"prediction_layer/conv_6"),f=r(64,128,3,"prediction_layer/conv_7"),g=a(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),b=a(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),y=a(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=a(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),v=a(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),I=a(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),N=a(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),C=a(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),_=a(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),F=a(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),D=a(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),$=a(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:l,conv_1:u,conv_2:p,conv_3:d,conv_4:c,conv_5:h,conv_6:m,conv_7:f,box_predictor_0:{box_encoding_predictor:g,class_predictor:b},box_predictor_1:{box_encoding_predictor:y,class_predictor:x},box_predictor_2:{box_encoding_predictor:v,class_predictor:I},box_predictor_3:{box_encoding_predictor:N,class_predictor:C},box_predictor_4:{box_encoding_predictor:_,class_predictor:F},box_predictor_5:{box_encoding_predictor:D,class_predictor:$}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function yD(e){let t=[],{extractWeights:n,getRemainingWeights:a}=_n(e),{extractMobilenetV1Params:r,extractPredictionLayerParams:s}=Yfe(n,t),i=r(),o=s(),u={extra_dim:xd(n(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{params:{mobilenetv1:i,prediction_layer:o,output_layer:u},paramMappings:t}}function Zfe(e,t){let n=sa(e,t);function a(u,p,d){let c=n(`${u}/Conv2d_${p}_pointwise/weights`,4,`${d}/filters`),h=n(`${u}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${d}/batch_norm_offset`);return{filters:c,batch_norm_offset:h}}function r(u){let p=`mobilenetv1/conv_${u}`,d=`MobilenetV1/Conv2d_${u}_depthwise`,c=`${p}/depthwise_conv`,h=`${p}/pointwise_conv`,m=n(`${d}/depthwise_weights`,4,`${c}/filters`),f=n(`${d}/BatchNorm/gamma`,1,`${c}/batch_norm_scale`),g=n(`${d}/BatchNorm/beta`,1,`${c}/batch_norm_offset`),b=n(`${d}/BatchNorm/moving_mean`,1,`${c}/batch_norm_mean`),y=n(`${d}/BatchNorm/moving_variance`,1,`${c}/batch_norm_variance`);return{depthwise_conv:{filters:m,batch_norm_scale:f,batch_norm_offset:g,batch_norm_mean:b,batch_norm_variance:y},pointwise_conv:a("MobilenetV1",u,h)}}function s(){return{conv_0:a("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:r(1),conv_2:r(2),conv_3:r(3),conv_4:r(4),conv_5:r(5),conv_6:r(6),conv_7:r(7),conv_8:r(8),conv_9:r(9),conv_10:r(10),conv_11:r(11),conv_12:r(12),conv_13:r(13)}}function i(u,p){let d=n(`${u}/weights`,4,`${p}/filters`),c=n(`${u}/biases`,1,`${p}/bias`);return{filters:d,bias:c}}function o(u){let p=i(`Prediction/BoxPredictor_${u}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${u}/box_encoding_predictor`),d=i(`Prediction/BoxPredictor_${u}/ClassPredictor`,`prediction_layer/box_predictor_${u}/class_predictor`);return{box_encoding_predictor:p,class_predictor:d}}function l(){return{conv_0:a("Prediction",0,"prediction_layer/conv_0"),conv_1:a("Prediction",1,"prediction_layer/conv_1"),conv_2:a("Prediction",2,"prediction_layer/conv_2"),conv_3:a("Prediction",3,"prediction_layer/conv_3"),conv_4:a("Prediction",4,"prediction_layer/conv_4"),conv_5:a("Prediction",5,"prediction_layer/conv_5"),conv_6:a("Prediction",6,"prediction_layer/conv_6"),conv_7:a("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:o(0),box_predictor_1:o(1),box_predictor_2:o(2),box_predictor_3:o(3),box_predictor_4:o(4),box_predictor_5:o(5)}}return{extractMobilenetV1Params:s,extractPredictionLayerParams:l}}function xD(e){let t=[],{extractMobilenetV1Params:n,extractPredictionLayerParams:a}=Zfe(e,t),r=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Lr(r))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${r}`);let s={mobilenetv1:n(),prediction_layer:a(),output_layer:{extra_dim:r}};return En(e,t),{params:s,paramMappings:t}}function Ra(e,t,n){return O(()=>{let a=$t(e,t.filters,n,"same");return a=X(a,t.batch_norm_offset),an(a,0,6)})}var Jfe=.0010000000474974513;function Qfe(e,t,n){return O(()=>{let a=Ns(e,t.filters,n,"same");return a=Ss(a,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,Jfe),an(a,0,6)})}function ege(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function vD(e,t){return O(()=>{let n,a=Ra(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((s,i)=>{let o=i+1,l=ege(o);a=Qfe(a,s.depthwise_conv,l),a=Ra(a,s.pointwise_conv,[1,1]),o===11&&(n=a)}),n===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:a,conv11:n}})}function tge(e,t,n){let a=e.arraySync(),r=Math.min(a[t][0],a[t][2]),s=Math.min(a[t][1],a[t][3]),i=Math.max(a[t][0],a[t][2]),o=Math.max(a[t][1],a[t][3]),l=Math.min(a[n][0],a[n][2]),u=Math.min(a[n][1],a[n][3]),p=Math.max(a[n][0],a[n][2]),d=Math.max(a[n][1],a[n][3]),c=(i-r)*(o-s),h=(p-l)*(d-u);if(c<=0||h<=0)return 0;let m=Math.max(r,l),f=Math.max(s,u),g=Math.min(i,p),b=Math.min(o,d),y=Math.max(g-m,0)*Math.max(b-f,0);return y/(c+h-y)}function wD(e,t,n,a,r){let s=e.shape[0],i=Math.min(n,s),o=t.map((p,d)=>({score:p,boxIndex:d})).filter(p=>p.score>r).sort((p,d)=>d.score-p.score),l=p=>p<=a?1:0,u=[];return o.forEach(p=>{if(u.length>=i)return;let d=p.score;for(let c=u.length-1;c>=0;--c){let h=tge(e,p.boxIndex,u[c]);if(h!==0&&(p.score*=l(h),p.score<=r))break}d===p.score&&u.push(p.boxIndex)}),u}function nge(e){let t=dt(De(e,[1,0])),n=[pe(t[2],t[0]),pe(t[3],t[1])],a=[X(t[0],he(n[0],2)),X(t[1],he(n[1],2))];return{sizes:n,centers:a}}function age(e,t){let{sizes:n,centers:a}=nge(e),r=dt(De(t,[1,0])),s=he(z(dn(he(r[2],5)),n[0]),2),i=X(z(he(r[0],10),n[0]),a[0]),o=he(z(dn(he(r[3],5)),n[1]),2),l=X(z(he(r[1],10),n[1]),a[1]);return De(At([pe(i,s),pe(l,o),X(i,s),X(l,o)]),[1,0])}function kD(e,t,n){return O(()=>{let a=e.shape[0],r=age(W(Mn(n.extra_dim,[a,1,1]),[-1,4]),W(e,[-1,4]));r=W(r,[a,r.shape[0]/a,4]);let s=ha(Ve(t,[0,0,1],[-1,-1,-1])),i=Ve(s,[0,0,0],[-1,-1,1]);i=W(i,[a,i.shape[1]]);let o=dt(r),l=dt(i);return{boxes:o,scores:l}})}function ol(e,t){return O(()=>{let n=e.shape[0],a=W(il(e,t.box_encoding_predictor),[n,-1,1,4]),r=W(il(e,t.class_predictor),[n,-1,3]);return{boxPredictionEncoding:a,classPrediction:r}})}function ID(e,t,n){return O(()=>{let a=Ra(e,n.conv_0,[1,1]),r=Ra(a,n.conv_1,[2,2]),s=Ra(r,n.conv_2,[1,1]),i=Ra(s,n.conv_3,[2,2]),o=Ra(i,n.conv_4,[1,1]),l=Ra(o,n.conv_5,[2,2]),u=Ra(l,n.conv_6,[1,1]),p=Ra(u,n.conv_7,[2,2]),d=ol(t,n.box_predictor_0),c=ol(e,n.box_predictor_1),h=ol(r,n.box_predictor_2),m=ol(i,n.box_predictor_3),f=ol(l,n.box_predictor_4),g=ol(p,n.box_predictor_5),b=et([d.boxPredictionEncoding,c.boxPredictionEncoding,h.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),y=et([d.classPrediction,c.classPrediction,h.classPrediction,m.classPrediction,f.classPrediction,g.classPrediction],1);return{boxPredictions:b,classPredictions:y}})}var Ma=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 ll=class extends fn{constructor(){super("SsdMobilenetv1")}forwardInput(t){let{params:n}=this;if(!n)throw new Error("SsdMobilenetv1 - load model before inference");return O(()=>{let a=re(t.toBatchTensor(512,!1),"float32"),r=pe(he(a,127.5),1),s=vD(r,n.mobilenetv1),{boxPredictions:i,classPredictions:o}=ID(s.out,s.conv11,n.prediction_layer);return kD(i,o,n.output_layer)})}async forward(t){return this.forwardInput(await vt(t))}async locateFaces(t,n={}){let{maxResults:a,minConfidence:r}=new Ma(n),s=await vt(t),{boxes:i,scores:o}=this.forwardInput(s),l=i[0],u=o[0];for(let x=1;x<i.length;x++)i[x].dispose(),o[x].dispose();let p=Array.from(u.dataSync()),c=wD(l,p,a,.5,r),h=s.getReshapedInputDimensions(0),m=s.inputSize,f=m/h.width,g=m/h.height,b=l.arraySync(),y=c.map(x=>{let[v,I]=[Math.max(0,b[x][0]),Math.min(1,b[x][2])].map(_=>_*g),[N,C]=[Math.max(0,b[x][1]),Math.min(1,b[x][3])].map(_=>_*f);return new Ft(p[x],new xp(N,v,C-N,I-v),{height:s.getInputHeight(0),width:s.getInputWidth(0)})});return l.dispose(),u.dispose(),y}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(t){return xD(t)}extractParams(t){return yD(t)}};function rge(e){let t=new ll;return t.extractWeights(e),t}function GCe(e){return rge(e)}var SD=class extends ll{};var ND=.4,TD=[new He(.738768,.874946),new He(2.42204,2.65704),new He(4.30971,7.04493),new He(10.246,4.59428),new He(12.6868,11.8741)],CD=[new He(1.603231,2.094468),new He(6.041143,7.080126),new He(2.882459,3.518061),new He(4.266906,5.178857),new He(9.041765,10.66308)],ED=[117.001,114.697,97.404],_D="tiny_yolov2_model",AD="tiny_yolov2_separable_conv_model";var dg=e=>typeof e=="number";function FD(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(!dg(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=>dg(t.x)&&dg(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(dg)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Mp(e){return O(()=>{let t=z(e,ve(.10000000149011612));return X(Ke(pe(e,t)),t)})}function Br(e,t){return O(()=>{let n=xa(e,[[0,0],[1,1],[1,1],[0,0]]);return n=$t(n,t.conv.filters,[1,1],"valid"),n=pe(n,t.bn.sub),n=z(n,t.bn.truediv),n=X(n,t.conv.bias),Mp(n)})}function Vr(e,t){return O(()=>{let n=xa(e,[[0,0],[1,1],[1,1],[0,0]]);return n=Es(n,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),n=X(n,t.bias),Mp(n)})}function sge(e,t){let n=Tp(e,t);function a(i,o){let l=qe(e(i)),u=qe(e(i));return t.push({paramPath:`${o}/sub`},{paramPath:`${o}/truediv`}),{sub:l,truediv:u}}function r(i,o,l){let u=n(i,o,3,`${l}/conv`),p=a(o,`${l}/bn`);return{conv:u,bn:p}}let s=Cp(e,t);return{extractConvParams:n,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}}function $D(e,t,n,a){let{extractWeights:r,getRemainingWeights:s}=_n(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:u}=sge(r,i),p;if(t.withSeparableConvs){let[d,c,h,m,f,g,b,y,x]=a,v=t.isFirstLayerConv2d?o(d,c,3,"conv0"):u(d,c,"conv0"),I=u(c,h,"conv1"),N=u(h,m,"conv2"),C=u(m,f,"conv3"),_=u(f,g,"conv4"),F=u(g,b,"conv5"),D=y?u(b,y,"conv6"):void 0,$=x?u(y,x,"conv7"):void 0,S=o(x||y||b,5*n,1,"conv8");p={conv0:v,conv1:I,conv2:N,conv3:C,conv4:_,conv5:F,conv6:D,conv7:$,conv8:S}}else{let[d,c,h,m,f,g,b,y,x]=a,v=l(d,c,"conv0"),I=l(c,h,"conv1"),N=l(h,m,"conv2"),C=l(m,f,"conv3"),_=l(f,g,"conv4"),F=l(g,b,"conv5"),D=l(b,y,"conv6"),$=l(y,x,"conv7"),S=o(x,5*n,1,"conv8");p={conv0:v,conv1:I,conv2:N,conv3:C,conv4:_,conv5:F,conv6:D,conv7:$,conv8:S}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:p,paramMappings:i}}function ige(e,t){let n=sa(e,t);function a(o){let l=n(`${o}/sub`,1),u=n(`${o}/truediv`,1);return{sub:l,truediv:u}}function r(o){let l=n(`${o}/filters`,4),u=n(`${o}/bias`,1);return{filters:l,bias:u}}function s(o){let l=r(`${o}/conv`),u=a(`${o}/bn`);return{conv:l,bn:u}}let i=Ep(n);return{extractConvParams:r,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function DD(e,t){let n=[],{extractConvParams:a,extractConvWithBatchNormParams:r,extractSeparableConvParams:s}=ige(e,n),i;if(t.withSeparableConvs){let o=t.filterSizes&&t.filterSizes.length||9;i={conv0:t.isFirstLayerConv2d?a("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:o>7?s("conv6"):void 0,conv7:o>8?s("conv7"):void 0,conv8:a("conv8")}}else i={conv0:r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:r("conv6"),conv7:r("conv7"),conv8:a("conv8")};return En(e,n),{params:i,paramMappings:n}}var br=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 hg=class hg extends fn{constructor(t){super("TinyYolov2"),FD(t),this._config=t}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(t,n){let a=Br(t,n.conv0);return a=Dt(a,[2,2],[2,2],"same"),a=Br(a,n.conv1),a=Dt(a,[2,2],[2,2],"same"),a=Br(a,n.conv2),a=Dt(a,[2,2],[2,2],"same"),a=Br(a,n.conv3),a=Dt(a,[2,2],[2,2],"same"),a=Br(a,n.conv4),a=Dt(a,[2,2],[2,2],"same"),a=Br(a,n.conv5),a=Dt(a,[2,2],[1,1],"same"),a=Br(a,n.conv6),a=Br(a,n.conv7),il(a,n.conv8,"valid",!1)}runMobilenet(t,n){let a=this.config.isFirstLayerConv2d?Mp(il(t,n.conv0,"valid",!1)):Vr(t,n.conv0);return a=Dt(a,[2,2],[2,2],"same"),a=Vr(a,n.conv1),a=Dt(a,[2,2],[2,2],"same"),a=Vr(a,n.conv2),a=Dt(a,[2,2],[2,2],"same"),a=Vr(a,n.conv3),a=Dt(a,[2,2],[2,2],"same"),a=Vr(a,n.conv4),a=Dt(a,[2,2],[2,2],"same"),a=Vr(a,n.conv5),a=Dt(a,[2,2],[1,1],"same"),a=n.conv6?Vr(a,n.conv6):a,a=n.conv7?Vr(a,n.conv7):a,il(a,n.conv8,"valid",!1)}forwardInput(t,n){let{params:a}=this;if(!a)throw new Error("TinyYolov2 - load model before inference");return O(()=>{let r=re(t.toBatchTensor(n,!1),"float32");return r=this.config.meanRgb?gr(r,this.config.meanRgb):r,r=r.div(255),this.config.withSeparableConvs?this.runMobilenet(r,a):this.runTinyYolov2(r,a)})}async forward(t,n){return this.forwardInput(await vt(t),n)}async detect(t,n={}){let{inputSize:a,scoreThreshold:r}=new br(n),s=await vt(t),i=await this.forwardInput(s,a),o=O(()=>dt(i)[0].expandDims()),l={width:s.getInputWidth(0),height:s.getInputHeight(0)},u=await this.extractBoxes(o,s.getReshapedInputDimensions(0),r);i.dispose(),o.dispose();let p=u.map(g=>g.box),d=u.map(g=>g.score),c=u.map(g=>g.classScore),h=u.map(g=>this.config.classes[g.label]);return B$(p.map(g=>g.rescale(a)),d,this.config.iouThreshold,!0).map(g=>new yp(d[g],c[g],h[g],p[g],l))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return DD(t,this.config)}extractParams(t){let n=this.config.filterSizes||hg.DEFAULT_FILTER_SIZES,a=n?n.length:void 0;if(a!==7&&a!==8&&a!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${a} filterSizes in config`);return $D(t,this.config,this.boxEncodingSize,n)}async extractBoxes(t,n,a){let{width:r,height:s}=n,i=Math.max(r,s),o=i/r,l=i/s,u=t.shape[1],p=this.config.anchors.length,[d,c,h]=O(()=>{let b=t.reshape([u,u,p,this.boxEncodingSize]),y=b.slice([0,0,0,0],[u,u,p,4]),x=b.slice([0,0,0,4],[u,u,p,1]),v=this.withClassScores?ja(b.slice([0,0,0,5],[u,u,p,this.config.classes.length]),3):ve(0);return[y,x,v]}),m=[],f=await c.array(),g=await d.array();for(let b=0;b<u;b++)for(let y=0;y<u;y++)for(let x=0;x<p;x++){let v=qf(f[b][y][x][0]);if(!a||v>a){let I=(y+qf(g[b][y][x][0]))/u*o,N=(b+qf(g[b][y][x][1]))/u*l,C=Math.exp(g[b][y][x][2])*this.config.anchors[x].x/u*o,_=Math.exp(g[b][y][x][3])*this.config.anchors[x].y/u*l,F=I-C/2,D=N-_/2,$={row:b,col:y,anchor:x},{classScore:S,label:M}=this.withClassScores?await this.extractPredictedClass(h,$):{classScore:1,label:0};m.push({box:new bp(F,D,F+C,D+_),score:v,classScore:v*S,label:M,...$})}}return d.dispose(),c.dispose(),h.dispose(),m}async extractPredictedClass(t,n){let{row:a,col:r,anchor:s}=n,i=await t.array();return Array(this.config.classes.length).fill(0).map((o,l)=>i[a][r][s][l]).map((o,l)=>({classScore:o,label:l})).reduce((o,l)=>o.classScore>l.classScore?o:l)}};hg.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var Op=hg;var Pp=class extends Op{constructor(t=!0){let n={withSeparableConvs:t,iouThreshold:ND,classes:["face"],...t?{anchors:CD,meanRgb:ED}:{anchors:TD,withClassScores:!0}};super(n)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new Ft(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?AD:_D}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};function MEe(e,t=!0){let n=new Pp(t);return n.extractWeights(e),n}var mg=class extends br{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}};var Oa=class{async then(t){return t(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function ul(e,t,n,a,r=({alignedRect:s})=>s){let s=e.map(l=>Fp(l)?r(l):l.detection),i=a||(t instanceof Ce?await Ld(t,s):await Pd(t,s)),o=await n(i);return i.forEach(l=>l instanceof Ce&&l.dispose()),o}async function Lp(e,t,n,a,r){return ul([e],t,async s=>n(s[0]),a,r)}var RD=.4,MD=[new He(1.603231,2.094468),new He(6.041143,7.080126),new He(2.882459,3.518061),new He(4.266906,5.178857),new He(9.041765,10.66308)],OD=[117.001,114.697,97.404];var zp=class extends Op{constructor(){let t={withSeparableConvs:!0,iouThreshold:RD,classes:["face"],anchors:MD,meanRgb:OD,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(t)}get anchors(){return this.config.anchors}async locateFaces(t,n){return(await this.detect(t,n)).map(r=>new Ft(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(t){return super.extractParamsFromWeightMap(t)}};var rt={ssdMobilenetv1:new ll,tinyFaceDetector:new zp,tinyYolov2:new Pp,faceLandmark68Net:new Dp,faceLandmark68TinyNet:new pg,faceRecognitionNet:new Rp,faceExpressionNet:new rg,ageGenderNet:new lg},oge=(e,t)=>rt.ssdMobilenetv1.locateFaces(e,t),c_e=(e,t)=>rt.tinyFaceDetector.locateFaces(e,t),d_e=(e,t)=>rt.tinyYolov2.locateFaces(e,t),lge=e=>rt.faceLandmark68Net.detectLandmarks(e),h_e=e=>rt.faceLandmark68TinyNet.detectLandmarks(e),m_e=e=>rt.faceRecognitionNet.computeFaceDescriptor(e),f_e=e=>rt.faceExpressionNet.predictExpressions(e),g_e=e=>rt.ageGenderNet.predictAgeAndGender(e),uge=e=>rt.ssdMobilenetv1.load(e),b_e=e=>rt.tinyFaceDetector.load(e),y_e=e=>rt.tinyYolov2.load(e),x_e=e=>rt.faceLandmark68Net.load(e),v_e=e=>rt.faceLandmark68TinyNet.load(e),w_e=e=>rt.faceRecognitionNet.load(e),k_e=e=>rt.faceExpressionNet.load(e),I_e=e=>rt.ageGenderNet.load(e),S_e=uge,N_e=oge,T_e=lge;var fg=class extends Oa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.extractedFaces=r}},pl=class extends fg{async run(){let t=await this.parentTask,n=await ul(t,this.input,async a=>Promise.all(a.map(r=>rt.faceExpressionNet.predictExpressions(r))),this.extractedFaces);return t.map((a,r)=>Nk(a,n[r]))}withAgeAndGender(){return new dl(this,this.input)}},cl=class extends fg{async run(){let t=await this.parentTask;if(!t)return;let n=await Lp(t,this.input,a=>rt.faceExpressionNet.predictExpressions(a),this.extractedFaces);return Nk(t,n)}withAgeAndGender(){return new hl(this,this.input)}},Os=class extends pl{withAgeAndGender(){return new Ls(this,this.input)}withFaceDescriptors(){return new Ws(this,this.input)}},Ps=class extends cl{withAgeAndGender(){return new zs(this,this.input)}withFaceDescriptor(){return new Bs(this,this.input)}};var gg=class extends Oa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.extractedFaces=r}},dl=class extends gg{async run(){let t=await this.parentTask,n=await ul(t,this.input,async a=>Promise.all(a.map(r=>rt.ageGenderNet.predictAgeAndGender(r))),this.extractedFaces);return t.map((a,r)=>{let{age:s,gender:i,genderProbability:o}=n[r];return Fk($k(a,i,o),s)})}withFaceExpressions(){return new pl(this,this.input)}},hl=class extends gg{async run(){let t=await this.parentTask;if(!t)return;let{age:n,gender:a,genderProbability:r}=await Lp(t,this.input,s=>rt.ageGenderNet.predictAgeAndGender(s),this.extractedFaces);return Fk($k(t,a,r),n)}withFaceExpressions(){return new cl(this,this.input)}},Ls=class extends dl{withFaceExpressions(){return new Os(this,this.input)}withFaceDescriptors(){return new Ws(this,this.input)}},zs=class extends hl{withFaceExpressions(){return new Ps(this,this.input)}withFaceDescriptor(){return new Bs(this,this.input)}};var bg=class extends Oa{constructor(n,a){super();this.parentTask=n;this.input=a}},Ws=class extends bg{async run(){let t=await this.parentTask;return(await ul(t,this.input,a=>Promise.all(a.map(r=>rt.faceRecognitionNet.computeFaceDescriptor(r))),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}))).map((a,r)=>Ak(t[r],a))}withFaceExpressions(){return new Os(this,this.input)}withAgeAndGender(){return new Ls(this,this.input)}},Bs=class extends bg{async run(){let t=await this.parentTask;if(!t)return;let n=await Lp(t,this.input,a=>rt.faceRecognitionNet.computeFaceDescriptor(a),null,a=>a.landmarks.align(null,{useDlibAlignment:!0}));return Ak(t,n)}withFaceExpressions(){return new Ps(this,this.input)}withAgeAndGender(){return new zs(this,this.input)}};var yg=class extends Oa{constructor(n,a,r){super();this.parentTask=n;this.input=a;this.useTinyLandmarkNet=r}get landmarkNet(){return this.useTinyLandmarkNet?rt.faceLandmark68TinyNet:rt.faceLandmark68Net}},xg=class extends yg{async run(){let t=await this.parentTask,n=t.map(i=>i.detection),a=this.input instanceof Ce?await Ld(this.input,n):await Pd(this.input,n),r=await Promise.all(a.map(i=>this.landmarkNet.detectLandmarks(i)));return a.forEach(i=>i instanceof Ce&&i.dispose()),t.filter((i,o)=>r[o]).map((i,o)=>Vd(i,r[o]))}withFaceExpressions(){return new Os(this,this.input)}withAgeAndGender(){return new Ls(this,this.input)}withFaceDescriptors(){return new Ws(this,this.input)}},vg=class extends yg{async run(){let t=await this.parentTask;if(!t)return;let{detection:n}=t,a=this.input instanceof Ce?await Ld(this.input,[n]):await Pd(this.input,[n]),r=await this.landmarkNet.detectLandmarks(a[0]);return a.forEach(s=>s instanceof Ce&&s.dispose()),Vd(t,r)}withFaceExpressions(){return new Ps(this,this.input)}withAgeAndGender(){return new zs(this,this.input)}withFaceDescriptor(){return new Bs(this,this.input)}};var wg=class extends Oa{constructor(n,a=new Ma){super();this.input=n;this.options=a}},Gd=class extends wg{async run(){let{input:t,options:n}=this,a;if(n instanceof mg)a=rt.tinyFaceDetector.locateFaces(t,n);else if(n instanceof Ma)a=rt.ssdMobilenetv1.locateFaces(t,n);else if(n instanceof br)a=rt.tinyYolov2.locateFaces(t,n);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return a}runAndExtendWithFaceDetections(){return new Promise((t,n)=>{this.run().then(a=>t(a.map(r=>wp({},r)))).catch(a=>n(a))})}withFaceLandmarks(t=!1){return new xg(this.runAndExtendWithFaceDetections(),this.input,t)}withFaceExpressions(){return new pl(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new dl(this.runAndExtendWithFaceDetections(),this.input)}},kg=class extends wg{async run(){let t=await new Gd(this.input,this.options),n=t[0];return t.forEach(a=>{a.score>n.score&&(n=a)}),n}runAndExtendWithFaceDetection(){return new Promise(async t=>{let n=await this.run();t(n?wp({},n):void 0)})}withFaceLandmarks(t=!1){return new vg(this.runAndExtendWithFaceDetection(),this.input,t)}withFaceExpressions(){return new cl(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new hl(this.runAndExtendWithFaceDetection(),this.input)}};function IAe(e,t=new Ma){return new kg(e,t)}function Dk(e,t=new Ma){return new Gd(e,t)}async function pge(e,t){return Dk(e,new Ma(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function _Ae(e,t={}){return Dk(e,new br(t)).withFaceLandmarks().withFaceDescriptors()}var AAe=pge;function PD(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");let n=Array.from(e),a=Array.from(t);return Math.sqrt(n.map((r,s)=>r-a[s]).reduce((r,s)=>r+s*s,0))}var LD=class e{constructor(t,n=.6){this._distanceThreshold=n;let a=Array.isArray(t)?t:[t];if(!a.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let r=1,s=()=>`person ${r++}`;this._labeledDescriptors=a.map(i=>{if(i instanceof rl)return i;if(i instanceof Float32Array)return new rl(s(),[i]);if(i.descriptor&&i.descriptor instanceof Float32Array)return new rl(s(),[i.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(t,n){return n.map(a=>PD(a,t)).reduce((a,r)=>a+r,0)/(n.length||1)}matchDescriptor(t){return this.labeledDescriptors.map(({descriptors:n,label:a})=>new Dd(a,this.computeMeanDistance(t,n))).reduce((n,a)=>n.distance<a.distance?n:a)}findBestMatch(t){let n=this.matchDescriptor(t);return n.distance<this._distanceThreshold?n:new Dd("unknown",n.distance)}toJSON(){return{distanceThreshold:this._distanceThreshold,labeledDescriptors:this._labeledDescriptors.map(t=>t.toJSON())}}static fromJSON(t){let n=t.labeledDescriptors.map(a=>rl.fromJSON(a));return new e(n,t.distanceThreshold)}};function KAe(e){let t=new zp;return t.extractWeights(e),t}function cge(e,t){let{width:n,height:a}=new aa(t.width,t.height);if(n<=0||a<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:n,height:a})}`);if(Array.isArray(e))return e.map(r=>cge(r,{width:n,height:a}));if(Fp(e)){let r=e.detection.forSize(n,a),s=e.unshiftedLandmarks.forSize(r.box.width,r.box.height);return Vd(wp(e,r),s)}return zr(e)?wp(e,e.detection.forSize(n,a)):e instanceof ka||e instanceof Ft?e.forSize(n,a):e}var sFe=sD;export{lg as AgeGenderNet,bp as BoundingBox,mn as Box,Oa as ComposableTask,Ws as ComputeAllFaceDescriptorsTask,bg as ComputeFaceDescriptorsTaskBase,Bs as ComputeSingleFaceDescriptorTask,xg as DetectAllFaceLandmarksTask,Gd as DetectAllFacesTask,yg as DetectFaceLandmarksTaskBase,wg as DetectFacesTaskBase,vg as DetectSingleFaceLandmarksTask,kg as DetectSingleFaceTask,aa as Dimensions,nD as FACE_EXPRESSION_LABELS,Ft as FaceDetection,SD as FaceDetectionNet,rg as FaceExpressionNet,Ms as FaceExpressions,Dp as FaceLandmark68Net,pg as FaceLandmark68TinyNet,hD as FaceLandmarkNet,ka as FaceLandmarks,U$ as FaceLandmarks5,vp as FaceLandmarks68,Dd as FaceMatch,LD as FaceMatcher,Rp as FaceRecognitionNet,Ck as Gender,Rd as LabeledBox,rl as LabeledFaceDescriptors,Wr as NetInput,fn as NeuralNetwork,yp as ObjectDetection,He as Point,G$ as PredictedBox,xp as Rect,ll as SsdMobilenetv1,Ma as SsdMobilenetv1Options,zp as TinyFaceDetector,mg as TinyFaceDetectorOptions,Pp as TinyYolov2,br as TinyYolov2Options,AAe as allFaces,pge as allFacesSsdMobilenetv1,_Ae as allFacesTinyYolov2,H$ as awaitMediaLoaded,q$ as bufferToImage,m_e as computeFaceDescriptor,Np as createCanvas,Yf as createCanvasFromMedia,GCe as createFaceDetectionNet,G2e as createFaceRecognitionNet,rge as createSsdMobilenetv1,KAe as createTinyFaceDetector,MEe as createTinyYolov2,Dk as detectAllFaces,lge as detectFaceLandmarks,h_e as detectFaceLandmarksTiny,T_e as detectLandmarks,IAe as detectSingleFace,rD as draw,at as env,PD as euclideanDistance,Fk as extendWithAge,Ak as extendWithFaceDescriptor,wp as extendWithFaceDetection,Nk as extendWithFaceExpressions,Vd as extendWithFaceLandmarks,$k as extendWithGender,Ld as extractFaceTensors,Pd as extractFaces,Qke as fetchImage,X$ as fetchJson,rIe as fetchNetWeights,Rs as fetchOrThrow,pIe as fetchVideo,ra as getContext2dOrThrow,Sp as getMediaDimensions,j$ as imageTensorToCanvas,K$ as imageToSquare,m0e as inverseSigmoid,z$ as iou,Sk as isMediaElement,Xf as isMediaLoaded,K2e as isWithAge,zr as isWithFaceDetection,aD as isWithFaceExpressions,Fp as isWithFaceLandmarks,J2e as isWithGender,I_e as loadAgeGenderModel,S_e as loadFaceDetectionModel,k_e as loadFaceExpressionModel,x_e as loadFaceLandmarkModel,v_e as loadFaceLandmarkTinyModel,w_e as loadFaceRecognitionModel,uge as loadSsdMobilenetv1Model,b_e as loadTinyFaceDetectorModel,y_e as loadTinyYolov2Model,Z$ as loadWeightMap,N_e as locateFaces,bIe as matchDimensions,W$ as minBbox,rt as nets,B$ as nonMaxSuppression,gr as normalize,V$ as padToSquare,g_e as predictAgeAndGender,f_e as recognizeFaceExpressions,cge as resizeResults,kp as resolveInput,d0e as shuffleArray,qf as sigmoid,oge as ssdMobilenetv1,Pe as tf,c_e as tinyFaceDetector,d_e as tinyYolov2,vt as toNetInput,L$ as utils,FD as validateConfig,sFe as version};
|
|
//# sourceMappingURL=face-api.esm.js.map
|