learning_model 1.0.50 → 1.0.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/learning/mobilenet.ts +26 -0
- package/package.json +3 -3
- package/dist/index.bundle.js +0 -2
- package/dist/index.bundle.js.LICENSE.txt +0 -335
- package/dist/index.d.ts +0 -3
- package/dist/index.html +0 -1
- package/dist/index.js +0 -10
- package/dist/learning/base.d.ts +0 -23
- package/dist/learning/base.js +0 -2
- package/dist/learning/data_model.d.ts +0 -41
- package/dist/learning/data_model.js +0 -205
- package/dist/learning/data_model.test.d.ts +0 -1
- package/dist/learning/data_model.test.js +0 -56
- package/dist/learning/mobilenet.d.ts +0 -49
- package/dist/learning/mobilenet.js +0 -345
- package/dist/learning/mobilenet.test.d.ts +0 -1
- package/dist/learning/mobilenet.test.js +0 -79
- package/dist/lib/index.d.ts +0 -3
- package/dist/lib/learning/base.d.ts +0 -23
- package/dist/lib/learning/data_model.d.ts +0 -41
- package/dist/lib/learning/data_model.test.d.ts +0 -1
- package/dist/lib/learning/mobilenet.d.ts +0 -49
- package/dist/lib/learning/mobilenet.test.d.ts +0 -1
- package/dist/lib/utils/canvas.d.ts +0 -3
- package/dist/lib/utils/data_manager.d.ts +0 -15
- package/dist/lib/utils/dataset.d.ts +0 -6
- package/dist/lib/utils/tf.d.ts +0 -7
- package/dist/utils/canvas.d.ts +0 -3
- package/dist/utils/canvas.js +0 -47
- package/dist/utils/data_manager.d.ts +0 -15
- package/dist/utils/data_manager.js +0 -62
- package/dist/utils/dataset.d.ts +0 -6
- package/dist/utils/dataset.js +0 -21
- package/dist/utils/tf.d.ts +0 -7
- package/dist/utils/tf.js +0 -126
package/dist/index.bundle.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! For license information please see index.bundle.js.LICENSE.txt */
|
|
2
|
-
(()=>{var e={951:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Abs:()=>et,Acos:()=>tt,Acosh:()=>nt,AdadeltaOptimizer:()=>Qo,AdagradOptimizer:()=>tl,AdamOptimizer:()=>rl,AdamaxOptimizer:()=>cl,Add:()=>st,AddN:()=>rt,All:()=>at,Any:()=>it,ArgMax:()=>ot,ArgMin:()=>lt,Asin:()=>ut,Asinh:()=>ct,Atan:()=>ht,Atan2:()=>pt,Atanh:()=>dt,AvgPool:()=>ft,AvgPool3D:()=>gt,AvgPool3DGrad:()=>yt,AvgPoolGrad:()=>mt,BatchMatMul:()=>bt,BatchToSpaceND:()=>xt,Bincount:()=>wt,BitwiseAnd:()=>vt,BroadcastArgs:()=>It,BroadcastTo:()=>kt,Callback:()=>TS,CallbackList:()=>rw,Cast:()=>Nt,Ceil:()=>St,ClipByValue:()=>Tt,Complex:()=>Ct,ComplexAbs:()=>$t,Concat:()=>Et,Conv2D:()=>Rt,Conv2DBackpropFilter:()=>At,Conv2DBackpropInput:()=>_t,Conv3D:()=>Ft,Conv3DBackpropFilterV2:()=>Dt,Conv3DBackpropInputV2:()=>Ot,Cos:()=>Mt,Cosh:()=>Lt,CropAndResize:()=>Bt,Cumprod:()=>zt,Cumsum:()=>Pt,CustomCallback:()=>ow,DataStorage:()=>X,DenseBincount:()=>Wt,DepthToSpace:()=>Vt,DepthwiseConv2dNative:()=>Ut,DepthwiseConv2dNativeBackpropFilter:()=>Gt,DepthwiseConv2dNativeBackpropInput:()=>Ht,Diag:()=>jt,Dilation2D:()=>qt,Dilation2DBackpropFilter:()=>Xt,Dilation2DBackpropInput:()=>Kt,Draw:()=>Yt,ENV:()=>Ze,EarlyStopping:()=>ES,Einsum:()=>Jt,Elu:()=>Qt,EluGrad:()=>en,Environment:()=>qe,Equal:()=>nn,Erf:()=>tn,Exp:()=>sn,ExpandDims:()=>rn,Expm1:()=>an,FFT:()=>on,Fill:()=>ln,FlipLeftRight:()=>un,Floor:()=>cn,FloorDiv:()=>hn,FromPixels:()=>fr,FusedBatchNorm:()=>dn,FusedConv2D:()=>yr,FusedDepthwiseConv2D:()=>br,GPGPUContext:()=>tL,GatherNd:()=>fn,GatherV2:()=>pn,GraphModel:()=>ZT,Greater:()=>mn,GreaterEqual:()=>gn,History:()=>iw,IFFT:()=>bn,Identity:()=>yn,Imag:()=>xn,InputSpec:()=>ux,IsFinite:()=>wn,IsInf:()=>vn,IsNan:()=>kn,KernelBackend:()=>Y,LRN:()=>On,LRNGrad:()=>Mn,LayerVariable:()=>ix,LayersModel:()=>dv,LeakyRelu:()=>In,Less:()=>Nn,LessEqual:()=>Sn,LinSpace:()=>Tn,Log:()=>Cn,Log1p:()=>$n,LogSoftmax:()=>Fn,LogicalAnd:()=>En,LogicalNot:()=>Rn,LogicalOr:()=>An,LogicalXor:()=>_n,LowerBound:()=>Dn,MathBackendCPU:()=>p$,MathBackendWebGL:()=>Nz,MatrixBandPart:()=>Ln,Max:()=>zn,MaxPool:()=>Bn,MaxPool3D:()=>Vn,MaxPool3DGrad:()=>Un,MaxPoolGrad:()=>Wn,MaxPoolWithArgmax:()=>Gn,Maximum:()=>Pn,Mean:()=>Hn,Min:()=>jn,Minimum:()=>qn,MirrorPad:()=>Kn,Mod:()=>Xn,MomentumOptimizer:()=>dl,Multinomial:()=>Yn,Multiply:()=>Zn,Neg:()=>Jn,NonMaxSuppressionV3:()=>es,NonMaxSuppressionV4:()=>ts,NonMaxSuppressionV5:()=>ns,NotEqual:()=>Qn,OP_SCOPE_SUFFIX:()=>Ya,OneHot:()=>rs,OnesLike:()=>ss,Optimizer:()=>Jo,OptimizerConstructors:()=>Mu,Pack:()=>as,PadV2:()=>is,Pool:()=>os,Pow:()=>ls,Prelu:()=>us,Prod:()=>cs,RMSPropOptimizer:()=>pl,RNN:()=>kk,RaggedGather:()=>hs,RaggedRange:()=>ds,RaggedTensorToTensor:()=>ps,Range:()=>fs,Rank:()=>xa,Real:()=>ms,RealDiv:()=>Zt,Reciprocal:()=>gs,Reduction:()=>Nf,Relu:()=>ys,Relu6:()=>Is,Reshape:()=>bs,ResizeBilinear:()=>vs,ResizeBilinearGrad:()=>ks,ResizeNearestNeighbor:()=>xs,ResizeNearestNeighborGrad:()=>ws,Reverse:()=>Ns,RotateWithOffset:()=>mr,Round:()=>Ss,Rsqrt:()=>Ts,SGDOptimizer:()=>hl,ScatterNd:()=>Cs,SearchSorted:()=>Es,Select:()=>Rs,Selu:()=>As,Sequential:()=>gv,Sigmoid:()=>Ms,Sign:()=>Os,Sin:()=>Fs,Sinh:()=>Ds,Slice:()=>_s,Softmax:()=>Vs,Softplus:()=>Ls,SpaceToBatchND:()=>Bs,SparseFillEmptyRows:()=>Us,SparseReshape:()=>Gs,SparseSegmentMean:()=>Hs,SparseSegmentSum:()=>js,SparseToDense:()=>qs,SplitV:()=>Ws,Sqrt:()=>zs,Square:()=>Xs,SquaredDifference:()=>Ks,StaticRegexReplace:()=>Ys,Step:()=>pr,StridedSlice:()=>Zs,StringNGrams:()=>Js,StringSplit:()=>Qs,StringToHashBucketFast:()=>er,Sub:()=>tr,Sum:()=>Ps,SymbolicTensor:()=>cx,Tan:()=>nr,Tanh:()=>sr,Tensor:()=>ga,TensorBuffer:()=>da,TensorScatterUpdate:()=>$s,Tile:()=>rr,TopK:()=>ar,Transform:()=>ir,Transpose:()=>or,Unique:()=>lr,Unpack:()=>ur,UnsortedSegmentSum:()=>cr,UpperBound:()=>hr,Variable:()=>ba,ZerosLike:()=>dr,_FusedMatMul:()=>gr,abs:()=>al,acos:()=>Lu,acosh:()=>zu,add:()=>Ao,addN:()=>Pu,all:()=>Bu,any:()=>Wu,argMax:()=>Vu,argMin:()=>Uu,asin:()=>Gu,asinh:()=>Hu,atan:()=>ju,atan2:()=>qu,atanh:()=>Ku,avgPool:()=>hc,avgPool3d:()=>dc,backend:()=>ki,backend_util:()=>y,basicLSTMCell:()=>yc,batchNorm:()=>xc,batchNorm2d:()=>wc,batchNorm3d:()=>vc,batchNorm4d:()=>kc,batchToSpaceND:()=>bc,bincount:()=>Ic,bitwiseAnd:()=>Nc,booleanMaskAsync:()=>Sp,broadcastArgs:()=>Sc,broadcastTo:()=>Tc,broadcast_util:()=>o,browser:()=>c,buffer:()=>Co,callbacks:()=>RS,cast:()=>$o,ceil:()=>Cc,clipByValue:()=>$c,clone:()=>Eo,complex:()=>Ja,concat:()=>pc,concat1d:()=>Ec,concat2d:()=>Rc,concat3d:()=>Ac,concat4d:()=>_c,constraints:()=>x,conv1d:()=>Dc,conv2d:()=>Fc,conv2dTranspose:()=>Mc,conv3d:()=>Lc,conv3dTranspose:()=>Pc,copyRegisteredKernels:()=>Rr,cos:()=>Bc,cosh:()=>Wc,cosineWindow:()=>_p,cumprod:()=>Vc,cumsum:()=>Uc,customGrad:()=>Uo,data:()=>H,denseBincount:()=>Gc,deprecationWarn:()=>ii,depthToSpace:()=>Hc,depthwiseConv2d:()=>jc,deregisterOp:()=>MS,device_util:()=>a,diag:()=>qc,dilation2d:()=>Kc,disableDeprecationWarnings:()=>ai,dispose:()=>di,disposeVariables:()=>oi,div:()=>Fo,divNoNan:()=>Zc,dot:()=>Jc,dropout:()=>Rp,einsum:()=>Qc,elu:()=>eh,enableDebugMode:()=>ri,enableProdMode:()=>si,enclosingPowerOfTwo:()=>Ap,engine:()=>li,ensureShape:()=>th,env:()=>Xe,equal:()=>Xc,erf:()=>nh,euclideanNorm:()=>gh,exp:()=>yh,expandDims:()=>bh,expm1:()=>xh,eye:()=>vh,fft:()=>Qd,fill:()=>el,findBackend:()=>xi,findBackendFactory:()=>wi,floor:()=>kh,floorDiv:()=>_o,forceHalfFloat:()=>Tz,fused:()=>m,gather:()=>Ih,gatherND:()=>Ep,gather_util:()=>h,getBackend:()=>yi,getGradient:()=>Nr,getKernel:()=>Ir,getKernelsForBackend:()=>Sr,gpgpu_util:()=>K,grad:()=>zo,grads:()=>Po,greater:()=>Nh,greaterEqual:()=>Sh,ifft:()=>ep,imag:()=>Ll,image:()=>Gf,inTopKAsync:()=>Fp,initializers:()=>w,input:()=>xv,io:()=>l,irfft:()=>tp,isFinite:()=>Th,isInf:()=>Ch,isNaN:()=>$h,keep:()=>pi,kernel_impls:()=>b,layers:()=>v,leakyRelu:()=>Eh,less:()=>Rh,lessEqual:()=>Ah,linalg:()=>Hf,linspace:()=>_h,loadGraphModel:()=>JT,loadGraphModelSync:()=>QT,loadLayersModel:()=>mv,localResponseNormalization:()=>Fh,log:()=>Dh,log1p:()=>Oh,logSigmoid:()=>Lh,logSoftmax:()=>zh,logSumExp:()=>Ph,logicalAnd:()=>Bh,logicalNot:()=>Wh,logicalOr:()=>Vh,logicalXor:()=>Uh,losses:()=>jf,lowerBound:()=>jh,matMul:()=>Ol,math:()=>u,max:()=>hh,maxPool:()=>qh,maxPool3d:()=>Kh,maxPoolWithArgmax:()=>Xh,maximum:()=>ul,mean:()=>Yh,memory:()=>ui,meshgrid:()=>Qh,metrics:()=>k,min:()=>dh,minimum:()=>ed,mirrorPad:()=>td,mod:()=>nd,model:()=>yv,models:()=>I,moments:()=>sd,movingAverage:()=>Tp,mul:()=>Do,multiRNNCell:()=>rd,multinomial:()=>ad,neg:()=>zl,nextFrame:()=>Zf,norm:()=>mh,notEqual:()=>id,oneHot:()=>Ml,ones:()=>Jh,onesLike:()=>od,op:()=>Za,outerProduct:()=>ld,pad:()=>ud,pad1d:()=>cd,pad2d:()=>hd,pad3d:()=>dd,pad4d:()=>pd,pool:()=>md,pow:()=>nl,prelu:()=>gd,print:()=>Ro,prod:()=>yd,profile:()=>ci,raggedGather:()=>bd,raggedRange:()=>xd,raggedTensorToTensor:()=>wd,rand:()=>vd,randomGamma:()=>Td,randomNormal:()=>Cd,randomStandardNormal:()=>$d,randomUniform:()=>Ed,randomUniformInt:()=>Rd,range:()=>Ad,ready:()=>gi,real:()=>Pl,reciprocal:()=>_d,registerBackend:()=>vi,registerCallbackConstructor:()=>wv,registerGradient:()=>Cr,registerKernel:()=>Tr,registerOp:()=>DS,regularizers:()=>N,relu:()=>Fd,relu6:()=>Dd,removeBackend:()=>bi,reshape:()=>cc,reverse:()=>Od,reverse1d:()=>Md,reverse2d:()=>Ld,reverse3d:()=>zd,reverse4d:()=>Pd,rfft:()=>sp,round:()=>Bd,rsqrt:()=>Wd,scalar:()=>Ho,scatterND:()=>Cp,scatter_util:()=>d,searchSorted:()=>Hh,selu:()=>Vd,separableConv2d:()=>Ud,sequential:()=>bv,serialization:()=>i,setBackend:()=>mi,setPlatform:()=>Ii,setWebGLContext:()=>KD,setdiff1dAsync:()=>Gd,shared:()=>j,sigmoid:()=>fc,sign:()=>Hd,signal:()=>Uf,sin:()=>jd,sinh:()=>qd,slice:()=>mc,slice1d:()=>Kd,slice2d:()=>Xd,slice3d:()=>Yd,slice4d:()=>Zd,slice_util:()=>p,softmax:()=>Jd,softplus:()=>Mh,spaceToBatchND:()=>fd,sparse:()=>qf,sparseToDense:()=>$p,spectral:()=>Vf,split:()=>np,sqrt:()=>Oo,square:()=>Mo,squaredDifference:()=>rp,squeeze:()=>ap,stack:()=>ip,step:()=>op,stridedSlice:()=>lp,string:()=>Kf,sub:()=>sl,sum:()=>ph,sumOutType:()=>Ta,tan:()=>up,tanh:()=>gc,tensor:()=>ei,tensor1d:()=>cp,tensor2d:()=>hp,tensor3d:()=>Vl,tensor4d:()=>dp,tensor5d:()=>pp,tensor6d:()=>fp,tensorScatterUpdate:()=>mp,tensor_util:()=>r,test_util:()=>f,tidy:()=>hi,tile:()=>wh,time:()=>fi,topk:()=>gp,train:()=>Xf,transpose:()=>Bl,truncatedNormal:()=>yp,unique:()=>bp,unregisterGradient:()=>Er,unregisterKernel:()=>$r,unsortedSegmentSum:()=>xp,unstack:()=>wp,upcastType:()=>Sa,upperBound:()=>vp,util:()=>s,valueAndGrad:()=>Bo,valueAndGrads:()=>Wo,variable:()=>kp,variableGrads:()=>Vo,version:()=>vH,version_converter:()=>eC,version_core:()=>Ou,version_cpu:()=>BR,version_layers:()=>jw,version_webgl:()=>Sz,webgl:()=>Cz,webgl_util:()=>q,where:()=>Yc,whereAsync:()=>Np,zeros:()=>Zh,zerosLike:()=>Lo});var s={};n.r(s),n.d(s,{arraysEqual:()=>de,arraysEqualWithNull:()=>he,assert:()=>ie,assertNonNegativeIntegerDimensions:()=>Ve,assertNonNull:()=>le,assertShapesMatch:()=>oe,bytesFromStringArray:()=>$e,bytesPerElement:()=>Ce,checkConversionForErrors:()=>Ne,clamp:()=>ee,computeStrides:()=>Oe,convertBackendValuesAndArrayBuffer:()=>ze,createScalarValue:()=>qr,createShuffledIndices:()=>ge,decodeString:()=>Jr,distSquared:()=>ae,encodeString:()=>Zr,fetch:()=>Yr,fingerPrint64:()=>jr,flatten:()=>ea,getArrayFromDType:()=>Ie,getTypedArrayFromDType:()=>ke,hasEncodingLoss:()=>Te,hexToLong:()=>Or,indexToLoc:()=>Ge,inferDtype:()=>_e,inferFromImplicitShape:()=>xe,isBoolean:()=>Re,isFunction:()=>Fe,isInt:()=>pe,isNumber:()=>Ae,isPromise:()=>He,isScalarShape:()=>ce,isString:()=>Ee,isTypedArray:()=>Qr,isValidDtype:()=>Se,locToIndex:()=>Ue,makeOnesTypedArray:()=>Pe,makeZerosNestedTypedArray:()=>We,makeZerosTypedArray:()=>Be,nearestDivisor:()=>De,nearestLargerEven:()=>te,now:()=>Xr,parseAxisParam:()=>we,randUniform:()=>re,repeatedTry:()=>be,rightPad:()=>ye,shuffle:()=>J,shuffleCombo:()=>Q,sizeFromShape:()=>ue,sizeToSquarishShape:()=>me,squeezeShape:()=>ve,sum:()=>se,swap:()=>ne,tanh:()=>fe,toNestedArray:()=>Le,toTypedArray:()=>Kr});var r={};n.r(r),n.d(r,{assertTypesMatch:()=>Ra,getTensorsInContainer:()=>_a,isTensorInList:()=>Aa,makeTypesMatch:()=>Ea});var a={};n.r(a),n.d(a,{isBrowser:()=>Ua,isMobile:()=>Va,mockIsMobile:()=>Wa});var i={};n.r(i),n.d(i,{Serializable:()=>Ko,SerializationMap:()=>Xo,getRegisteredName:()=>Zo,registerClass:()=>Yo});var o={};n.r(o),n.d(o,{assertAndGetBroadcastShape:()=>ll,getBroadcastDims:()=>il,getReductionAxes:()=>ol});var l={};n.r(l),n.d(l,{CompositeArrayBuffer:()=>ni,browserFiles:()=>bl,browserHTTPRequest:()=>Cl,concatenateArrayBuffers:()=>Oi,copyModel:()=>vo,decodeWeights:()=>Ti,decodeWeightsStream:()=>Ai,encodeWeights:()=>Si,fromMemory:()=>Al,fromMemorySync:()=>_l,getLoadHandlers:()=>ji,getModelArtifactsForJSON:()=>Pi,getModelArtifactsForJSONSync:()=>zi,getModelArtifactsInfoForJSON:()=>Bi,getSaveHandlers:()=>Hi,getWeightSpecs:()=>Wi,http:()=>Tl,isHTTPScheme:()=>Nl,listModels:()=>xo,loadWeights:()=>vl,moveModel:()=>ko,registerLoadRouter:()=>Gi,registerSaveRouter:()=>Ui,removeModel:()=>wo,weightsLoaderFactory:()=>kl,withSaveHandler:()=>Fl,withSaveHandlerSync:()=>Dl});var u={};n.r(u),n.d(u,{confusionMatrix:()=>Wl});var c={};n.r(c),n.d(c,{draw:()=>Yl,fromPixels:()=>Zl,fromPixelsAsync:()=>ql,toPixels:()=>Xl});var h={};n.r(h),n.d(h,{prepareAndValidate:()=>Jl});var d={};n.r(d),n.d(d,{calculateShapes:()=>tu,validateInput:()=>eu,validateUpdateShape:()=>Ql});var p={};n.r(p),n.d(p,{assertParamsValid:()=>ru,computeFlatOffset:()=>yu,computeOutShape:()=>iu,getNormalizedAxes:()=>cu,isSliceContinous:()=>gu,maskToAxes:()=>au,parseSliceParams:()=>bu,sliceInfo:()=>xu,startForAxis:()=>fu,startIndicesWithElidedDims:()=>hu,stopForAxis:()=>mu,stopIndicesWithElidedDims:()=>du,stridesForAxis:()=>pu,stridesWithElidedDims:()=>ou});var f={};n.r(f),n.d(f,{TEST_EPSILON_FLOAT16:()=>ku,createVideoElement:()=>Fu,encodeStrings:()=>_u,expectArrayBuffersEqual:()=>Au,expectArraysClose:()=>Iu,expectArraysEqual:()=>Cu,expectNumbersClose:()=>$u,expectPromiseToFail:()=>Tu,expectValuesInRange:()=>Ru,play:()=>Du,testEpsilon:()=>Nu});var m={};n.r(m),n.d(m,{conv2d:()=>Pp,depthwiseConv2d:()=>Vp,matMul:()=>Up});var g={};n.r(g),n.d(g,{collectGatherOpShapeInfo:()=>eg,computeOutShape:()=>Qm,segOpComputeOptimalWindowSize:()=>Jm});var y={};n.r(y),n.d(y,{ERF_A1:()=>gm,ERF_A2:()=>ym,ERF_A3:()=>bm,ERF_A4:()=>xm,ERF_A5:()=>wm,ERF_P:()=>mm,PARALLELIZE_THRESHOLD:()=>am,RowPartitionType:()=>em,SELU_SCALE:()=>fm,SELU_SCALEALPHA:()=>pm,applyActivation:()=>Lp,assertAndGetBroadcastShape:()=>ll,assertAxesAreInnerMostDims:()=>oh,assertParamsConsistent:()=>Jf,assignToTypedArray:()=>Tm,axesAreInnerMostDims:()=>sh,calculateShapes:()=>tu,checkEinsumDimSizes:()=>Om,checkPadOnDimRoundingMode:()=>uc,combineLocations:()=>rh,combineRaggedTensorToTensorShapes:()=>tm,complexWithEvenIndex:()=>Im,complexWithOddIndex:()=>Nm,computeConv2DInfo:()=>Ju,computeConv3DInfo:()=>Qu,computeDefaultPad:()=>ec,computeDilation2DInfo:()=>Xu,computeOptimalWindowSize:()=>im,computeOutAndReduceShapes:()=>ah,computeOutShape:()=>Qf,computePool2DInfo:()=>Yu,computePool3DInfo:()=>Zu,convertConv2DDataFormat:()=>lc,decodeEinsumEquation:()=>Fm,eitherStridesOrDilationsAreOne:()=>ic,expandShapeToKeepDim:()=>ih,exponent:()=>$m,exponents:()=>Cm,fromStringArrayToUint8:()=>ng,fromUint8ToStringArray:()=>tg,getAxesPermutation:()=>lh,getBroadcastDims:()=>il,getComplexWithIndex:()=>Sm,getEinsumComputePath:()=>Mm,getEinsumPermutation:()=>Dm,getFusedBiasGradient:()=>Mp,getFusedDyActivation:()=>Op,getImageCenter:()=>om,getInnerMostAxes:()=>ch,getPermuted:()=>um,getRaggedRank:()=>sm,getReductionAxes:()=>ol,getReshaped:()=>lm,getReshapedPermuted:()=>cm,getRowPartitionTypesHelper:()=>nm,getSliceBeginCoords:()=>hm,getSliceSize:()=>dm,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Bm,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>Wm,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Vm,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Hm,getSparseReshapeInputOutputMismatchErrorMessage:()=>qm,getSparseReshapeInputOutputMultipleErrorMessage:()=>jm,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>Um,getSparseReshapeNegativeOutputDimErrorMessage:()=>Gm,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>Zm,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>Km,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>Xm,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>Ym,getUndoAxesPermutation:()=>uh,isIdentityPermutation:()=>Lm,log:()=>wr,mergeRealAndImagArrays:()=>vm,prepareAndValidate:()=>Jl,prepareSplitSize:()=>Pm,segment_util:()=>g,shouldFuse:()=>zp,slice_util:()=>p,splitRealAndImagArrays:()=>km,stridesOrDilationsArePositive:()=>oc,tupleValuesAreOne:()=>ac,upcastType:()=>Sa,validateDefaultValueShape:()=>rm,validateInput:()=>eu,validateUpdateShape:()=>Ql,warn:()=>xr});var b={};n.r(b),n.d(b,{nonMaxSuppressionV3Impl:()=>sf,nonMaxSuppressionV4Impl:()=>rf,nonMaxSuppressionV5Impl:()=>af,whereImpl:()=>Ip});var x={};n.r(x),n.d(x,{maxNorm:()=>Ox,minMaxNorm:()=>zx,nonNeg:()=>Lx,unitNorm:()=>Mx});var w={};n.r(w),n.d(w,{constant:()=>Wx,glorotNormal:()=>Kx,glorotUniform:()=>qx,heNormal:()=>Xx,heUniform:()=>Yx,identity:()=>Hx,leCunNormal:()=>Zx,leCunUniform:()=>Jx,ones:()=>Bx,orthogonal:()=>Qx,randomNormal:()=>Ux,randomUniform:()=>Vx,truncatedNormal:()=>Gx,varianceScaling:()=>jx,zeros:()=>Px});var v={};n.r(v),n.d(v,{Layer:()=>fx,RNN:()=>kk,RNNCell:()=>Ik,activation:()=>nN,add:()=>hN,alphaDropout:()=>tS,average:()=>dN,averagePooling1d:()=>vN,averagePooling2d:()=>NN,averagePooling3d:()=>CN,avgPool1d:()=>kN,avgPool2d:()=>SN,avgPool3d:()=>$N,avgPooling1d:()=>IN,avgPooling2d:()=>TN,avgPooling3d:()=>EN,batchNormalization:()=>bN,bidirectional:()=>qN,categoryEncoding:()=>iS,centerCrop:()=>rS,concatenate:()=>pN,conv1d:()=>qI,conv2d:()=>KI,conv2dTranspose:()=>XI,conv3d:()=>YI,conv3dTranspose:()=>ZI,convLstm2d:()=>UN,convLstm2dCell:()=>GN,cropping2D:()=>QI,dense:()=>sN,depthwiseConv2d:()=>tN,dot:()=>yN,dropout:()=>rN,elu:()=>WI,embedding:()=>cN,flatten:()=>iN,gaussianDropout:()=>eS,gaussianNoise:()=>QN,globalAveragePooling1d:()=>RN,globalAveragePooling2d:()=>AN,globalMaxPool1d:()=>XN,globalMaxPool2d:()=>YN,globalMaxPooling1d:()=>_N,globalMaxPooling2d:()=>FN,gru:()=>LN,gruCell:()=>zN,input:()=>xv,inputLayer:()=>BI,layerNormalization:()=>xN,leakyReLU:()=>UI,lstm:()=>PN,lstmCell:()=>BN,masking:()=>nS,maxPool1d:()=>ZN,maxPool2d:()=>JN,maxPooling1d:()=>DN,maxPooling2d:()=>ON,maxPooling3d:()=>MN,maximum:()=>fN,minimum:()=>mN,multiply:()=>gN,permute:()=>uN,prelu:()=>GI,randomWidth:()=>oS,reLU:()=>VI,repeatVector:()=>oN,rescaling:()=>sS,reshape:()=>lN,resizing:()=>aS,rnn:()=>HN,separableConv2d:()=>JI,simpleRNN:()=>WN,simpleRNNCell:()=>VN,softmax:()=>HI,spatialDropout1d:()=>aN,stackedRNNCells:()=>jN,thresholdedReLU:()=>jI,timeDistributed:()=>KN,upSampling2d:()=>eN,zeroPadding2d:()=>wN});var k={};n.r(k),n.d(k,{MAPE:()=>bS,MSE:()=>vS,binaryAccuracy:()=>lS,binaryCrossentropy:()=>uS,categoricalAccuracy:()=>hS,categoricalCrossentropy:()=>dS,cosineProximity:()=>mS,mape:()=>xS,meanAbsoluteError:()=>gS,meanAbsolutePercentageError:()=>yS,meanSquaredError:()=>wS,mse:()=>kS,precision:()=>pS,recall:()=>fS,sparseCategoricalAccuracy:()=>cS});var I={};n.r(I),n.d(I,{modelFromJSON:()=>fv});var N={};n.r(N),n.d(N,{l1:()=>NS,l1l2:()=>IS,l2:()=>SS});var S={};n.r(S),n.d(S,{json:()=>HS});var T={};n.r(T),n.d(T,{json:()=>jS});var C={};n.r(C),n.d(C,{json:()=>qS});var $={};n.r($),n.d($,{json:()=>KS});var E={};n.r(E),n.d(E,{json:()=>XS});var R={};n.r(R),n.d(R,{json:()=>YS});var A={};n.r(A),n.d(A,{json:()=>ZS});var _={};n.r(_),n.d(_,{json:()=>JS});var F={};n.r(F),n.d(F,{json:()=>QS});var D={};n.r(D),n.d(D,{json:()=>eT});var O={};n.r(O),n.d(O,{json:()=>tT});var M={};n.r(M),n.d(M,{json:()=>nT});var L={};n.r(L),n.d(L,{json:()=>sT});var z={};n.r(z),n.d(z,{json:()=>rT});var P={};n.r(P),n.d(P,{json:()=>aT});var B={};n.r(B),n.d(B,{json:()=>iT});var W={};n.r(W),n.d(W,{json:()=>oT});var V={};n.r(V),n.d(V,{json:()=>lT});var U={};n.r(U),n.d(U,{json:()=>uT});var G={};n.r(G),n.d(G,{OP_SCOPE_SUFFIX:()=>Ya,abs:()=>al,acos:()=>Lu,acosh:()=>zu,add:()=>Ao,addN:()=>Pu,all:()=>Bu,any:()=>Wu,argMax:()=>Vu,argMin:()=>Uu,asin:()=>Gu,asinh:()=>Hu,atan:()=>ju,atan2:()=>qu,atanh:()=>Ku,avgPool:()=>hc,avgPool3d:()=>dc,basicLSTMCell:()=>yc,batchNorm:()=>xc,batchNorm2d:()=>wc,batchNorm3d:()=>vc,batchNorm4d:()=>kc,batchToSpaceND:()=>bc,bincount:()=>Ic,bitwiseAnd:()=>Nc,booleanMaskAsync:()=>Sp,broadcastArgs:()=>Sc,broadcastTo:()=>Tc,buffer:()=>Co,cast:()=>$o,ceil:()=>Cc,clipByValue:()=>$c,clone:()=>Eo,complex:()=>Ja,concat:()=>pc,concat1d:()=>Ec,concat2d:()=>Rc,concat3d:()=>Ac,concat4d:()=>_c,conv1d:()=>Dc,conv2d:()=>Fc,conv2dTranspose:()=>Mc,conv3d:()=>Lc,conv3dTranspose:()=>Pc,cos:()=>Bc,cosh:()=>Wc,cosineWindow:()=>_p,cumprod:()=>Vc,cumsum:()=>Uc,denseBincount:()=>Gc,depthToSpace:()=>Hc,depthwiseConv2d:()=>jc,diag:()=>qc,dilation2d:()=>Kc,div:()=>Fo,divNoNan:()=>Zc,dot:()=>Jc,dropout:()=>Rp,einsum:()=>Qc,elu:()=>eh,enclosingPowerOfTwo:()=>Ap,ensureShape:()=>th,equal:()=>Xc,erf:()=>nh,euclideanNorm:()=>gh,exp:()=>yh,expandDims:()=>bh,expm1:()=>xh,eye:()=>vh,fft:()=>Qd,fill:()=>el,floor:()=>kh,floorDiv:()=>_o,fused:()=>m,gather:()=>Ih,gatherND:()=>Ep,greater:()=>Nh,greaterEqual:()=>Sh,ifft:()=>ep,imag:()=>Ll,image:()=>Gf,inTopKAsync:()=>Fp,irfft:()=>tp,isFinite:()=>Th,isInf:()=>Ch,isNaN:()=>$h,leakyRelu:()=>Eh,less:()=>Rh,lessEqual:()=>Ah,linalg:()=>Hf,linspace:()=>_h,localResponseNormalization:()=>Fh,log:()=>Dh,log1p:()=>Oh,logSigmoid:()=>Lh,logSoftmax:()=>zh,logSumExp:()=>Ph,logicalAnd:()=>Bh,logicalNot:()=>Wh,logicalOr:()=>Vh,logicalXor:()=>Uh,losses:()=>jf,lowerBound:()=>jh,matMul:()=>Ol,max:()=>hh,maxPool:()=>qh,maxPool3d:()=>Kh,maxPoolWithArgmax:()=>Xh,maximum:()=>ul,mean:()=>Yh,meshgrid:()=>Qh,min:()=>dh,minimum:()=>ed,mirrorPad:()=>td,mod:()=>nd,moments:()=>sd,movingAverage:()=>Tp,mul:()=>Do,multiRNNCell:()=>rd,multinomial:()=>ad,neg:()=>zl,norm:()=>mh,notEqual:()=>id,oneHot:()=>Ml,ones:()=>Jh,onesLike:()=>od,op:()=>Za,outerProduct:()=>ld,pad:()=>ud,pad1d:()=>cd,pad2d:()=>hd,pad3d:()=>dd,pad4d:()=>pd,pool:()=>md,pow:()=>nl,prelu:()=>gd,print:()=>Ro,prod:()=>yd,raggedGather:()=>bd,raggedRange:()=>xd,raggedTensorToTensor:()=>wd,rand:()=>vd,randomGamma:()=>Td,randomNormal:()=>Cd,randomStandardNormal:()=>$d,randomUniform:()=>Ed,randomUniformInt:()=>Rd,range:()=>Ad,real:()=>Pl,reciprocal:()=>_d,relu:()=>Fd,relu6:()=>Dd,reshape:()=>cc,reverse:()=>Od,reverse1d:()=>Md,reverse2d:()=>Ld,reverse3d:()=>zd,reverse4d:()=>Pd,rfft:()=>sp,round:()=>Bd,rsqrt:()=>Wd,scalar:()=>Ho,scatterND:()=>Cp,searchSorted:()=>Hh,selu:()=>Vd,separableConv2d:()=>Ud,setdiff1dAsync:()=>Gd,sigmoid:()=>fc,sign:()=>Hd,signal:()=>Uf,sin:()=>jd,sinh:()=>qd,slice:()=>mc,slice1d:()=>Kd,slice2d:()=>Xd,slice3d:()=>Yd,slice4d:()=>Zd,softmax:()=>Jd,softplus:()=>Mh,spaceToBatchND:()=>fd,sparse:()=>qf,sparseToDense:()=>$p,spectral:()=>Vf,split:()=>np,sqrt:()=>Oo,square:()=>Mo,squaredDifference:()=>rp,squeeze:()=>ap,stack:()=>ip,step:()=>op,stridedSlice:()=>lp,string:()=>Kf,sub:()=>sl,sum:()=>ph,tan:()=>up,tanh:()=>gc,tensor:()=>ei,tensor1d:()=>cp,tensor2d:()=>hp,tensor3d:()=>Vl,tensor4d:()=>dp,tensor5d:()=>pp,tensor6d:()=>fp,tensorScatterUpdate:()=>mp,tile:()=>wh,topk:()=>gp,transpose:()=>Bl,truncatedNormal:()=>yp,unique:()=>bp,unsortedSegmentSum:()=>xp,unstack:()=>wp,upperBound:()=>vp,variable:()=>kp,where:()=>Yc,whereAsync:()=>Np,zeros:()=>Zh,zerosLike:()=>Lo});var H={};n.r(H),n.d(H,{CSVDataset:()=>GC,Dataset:()=>_C,FileDataSource:()=>s$,TextLineDataset:()=>LC,URLDataSource:()=>r$,array:()=>DC,csv:()=>a$,func:()=>i$,generator:()=>o$,microphone:()=>u$,version_data:()=>c$,webcam:()=>l$,zip:()=>OC});var j={};n.r(j),n.d(j,{addImpl:()=>E$,bincountImpl:()=>F$,bincountReduceImpl:()=>D$,bitwiseAndImpl:()=>O$,castImpl:()=>N$,ceilImpl:()=>W$,concatImpl:()=>G$,equalImpl:()=>H$,expImpl:()=>K$,expm1Impl:()=>Z$,floorDivImpl:()=>sE,floorImpl:()=>eE,gatherNdImpl:()=>iE,gatherV2Impl:()=>oE,greaterEqualImpl:()=>hE,greaterImpl:()=>lE,lessEqualImpl:()=>yE,lessImpl:()=>fE,linSpaceImpl:()=>wE,logImpl:()=>vE,maxImpl:()=>NE,maximumImpl:()=>SE,minimumImpl:()=>$E,multiplyImpl:()=>AE,negImpl:()=>OE,notEqualImpl:()=>LE,prodImpl:()=>UE,raggedGatherImpl:()=>KE,raggedRangeImpl:()=>YE,raggedTensorToTensorImpl:()=>tR,rangeImpl:()=>nR,rsqrtImpl:()=>sR,scatterImpl:()=>iR,sigmoidImpl:()=>oR,simpleAbsImpl:()=>f$,sliceImpl:()=>cR,sparseFillEmptyRowsImpl:()=>pR,sparseReshapeImpl:()=>fR,sparseSegmentReductionImpl:()=>mR,sqrtImpl:()=>gR,squaredDifferenceImpl:()=>xR,staticRegexReplaceImpl:()=>kR,stridedSliceImpl:()=>SR,stringNGramsImpl:()=>CR,stringSplitImpl:()=>ER,stringToHashBucketFastImpl:()=>RR,subImpl:()=>AR,tileImpl:()=>OR,topKImpl:()=>zR,transposeImpl:()=>BE,uniqueImpl:()=>PR});var q={};n.r(q),n.d(q,{assertNotComplex:()=>eM,bindCanvasToFramebuffer:()=>$O,bindColorTextureToFramebuffer:()=>EO,bindTextureToProgramUniformSampler:()=>CO,bindTextureUnit:()=>IO,bindVertexBufferToProgramAttribute:()=>kO,callAndCheck:()=>sO,canBeRepresented:()=>iO,createFragmentShader:()=>cO,createFramebuffer:()=>vO,createProgram:()=>pO,createStaticIndexBuffer:()=>yO,createStaticVertexBuffer:()=>gO,createTexture:()=>xO,createVertexShader:()=>uO,getBatchDim:()=>OO,getExtensionOrThrow:()=>lO,getFramebufferErrorMessage:()=>_O,getMaxTexturesInShader:()=>jO,getNumChannels:()=>bO,getProgramUniformLocation:()=>TO,getProgramUniformLocationOrThrow:()=>SO,getRowsCols:()=>MO,getShapeAs3D:()=>LO,getTextureShapeFromLogicalShape:()=>zO,getWebGLDisjointQueryTimerVersion:()=>qO,getWebGLErrorMessage:()=>oO,getWebGLMaxTextureSize:()=>UO,hasExtension:()=>KO,isCapableOfRenderingToFloatTexture:()=>YO,isDownloadFloatTextureEnabled:()=>ZO,isReshapeFree:()=>BO,isWebGLFenceEnabled:()=>QO,isWebGLVersionEnabled:()=>XO,linkProgram:()=>fO,logShaderSourceAndInfoLog:()=>dO,resetMaxTextureSize:()=>GO,resetMaxTexturesInShader:()=>HO,unbindColorTextureFromFramebuffer:()=>RO,unbindTextureUnit:()=>NO,validateFramebuffer:()=>AO,validateProgram:()=>mO,validateTextureSize:()=>wO});var K={};n.r(K),n.d(K,{bindVertexProgramAttributeStreams:()=>qM,createBufferFromOutputTexture:()=>YM,createFloat16MatrixTexture:()=>BM,createFloat16PackedMatrixTexture:()=>jM,createFloat32MatrixTexture:()=>zM,createIndexBuffer:()=>OM,createPackedMatrixTexture:()=>GM,createUnsignedBytesMatrixTexture:()=>VM,createVertexBuffer:()=>DM,createVertexShader:()=>FM,downloadByteEncodedFloatMatrixFromOutputTexture:()=>JM,downloadFloat32MatrixFromBuffer:()=>ZM,downloadMatrixFromPackedOutputTexture:()=>eL,downloadPackedMatrixFromBuffer:()=>QM,getInternalFormatForFloat16MatrixTexture:()=>PM,getInternalFormatForFloat16PackedMatrixTexture:()=>HM,getInternalFormatForFloat32MatrixTexture:()=>LM,getInternalFormatForPackedMatrixTexture:()=>UM,getInternalFormatForUnsignedBytesMatrixTexture:()=>WM,uploadDenseMatrixToTexture:()=>KM,uploadPixelDataToTexture:()=>XM});class X{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}}class Y{refCount(e){return Z("refCount")}incRef(e){return Z("incRef")}timerAvailable(){return!0}time(e){return Z("time")}read(e){return Z("read")}readSync(e){return Z("readSync")}readToGPU(e,t){return Z("readToGPU")}numDataIds(){return Z("numDataIds")}disposeData(e,t){return Z("disposeData")}write(e,t,n){return Z("write")}move(e,t,n,s,r){return Z("move")}createTensorFromGPUData(e,t,n){return Z("createTensorFromGPUData")}memory(){return Z("memory")}floatPrecision(){return Z("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Z("dispose")}}function Z(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 J(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,ne(e,t,n)}function Q(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,s=0;for(;n>0;)s=Math.random()*n|0,n--,ne(e,n,s),ne(t,n,s)}function ee(e,t,n){return Math.max(e,Math.min(t,n))}function te(e){return e%2==0?e:e+1}function ne(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function se(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function re(e,t){const n=Math.random();return t*n+(1-n)*e}function ae(e,t){let n=0;for(let s=0;s<e.length;s++){const r=Number(e[s])-Number(t[s]);n+=r*r}return n}function ie(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function oe(e,t,n=""){ie(de(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function le(e){ie(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function ue(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function ce(e){return 0===e.length}function he(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}function de(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function pe(e){return e%1==0}function fe(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function me(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ge(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return J(t),t}function ye(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function be(e,t=(e=>0),n,s){return new Promise(((r,a)=>{let i=0;const o=()=>{if(e())return void r();i++;const l=t(i);null!=n&&i>=n?a():null!=s?s(o,l):setTimeout(o,l)};o()}))}function xe(e,t){let n=1,s=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${t}`);s=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===s){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)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}`);const r=e.slice();return r[s]=t/n,r}function we(e,t){const n=t.length;return ie((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),ie(e.every((e=>pe(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function ve(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:we(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=a){if(a[i]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==a[i]||a[i]>t)&&1===e[t]&&(n.push(e[t]),s.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function ke(e,t){return Ie(e,t)}function Ie(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function Ne(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function Se(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function Te(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function Ce(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function $e(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}function Ee(e){return"string"==typeof e||e instanceof String}function Re(e){return"boolean"==typeof e}function Ae(e){return"number"==typeof e}function _e(e){return Array.isArray(e)?_e(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Ae(e)?"float32":Ee(e)?"string":Re(e)?"bool":"float32"}function Fe(e){return!!(e&&e.constructor&&e.call&&e.apply)}function De(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Oe(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function Me(e,t,n,s=!1){const r=new Array;if(1===t.length){const a=t[0]*(s?2:1);for(let t=0;t<a;t++)r[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(s?2:1);for(let t=0;t<a;t++)r[t]=Me(e+t*o,i,n,s)}return r}function Le(e,t,n=!1){if(0===e.length)return t[0];const s=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===s)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return Me(0,e,t,n)}function ze(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Pe(e,t){const n=Be(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function Be(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function We(e,t){const n=e.reduce(((e,t)=>e*t),1);if(null==t||"float32"===t)return Le(e,new Float32Array(n));if("int32"===t)return Le(e,new Int32Array(n));if("bool"===t)return Le(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ve(e){e.forEach((t=>{ie(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Ue(e,t,n){if(0===t)return 0;if(1===t)return e[0];let s=e[e.length-1];for(let t=0;t<e.length-1;++t)s+=n[t]*e[t];return s}function Ge(e,t,n){if(0===t)return[];if(1===t)return[e];const s=new Array(t);for(let t=0;t<s.length-1;++t)s[t]=Math.floor(e/n[t]),e-=s[t]*n[t];return s[s.length-1]=e,s}function He(e){return e&&e.then&&"function"==typeof e.then}const je="tfjsflags";class qe{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Ke,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Xe().getBool("IS_TEST")||Xe().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},null!=this.urlFlags[e]){const t=this.urlFlags[e];Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(He(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(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])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(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(je in e){e[je].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}}function Ke(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Xe(){return Ze}let Ye,Ze=null;function Je(){if(null==Ye){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Ye=e}return Ye}function Qe(e,t){const n=function(){const e=Je();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const et="Abs",tt="Acos",nt="Acosh",st="Add",rt="AddN",at="All",it="Any",ot="ArgMax",lt="ArgMin",ut="Asin",ct="Asinh",ht="Atan",dt="Atanh",pt="Atan2",ft="AvgPool",mt="AvgPoolGrad",gt="AvgPool3D",yt="AvgPool3DGrad",bt="BatchMatMul",xt="BatchToSpaceND",wt="Bincount",vt="BitwiseAnd",kt="BroadcastTo",It="BroadcastArgs",Nt="Cast",St="Ceil",Tt="ClipByValue",Ct="Complex",$t="ComplexAbs",Et="Concat",Rt="Conv2D",At="Conv2DBackpropFilter",_t="Conv2DBackpropInput",Ft="Conv3D",Dt="Conv3DBackpropFilterV2",Ot="Conv3DBackpropInputV2",Mt="Cos",Lt="Cosh",zt="Cumprod",Pt="Cumsum",Bt="CropAndResize",Wt="DenseBincount",Vt="DepthToSpace",Ut="DepthwiseConv2dNative",Gt="DepthwiseConv2dNativeBackpropFilter",Ht="DepthwiseConv2dNativeBackpropInput",jt="Diag",qt="Dilation2D",Kt="Dilation2DBackpropInput",Xt="Dilation2DBackpropFilter",Yt="Draw",Zt="RealDiv",Jt="Einsum",Qt="Elu",en="EluGrad",tn="Erf",nn="Equal",sn="Exp",rn="ExpandDims",an="Expm1",on="FFT",ln="Fill",un="FlipLeftRight",cn="Floor",hn="FloorDiv",dn="FusedBatchNorm",pn="GatherV2",fn="GatherNd",mn="Greater",gn="GreaterEqual",yn="Identity",bn="IFFT",xn="Imag",wn="IsFinite",vn="IsInf",kn="IsNan",In="LeakyRelu",Nn="Less",Sn="LessEqual",Tn="LinSpace",Cn="Log",$n="Log1p",En="LogicalAnd",Rn="LogicalNot",An="LogicalOr",_n="LogicalXor",Fn="LogSoftmax",Dn="LowerBound",On="LRN",Mn="LRNGrad",Ln="MatrixBandPart",zn="Max",Pn="Maximum",Bn="MaxPool",Wn="MaxPoolGrad",Vn="MaxPool3D",Un="MaxPool3DGrad",Gn="MaxPoolWithArgmax",Hn="Mean",jn="Min",qn="Minimum",Kn="MirrorPad",Xn="Mod",Yn="Multinomial",Zn="Multiply",Jn="Neg",Qn="NotEqual",es="NonMaxSuppressionV3",ts="NonMaxSuppressionV4",ns="NonMaxSuppressionV5",ss="OnesLike",rs="OneHot",as="Pack",is="PadV2",os="Pool",ls="Pow",us="Prelu",cs="Prod",hs="RaggedGather",ds="RaggedRange",ps="RaggedTensorToTensor",fs="Range",ms="Real",gs="Reciprocal",ys="Relu",bs="Reshape",xs="ResizeNearestNeighbor",ws="ResizeNearestNeighborGrad",vs="ResizeBilinear",ks="ResizeBilinearGrad",Is="Relu6",Ns="Reverse",Ss="Round",Ts="Rsqrt",Cs="ScatterNd",$s="TensorScatterUpdate",Es="SearchSorted",Rs="Select",As="Selu",_s="Slice",Fs="Sin",Ds="Sinh",Os="Sign",Ms="Sigmoid",Ls="Softplus",zs="Sqrt",Ps="Sum",Bs="SpaceToBatchND",Ws="SplitV",Vs="Softmax",Us="SparseFillEmptyRows",Gs="SparseReshape",Hs="SparseSegmentMean",js="SparseSegmentSum",qs="SparseToDense",Ks="SquaredDifference",Xs="Square",Ys="StaticRegexReplace",Zs="StridedSlice",Js="StringNGrams",Qs="StringSplit",er="StringToHashBucketFast",tr="Sub",nr="Tan",sr="Tanh",rr="Tile",ar="TopK",ir="Transform",or="Transpose",lr="Unique",ur="Unpack",cr="UnsortedSegmentSum",hr="UpperBound",dr="ZerosLike",pr="Step",fr="FromPixels",mr="RotateWithOffset",gr="_FusedMatMul",yr="FusedConv2D",br="FusedDepthwiseConv2D";function xr(...e){Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.warn(...e)}function wr(...e){Xe().getBool("IS_TEST")||Xe().getBool("PROD")||console.log(...e)}const vr=Qe("kernelRegistry",(()=>new Map)),kr=Qe("gradRegistry",(()=>new Map));function Ir(e,t){const n=Ar(e,t);return vr.get(n)}function Nr(e){return kr.get(e)}function Sr(e){const t=vr.entries(),n=[];for(;;){const{done:s,value:r}=t.next();if(s)break;const[a,i]=r,[o]=a.split("_");o===e&&n.push(i)}return n}function Tr(e){const{kernelName:t,backendName:n}=e,s=Ar(t,n);vr.has(s)&&xr(`The kernel '${t}' for backend '${n}' is already registered`),vr.set(s,e)}function Cr(e){const{kernelName:t}=e;kr.has(t)&&Xe().getBool("DEBUG")&&xr(`Overriding the gradient for '${t}'`),kr.set(t,e)}function $r(e,t){const n=Ar(e,t);if(!vr.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);vr.delete(n)}function Er(e){if(!kr.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);kr.delete(e)}function Rr(e,t){Sr(e).forEach((e=>{Tr(Object.assign({},e,{backendName:t}))}))}function Ar(e,t){return`${t}_${e}`}function _r(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Fr=n(570);const Dr=n.n(Fr)()||Fr;function Or(e){return Dr.fromString(e,!0,16)}const Mr=Or("c3a5c85c97cb3127"),Lr=Or("b492b66fbe98f273"),zr=Or("9ae16a3b2f90404f");function Pr(e){return e.xor(e.shru(47))}function Br(e,t,n){const s=e.slice(t,t+n);return Dr.fromBytes(Array.from(s),!0,!0)}function Wr(e,t){return Br(e,t,8)}function Vr(e,t){return Br(e,t,4)}function Ur(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Gr(e,t,n=Or("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function Hr(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=Ur(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(Ur(r,44)),[r.add(s),a.add(i)]}(Wr(e,t),Wr(e,t+8),Wr(e,t+16),Wr(e,t+24),n,s)}function jr(e,t=e.length){const n=Dr.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=zr.add(2*t),s=Wr(e,0).add(zr),r=Wr(e,t-8);return Gr(Ur(r,37).mul(n).add(s),Ur(s,25).add(r).mul(n),n)}if(t>=4){const n=zr.add(2*t);return Gr(Vr(e,0).shl(3).add(t),Vr(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return Pr(zr.mul(n).xor(Mr.mul(s))).mul(zr)}return zr}(e,t):function(e,t=e.length){const n=zr.add(2*t),s=Wr(e,0).mul(Lr),r=Wr(e,8),a=Wr(e,t-8).mul(n),i=Wr(e,t-16).mul(zr);return Gr(Ur(s.add(r),43).add(Ur(a,30)).add(i),s.add(Ur(r.add(zr),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=zr.add(2*t),s=Wr(e,0).mul(zr),r=Wr(e,8),a=Wr(e,t-8).mul(n),i=Wr(e,t-16).mul(zr),o=Ur(s.add(r),43).add(Ur(a,30)).add(i),l=Gr(o,s.add(Ur(r.add(zr),18)).add(a),n),u=Wr(e,16).mul(n),c=Wr(e,24),h=o.add(Wr(e,t-32)).mul(n),d=l.add(Wr(e,t-24)).mul(n);return Gr(Ur(u.add(c),43).add(Ur(h,30)).add(d),u.add(Ur(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(Lr).add(113),a=Pr(r.mul(zr).add(113)).mul(zr),i=[Dr.UZERO,Dr.UZERO],o=[Dr.UZERO,Dr.UZERO];s=s.mul(zr).add(Wr(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=Ur(s.add(r).add(i[0]).add(Wr(e,l+8)),37).mul(Lr),r=Ur(r.add(i[1]).add(Wr(e,l+48)),42).mul(Lr),s=s.xor(o[1]),r=r.add(i[0]).add(Wr(e,l+40)),a=Ur(a.add(o[0]),33).mul(Lr),i=Hr(e,l,i[1].mul(Lr),s.add(o[0])),o=Hr(e,l+32,a.add(o[1]),r.add(Wr(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=Lr.add(a.and(255).shl(1));return l=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),s=Ur(s.add(r).add(i[0]).add(Wr(e,l+8)),37).mul(h),r=Ur(r.add(i[1]).add(Wr(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(Wr(e,l+40))),a=Ur(a.add(o[0]),33).mul(h),i=Hr(e,l,i[1].mul(h),s.add(o[0])),o=Hr(e,l+32,a.add(o[1]),r.add(Wr(e,l+16))),[a,s]=[s,a],Gr(Gr(i[0],o[0],h).add(Pr(r).mul(Mr)).add(a),Gr(i[1],o[1],h).add(s),h)}function qr(e,t){return"string"===t?Zr(e):Kr([e],t)}function Kr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ea(e)),Xe().getBool("DEBUG")&&Ne(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Xr(){return Xe().platform.now()}function Yr(e,t){return Xe().platform.fetch(e,t)}function Zr(e,t="utf-8"){return t=t||"utf-8",Xe().platform.encode(e,t)}function Jr(e,t="utf-8"){return t=t||"utf-8",Xe().platform.decode(e,t)}function Qr(e){return null!=Xe().platform.isTypedArray?Xe().platform.isTypedArray(e):_r(e)}function ea(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||He(e)||null==e||Qr(e)&&n)t.push(e);else if(Array.isArray(e)||Qr(e))for(let s=0;s<e.length;++s)ea(e[s],t,n);else{let s=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(s=Math.max(s,Number(t)));for(let r=0;r<=s;r++)ea(e[r],t,n)}return t}class ta{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new sa)}profileKernel(e,t,n){let s;const r=()=>{s=n()};let a;const i=Xr();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:Xr()-i})}if(Xe().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then((t=>{na(t,n.dtype,e)}))}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),s,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],r,n[2])}))}))}}function na(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}class sa{logKernelProfile(e,t,n,s,r,a){const i="number"==typeof s?ye(`${s}ms`,9):s.error,o=ye(e,25),l=t.rank,u=t.size,c=ye(t.shape.toString(),14);let h="";for(const e in r){const n=r[e];if(null!=n){const s=n.shape||t.shape,r=s.length;h+=`${e}: ${r}D ${r>0?s:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}const ra=20,aa=3,ia=7;function oa(e,t,n,s){const r=Oe(t),a=function(e,t,n,s){const r=ue(t),a=s[s.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?ha(e):e;if(o>1)for(let e=0;e<r/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],la(l[t+e],0,n).length)}return i}(e,t,n,r),i=t.length,o=ca(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map((e=>" "+e)).join("\n")),l.join("\n")}function la(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(ia))} + ${parseFloat(e[1].toFixed(ia))}j`:Ee(e)?`'${e}'`:"bool"===n?ua(e):parseFloat(e.toFixed(ia)).toString(),ye(s,t)}function ua(e){return 0===e?"false":"true"}function ca(e,t,n,s,r,a=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[la(ha(e)[0],0,n)]}return"bool"===n?[ua(e[0])]:[e[0].toString()]}if(1===l){if(o>ra){const t=aa*i;let s=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-aa)*i,o*i));return"complex64"===n&&(s=ha(s),a=ha(a)),["["+s.map(((e,t)=>la(e,r[t],n))).join(", ")+", ..., "+a.map(((e,t)=>la(e,r[o-aa+t],n))).join(", ")+"]"]}return["["+("complex64"===n?ha(e):Array.from(e)).map(((e,t)=>la(e,r[t],n))).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,d=[];if(o>ra){for(let t=0;t<aa;t++){const s=t*h,a=s+h;d.push(...ca(e.slice(s,a),u,n,c,r,!1))}d.push("...");for(let t=o-aa;t<o;t++){const s=t*h,a=s+h;d.push(...ca(e.slice(s,a),u,n,c,r,t===o-1))}}else for(let t=0;t<o;t++){const s=t*h,a=s+h;d.push(...ca(e.slice(s,a),u,n,c,r,t===o-1))}const p=2===l?",":"";d[0]="["+(o>0?d[0]+p:"");for(let e=1;e<d.length-1;e++)d[e]=" "+d[e]+p;let f=",\n";for(let e=2;e<l;e++)f+="\n";return d[d.length-1]=" "+d[d.length-1]+"]"+(a?"":f),d}function ha(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class da{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=ue(e),null!=n){const e=n.length;ie(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)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||Ie(t,this.size),this.strides=Oe(e)}set(e,...t){0===t.length&&(t=[0]),ie(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)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(0===this.rank)return[];if(1===this.rank)return[e];const 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 pa().makeTensor(this.values,this.shape,this.dtype)}}let pa=null,fa=null,ma=null;class ga{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ue(e),this.strides=Oe(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return fa.buffer(this.shape,this.dtype,e)}bufferSync(){return fa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Le(this.shape,e,"complex64"===this.dtype)}arraySync(){return Le(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=pa().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>Jr(e)))}catch(e){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(),pa().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=pa().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Jr(e)))}catch(e){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();const e=await pa().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),pa().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return fa.print(this,e)}clone(){return this.throwIfDisposed(),fa.clone(this)}toString(e=!1){return oa(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),fa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),pa().makeVariable(this,e,t,n)}}function ya(){return Qe("Tensor",(()=>ga))}Object.defineProperty(ga,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),ya();class ba extends ga{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s),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(!de(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);pa().disposeTensor(this),this.dataId=e.dataId,pa().incRef(this,null)}dispose(){pa().disposeVariable(this),this.isDisposedInternal=!0}}var xa,wa,va,ka,Ia;Object.defineProperty(ba,Symbol.hasInstance,{value:e=>e instanceof ga&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(xa||(xa={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(wa||(wa={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(va||(va={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(ka||(ka={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ia||(Ia={}));const Na={float32:ka,int32:wa,bool:va,complex64:Ia};function Sa(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Na[e][t]}function Ta(e){return Sa(e,"int32")}function Ca(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function $a(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Ea(e,t){if(e.dtype===t.dtype)return[e,t];const n=Sa(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Ra(e,t){ie(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function Aa(e,t){return t.some((t=>t.id===e.id))}function _a(e){const t=[];return Fa(e,t,new Set),t}function Fa(e,t,n){if(null==e)return;if(e instanceof ga)return void t.push(e);if(s=e,!Array.isArray(s)&&"object"!=typeof s)return;var s;const r=e;for(const e in r){const s=r[e];n.has(s)||(n.add(s),Fa(s,t,n))}}function Da(e){return null!=e.kernelName}class Oa{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(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Ma{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Oa}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)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(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(xr(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new ta(this.backendInstance),!0}setupRegisteredKernels(){Sr(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){Sr(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof Y||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,xr(`Initialization of backend ${e} failed`),xr(n.stack||n.message)),!1)));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}}catch(t){return xr(`Initialization of backend ${e} failed`),xr(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:s,asyncInit:r}=this.initializeBackend(n);if(r||s)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,r=this.readSync(t),a=s.refCount(t);s.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,s=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}return this.scopedRun((()=>this.startScope(s)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Ma.nextTensorId++}nextVariableId(){return Ma.nextVariableId++}clone(e){const t=za.runKernel(yn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return za.runKernel(Nt,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=Ir(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let r=0;n.forEach((e=>{r+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-r-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=Da(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Da(e)){const{kernelName:t,inputs:r,attrs:a}=e;null==this.backendName&&this.backend;const l=Ir(t,this.backendName);ie(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:r,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(s){const e=this.getTensorsForGradient(t,r,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,r=e=>{s&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,r)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:c}=e,h=Da(e)?null:e.backwardsFunc;let d;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(d=this.profiler.profileKernel(l,u,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()})),s&&this.addTapeNode(l,u,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((e=>null!=u[e]?u[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const s=Nr(e);if(null!=s){const e=s.inputsToSave||[],r=s.outputsToSave||[];let a;s.saveAllInputs?(ie(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>r[t]));return a.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;"string"===n&&Ee(e[0])&&(r=e.map((e=>Zr(e))));const a=s.write(r,t,n),i=new ga(t,n,a,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(a),t=$e(r);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const r={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(r,s)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:s,dtype:r}=e,a=new ga(s,r,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const r=new ba(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[r.name])throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*Ce(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof ba||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*Ce(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,s,r,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=Nr(e);null!=o&&(s=o.gradFunc),null!=s&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],s=Be(e.size,e.dtype);return this.makeTensor(s,e.shape,e.dtype)}return e})),s(e.length>1?e:e[0],r,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=_a(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==s.id||this.track(e)}))}gradients(e,t,n,s=!1){if(ie(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const r=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));ie(r instanceof ga,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const s={},r={};for(let e=0;e<t.length;e++)s[t[e].id]=!0;for(let n=0;n<e.length;n++){const a=e[n],i=a.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(s[n.id]){a.outputs.forEach((e=>s[e.id]=!0)),o=!0,r[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],s=n.inputs;for(let e=0;e<n.outputs.length;e++)if(a[n.outputs[e].id]){for(const e in s)a[s[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(r[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const r=n.inputs[t];s[r.id]&&(e[t]=r)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,r);if(!s&&0===a.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[r.id]=null==n?function(e){const t=Pe(ue(e),"float32");return za.makeTensor(t,e,"float32")}(r.shape):n,function(e,t,n,s){for(let r=t.length-1;r>=0;r--){const a=t[r],i=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const r=n((()=>o[t]()));if("float32"!==r.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${r.dtype}'`);const i=a.inputs[t];if(!de(r.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${r.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=r;else{const t=e[i.id];e[i.id]=s(t,r),t.dispose()}}}}(e,a,(e=>this.tidy(e)),Pa);const s=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:r,grads:s}}))}customGrad(e){return ie(Fe(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;ie(t.every((e=>e instanceof ga)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const s={};t.forEach(((e,t)=>{s[t]=e}));return this.runKernelFunc({forwardFunc:(s,r)=>(n=e(...t,r),ie(n.value instanceof ga,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),ie(Fe(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,s)=>{const r=n.gradFunc(e,s),a=Array.isArray(r)?r:[r];ie(a.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),ie(a.every((e=>e instanceof ga)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const i={};return a.forEach(((e,t)=>{i[t]=()=>e})),i},inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Xr(),n=await this.backend.time(e);return n.wallMs=Xr()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Oa;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function La(){const e=Je();if(null==e._tfengine){const t=new qe(e);e._tfengine=new Ma(t)}var t;return t=e._tfengine.ENV,Ze=t,pa=()=>e._tfengine,e._tfengine}Ma.nextTensorId=0,Ma.nextVariableId=0;const za=La();function Pa(e,t){const n={a:e,b:t};return za.runKernel(st,n)}let Ba;function Wa(e){Ba=e}function Va(e){if(void 0!==Ba)return Ba;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.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 Ua(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const Ga=Xe();function Ha(e,t){let n=e;if(Qr(e))return"string"===t?[]:[e.length];if(Ca(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if($a(e))return[e.buffer.size/(null==t?4:Ce(t))];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||Qr(n)&&"string"!==t;)s.push(n.length),n=n[0];return Array.isArray(e)&&Xe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&ja(e,s,[]),s}function ja(e,t,n){if(n=n||[],!Array.isArray(e)&&!Qr(e))return void ie(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));ie(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),ie(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const s=t.slice(1);for(let t=0;t<e.length;++t)ja(e[t],s,n.concat(t))}function qa(e,t,n,s){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}}function Ka(e,t,n,s="numeric"){if(e instanceof ya())return qa(s,e.dtype,t,n),e;let r=_e(e);if("string"!==r&&["bool","int32","float32"].indexOf(s)>=0&&(r=s),qa(s,r,t,n),null==e||!Qr(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const s=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${s}'`)}const a=Ha(e,r);Qr(e)||Array.isArray(e)||(e=[e]);const i="string"!==r?Kr(e,r):ea(e,[],!0);return za.makeTensor(i,a,r)}function Xa(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,r)=>Ka(e,`${t}[${r}]`,n,s)))}Ga.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.")})),Ga.registerFlag("IS_BROWSER",(()=>Ua())),Ga.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),Ga.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Ga.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),Ga.registerFlag("PROD",(()=>!1)),Ga.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Ga.getBool("DEBUG"))),Ga.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Ga.registerFlag("IS_TEST",(()=>!1)),Ga.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>Ga.getBool("DEBUG"))),Ga.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Ga.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Ga.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const Ya="__op";function Za(e){const t=Object.keys(e);if(1!==t.length)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];const s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=Ya;const r=(...e)=>{za.startScope(n);try{const t=s(...e);return He(t)&&console.error("Cannot return a Promise inside of tidy."),za.endScope(t),t}catch(e){throw za.endScope(null),e}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}const Ja=Za({complex_:function(e,t){const n=Ka(e,"real","complex"),s=Ka(t,"imag","complex");oe(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const r={real:n,imag:s};return za.runKernel(Ct,r)}});function Qa(e,t,n,s){if(null==s)s=_e(e);else if("complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if($a(e)||Ca(e)){if("float32"!==s&&"int32"!==s)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return za.backend.createTensorFromGPUData(e,t||n,s)}if(!Qr(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)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(null!=t){Ve(t);const e=ue(t),s=ue(n);ie(e===s,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${s}`));for(let e=0;e<n.length;++e){const s=n[e],r=e!==n.length-1||s!==ue(t.slice(e));ie(n[e]===t[e]||!r,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Qr(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?Kr(e,s):ea(e,[],!0),za.makeTensor(e,t,s)}function ei(e,t,n){return Qa(e,t,Ha(e,n),n)}const ti={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class ni{static join(e){return new ni(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>Qr(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const s=e[n];n!==e.length-1&&s.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const r=t+s.byteLength;this.shards.push({buffer:s,start:t,end:r}),t=r}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const s=new ArrayBuffer(t-e),r=new Uint8Array(s);let a=0;for(let s=n;s<this.shards.length;s++){const n=this.shards[s],i=e+a-n.start,o=a,l=Math.min(t,n.end)-n.start,u=new Uint8Array(n.buffer,i,l-i);if(r.set(u,o),a+=u.length,t<n.end)break}return s}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,s=e.length;for(;n<=s;){const r=Math.floor((s-n)/2)+n,a=t(e[r]);if(0===a)return r;a<0?s=r:n=r+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function si(){Xe().set("PROD",!0)}function ri(){Xe().set("DEBUG",!0)}function ai(){Xe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function ii(e){Xe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function oi(){za.disposeVariables()}function li(){return za}function ui(){return za.memory()}function ci(e){return za.profile(e)}function hi(e,t){return za.tidy(e,t)}function di(e){_a(e).forEach((e=>e.dispose()))}function pi(e){return za.keep(e)}function fi(e){return za.time(e)}function mi(e){return za.setBackend(e)}function gi(){return za.ready()}function yi(){return za.backendName}function bi(e){za.removeBackend(e)}function xi(e){return za.findBackend(e)}function wi(e){return za.findBackendFactory(e)}function vi(e,t,n=1){return za.registerBackend(e,t,n)}function ki(){return za.backend}function Ii(e,t){Xe().setPlatform(e,t)}ma=ii;const Ni=4;async function Si(e,t){const n=[],s=[],r=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let a=0;a<r.length;++a){const i=r[a],o=Array.isArray(e)?e[a].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const l={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+Ni*t.length,s=new Uint8Array(n);let r=0;for(let e=0;e<t.length;e++){const n=t[e],a=new Uint8Array(new Uint32Array([n.length]).buffer);s.set(a,r),r+=Ni,s.set(n,r),r+=n.length}e(s)}));s.push(e)}else s.push(o.data());null!=t&&(l.group=t),n.push(l)}return{data:_i(await Promise.all(s)),specs:n}}function Ti(e,t){const n=new ni(e),s={};let r=0;for(const e of t){const t=Ci(e,((e,t)=>n.slice(r+e,r+t)));s[e.name]=Ei(e,n.slice(r,r+t)),r+=t}return s}function Ci(e,t){const n=ue(e.shape);let s;if("quantization"in e){const t=e.quantization;s=ti[t.dtype]}else{if("string"===e.dtype){let e=0;for(let s=0;s<n;s++)e+=Ni+new Uint32Array(t(e,e+Ni))[0];return e}s=ti[e.dtype]}return n*s}async function $i(e,t){const n=ue(e.shape);let s;if("quantization"in e){const t=e.quantization;s=ti[t.dtype]}else{if("string"===e.dtype){let e=0;for(let s=0;s<n;s++)e+=Ni+new Uint32Array(await t(e,e+Ni))[0];return e}s=ti[e.dtype]}return n*s}function Ei(e,t){const n=e.name,s=e.dtype,r=e.shape,a=ue(r);let i,o=0;if("quantization"in e){const r=e.quantization;if("uint8"===r.dtype||"uint16"===r.dtype){if(!("min"in r)||!("scale"in r))throw new Error(`Weight ${e.name} with quantization ${r.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==r.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${r.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==s)throw new Error(`Weight ${e.name} is quantized with ${r.dtype} which only supports weights of type float32 not ${s}.`)}const l=ti[r.dtype],u="uint8"===r.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===s)if("uint8"===r.dtype||"uint16"===r.dtype){i=new Float32Array(u.length);for(let e=0;e<u.length;e++){const t=u[e];i[e]=t*r.scale+r.min}}else{if("float16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;!(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const 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}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return s=>{const r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let r=0;r<s.length;r++){const i=s[r],o=e[n[i>>10]+(1023&i)]+t[i>>10];a[r]=o}return new Float32Array(r)}}();i=e(u)}}else{if("int32"!==s)throw new Error(`Unsupported dtype in weight '${n}': ${s}`);if("uint8"!==r.dtype&&"uint16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.dtype} for weight type int32.`);i=new Int32Array(u.length);for(let e=0;e<u.length;e++){const t=u[e];i[e]=Math.round(t*r.scale+r.min)}}o+=a*l}else if("string"===s){const n=ue(e.shape);i=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+Ni))[0];o+=Ni;const n=new Uint8Array(t.slice(o,o+e));i.push(n),o+=e}}else{const e=ti[s];if("float32"===s)i=new Float32Array(t);else if("int32"===s)i=new Int32Array(t);else{if("bool"!==s){if("complex64"===s){i=new Float32Array(t);const e=new Float32Array(i.length/2),n=new Float32Array(i.length/2);for(let t=0;t<e.length;t++)e[t]=i[2*t],n[t]=i[2*t+1];const s=ei(e,r,"float32"),a=ei(n,r,"float32"),o=Ja(s,a);return s.dispose(),a.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${s}`)}i=new Uint8Array(t)}o+=a*e}return ei(i,r,s)}async function Ri(e,t,n){let s=new Uint8Array(t);for(;s.byteLength<n;){const{done:t,value:r}=await e.read();if(t&&null==r){const e=n-s.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const a=new Uint8Array(s.length+r.byteLength);a.set(s,0),a.set(new Uint8Array(r),s.length),s=a}return s.buffer}async function Ai(e,t){const n={},s=e.getReader();let r=new ArrayBuffer(0);for(const e of t){const t=await $i(e,(async(e,t)=>(r=await Ri(s,r,t),r.slice(e,t))));r=await Ri(s,r,t);const a=r.slice(0,t);r=r.slice(t);const i=Ei(e,a);if(n[e.name]=i,"webgpu"===yi()){const e=ki();"uploadToGPU"in e&&ue(i.shape)>=Xe().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(i.dataId)}}return n}function _i(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const s=new Uint8Array(t);let r=0;return n.forEach((e=>{s.set(new Uint8Array(e.buffer),r),r+=e.byteLength})),s.buffer}const Fi="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Di(e){return Fi?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function Oi(e){return ni.join(e)}function Mi(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Li(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function zi(e,t,n){const s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(s.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");s.weightSpecs=t,s.weightData=n}return null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(s.initializerSignature=e.initializerSignature),s}async function Pi(e,t){let n,s;return null!=e.weightsManifest&&([n,s]=await t(e.weightsManifest)),zi(e,n,s)}function Bi(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Di(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Di(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new ni(e.weightData).byteLength}}function Wi(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Vi{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Vi.instance&&(Vi.instance=new Vi),Vi.instance}static registerSaveRouter(e){Vi.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Vi.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Vi.getHandlers(e,"save")}static getLoadHandlers(e,t){return Vi.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[];return("load"===t?Vi.getInstance().loadRouters:Vi.getInstance().saveRouters).forEach((t=>{const r=t(e,n);null!==r&&s.push(r)})),s}}const Ui=e=>Vi.registerSaveRouter(e),Gi=e=>Vi.registerLoadRouter(e),Hi=e=>Vi.getSaveHandlers(e),ji=(e,t)=>Vi.getLoadHandlers(e,t),qi="tensorflowjs",Ki="models_store",Xi="model_info_store";function Yi(){if(!Xe().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Zi(e){const t=e.result;t.createObjectStore(Ki,{keyPath:"modelPath"}),t.createObjectStore(Xi,{keyPath:"modelPath"})}class Ji{constructor(e){if(this.indexedDB=Yi(),null==e||!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(((e,n)=>{const s=this.indexedDB.open(qi,1);s.onupgradeneeded=()=>Zi(s),s.onsuccess=()=>{const r=s.result;if(null==t){const t=r.transaction(Ki,"readonly"),s=t.objectStore(Ki).get(this.modelPath);s.onsuccess=()=>{if(null==s.result)return r.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=e=>(r.close(),n(s.error)),t.oncomplete=()=>r.close()}else{t.weightData=ni.join(t.weightData);const s=Bi(t),a=r.transaction(Xi,"readwrite");let i,o,l=a.objectStore(Xi);try{i=l.put({modelPath:this.modelPath,modelArtifactsInfo:s})}catch(e){return n(e)}i.onsuccess=()=>{o=r.transaction(Ki,"readwrite");const i=o.objectStore(Ki);let u;try{u=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:s})}catch(e){return n(e)}u.onsuccess=()=>e({modelArtifactsInfo:s}),u.onerror=e=>{l=a.objectStore(Xi);const t=l.delete(this.modelPath);t.onsuccess=()=>(r.close(),n(u.error)),t.onerror=e=>(r.close(),n(u.error))}},i.onerror=e=>(r.close(),n(i.error)),a.oncomplete=()=>{null==o?r.close():o.oncomplete=()=>r.close()}}},s.onerror=e=>n(s.error)}))}}Ji.URL_SCHEME="indexeddb://";const Qi=e=>{return Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ji.URL_SCHEME)?(t=e.slice(Ji.URL_SCHEME.length),new Ji(t)):null;var t};Vi.registerSaveRouter(Qi),Vi.registerLoadRouter(Qi);class eo{constructor(){this.indexedDB=Yi()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(qi,1);n.onupgradeneeded=()=>Zi(n),n.onsuccess=()=>{const s=n.result,r=s.transaction(Xi,"readonly"),a=r.objectStore(Xi).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(s.close(),t(a.error)),r.oncomplete=()=>s.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Ji.URL_SCHEME)?t.slice(Ji.URL_SCHEME.length):t,new Promise(((t,n)=>{const s=this.indexedDB.open(qi,1);s.onupgradeneeded=()=>Zi(s),s.onsuccess=()=>{const r=s.result,a=r.transaction(Xi,"readwrite"),i=a.objectStore(Xi),o=i.get(e);let l;o.onsuccess=()=>{if(null==o.result)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const s=i.delete(e),a=()=>{l=r.transaction(Ki,"readwrite");const s=l.objectStore(Ki).delete(e);s.onsuccess=()=>t(o.result.modelArtifactsInfo),s.onerror=e=>n(o.error)};s.onsuccess=a,s.onerror=e=>(a(),r.close(),n(o.error))}},o.onerror=e=>(r.close(),n(o.error)),a.oncomplete=()=>{null==l?r.close():l.oncomplete=()=>r.close()}},s.onerror=e=>n(s.error)}))}}const to="/",no="tensorflowjs_models",so="info",ro="model_topology",ao="weight_specs",io="weight_data",oo="model_metadata";function lo(e){return{info:[no,e,so].join(to),topology:[no,e,ro].join(to),weightSpecs:[no,e,ao].join(to),weightData:[no,e,io].join(to),modelMetadata:[no,e,oo].join(to)}}function uo(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function co(e){const t=e.split(to);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(to)}class ho{constructor(e){if(!Xe().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=lo(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.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=Bi(e),r=ni.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Fi)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,s=t.length;e<s;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(r));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:s}}catch(e){throw uo(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=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==s)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;const r=this.LS.getItem(this.keys.modelMetadata);if(null!=r){const e=JSON.parse(r);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const a=this.LS.getItem(this.keys.weightData);if(null==a)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(Fi){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(a),t}}ho.URL_SCHEME="localstorage://";const po=e=>{return Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ho.URL_SCHEME)?(t=e.slice(ho.URL_SCHEME.length),new ho(t)):null;var t};Vi.registerSaveRouter(po),Vi.registerLoadRouter(po);class fo{constructor(){ie(Xe().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),ie("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=no+to,n=to+so;for(let s=0;s<this.LS.length;++s){const r=this.LS.key(s);if(r.startsWith(t)&&r.endsWith(n)){e[co(r)]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){var t;const n=lo(e=(t=e).startsWith(ho.URL_SCHEME)?t.slice(ho.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const s=JSON.parse(this.LS.getItem(n.info));return uo(n),s}}const mo="://";class go{constructor(){this.managers={}}static getInstance(){return null==go.instance&&(go.instance=new go),go.instance}static registerManager(e,t){ie(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(mo)&&(e=e.slice(0,e.indexOf(mo))),ie(e.length>0,(()=>"scheme must not be an empty string."));const n=go.getInstance();ie(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=go.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(go.getInstance().managers)}}function yo(e){if(-1===e.indexOf(mo))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${go.getSchemes().join(",")}`);return{scheme:e.split(mo)[0],path:e.split(mo)[1]}}async function bo(e,t,n=!1){ie(e!==t,(()=>`Old path and new path are the same: '${e}'`));const s=Vi.getLoadHandlers(e);ie(s.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),ie(s.length<2,(()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`));const r=s[0],a=Vi.getSaveHandlers(t);ie(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),ie(a.length<2,(()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`));const i=a[0],o=yo(e).scheme,l=yo(e).path,u=o===yo(e).scheme,c=await r.load();n&&u&&await go.getManager(o).removeModel(l);const h=await i.save(c);return n&&!u&&await go.getManager(o).removeModel(l),h.modelArtifactsInfo}async function xo(){const e=go.getSchemes(),t={};for(const n of e){const e=await go.getManager(n).listModels();for(const s in e){t[n+mo+s]=e[s]}}return t}async function wo(e){const t=yo(e);return go.getManager(t.scheme).removeModel(t.path)}async function vo(e,t){return bo(e,t,!1)}async function ko(e,t){return bo(e,t,!0)}class Io{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("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Xe().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}isTypedArray(e){return _r(e)}}if(Xe().get("IS_BROWSER")){Xe().setPlatform("browser",new Io);try{go.registerManager(ho.URL_SCHEME,new fo)}catch(e){}try{go.registerManager(Ji.URL_SCHEME,new eo)}catch(e){}}const No=()=>n(817);let So;class To{constructor(){this.util=n(590),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Xe().global.fetch?Xe().global.fetch(e,t):(null==So&&(So=No()),So(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":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)}}function Co(e,t="float32",n){return t=t||"float32",Ve(e),new da(e,t,n)}Xe().get("IS_NODE")&&!Xe().get("IS_BROWSER")&&Xe().setPlatform("node",new To);const $o=Za({cast_:function(e,t){const n=Ka(e,"x","cast");if(!Se(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const s={x:n},r={dtype:t};return za.runKernel(Nt,s,r)}});const Eo=Za({clone_:function(e){const t={x:Ka(e,"x","clone","string_or_numeric")};return za.runKernel(yn,t)}});function Ro(e,t=!1){console.log(e.toString(t))}La();fa={buffer:Co,cast:$o,clone:Eo,print:Ro};const Ao=Za({add_:function(e,t){let n=Ka(e,"a","add"),s=Ka(t,"b","add");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(st,r)}});const _o=Za({floorDiv_:function(e,t){let n=Ka(e,"a","floorDiv"),s=Ka(t,"b","floorDiv");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(hn,r)}});const Fo=Za({div_:function(e,t){let n=Ka(e,"a","div"),s=Ka(t,"b","div");if([n,s]=Ea(n,s),"int32"===n.dtype&&"int32"===s.dtype)return _o(n,s);const r={a:n,b:s};return za.runKernel(Zt,r,{})}});const Do=Za({mul_:function(e,t){let n=Ka(e,"a","mul"),s=Ka(t,"b","mul");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(Zn,r)}});const Oo=Za({sqrt_:function(e){const t={x:Ka(e,"x","sqrt","float32")};return za.runKernel(zs,t)}});const Mo=Za({square_:function(e){const t=Ka(e,"x","square");return za.runKernel("Square",{x:t},{})}});const Lo=Za({zerosLike_:function(e){const t={x:Ka(e,"x","zerosLike")};return za.runKernel(dr,t)}});function zo(e){return ie(Fe(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const s=Ka(t,"x","tf.grad","string_or_numeric"),r=null!=n?Ka(n,"dy","tf.grad"):null;return za.tidy((()=>{const{value:t,grads:n}=za.gradients((()=>e(s)),[s],r);return null!=r&&oe(t.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Go(n),n[0]}))}}function Po(e){return ie(Fe(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{ie(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const s=Xa(t,"args","tf.grads","string_or_numeric"),r=null!=n?Ka(n,"dy","tf.grads"):null;return za.tidy((()=>{const{value:t,grads:n}=za.gradients((()=>e(...s)),s,r);return null!=r&&oe(t.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Go(n),n}))}}function Bo(e){return ie(Fe(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{ie(t instanceof ga,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),ie(null==n||n instanceof ga,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:s,value:r}=za.gradients((()=>e(t)),[t],n);return Go(s),{grad:s[0],value:r}}}function Wo(e){return ie(Fe(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{ie(Array.isArray(t)&&t.every((e=>e instanceof ga)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),ie(null==n||n instanceof ga,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const s=za.gradients((()=>e(...t)),t,n);return null!=n&&oe(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Go(s.grads),s}}function Vo(e,t){ie(Fe(e),(()=>"The f passed in variableGrads(f) must be a function")),ie(null==t||Array.isArray(t)&&t.every((e=>e instanceof ba)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in za.registeredVariables)t.push(za.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,r=t.length;t=t.filter((e=>e.trainable)),ie(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`));const{value:a,grads:i}=za.gradients(e,t,null,!0);ie(i.some((e=>null!=e)),(()=>"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().")),ie(0===a.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=i[t]&&(o[e.name]=i[t])})),null!=s&&s.forEach((e=>o[e.name]=null)),{value:a,grads:o}}function Uo(e){return za.customGrad(e)}function Go(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}function Ho(e,t){if((Qr(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Qr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Qa(e,[],[],t)}const jo=new Map,qo=new Map;class Ko{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Xo{constructor(){this.classNameMap={}}static getMap(){return null==Xo.instance&&(Xo.instance=new Xo),Xo.instance}static register(e){Xo.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Yo(e,t,n){ie(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),ie("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),ie(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),void 0===t&&(t="Custom"),void 0===n&&(n=e.className);const s=t+">"+n;return Xo.register(e),jo.set(s,e),qo.set(e,s),e}function Zo(e){return qo.has(e)?qo.get(e):e.className}class Jo extends Ko{minimize(e,t=!1,n){const{value:s,grads:r}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:r[e.name]})));this.applyGradients(e)}else this.applyGradients(r);return di(r),t?s:(s.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Vo(e,t)}dispose(){null!=this.iterations_&&di(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Ho(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(Jo,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Qo extends Jo{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=za.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=za.registeredVariables[t],r=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:hi((()=>Lo(s).variable(r)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:hi((()=>Lo(s).variable(r)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;hi((()=>{const e=Ao(Do(i,this.rho),Do(Mo(a),1-this.rho)),t=Do(Fo(Oo(Ao(o,this.epsilon)),Oo(Ao(i,this.epsilon))),a),n=Ao(Do(o,this.rho),Do(Mo(t),1-this.rho));i.assign(e),o.assign(n);const r=Ao(Do(t,-this.learningRate),s);s.assign(r)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(di(this.accumulatedGrads.map((e=>e.variable))),di(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.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)}}function el(e,t,n){Ve(e);const s={shape:e,value:t,dtype:n=n||_e(t)};return za.runKernel(ln,{},s)}class tl extends Jo{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((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=za.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:hi((()=>el(s.shape,this.initialAccumulatorValue).variable(e)))}}const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=this.accumulatedGrads[n].variable;hi((()=>{const e=Ao(a,Mo(r));a.assign(e);const t=Ao(Do(Fo(r,Oo(Ao(e,za.backend.epsilon()))),-this.learningRate),s);s.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&di(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);this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}const nl=Za({pow_:function(e,t){let n=Ka(e,"base","pow"),s=Ka(t,"exp","pow");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(ls,r)}});const sl=Za({sub_:function(e,t){let n=Ka(e,"a","sub"),s=Ka(t,"b","sub");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(tr,r)}});class rl extends Jo{static get className(){return"Adam"}constructor(e,t,n,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],hi((()=>{this.accBeta1=Ho(t).variable(),this.accBeta2=Ho(n).variable()})),null==s&&(this.epsilon=za.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);hi((()=>{const n=sl(1,this.accBeta1),s=sl(1,this.accBeta2);t.forEach(((t,r)=>{const a=za.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:hi((()=>Lo(a).variable(i)))}),null==this.accumulatedSecondMoment[r]&&(this.accumulatedSecondMoment[r]={originalName:`${t}/v`,variable:hi((()=>Lo(a).variable(i)))});const o=Array.isArray(e)?e[r].tensor:e[t];if(null==o)return;const l=this.accumulatedFirstMoment[r].variable,u=this.accumulatedSecondMoment[r].variable,c=Ao(Do(l,this.beta1),Do(o,1-this.beta1)),h=Ao(Do(u,this.beta2),Do(Mo(o),1-this.beta2)),d=Fo(c,n),p=Fo(h,s);l.assign(c),u.assign(h);const f=Ao(Do(Fo(d,Ao(Oo(p),this.epsilon)),-this.learningRate),a);a.assign(f)})),this.accBeta1.assign(Do(this.accBeta1,this.beta1)),this.accBeta2.assign(Do(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&di(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&di(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),hi((()=>{this.accBeta1.assign(nl(this.beta1,this.iterations_+1)),this.accBeta2.assign(nl(this.beta2,this.iterations_+1))}));const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.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)}}const al=Za({abs_:function(e){const t=Ka(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return za.runKernel($t,e)}{const e={x:t};return za.runKernel(et,e)}}});function il(e,t){const n=e.length,s=[];for(let r=0;r<n;r++){const a=n-1-r,i=e[a]||1;(t[t.length-1-r]||1)>1&&1===i&&s.unshift(a)}return s}function ol(e,t){const n=[];for(let s=0;s<t.length;s++){const r=e[e.length-s-1],a=t.length-s-1,i=t[a];(null==r||1===r&&i>1)&&n.unshift(a)}return n}function ll(e,t){const n=Math.max(e.length,t.length),s=new Array(n);for(let r=0;r<n;r++){let a=e[e.length-r-1];null==a&&(a=1);let i=t[t.length-r-1];if(null==i&&(i=1),1===a)s[n-r-1]=i;else if(1===i)s[n-r-1]=a;else{if(a!==i){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}s[n-r-1]=a}}return s}const ul=Za({maximum_:function(e,t){let n=Ka(e,"a","maximum"),s=Ka(t,"b","maximum");[n,s]=Ea(n,s),"bool"===n.dtype&&(n=$o(n,"int32"),s=$o(s,"int32")),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(Pn,r)}});class cl extends Jo{static get className(){return"Adamax"}constructor(e,t,n,s=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],hi((()=>{this.iteration=Ho(0).variable(),this.accBeta1=Ho(t).variable()})),null==s&&(this.epsilon=za.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);hi((()=>{const n=sl(1,this.accBeta1),s=Fo(-this.learningRate,Ao(Do(this.iteration,this.decay),1));t.forEach(((t,r)=>{const a=za.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Lo(a).variable(i)}),null==this.accumulatedWeightedInfNorm[r]&&(this.accumulatedWeightedInfNorm[r]={originalName:`${t}/v`,variable:Lo(a).variable(i)});const o=Array.isArray(e)?e[r].tensor:e[t];if(null==o)return;const l=this.accumulatedFirstMoment[r].variable,u=this.accumulatedWeightedInfNorm[r].variable,c=Ao(Do(l,this.beta1),Do(o,1-this.beta1)),h=Do(u,this.beta2),d=al(o),p=ul(h,d);l.assign(c),u.assign(p);const f=Ao(Do(Fo(s,n),Fo(c,Ao(p,this.epsilon))),a);a.assign(f)})),this.iteration.assign(Ao(this.iteration,1)),this.accBeta1.assign(Do(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&di(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&di(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)}}class hl extends Jo{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const r=za.registeredVariables[t];hi((()=>{const e=Ao(Do(this.c,s),r);r.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=pi(Ho(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class dl extends hl{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=Ho(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=za.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:hi((()=>Lo(s).variable(e)))}}const r=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&hi((()=>{let e;const t=Ao(Do(this.m,r),a);e=this.useNesterov?Ao(Do(this.c,Ao(a,Do(t,this.m))),s):Ao(Do(this.c,t),s),r.assign(t),s.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&di(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);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class pl extends Jo{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,s=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,null==s&&(this.epsilon=za.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=za.registeredVariables[t],r=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:hi((()=>Lo(s).variable(r)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:hi((()=>Lo(s).variable(r)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:hi((()=>Lo(s).variable(r)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;hi((()=>{const e=Ao(Do(i,this.decay),Do(Mo(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,r=Ao(Do(t,this.decay),Do(a,1-this.decay)),l=Fo(Do(a,this.learningRate),Oo(sl(e,Ao(Mo(r),this.epsilon)))),u=Ao(Do(o,this.momentum),l);i.assign(e),t.assign(r),o.assign(u);const c=sl(s,u);s.assign(c)}else{const e=Ao(Do(i,this.decay),Do(Mo(a),1-this.decay)),t=Ao(Do(o,this.momentum),Fo(Do(a,this.learningRate),Oo(Ao(e,this.epsilon))));i.assign(e),o.assign(t);const n=sl(s,t);s.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&di(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&di(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&di(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.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)}}const fl=[Qo,tl,rl,cl,dl,pl,hl];function ml(e){return new Promise((e=>setTimeout(e))).then(e)}class gl{constructor(e){if(!Xe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(gl.URL_SCHEME)&&(e=e.slice(gl.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=ni.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=Li(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),s=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),r=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(r.download=this.modelJsonFileName,r.href=s,await ml((()=>r.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await ml((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Bi(e)}}}}gl.URL_SCHEME="downloads://";class yl{constructor(e){if(null==e||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)=>{const n=new FileReader;n.onload=n=>{const s=JSON.parse(n.target.result),r=s.modelTopology;if(null==r)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==s.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:r});const a=Pi(s,(e=>this.loadWeights(e)));e(a)},n.onerror=e=>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){const t=[],n=[];for(const s of e)t.push(...s.weights),n.push(...s.paths);const s=this.checkManifestAndWeightFiles(e),r=n.map((e=>this.loadWeightsFile(e,s[e])));return Promise.all(r).then((e=>[t,e]))}loadWeightsFile(e,t){return new Promise(((n,s)=>{const r=new FileReader;r.onload=e=>{const t=e.target.result;n(t)},r.onerror=t=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Mi(e.name))),s={};for(const r of e)r.paths.forEach((e=>{const r=Mi(e);if(-1!==t.indexOf(r))throw new Error(`Duplicate file basename found in weights manifest: '${r}'`);if(t.push(r),-1===n.indexOf(r))throw new Error(`Weight file with basename '${r}' is not provided.`);s[e]=this.weightsFiles[n.indexOf(r)]}));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 s}}function bl(e){return new yl(e)}function xl(e,t,n,s){!function(e){ie(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){ie(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),ie(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),ie(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,s=null==s?1:s);let r=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++r/e.length*(s-n);return t(i),a})),a))))}async function wl(e,t){null==t&&(t={});const n=null==t.fetchFunc?Xe().platform.fetch:t.fetchFunc,s=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),r=(null==t.onProgress?await Promise.all(s):await xl(s,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(r):await xl(r,t.onProgress,.5,1)}async function vl(e,t="",n,s){return kl((e=>wl(e,{requestInit:s})))(e,t,n)}function kl(e){return async(t,n="",s)=>{const r=t.map((()=>!1)),a={},i=null!=s?s.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const l="quantization"in e?e.quantization.dtype:e.dtype,u=ti[l]*ue(e.shape),c=()=>{r[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:u})};null!=s?s.forEach(((t,n)=>{t===e.name&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=u}))})),!i.every((e=>e))){const e=s.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const l=r.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),u=[];l.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;u.push(t)}))}));const c=await e(u),h={};let d=0;return l.forEach((e=>{const n=t[e].paths.length,s=new ni(c.slice(d,d+n));a[e].forEach((e=>{const t=Ti(s.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),d+=n})),h}}Vi.registerSaveRouter((e=>Xe().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(gl.URL_SCHEME)?function(e="model"){return new gl(e)}(e.slice(gl.URL_SCHEME.length)):null));class Il{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(ie("function"==typeof t.fetchFunc,(()=>"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=Xe().platform.fetch,ie(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&ie(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)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.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=Li(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=ni.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Bi(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async loadModelJSON(){const 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(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" 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.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,s=t.weightsManifest;if(null==n&&null==s)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();return Pi(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Wi(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const s=null==t.fetchFunc?Xe().platform.fetch:t.fetchFunc;let r,a=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var i;a<e.length;){if(!r){const n=(await s(e[a],t.requestInit,{isBinary:!0})).body;r=n.getReader()}const{done:o,value:l}=await r.read();if(!o)return void n.enqueue(l);a++,r=void 0,null===(i=t.onProgress)||void 0===i||i.call(t,a/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}(t),r=this.weightPathPrefix||n,a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(r+e+s);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e);return[Wi(e),await wl(t,this.loadOptions)]}}function Nl(e){return null!=e.match(Il.URL_SCHEME_REGEX)}Il.URL_SCHEME_REGEX=/^https?:\/\//;const Sl=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Nl(e))):Nl(e),n)return Tl(e,t)}return null};function Tl(e,t){return new Il(e,t)}function Cl(e,t){return Tl(e,t)}Vi.registerSaveRouter(Sl),Vi.registerLoadRouter(Sl);class $l{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class El{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class Rl{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Al(e,t,n,s){return new Rl(_l(...arguments))}function _l(e,t,n,s){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new $l(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 $l({modelTopology:e}))}return 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 $l({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}function Fl(e){return new El(e)}function Dl(e){return new El(e)}const Ol=Za({matMul_:function(e,t,n=!1,s=!1){let r=Ka(e,"a","matMul"),a=Ka(t,"b","matMul");[r,a]=Ea(r,a);const i={a:r,b:a},o={transposeA:n,transposeB:s};return za.runKernel(bt,i,o)}});const Ml=Za({oneHot_:function(e,t,n=1,s=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:Ka(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:s};return za.runKernel(rs,a,i)}});const Ll=Za({imag_:function(e){const t={input:Ka(e,"input","imag")};return za.runKernel(xn,t)}});const zl=Za({neg_:function(e){const t={x:Ka(e,"x","neg")};return za.runKernel(Jn,t)}});const Pl=Za({real_:function(e){const t={input:Ka(e,"input","real")};return za.runKernel(ms,t)}});const Bl=Za({transpose_:function(e,t,n){const s=Ka(e,"x","transpose");if(null==t&&(t=s.shape.map(((e,t)=>t)).reverse()),ie(s.rank===t.length,(()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`)),t.forEach((e=>{ie(e>=0&&e<s.rank,(()=>"All entries in 'perm' must be between 0 and "+(s.rank-1)+` but got ${t}`))})),s.rank<=1)return s.clone();const r={x:s},a={perm:t};return"complex64"===s.dtype?hi((()=>{let e=Pl(s),t=Ll(s);return e=za.runKernel(or,{x:e},a),t=za.runKernel(or,{x:t},a),n&&(t=zl(t)),Ja(e,t)})):za.runKernel(or,r,a)}});const Wl=Za({confusionMatrix_:function(e,t,n){const s=Ka(e,"labels","confusionMatrix"),r=Ka(t,"predictions","confusionMatrix");ie(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),ie(1===s.rank,(()=>`Expected the rank of labels to be 1, but got ${s.rank}`)),ie(1===r.rank,(()=>`Expected the rank of predictions to be 1, but got ${r.rank}`)),ie(s.shape[0]===r.shape[0],(()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`)),ie(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const a=Ml($o(s,"int32"),n),i=Ml($o(r,"int32"),n),o=Bl(a),l=Ol(o,i);return $o(l,"int32")}});function Vl(e,t,n){if(le(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const s=Ha(e,n);if(3!==s.length&&1!==s.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Qa(e,t,s,n)}let Ul,Gl=!1;function Hl(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,r=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)s=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)r=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))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}`);o=!0}if(null!=Ir(fr,za.backendName)){const n={pixels:e},s={numChannels:t};return za.runKernel(fr,n,s)}const[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i)c=e.getContext("2d").getImageData(0,0,l,u).data;else if(s||n)c=e.data;else if(a||r||o){if(null==Ul)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Ul=new OffscreenCanvas(1,1).getContext("2d")}else Ul=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ul.canvas.width=l,Ul.canvas.height=u,Ul.drawImage(e,0,0,l,u),c=Ul.getImageData(0,0,l,u).data}if(4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)h[n*t+e]=c[4*n+e]}return Vl(h,[u,l,t],"int32")}function jl(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}async function ql(e,t=3){let n=null;if(Xe().getBool("WRAP_TO_IMAGEBITMAP")&&jl(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return Hl(n,t)}function Kl(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}async function Xl(e,t){let n=Ka(e,"img","toPixels");if(!(e instanceof ga)){const e=n;n=$o(e,"int32"),e.dispose()}Kl(n);const[s,r]=n.shape.slice(0,2),a=2===n.rank?1:n.shape[2],i=await n.data(),o="float32"===n.dtype?255:1,l=new Uint8ClampedArray(r*s*4);for(let e=0;e<s*r;++e){const t=[0,0,0,255];for(let s=0;s<a;s++){const r=i[e*a+s];if("float32"===n.dtype){if(r<0||r>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${r}.`)}else if("int32"===n.dtype&&(r<0||r>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${r}.`);1===a?(t[0]=r*o,t[1]=r*o,t[2]=r*o):t[s]=r*o}const s=4*e;l[s+0]=Math.round(t[0]),l[s+1]=Math.round(t[1]),l[s+2]=Math.round(t[2]),l[s+3]=Math.round(t[3])}if(null!=t){if(!Gl){null!=Ir(Yt,za.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Gl=!0)}t.width=r,t.height=s;const e=t.getContext("2d"),n=new ImageData(l,r,s);e.putImageData(n,0,0)}return n!==e&&n.dispose(),l}function Yl(e,t,n){let s=Ka(e,"img","draw");if(!(e instanceof ga)){const e=s;s=$o(e,"int32"),e.dispose()}Kl(s),function(e){const t=(null==e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null==n?void 0:n.imageOptions);const r={image:s},a={canvas:t,options:n};za.runKernel(Yt,r,a)}const Zl=Za({fromPixels_:Hl});function Jl(e,t){const n=e.shape.length,s=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(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(0===ue(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const r=t.shape,a=r[r.length-1];let i=1;for(let e=0;e<r.length-1;++e)i*=r[e];const o=e.shape,l=r.slice();l.pop();let u=1;for(let e=a;e<n;++e)u*=o[e],l.push(o[e]);const c=[...Oe(e.shape).map((e=>e/u)),1].slice(0,a);return[l,i,u,c]}function Ql(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(a+` update.rank < ${r}. `);if(e.length<s+(n.rank-r))throw new Error(a+` Output shape length < ${s+(n.rank-r)}`);if(n.rank!==r+e.length-s)throw new Error(a+" update.rank != "+(r+e.length-s));for(let e=0;e<r;++e)if(n.shape[e]!==t.shape[e])throw new Error(a+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-r;++t)if(n.shape[t+r]!==e[t+s])throw new Error(a+` updates.shape[${t+r}] (${n.shape[t+r]}) != shape[${t+r}] (${e[t+r]})`)}function eu(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("int32"!==t.dtype)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(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Ql(n,t,e)}function tu(e,t,n){const s=t.shape.length,r=s>1?t.shape[s-1]:1,a=n.length;let i=1;for(let e=r;e<a;++e)i*=n[e];const o=r<1?1:r;return{sliceRank:r,numUpdates:ue(t.shape)/o,sliceSize:i,strides:[...Oe(n.slice(0,r)),1],outputSize:ue(n)}}const nu=-2,su=-1;function ru(e,t,n){const s=e.shape.length;ie(s===t.length,(()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`)),ie(s===n.length,(()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`));for(let r=0;r<s;++r)ie(t[r]+n[r]<=e.shape[r],(()=>`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`))}function au(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function iu(e,t,n){const s=[];for(let r=0;r<e.length;r++)s[r]=Math.ceil((t[r]-e[r])/n[r]);return s}function ou(e,t,n,s){const r=[...e];for(let e=r.length;e<s.length;e++)r.push(1);for(let e=0;e<n;e++)0===e?r[t]=1:(r.splice(t,0,1),r.pop());return r}function lu(e,t,n){return n<=e?n:n-(t-1)}function uu(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function cu(e,t,n,s,r,a,i,o,l){const u=e.length;let c=new Array(u),h=new Array(u),d=new Array(u);if(t.length&&n>0){const l=t[0],u=n+1;c=hu(i,l,u,s,e),h=du(o,l,u,r,e),d=ou(a,l,u,e)}else for(let t=0;t<u;t++)c[t]=fu(i,s,a,e,t,l),h[t]=mu(o,r,a,e,t,l),d[t]=pu(a,t,l);return{begin:c,end:h,strides:d}}function hu(e,t,n,s,r){const a=[...r],i=uu(n,t);for(let r=0;r<a.length;r++)if(i.indexOf(r)>-1)a[r]=0;else{const i=lu(t,n,r);let o=s[i];e&1<<i&&(o=0),a[r]=o}return a}function du(e,t,n,s,r){const a=[...r],i=uu(n,t);for(let r=0;r<a.length;r++)if(i.indexOf(r)>-1)a[r]=Number.MAX_SAFE_INTEGER;else{const i=lu(t,n,r);let o=s[i];e&1<<i&&(o=Number.MAX_SAFE_INTEGER),a[r]=o}for(let e=0;e<a.length;e++){const t=r[e];a[e]<0&&(a[e]+=t),a[e]=ee(0,a[e],r[e])}return a}function pu(e,t,n){let s=e[t];return(n&1<<t||null==s)&&(s=1),s}function fu(e,t,n,s,r,a){let i=t[r];const o=n[r]||1;(e&1<<r||a&1<<r||null==i)&&(i=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=s[r];return i<0&&(i+=l),i=ee(0,i,l-1),i}function mu(e,t,n,s,r,a){let i=t[r];const o=n[r]||1;(e&1<<r||a&1<<r||null==i)&&(i=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=s[r];return i<0&&(i+=l),i=o>0?ee(0,i,l):ee(-1,i,l-1),i}function gu(e,t,n){let s=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){s=e;break}for(let r=s+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function yu(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s<e.length-1;s++)n+=e[s]*t[s];return n}function bu(e,t,n){let s;const r=e.shape.length;let a;return s="number"==typeof t?[t,...new Array(r-1).fill(0)]:t.length<r?t.concat(new Array(r-t.length).fill(0)):t.slice(),s.forEach((e=>{ie(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(r).fill(-1):"number"==typeof n?[n,...new Array(r-1).fill(-1)]:n.length<r?n.concat(new Array(r-n.length).fill(-1)):n,a=a.map(((t,n)=>t>=0?t:(ie(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-s[n]))),[s,a]}function xu(e,t,n,s,r,a,i,o,l){let u;if(null==s?(u=new Array(t.length),u.fill(1)):u=s,null!=i&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let e=0;e<h.dims;e++)c&&1<<e&o&&h.numAddAxisAfterEllipsis++,1<<e&i&&(c=!0);c||(h.ellipsisMask|=1<<h.dims,h.dims++);const d={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,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 s=0;s<e.dims;s++)if(1<<s&e.ellipsisMask){const r=Math.min(t.dims-(e.dims-s)+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]=s}else if(1<<s&e.newAxisMask)t.finalShapeGatherIndices.push(nu),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}.`);null!=e.begin&&(t.begin[n]=e.begin[s]),null!=e.end&&(t.end[n]=e.end[s]),t.strides[n]=e.strides[s],e.beginMask&1<<s&&(t.beginMask|=1<<n),e.endMask&1<<s&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<s?(t.finalShapeGatherIndices.push(su),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(s)),t.inputShapeGatherIndicesSparse[n]=s,n++}}(h,d);let p=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===d.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(d.shrinkAxisMask&1<<t),s=e[t];if(-1===s){g.push(n?1:-1);continue}const r=[d.beginMask&1<<t,d.endMask&1<<t],a=[d.strides[t]>0?0:-1,d.strides[t]>0?s:s-1];if(n&&d.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===d.strides[t];const i=!!(d.beginMask&1<<t&&d.endMask&1<<t);if(d.beginValid&&d.endValid){if(n){const e=d.begin[t]<0?s+d.begin[t]:d.begin[t];if(d.begin[t]=e,d.end[t]=d.begin[t]+1,e<0||e>=s)throw Error(`slice index ${d.begin[t]} of dimension ${t} out of bounds.`)}else d.begin[t]=wu(d.begin[t],0,d.strides[t],s,r,a),d.end[t]=wu(d.end[t],1,d.strides[t],s,r,a);const e=1===d.strides[t]&&0===d.begin[t]&&d.end[t]===s;p=p&&e,f=f&&(0===t&&1===d.strides[t]||e)}else p=p&&1===d.strides[t]&&i,f=f&&(0===t&&1===d.strides[t]||i);let o,l=!1;if(d.beginValid&&d.endValid?(o=d.end[t]-d.begin[t],l=!0):n?(o=1,l=!0):i&&s>=0&&(o=d.strides[t]<0?-s:s,l=!0),l){let e;e=0===o||o<0!=d.strides[t]<0?0:Math.trunc(o/d.strides[t])+(o%d.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<d.finalShapeGatherIndices.length;++e){const t=d.finalShapeGatherIndices[e];t>=0?y.push(g[t]):t===nu&&y.push(1)}return{finalShapeSparse:y.filter(((e,t)=>d.finalShapeGatherIndices[t]!==nu)),finalShape:y,isIdentity:p,sliceDim0:f,isSimpleSlice:m,begin:d.begin,end:d.end,strides:d.strides}}function wu(e,t,n,s,r,a){if(r[t])return n>0?a[t]:a[t+1&1];{const t=e<0?s+e:e;return t<a[0]?a[0]:t>a[1]?a[1]:t}}const vu=.001,ku=.1;function Iu(e,t,n){return null==n&&(n=Nu()),Su(e,t,((e,t)=>Eu(e,t,n)))}function Nu(){return 32===za.backend.floatPrecision()?vu:ku}function Su(e,t,n){let s=!0;if((Qr(e)||Qr(t))&&(s=!1),Qr(e)&&Qr(t)&&(s=!0),s){const n=e.constructor.name,s=t.constructor.name;if(n!==s)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${s}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=Ha(e),s=Ha(t);if(!de(n,s))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${s}]`)}const r=Qr(e)?e:ea(e),a=Qr(t)?t:ea(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.\nActual: ${r}.\nExpected: ${a}.`);for(let e=0;e<a.length;++e){const t=r[e],s=a[e];if(!n(t,s))throw new Error(`Arrays differ: actual[${e}] = ${t}, expected[${e}] = ${s}.\nActual: ${r}.\nExpected: ${a}.`)}"undefined"!=typeof expect&&expect().nothing()}function Tu(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!=typeof expect&&expect().nothing()}function Cu(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return Ee(e)||Ee(e[0])||Ee(t)||Ee(t[0])?Su(e,n,((e,t)=>e==t)):Su(e,t,((e,t)=>Eu(e,t,0)))}function $u(e,t,n){if(null==n&&(n=Nu()),!Eu(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()}function Eu(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function Ru(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function Au(e,t){const n=new Float32Array(e),s=new Float32Array(t);if(n.length!==s.length)throw new Error(`Expected ArrayBuffer to be of length ${s.length}, but it was ${n.length}`);for(let e=0;e<s.length;e++)if(n[e]!==s[e])throw new Error(`Expected ArrayBuffer value at ${e} to be ${s[e]} but got ${n[e]} instead`)}function _u(e){for(let t=0;t<e.length;t++){const n=e[t];Array.isArray(n)?_u(n):e[t]=Zr(n)}return e}function Fu(e){const 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((e=>{t.addEventListener("loadeddata",(n=>e(t))),t.load()}))}async function Du(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))}const Ou="4.20.0";class Mu{static sgd(e){return new hl(e)}static momentum(e,t,n=!1){return new dl(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new pl(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new rl(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Qo(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new cl(e,t,n,s,r)}static adagrad(e,t=.1){return new tl(e,t)}}const Lu=Za({acos_:function(e){const t={x:Ka(e,"x","acos")};return za.runKernel(tt,t)}});const zu=Za({acosh_:function(e){const t={x:Ka(e,"x","acosh")};return za.runKernel(nt,t)}});const Pu=Za({addN_:function(e){ie(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),ie(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>Ka(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!de(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const s=t;return za.runKernel(rt,s)}});const Bu=Za({all_:function(e,t=null,n=!1){const s={x:Ka(e,"x","all","bool")},r={axis:t,keepDims:n};return za.runKernel(at,s,r)}});const Wu=Za({any_:function(e,t=null,n=!1){const s={x:Ka(e,"x","any","bool")},r={axis:t,keepDims:n};return za.runKernel(it,s,r)}});const Vu=Za({argMax_:function(e,t=0){const n={x:Ka(e,"x","argMax")},s={axis:t};return za.runKernel(ot,n,s)}});const Uu=Za({argMin_:function(e,t=0){const n={x:Ka(e,"x","argMin")},s={axis:t};return za.runKernel(lt,n,s)}});const Gu=Za({asin_:function(e){const t={x:Ka(e,"x","asin")};return za.runKernel(ut,t)}});const Hu=Za({asinh_:function(e){const t={x:Ka(e,"x","asinh")};return za.runKernel(ct,t)}});const ju=Za({atan_:function(e){const t={x:Ka(e,"x","atan")};return za.runKernel(ht,t)}});const qu=Za({atan2_:function(e,t){let n=Ka(e,"a","atan2"),s=Ka(t,"b","atan2");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(pt,r)}});const Ku=Za({atanh_:function(e){const t={x:Ka(e,"x","atanh")};return za.runKernel(dt,t)}});function Xu(e,t,n,s,r="NHWC",a){return Ju(e,[...t,e[3]],n,a,s,null,null,lc(r))}function Yu(e,t,n,s,r,a,i="channelsLast"){const[o,l]=tc(t);let u;if("channelsLast"===i)u=[o,l,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);u=[o,l,e[1],e[1]]}return Ju(e,u,n,s,r,a,!1,i)}function Zu(e,t,n,s,r,a,i="NDHWC"){const[o,l,u]=nc(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,l,u,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,l,u,e[1],e[1]]}return Qu(e,c,n,s,r,!1,h,a)}function Ju(e,t,n,s,r,a,i=!1,o="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,u,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,u,c]=e}const[d,p,,f]=t,[m,g]=tc(n),[y,b]=tc(s),x=sc(d,y),w=sc(p,b),{padInfo:v,outHeight:k,outWidth:I}=function(e,t,n,s,r,a,i,o,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const r=function(e,t,n,s,r){null==s&&(s=ec(e,t,n));const a=e[0],i=e[1],o=rc((a-t+2*s)/n+1,r),l=rc((i-t+2*s)/n+1,r);return[o,l]}([t,n],a,s,e,o);c=r[0],h=r[1]}else if("same"===e){c=Math.ceil(t/s),h=Math.ceil(n/r);const e=Math.max(0,(c-1)*s+a-t),o=Math.max(0,(h-1)*r+i-n),l=Math.floor(e/2),d=e-l,p=Math.floor(o/2);u={top:l,bottom:d,left:p,right:o-p,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/s),h=Math.ceil((n-i+1)/r);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const d="channelsLast"===l?e[1][0]:e[2][0],p="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],m="channelsLast"===l?e[2][1]:e[3][1];u={top:d,bottom:p,left:f,right:m,type:0===d&&0===p&&0===f&&0===m?"VALID":"EXPLICIT"},c=rc((t-a+d+p)/s+1,o),h=rc((n-i+f+m)/r+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(r,u,c,m,g,x,w,a,o),N=i?f*h:f;let S;return"channelsFirst"===o?S=[l,N,k,I]:"channelsLast"===o&&(S=[l,k,I,N]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:c,inChannels:h,outHeight:k,outWidth:I,outChannels:N,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:p,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function Qu(e,t,n,s,r,a=!1,i="channelsLast",o){let[l,u,c,h,d]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[l,d,u,c,h]=e}const[p,f,m,,g]=t,[y,b,x]=nc(n),[w,v,k]=nc(s),I=sc(p,w),N=sc(f,v),S=sc(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,s,r,a,i,o,l,u,c){let h,d,p,f;"valid"===e&&(e=0);if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,s,r,a){null==r&&(r=ec(e,t[0],s[0]));const i=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*r>=t[n]&&(i[n]=rc((e[n]-t[n]+2*r)/s[n]+1,a));return i}([t,n,s,1],[o,l,u],1,[r,a,i],e,c);d=m[0],p=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{d=Math.ceil(t/r),p=Math.ceil(n/a),f=Math.ceil(s/i);const e=(d-1)*r+o-t,c=(p-1)*a+l-n,m=(f-1)*i+u-s,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}}return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}(r,u,c,h,y,b,x,I,N,S,o),R=a?g*d:g;let A;return"channelsFirst"===i?A=[l,R,C,$,E]:"channelsLast"===i&&(A=[l,C,$,E,R]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:C,outHeight:$,outWidth:E,outChannels:R,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:w,dilationHeight:v,dilationWidth:k,inShape:e,outShape:A,filterShape:t}}function ec(e,t,n,s=1){const r=sc(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function tc(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function nc(e){return"number"==typeof e?[e,e,e]:e}function sc(e,t){return t<=1?e:e+(e-1)*(t-1)}function rc(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 ac(e){const[t,n,s]=tc(e);return 1===t&&1===n&&1===s}function ic(e,t){return ac(e)||ac(t)}function oc(e){return tc(e).every((e=>e>0))}function lc(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function uc(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)ie(pe(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{ie(pe(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const cc=Za({reshape_:function(e,t){const n={x:Ka(e,"x","reshape","string_or_numeric")},s={shape:t};return za.runKernel(bs,n,s)}});const hc=Za({avgPool_:function(e,t,n,s,r){const a=Ka(e,"x","avgPool","float32");ie(ic(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let i=a,o=!1;3===a.rank&&(o=!0,i=cc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),uc("avgPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r};let c=za.runKernel(ft,l,u);return c=$o(c,a.dtype),o?cc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const dc=Za({avgPool3d_:function(e,t,n,s,r,a="NDHWC"){const i=Ka(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=cc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),ie("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),ie("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),uc("avgPool3d",s,r);const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a};let h=za.runKernel(gt,u,c);return h=$o(h,o.dtype),l?cc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const pc=Za({concat_:function(e,t=0){ie(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Xa(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Eo(n[0]);const s=n,r={axis:t};return za.runKernel(Et,s,r)}});const fc=Za({sigmoid_:function(e){const t={x:Ka(e,"x","sigmoid","float32")};return za.runKernel(Ms,t)}});const mc=Za({slice_:function(e,t,n){const s=Ka(e,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");const r={x:s},a={begin:t,size:n};return za.runKernel(_s,r,a)}});const gc=Za({tanh_:function(e){const t={x:Ka(e,"x","tanh","float32")};return za.runKernel(sr,t)}});const yc=Za({basicLSTMCell_:function(e,t,n,s,r,a){const i=Ka(e,"forgetBias","basicLSTMCell"),o=Ka(t,"lstmKernel","basicLSTMCell"),l=Ka(n,"lstmBias","basicLSTMCell"),u=Ka(s,"data","basicLSTMCell"),c=Ka(r,"c","basicLSTMCell"),h=Ka(a,"h","basicLSTMCell"),d=pc([u,h],1),p=Ol(d,o),f=Ao(p,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=mc(f,[0,0],y),x=mc(f,[0,g],y),w=mc(f,[0,2*g],y),v=mc(f,[0,3*g],y),k=Ao(Do(fc(b),gc(x)),Do(c,fc(Ao(i,w))));return[k,Do(gc(k),fc(v))]}});const bc=Za({batchToSpaceND_:function(e,t,n){const s=Ka(e,"x","batchToSpaceND"),r=t.reduce(((e,t)=>e*t));ie(s.rank>=1+t.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`)),ie(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),ie(s.shape[0]%r==0,(()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`));const a={x:s},i={blockShape:t,crops:n};return za.runKernel(xt,a,i)}});const xc=Za({batchNorm_:function(e,t,n,s,r,a){null==a&&(a=.001);const i=Ka(e,"x","batchNorm"),o=Ka(t,"mean","batchNorm"),l=Ka(n,"variance","batchNorm");let u,c;null!=r&&(u=Ka(r,"scale","batchNorm")),null!=s&&(c=Ka(s,"offset","batchNorm")),ie(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?cc(e,[1,1,1,e.size]):2===e.rank?cc(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?cc(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:u,offset:c,mean:o,variance:l},d={varianceEpsilon:a},p=za.runKernel(dn,h,d);return cc(p,i.shape)}});const wc=Za({batchNorm2d_:function(e,t,n,s,r,a){const i=Ka(e,"x","batchNorm"),o=Ka(t,"mean","batchNorm"),l=Ka(n,"variance","batchNorm");let u,c;return null!=r&&(u=Ka(r,"scale","batchNorm")),null!=s&&(c=Ka(s,"offset","batchNorm")),ie(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),ie(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),ie(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=u&&ie(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&ie(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),xc(i,o,l,c,u,a)}});const vc=Za({batchNorm3d_:function(e,t,n,s,r,a){const i=Ka(e,"x","batchNorm"),o=Ka(t,"mean","batchNorm"),l=Ka(n,"variance","batchNorm");let u,c;return null!=r&&(u=Ka(r,"scale","batchNorm")),null!=s&&(c=Ka(s,"offset","batchNorm")),ie(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),ie(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),ie(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=u&&ie(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&ie(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),xc(i,o,l,c,u,a)}});const kc=Za({batchNorm4d_:function(e,t,n,s,r,a){const i=Ka(e,"x","batchNorm"),o=Ka(t,"mean","batchNorm"),l=Ka(n,"variance","batchNorm");let u,c;return null!=r&&(u=Ka(r,"scale","batchNorm")),null!=s&&(c=Ka(s,"offset","batchNorm")),ie(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),ie(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),ie(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=u&&ie(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&ie(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),xc(i,o,l,c,u,a)}});const Ic=Za({bincount_:function(e,t,n){const s=Ka(e,"x","bincount"),r=Ka(t,"weights","bincount");ie("int32"===s.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`)),ie(n>=0,(()=>`size must be non-negative, but got ${n}.`)),ie(r.size===s.size||0===r.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`));const a={x:s,weights:r},i={size:n};return za.runKernel(wt,a,i)}});const Nc=Za({bitwiseAnd_:function(e,t){const n=Ka(e,"x","bitwiseAnd"),s=Ka(t,"y","bitwiseAnd");if(!de(n.shape,s.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${s.shape}`);if("int32"!==n.dtype||"int32"!==s.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${s.dtype}`);const r={a:n,b:s};return za.runKernel(vt,r)}});const Sc=Za({broadcastArgs_:function(e,t){const n=Ka(e,"s0","broadcastArgs","int32"),s=Ka(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==s.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);const r={s0:n,s1:s};return za.runKernel(It,r)}});const Tc=Za({broadcastTo_:function(e,t){let n=Ka(e,"broadcastTo","x");const s=n.shape;if(Ve(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=cc(n,e)}const r=n.shape,a=Array.from(t);for(let e=t.length-1;e>=0;e--)if(r[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(0===a.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Eo(n);const i={x:n},o={reps:a};return za.runKernel(rr,i,o)}});const Cc=Za({ceil_:function(e){const t={x:Ka(e,"x","ceil","float32")};return za.runKernel(St,t)}});const $c=Za({clipByValue_:function(e,t,n){const s=Ka(e,"x","clipByValue");if(ie(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return el(s.shape,t,s.dtype);const r={x:s},a={clipValueMin:t,clipValueMax:n};return za.runKernel(Tt,r,a)}});const Ec=Za({concat1d_:function(e){return pc(e,0)}});const Rc=Za({concat2d_:function(e,t){return pc(e,t)}});const Ac=Za({concat3d_:function(e,t){return pc(e,t)}});const _c=Za({concat4d_:function(e,t){return pc(e,t)}});const Fc=Za({conv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Ka(e,"x","conv2d","float32"),l=Ka(t,"filter","conv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=cc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),ie(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),uc("conv2d",s,i);const h="NHWC"===r?u.shape[3]:u.shape[1];ie(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),ie(ic(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),ie(oc(a),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),ie(oc(n),(()=>"Error in conv2D: Strides should be larger than 0."));const d={x:u,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},f=za.runKernel(Rt,d,p);return c?cc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const Dc=Za({conv1d_:function(e,t,n,s,r="NWC",a=1,i){const o=Ka(e,"x","conv1d"),l=Ka(t,"filter","conv1d");let u=o,c=!1;2===o.rank&&(c=!0,u=cc(o,[1,o.shape[0],o.shape[1]])),ie(3===u.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`)),ie(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),uc("conv1d",s,i),ie(u.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),ie(ic(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),ie(oc(a),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),ie(oc(n),(()=>"Error in conv1D: Stride should be larger than 0.")),ie("NWC"===r,(()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`));const h=cc(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=cc(u,[u.shape[0],1,u.shape[1],u.shape[2]]),p=Fc(d,h,[1,n],s,"NHWC",[1,a],i);return cc(p,c?[p.shape[2],p.shape[3]]:[p.shape[0],p.shape[2],p.shape[3]])}});const Oc=Za({conv2DBackpropInput_:function(e,t,n,s,r,a="NHWC",i){ie(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,u=!1;3===t.rank&&(u=!0,l=cc(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),ie(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),ie(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),ie(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===a?o[3]:o[1],h="NHWC"===a?l.shape[3]:l.shape[1];ie(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),ie(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),uc("conv2dDerInput",r,i);const d={dy:l,filter:n},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,inputShape:o},f=za.runKernel(_t,d,p);return u?cc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const Mc=Za({conv2dTranspose_:function(e,t,n,s,r,a){const i=Ka(e,"x","conv2dTranspose"),o=Ka(t,"filter","conv2dTranspose");return Oc(n,i,o,s,r,"NHWC",a)}});const Lc=Za({conv3d_:function(e,t,n,s,r="NDHWC",a=[1,1,1]){const i=Ka(e,"x","conv3d"),o=Ka(t,"filter","conv3d");let l=i,u=!1;4===i.rank&&(u=!0,l=cc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),ie(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),ie(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),ie(ic(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),ie("NDHWC"===r,(()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`)),ie(oc(a),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),ie(oc(n),(()=>"Error in conv3D: Strides should be larger than 0."));const c={x:l,filter:o},h={strides:n,pad:s,dataFormat:r,dilations:a},d=za.runKernel(Ft,c,h);return u?cc(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const zc=Za({conv3DBackpropInput_:function(e,t,n,s,r){ie(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let a=e,i=t,o=!1;4===t.rank&&(o=!0,i=cc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const l=a[4],u=i.shape[4];ie(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),ie(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),ie(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),ie(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),ie(u===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`));const c={dy:i,filter:n},h={pad:r,strides:s,inputShape:a},d=za.runKernel(Ot,c,h);return o?cc(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const Pc=Za({conv3dTranspose_:function(e,t,n,s,r){const a=Ka(e,"x","conv3dTranspose"),i=Ka(t,"filter","conv3dTranspose");return zc(n,a,i,s,r)}});const Bc=Za({cos_:function(e){const t={x:Ka(e,"x","cos","float32")};return za.runKernel(Mt,t)}});const Wc=Za({cosh_:function(e){const t={x:Ka(e,"x","cosh","float32")};return za.runKernel(Lt,t)}});const Vc=Za({cumprod_:function(e,t=0,n=!1,s=!1){const r={x:Ka(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:s};return za.runKernel(zt,r,a)}});const Uc=Za({cumsum_:function(e,t=0,n=!1,s=!1){const r={x:Ka(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:s};return za.runKernel(Pt,r,a)}});const Gc=Za({denseBincount_:function(e,t,n,s=!1){const r=Ka(e,"x","denseBincount"),a=Ka(t,"weights","denseBincount");ie("int32"===r.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`)),ie(r.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`)),ie(n>=0,(()=>`size must be non-negative, but got ${n}.`)),ie(a.size===r.size||0===a.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`));const i={x:r,weights:a},o={size:n,binaryOutput:s};return za.runKernel(Wt,i,o)}});const Hc=Za({depthToSpace_:function(e,t,n="NHWC"){const s=Ka(e,"x","depthToSpace","float32"),r="NHWC"===n?s.shape[1]:s.shape[2],a="NHWC"===n?s.shape[2]:s.shape[3],i="NHWC"===n?s.shape[3]:s.shape[1];ie(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),ie(r*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${r} and ${t} for depthToSpace with input shape\n ${s.shape}`)),ie(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${s.shape}`)),ie(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`));const o={x:s},l={blockSize:t,dataFormat:n};return za.runKernel(Vt,o,l)}});const jc=Za({depthwiseConv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Ka(e,"x","depthwiseConv2d","float32"),l=Ka(t,"filter","depthwiseConv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=cc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(4===u.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`)),ie(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const h="NHWC"===r?u.shape[3]:u.shape[1];ie(h===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`)),uc("depthwiseConv2d",s,i);const d={x:u,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},f=za.runKernel(Ut,d,p);return c?cc(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const qc=Za({diag_:function(e){const t={x:Ka(e,"x","diag")};return za.runKernel(jt,t)}});const Kc=Za({dilation2d_:function(e,t,n,s,r=[1,1],a="NHWC"){const i=Ka(e,"x","dilation2d"),o=Ka(t,"filter","dilation2d");ie(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),ie(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),ie("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let l=i,u=!1;3===i.rank&&(l=cc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0),ie(l.shape[3]===o.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`));const c={x:l,filter:o},h={strides:n,pad:s,dilations:r},d=za.runKernel(qt,c,h);return u?cc(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Xc=Za({equal_:function(e,t){let n=Ka(e,"a","equal","string_or_numeric"),s=Ka(t,"b","equal","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(nn,r)}});const Yc=Za({where_:function(e,t,n){const s=Ka(t,"a","where"),r=Ka(n,"b","where"),a=Ka(e,"condition","where","bool"),i=ll(ll(a.shape,s.shape),r.shape),o={condition:Tc(a,i),t:Tc(s,i),e:Tc(r,i)};return za.runKernel(Rs,o)}});const Zc=Za({divNoNan_:function(e,t){let n=Ka(e,"a","div"),s=Ka(t,"b","div");[n,s]=Ea(n,s);const r=Fo(n,s),a=Lo(r),i=Xc(s,a);return Yc(i,a,r)}});const Jc=Za({dot_:function(e,t){const n=Ka(e,"t1","dot"),s=Ka(t,"t2","dot");ie(!(1!==n.rank&&2!==n.rank||1!==s.rank&&2!==s.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`));const r=1===n.rank?n.size:n.shape[1],a=1===s.rank?s.size:s.shape[0];if(ie(r===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`)),1===n.rank&&1===s.rank){const e=cc(n,[1,-1]),t=cc(s,[-1,1]),r=Ol(e,t);return cc(r,[])}if(1===n.rank&&2===s.rank){const e=cc(n,[1,-1]),t=cc(s,[s.shape[0],s.shape[1]]),r=Ol(e,t);return cc(r,[r.size])}if(2===n.rank&&1===s.rank){const e=cc(s,[-1,1]),t=Ol(n,e);return cc(t,[t.size])}{const e=cc(s,[s.shape[0],s.shape[1]]);return Ol(n,e)}}});const Qc=Za({einsum_:function(e,...t){const n=t.map(((e,t)=>Ka(e,`tensors${t}`,"einsum"))),s={equation:e};return za.runKernel(Jt,n,s)}});const eh=Za({elu_:function(e){const t={x:Ka(e,"x","elu","float32")};return za.runKernel(Qt,t)}});const th=Za({ensureShape_:function(e,t){const n=Ka(e,"x","ensureShape","string_or_numeric");if(!he(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}});const nh=Za({erf_:function(e){let t=Ka(e,"x","erf");ie("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=$o(t,"float32"));const n={x:t};return za.runKernel(tn,n)}});function sh(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function rh(e,t,n){const s=e.length+t.length,r=[];let a=0,i=0;for(let o=0;o<s;o++)-1===n.indexOf(o)?r.push(e[a++]):r.push(t[i++]);return r}function ah(e,t){const n=[],s=e.length;for(let r=0;r<s;r++)-1===t.indexOf(r)&&n.push(e[r]);return[n,t.map((t=>e[t]))]}function ih(e,t){return rh(e,t.map((e=>1)),t)}function oh(e,t,n){ie(sh(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function lh(e,t){if(sh(e,t))return null;const n=[];for(let s=0;s<t;++s)-1===e.indexOf(s)&&n.push(s);return e.forEach((e=>n.push(e))),n}function uh(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function ch(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}const hh=Za({max_:function(e,t=null,n=!1){const s={x:Ka(e,"x","max")},r={reductionIndices:t,keepDims:n};return za.runKernel(zn,s,r)}});const dh=Za({min_:function(e,t=null,n=!1){const s={x:Ka(e,"x","min")},r={axis:t,keepDims:n};return za.runKernel(jn,s,r)}});const ph=Za({sum_:function(e,t=null,n=!1){let s=Ka(e,"x","sum");"bool"===s.dtype&&(s=$o(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return za.runKernel(Ps,r,a)}});function fh(e,t,n=null){if(0===e.rank)return al(e);if(1!==e.rank&&null===n)return fh(cc(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ph(al(e),n);if(t===1/0)return hh(al(e),n);if(t===-1/0)return dh(al(e),n);if("euclidean"===t||2===t)return Oo(ph(nl(al(e),Ho(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return hh(ph(al(e),n[0]),n[1]-1);if(t===1/0)return hh(ph(al(e),n[1]),n[0]);if(t===-1/0)return dh(ph(al(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Oo(ph(Mo(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const mh=Za({norm_:function(e,t="euclidean",n=null,s=!1){const r=fh(e=Ka(e,"x","norm"),t,n);let a=r.shape;if(s){const t=we(n,e.shape);a=ih(r.shape,t)}return cc(r,a)}});const gh=Za({euclideanNorm_:function(e,t=null,n=!1){return mh(e,"euclidean",t,n)}});const yh=Za({exp_:function(e){const t={x:Ka(e,"x","exp")};return za.runKernel(sn,t)}});const bh=Za({expandDims_:function(e,t=0){const n=Ka(e,"x","expandDims","string_or_numeric");ie(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const s={input:n},r={dim:t};return za.runKernel(rn,s,r)}});const xh=Za({expm1_:function(e){const t={x:Ka(e,"x","expm1")};return za.runKernel(an,t)}});const wh=Za({tile_:function(e,t){const n=Ka(e,"x","tile","string_or_numeric");ie(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const s={x:n},r={reps:t};return za.runKernel(rr,s,r)}});const vh=Za({eye_:function(e,t,n,s="float32"){null==t&&(t=e);const r=Co([e,t],s),a=e<=t?e:t;for(let e=0;e<a;++e)r.set(1,e,e);const i=cc(r.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return wh(bh(i,0),[n[0],1,1]);if(2===n.length)return wh(bh(bh(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return wh(bh(bh(bh(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.`)}});const kh=Za({floor_:function(e){const t={x:Ka(e,"x","floor","float32")};return za.runKernel(cn,t)}});const Ih=Za({gather_:function(e,t,n=0,s=0){const r={x:Ka(e,"x","gather"),indices:Ka(t,"indices","gather","int32")},a={axis:n,batchDims:s};return za.runKernel(pn,r,a)}});const Nh=Za({greater_:function(e,t){let n=Ka(e,"a","greater","string_or_numeric"),s=Ka(t,"b","greater","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(mn,r)}});const Sh=Za({greaterEqual_:function(e,t){let n=Ka(e,"a","greaterEqual","string_or_numeric"),s=Ka(t,"b","greaterEqual","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(gn,r)}});const Th=Za({isFinite_:function(e){const t={x:Ka(e,"x","isFinite")};return za.runKernel(wn,t)}});const Ch=Za({isInf_:function(e){const t={x:Ka(e,"x","isInf")};return za.runKernel(vn,t)}});const $h=Za({isNaN_:function(e){const t={x:Ka(e,"x","isNaN")};return za.runKernel(kn,t)}});const Eh=Za({leakyRelu_:function(e,t=.2){const n={x:Ka(e,"x","leakyRelu")},s={alpha:t};return za.runKernel(In,n,s)}});const Rh=Za({less_:function(e,t){let n=Ka(e,"a","less","string_or_numeric"),s=Ka(t,"b","less","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(Nn,r)}});const Ah=Za({lessEqual_:function(e,t){let n=Ka(e,"a","lessEqual","string_or_numeric"),s=Ka(t,"b","lessEqual","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(Sn,r)}});function _h(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const s={start:e,stop:t,num:n};return za.runKernel(Tn,{},s)}const Fh=Za({localResponseNormalization_:function(e,t=5,n=1,s=1,r=.5){const a=Ka(e,"x","localResponseNormalization");ie(4===a.rank||3===a.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`)),ie(pe(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=cc(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},u={depthRadius:t,bias:n,alpha:s,beta:r},c=za.runKernel(On,l,u);return o?cc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Dh=Za({log_:function(e){const t={x:Ka(e,"x","log","float32")};return za.runKernel(Cn,t)}});const Oh=Za({log1p_:function(e){const t={x:Ka(e,"x","log1p")};return za.runKernel($n,t)}});const Mh=Za({softplus_:function(e){const t={x:Ka(e,"x","softplus")};return za.runKernel(Ls,t)}});const Lh=Za({logSigmoid_:function(e){const t=Ka(e,"x","logSigmoid");return Uo((e=>({value:zl(Mh(zl(e))),gradFunc:t=>Do(t,fc(zl(e)))})))(t)}});const zh=Za({logSoftmax_:function(e,t=-1){const n=Ka(e,"logits","logSoftmax");if(-1===t&&(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}`);const s=Uo(((e,n)=>{const s=hh(e,t,!0),r=sl(e,s),a=sl($o(r,"float32"),Dh(ph(yh(r),t,!0)));n([a]);return{value:a,gradFunc:(e,n)=>{const[s]=n,r=yh(s);return sl(e,Do(ph(e,t,!0),r))}}}));return s(n)}});const Ph=Za({logSumExp_:function(e,t=null,n=!1){const s=Ka(e,"x","logSumExp"),r=we(t,s.shape),a=hh(s,r,!0),i=sl(s,a),o=yh(i),l=ph(o,r),u=Dh(l),c=Ao(cc(a,u.shape),u);if(n){const e=ih(c.shape,r);return cc(c,e)}return c}});const Bh=Za({logicalAnd_:function(e,t){const n=Ka(e,"a","logicalAnd","bool"),s=Ka(t,"b","logicalAnd","bool");ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(En,r)}});const Wh=Za({logicalNot_:function(e){const t={x:Ka(e,"x","logicalNot","bool")};return za.runKernel(Rn,t)}});const Vh=Za({logicalOr_:function(e,t){const n=Ka(e,"a","logicalOr","bool"),s=Ka(t,"b","logicalOr","bool");ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(An,r)}});const Uh=Za({logicalXor_:function(e,t){const n=Ka(e,"a","logicalXor","bool"),s=Ka(t,"b","logicalXor","bool");return ll(n.shape,s.shape),Bh(Vh(e,t),Wh(Bh(e,t)))}}),Gh=2147483648;const Hh=Za({searchSorted_:function(e,t,n="left"){const s=Ka(e,"sortedSequence","searchSorted"),r=Ka(t,"values","searchSorted"),a=s.shape[s.shape.length-1],i=r.shape[r.shape.length-1],o=cc(s,[-1,a]),l=cc(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(ue(l.shape)>=Gh)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=Gh)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const u={sortedSequence:o,values:l},c={side:n};return za.runKernel(Es,u,c)}});function jh(e,t){return Hh(e,t,"left")}const qh=Za({maxPool_:function(e,t,n,s,r){const a=Ka(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=cc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),ie(ic(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),uc("maxPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},c=za.runKernel(Bn,l,u);return o?cc(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Kh=Za({maxPool3d_:function(e,t=[1,1,1],n,s,r,a="NDHWC"){const i=Ka(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=cc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),ie(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),ie("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),uc("maxPool3d",s,r);const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},h=za.runKernel(Vn,u,c);return l?cc(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});const Xh=Za({maxPoolWithArgmax_:function(e,t,n,s,r=!1){const a={x:Ka(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},o=za.runKernel(Gn,a,i);return{result:o[0],indexes:o[1]}}});const Yh=Za({mean_:function(e,t=null,n=!1){const s={x:Ka(e,"x","mean")},r={axis:t,keepDims:n};return za.runKernel(Hn,s,r)}});function Zh(e,t="float32"){if(Ve(e),"complex64"===t){const t=Zh(e,"float32"),n=Zh(e,"float32");return Ja(t,n)}const n=Be(ue(e),t);return za.makeTensor(n,e,t)}function Jh(e,t="float32"){if(Ve(e),"complex64"===t){const t=Jh(e,"float32"),n=Zh(e,"float32");return Ja(t,n)}const n=Pe(ue(e),t);return za.makeTensor(n,e,t)}function Qh(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let s=Ka(e,"x","meshgrid",e instanceof ga?e.dtype:"float32");if(void 0===t)return[s];let r=Ka(t,"y","meshgrid",t instanceof ga?t.dtype:"float32");const a=ue(s.shape),i=ue(r.shape);return"xy"===n?(s=cc(s,[1,-1]),r=cc(r,[-1,1]),[Ol(Jh([i,1],s.dtype),s),Ol(r,Jh([1,a],r.dtype))]):(s=cc(s,[-1,1]),r=cc(r,[1,-1]),[Ol(s,Jh([1,i],s.dtype)),Ol(Jh([a,1],r.dtype),r)])}const ed=Za({minimum_:function(e,t){let n=Ka(e,"a","minimum"),s=Ka(t,"b","minimum");[n,s]=Ea(n,s),"bool"===n.dtype&&(n=$o(n,"int32"),s=$o(s,"int32")),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(qn,r)}});const td=Za({mirrorPad_:function(e,t,n){ie("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const s=Ka(e,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");ie(t.length===s.rank,(()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`));const r="reflect"===n?1:0;for(let e=0;e<s.rank;e++)ie(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),ie(t[e][0]>=0&&t[e][0]<=s.shape[e]-r&&t[e][1]>=0&&t[e][1]<=s.shape[e]-r,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${s.shape[e]-r} or less than 0 for input of shape ${s.shape}`));const a={paddings:t,mode:n},i={x:s};return za.runKernel(Kn,i,a)}});const nd=Za({mod_:function(e,t){let n=Ka(e,"a","mod"),s=Ka(t,"b","mod");[n,s]=Ea(n,s);const r={a:n,b:s};return za.runKernel(Xn,r)}});const sd=Za({moments_:function(e,t=null,n=!1){const s=we(t,(e=Ka(e,"x","moments")).shape),r=Yh(e,s,n);let a=r.shape;n||(a=ih(r.shape,s));const i=Mo(sl($o(e,"float32"),cc(r,a)));return{mean:r,variance:Yh(i,s,n)}}});const rd=Za({multiRNNCell_:function(e,t,n,s){const r=Ka(t,"data","multiRNNCell"),a=Xa(n,"c","multiRNNCell"),i=Xa(s,"h","multiRNNCell");let o=r;const l=[];for(let t=0;t<e.length;t++){const n=e[t](o,a[t],i[t]);l.push(n[0]),l.push(n[1]),o=n[1]}const u=[],c=[];for(let e=0;e<l.length;e+=2)u.push(l[e]),c.push(l[e+1]);return[u,c]}});const ad=Za({multinomial_:function(e,t,n,s=!1){const r=Ka(e,"logits","multinomial"),a=r.size,i=r.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?cc(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:s},u=za.runKernel(Yn,o,l);return 1===i?cc(u,[u.size]):u}});const id=Za({notEqual_:function(e,t){let n=Ka(e,"a","notEqual","string_or_numeric"),s=Ka(t,"b","notEqual","string_or_numeric");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(Qn,r)}});const od=Za({onesLike_:function(e){const t={x:Ka(e,"x","onesLike")};return za.runKernel(ss,t)}});const ld=Za({outerProduct_:function(e,t){const n=Ka(e,"v1","outerProduct"),s=Ka(t,"v2","outerProduct");ie(1===n.rank&&1===s.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`));const r=cc(n,[-1,1]),a=cc(s,[1,-1]);return Ol(r,a)}});const ud=Za({pad_:function(e,t,n=0){const s=Ka(e,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r={paddings:t,constantValue:n},a={x:s};return za.runKernel(is,a,r)}});const cd=Za({pad1d_:function(e,t,n=0){return ie(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),ud(e,[t],n)}});const hd=Za({pad2d_:function(e,t,n=0){return ie(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),ud(e,t,n)}});const dd=Za({pad3d_:function(e,t,n=0){return ie(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),ud(e,t,n)}});const pd=Za({pad4d_:function(e,t,n=0){return ie(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),ud(e,t,n)}});const fd=Za({spaceToBatchND_:function(e,t,n){const s=Ka(e,"x","spaceToBatchND");ie(s.rank>=1+t.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`)),ie(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),ie(s.shape.reduce(((e,s,r)=>r>0&&r<=t.length?e&&(s+n[r-1][0]+n[r-1][1])%t[r-1]==0:e),!0),(()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const r={x:s},a={blockShape:t,paddings:n};return za.runKernel(Bs,r,a)}});const md=Za({pool_:function(e,t,n,s,r,a,i){null==r&&(r=[1,1]),null==a&&(a=1),0===s&&(s="valid");const o=Ka(e,"x","maxPool");let l=o,u=!1;3===o.rank&&(u=!0,l=cc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),ie(ic(a,r),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`));const c=Yu(l.shape,t,a,r,s),h=[c.dilationHeight,c.dilationWidth];let d;d="same"===s?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))),s=n.map((e=>e-1)),r=s.map((e=>Math.floor(e/2))),a=s.map(((e,t)=>e-r[t]));return s.map(((e,t)=>[r[t],a[t]]))}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const p=1===h[0]&&1===h[1],[f,m]=function(e,t,n){const s=n.map((e=>e[0])),r=n.map((e=>e[1])),a=e.concat(s,r),i=t.map(((e,t)=>(e-a[t]%e)%e)),o=r.map(((e,t)=>e+i[t])),l=t.map(((e,t)=>[s[t],o[t]])),u=t.map(((e,t)=>[0,i[t]]));return[l,u]}([c.inHeight,c.inWidth],h,d),g=p?s:"valid",y=p?l:fd(l,h,f),b=("avg"===n?()=>hc(y,t,a,g,i):()=>qh(y,t,a,g,i))(),x=p?b:bc(b,h,m);return u?cc(x,[x.shape[1],x.shape[2],x.shape[3]]):x}});const gd=Za({prelu_:function(e,t){const n={x:Ka(e,"x","prelu"),alpha:Ka(t,"alpha","prelu")};return za.runKernel(us,n)}});const yd=Za({prod_:function(e,t=null,n=!1){let s=Ka(e,"x","prod");"bool"===s.dtype&&(s=$o(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return za.runKernel(cs,r,a)}});const bd=Za({raggedGather_:function(e,t,n,s){const r={paramsNestedSplits:e.map(((e,t)=>Ka(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:Ka(t,"paramsDenseValues","raggedGather"),indices:Ka(n,"indices","raggedGather","int32")},a={outputRaggedRank:s},i=za.runKernel(hs,r,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}});const xd=Za({raggedRange_:function(e,t,n){const s=Ka(e,"starts","raggedRange"),r={starts:s,limits:Ka(t,"limits","raggedRange",s.dtype),deltas:Ka(n,"deltas","raggedRange",s.dtype)},a=za.runKernel(ds,r);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}});const wd=Za({raggedTensorToTensor_:function(e,t,n,s,r){const a=Ka(e,"shape","raggedTensorToTensor","int32"),i=Ka(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:Ka(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:s.map(((e,t)=>Ka(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:r};return za.runKernel(ps,o,l)}});const vd=Za({rand_:function(e,t,n){Ve(e);const s=ue(e);let r=null;if(null==n||"float32"===n)r=new Float32Array(s);else if("int32"===n)r=new Int32Array(s);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);r=new Uint8Array(s)}for(let e=0;e<s;e++)r[e]=t();return za.makeTensor(r,e,n)}});var kd=n(391);class Id{constructor(e,t,n,s,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const a=r||Math.random();this.random=kd.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let s,r,a;do{s=2*this.random()-1,r=2*this.random()-1,a=s*s+r*r}while(a>=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*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 null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class Nd{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const r=s||Math.random();this.randu=kd.alea(r.toString()),this.randn=new Id(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,r,a;for(;;){do{s=this.randn.nextValue(),a=1+this.c*s}while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),r<t||Math.log(r)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class Sd{constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==s&&(s=Math.random()),"number"==typeof s&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=kd.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Td=Za({randomGamma_:function(e,t,n=1,s="float32",r){if(Ve(e),null==n&&(n=1),null==s&&(s="float32"),"float32"!==s&&"int32"!==s)throw new Error(`Unsupported data type ${s}`);const a=new Nd(t,n,s,r),i=Co(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const Cd=Za({randomNormal_:function(e,t=0,n=1,s,r){if(Ve(e),null!=s&&"bool"===s)throw new Error(`Unsupported data type ${s}`);const a=new Id(t,n,s,!1,r),i=Co(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const $d=Za({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return Cd(e,0,1,t,n)}});const Ed=Za({randomUniform_:function(e,t=0,n=1,s="float32",r){Ve(e);const a=Co(e,s),i=new Sd(t,n,null,r);for(let e=0;e<a.values.length;e++)a.values[e]=i.nextValue();return a.toTensor()}});const Rd=Za({randomUniformInt_:function(e,t,n,s){return Ed(e,t,n,"int32",s)}});function Ad(e,t,n=1,s="float32"){if(0===n)throw new Error("Cannot have a step of zero");const r={start:e,stop:t,step:n,dtype:s};return za.runKernel(fs,{},r)}const _d=Za({reciprocal_:function(e){const t={x:Ka(e,"x","reciprocal")};return za.runKernel(gs,t)}});const Fd=Za({relu_:function(e){const t={x:Ka(e,"x","relu")};return za.runKernel(ys,t)}});const Dd=Za({relu6_:function(e){const t={x:Ka(e,"x","relu6")};return za.runKernel(Is,t)}});const Od=Za({reverse_:function(e,t){const n={x:Ka(e,"x","reverse")},s={dims:t};return za.runKernel(Ns,n,s)}});const Md=Za({reverse1d_:function(e){const t=Ka(e,"x","reverse");return ie(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Od(t,0)}});const Ld=Za({reverse2d_:function(e,t){const n=Ka(e,"x","reverse");return ie(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Od(n,t)}});const zd=Za({reverse3d_:function(e,t){const n=Ka(e,"x","reverse");return ie(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Od(n,t)}});const Pd=Za({reverse4d_:function(e,t){const n=Ka(e,"x","reverse");return ie(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Od(n,t)}});const Bd=Za({round_:function(e){const t={x:Ka(e,"x","round")};return za.runKernel(Ss,t)}});const Wd=Za({rsqrt_:function(e){const t={x:Ka(e,"x","rsqrt","float32")};return za.runKernel(Ts,t)}});const Vd=Za({selu_:function(e){const t={x:Ka(e,"x","selu")};return za.runKernel(As,t)}});const Ud=Za({separableConv2d_:function(e,t,n,s,r,a=[1,1],i="NHWC"){const o=Ka(e,"x","separableConv2d"),l=Ka(t,"depthwiseFilter","separableConv2d"),u=Ka(n,"pointwiseFilter","separableConv2d");let c=o,h=!1;if(3===o.rank&&(h=!0,c=cc(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");ie(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),ie(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),ie(4===u.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),ie(1===u.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`)),ie(1===u.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`));const d=l.shape[2],p=l.shape[3];ie(u.shape[2]===d*p,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*p}, but got ${u.shape[2]}.`));const f=jc(c,l,s,r,i,a),m=Fc(f,u,1,"valid",i);return h?cc(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Gd=async function(e,t){const n=Ka(e,"x","setdiff1d"),s=Ka(t,"y","setdiff1d");ie(n.dtype===s.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`)),ie(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),ie(1===s.rank,(()=>`y should be 1D tensor, but got y (${s.shape}).`));const r=await n.data(),a=await s.data(),i=new Set(a);let o=0;for(let e=0;e<r.length;e++)i.has(r[e])||o++;const l=new da([o],n.dtype),u=new da([o],"int32");for(let e=0,t=0;e<r.length;e++)i.has(r[e])||(l.values[t]=r[e],u.values[t]=e,t++);return[l.toTensor(),u.toTensor()]};const Hd=Za({sign_:function(e){const t={x:Ka(e,"x","sign")};return za.runKernel(Os,t)}});const jd=Za({sin_:function(e){const t={x:Ka(e,"x","sin","float32")};return za.runKernel(Fs,t)}});const qd=Za({sinh_:function(e){const t={x:Ka(e,"x","sinh")};return za.runKernel(Ds,t)}});const Kd=Za({slice1d_:function(e,t,n){const s=Ka(e,"x","slice1d");return ie(1===s.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`)),mc(s,[t],[n])}});const Xd=Za({slice2d_:function(e,t,n){const s=Ka(e,"x","slice2d");return ie(2===s.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`)),mc(s,t,n)}});const Yd=Za({slice3d_:function(e,t,n){const s=Ka(e,"x","slice3d");return ie(3===s.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`)),mc(s,t,n)}});const Zd=Za({slice4d_:function(e,t,n){const s=Ka(e,"x","slice4d");return ie(4===s.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`)),mc(s,t,n)}});const Jd=Za({softmax_:function(e,t=-1){const n=Ka(e,"logits","softmax","float32");if(-1===t&&(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}`);const s={logits:n},r={dim:t};return za.runKernel(Vs,s,r)}});const Qd=Za({fft_:function(e){ie("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return za.runKernel(on,t)}});const ep=Za({ifft_:function(e){ie("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return za.runKernel(bn,t)}});const tp=Za({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const r=cc(e,[n,t]);s=ep(r)}else{const r=[n,2*(t-1)],a=cc(Pl(e),[n,t]),i=cc(Ll(e),[n,t]),o=Od(mc(a,[0,1],[n,t-2]),1),l=Do(Od(mc(i,[0,1],[n,t-2]),1),Ho(-1)),u=pc([a,o],1),c=pc([i,l],1),h=cc(Ja(u,c),[r[0],r[1]]);s=ep(h)}if(s=Pl(s),3===e.rank&&0!==e.shape[0]){const t=s,n=e.shape[0];s=cc(s,[n,s.shape[0]/n,s.shape[1]]),t.dispose()}return s}});const np=Za({split_:function(e,t,n=0){const s={x:Ka(e,"x","split")},r={numOrSizeSplits:t,axis:n};return za.runKernel(Ws,s,r)}});const sp=Za({rfft_:function(e,t){ie("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const s=e.size/n;let r;if(null!=t&&t<n){const s=e.shape.map((e=>0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,r=mc(e,s,a),n=t}else if(null!=t&&t>n){const s=e.shape.map((e=>e));s[e.shape.length-1]=t-n,r=pc([e,Zh(s)],e.shape.length-1),n=t}else r=e;const a=Lo(r),i=cc(Ja(r,a),[s,n]),o=Qd(i),l=Math.floor(n/2)+1,u=Pl(o),c=Ll(o),h=np(u,[l,n-l],u.shape.length-1),d=np(c,[l,n-l],c.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,cc(Ja(h[0],d[0]),p)}});const rp=Za({squaredDifference_:function(e,t){let n=Ka(e,"a","squaredDifference"),s=Ka(t,"b","squaredDifference");[n,s]=Ea(n,s),ll(n.shape,s.shape);const r={a:n,b:s};return za.runKernel(Ks,r,{})}});const ap=Za({squeeze_:function(e,t){const n=Ka(e,"x","squeeze","string_or_numeric");return cc(n,ve(n.shape,t).newShape)}});const ip=Za({stack_:function(e,t=0){const n=Xa(e,"tensors","stack","string_or_numeric");ie(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&ie(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,r={axis:t};return za.runKernel(as,s,r)}});const op=Za({step_:function(e,t=0){const n={x:Ka(e,"x","step")},s={alpha:t};return za.runKernel(pr,n,s)}});const lp=Za({stridedSlice_:function(e,t,n,s,r=0,a=0,i=0,o=0,l=0){const u={x:Ka(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return za.runKernel(Zs,u,c)}});const up=Za({tan_:function(e){const t={x:Ka(e,"x","tan","float32")};return za.runKernel(nr,t)}});function cp(e,t){le(e);const n=Ha(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Qa(e,null,n,t)}function hp(e,t,n){if(le(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=Ha(e,n);if(2!==s.length&&1!==s.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Qa(e,t,s,n)}function dp(e,t,n){if(le(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const s=Ha(e,n);if(4!==s.length&&1!==s.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Qa(e,t,s,n)}function pp(e,t,n){if(le(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const s=Ha(e,n);if(5!==s.length&&1!==s.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Qa(e,t,s,n)}function fp(e,t,n){if(le(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const s=Ha(e,n);if(6!==s.length&&1!==s.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Qa(e,t=t||s,s,n)}const mp=Za({tensorScatterUpdate_:function(e,t,n){const s=Ka(e,"tensor","tensorScatterupdate"),r=Ka(t,"indices","tensorScatterupdate","int32"),a=Ka(n,"updates","tensorScatterupdate");if(eu(a,r,s.shape),s.dtype!==a.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${s.dtype} and ${a.dtype}.`);const i={tensor:s,indices:r,updates:a};return za.runKernel($s,i,{})}});const gp=Za({topk_:function(e,t=1,n=!0){const s=Ka(e,"x","topk");if(0===s.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const r=s.shape[s.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}`);const a={x:s},i={k:t,sorted:n},[o,l]=za.runKernel(ar,a,i);return{values:o,indices:l}}});const yp=Za({truncatedNormal_:function(e,t=0,n=1,s,r){if(Ve(e),null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const a=new Id(t,n,s,!0,r),i=Co(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const bp=Za({unique_:function(e,t=0){const n=Ka(e,"x","unique","string_or_numeric");ie(n.rank>0,(()=>"The input tensor must be at least 1D"));const s={x:n},r={axis:t},[a,i]=za.runKernel(lr,s,r);return{values:a,indices:i}}});const xp=Za({unsortedSegmentSum_:function(e,t,n){const s=Ka(e,"x","unsortedSegmentSum"),r=Ka(t,"segmentIds","unsortedSegmentSum","int32");ie(pe(n),(()=>"numSegments must be of dtype int"));const a={x:s,segmentIds:r},i={numSegments:n};return za.runKernel(cr,a,i)}});const wp=Za({unstack_:function(e,t=0){const n=Ka(e,"x","unstack","string_or_numeric");ie(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const s={value:n},r={axis:t};return za.runKernel(ur,s,r)}});function vp(e,t){return Hh(e,t,"right")}function kp(e,t=!0,n,s){return za.makeVariable(e,t,n,s)}function Ip(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const s=Co(e,"int32"),r=Co([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const a=s.indexToLoc(n[t]),i=t*e.length;r.values.set(a,i)}return r.toTensor()}const Np=async function(e){const t=Ka(e,"condition","whereAsync","bool"),n=await t.data(),s=Ip(t.shape,n);return e!==t&&t.dispose(),s};const Sp=async function(e,t,n){const s=Ka(e,"tensor","boolMask"),r=Ka(t,"mask","boolMask","bool"),a=null==n?0:n,i=r.rank,o=s.shape;ie(i>0,(()=>"mask cannot be scalar")),oe(o.slice(a,a+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let e=a;e<a+i;e++)l*=o[e];const u=o.slice(0,a).concat([l],o.slice(a+i)),c=cc(s,u),h=cc(r,[-1]),d=await Np(h),p=ap(d,[1]),f=Ih(c,p,a);return e!==s&&s.dispose(),t!==r&&r.dispose(),p.dispose(),c.dispose(),h.dispose(),d.dispose(),f};const Tp=Za({movingAverage_:function(e,t,n,s,r=!0){const a=Ka(e,"v","movingAverage"),i=Ka(t,"x","movingAverage"),o=Ka(n,"decay","movingAverage");Ra(a,i),ie(de(a.shape,i.shape),(()=>"Shape mismatch in v and x"));const l=Ho(1),u=sl(l,o);let c=Do(sl(i,a),u);if(r){ie(null!=s,(()=>"When using zeroDebias: true, step is required."));const e=Ka(s,"step","movingAverage");c=Fo(c,sl(l,nl(o,e)))}return Ao(a,c)}});const Cp=Za({scatterND_:function(e,t,n){Ve(n);const s=Ka(e,"indices","scatterND","int32"),r=Ka(t,"updates","scatterND");eu(r,s,n);const a={indices:s,updates:r},i={shape:n};return za.runKernel(Cs,a,i)}});const $p=Za({sparseToDense_:function(e,t,n,s=0){Ve(n);const r=Ka(e,"sparseIndices","sparseToDense","int32"),a=Ka(t,"sparseValues","sparseToDense","string_or_numeric"),i=Ka(s,"defaultValue","sparseToDense",a.dtype);!function(e,t,n,s){if("int32"!==e.dtype)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}.`);const r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(r,a,n,i);const o={sparseIndices:r,sparseValues:a,defaultValue:i},l={outputShape:n};return za.runKernel(qs,o,l)}});const Ep=Za({gatherND_:function(e,t){const n=Ka(t,"indices","gatherND","int32"),s={params:Ka(e,"x","gatherND","string_or_numeric"),indices:n};return za.runKernel(fn,s)}});const Rp=Za({dropout_:function(e,t,n,s){const r=Ka(e,"x","dropout");if(ie("float32"===r.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`)),ie(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof ga?r.clone():r;const a=function(e,t){if(null==t)return e.shape.slice();if(de(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s<e.shape.length;s++)null==t[s]&&null!=e.shape[s]?n.push(e.shape[s]):n.push(t[s]);return n}return t}(r,n),i=1-t,o=Fo(kh(Ao(Ed(a,0,1,"float32",s),i)),i);return Do(r,o)}});function Ap(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function _p(e,t,n){const s=1-e%2,r=new Float32Array(e);for(let a=0;a<e;++a){const i=2*Math.PI*a/(e+s-1);r[a]=t-n*Math.cos(i)}return cp(r,"float32")}const Fp=async function(e,t,n=1){const s=Ka(e,"predictions","inTopK"),r=Ka(t,"targets","inTopK");ie(s.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`)),ie(s.rank-1===r.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`)),oe(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=s.shape[s.shape.length-1];ie(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const i=await s.data(),o=await r.data(),[l,u]=[i.length/a,a],c=ke("bool",l);for(let e=0;e<l;e++){const t=e*u,s=i.subarray(t,t+u),r=[];for(let e=0;e<s.length;e++)r.push({value:s[e],index:e});r.sort(((e,t)=>t.value-e.value)),c[e]=0;for(let t=0;t<n;t++)if(r[t].index===o[e]){c[e]=1;break}}return e!==s&&s.dispose(),t!==r&&r.dispose(),ei(c,r.shape,"bool")};const Dp=Za({conv2DBackpropFilter_:function(e,t,n,s,r,a="NHWC",i){let o=e;3===e.rank&&(o=cc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=cc(t,[1,t.shape[0],t.shape[1],t.shape[2]])),ie(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),ie(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),ie(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const u="NHWC"===a?o.shape[3]:o.shape[1],c="NHWC"===a?l.shape[3]:l.shape[1];ie(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),ie(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),uc("conv2dDerFilter",r,i);const h={x:o,dy:l},d={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,filterShape:n};return za.runKernel(At,h,d)}});function Op(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Do(e,op(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Mp(e,t){let n=t;const s=ol(e.shape,t.shape);return s.length>0&&(n=ph(n,s)),cc(n,e.shape)}function Lp(e,t,n,s){if("linear"===t)return e;if("relu"===t)return Fd(e);if("elu"===t)return eh(e);if("relu6"===t)return Dd(e);if("prelu"===t)return gd(e,n);if("leakyrelu"===t)return Eh(e,s);if("sigmoid"===t)return fc(e);throw new Error(`Unknown fused activation ${t}.`)}const zp=(e,t)=>!(e>0)||"linear"===t;const Pp=Za({fusedConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",!1===zp(za.state.gradientDepth,l)){ie("NHWC"===r,(()=>`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 h=Fc(e,t,n,s,r,a,i);return null!=o&&(h=Ao(h,o)),Lp(h,l,u,c)}const h=Ka(e,"x","conv2d","float32"),d=Ka(t,"filter","conv2d","float32");let p=h,f=!1;3===h.rank&&(f=!0,p=cc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===p.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`)),ie(4===d.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`)),uc("fused conv2d",s,i);const m="NHWC"===r?p.shape[3]:p.shape[1];ie(d.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${d.shape[2]}.`)),ie(ic(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const g=Ju(p.shape,d.shape,n,a,s,i);let y,b;if(null!=o&&(y=Ka(o,"bias","fused conv2d"),[y]=Ea(y,h),"NHWC"===r?ll(g.outShape,y.shape):(ie(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),ie(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=u){const e=u.shape;if(ie(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)ie(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{ll(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=Ka(u,"prelu weights","fused conv2d")}const x=(e,t)=>{ie("NHWC"===r,(()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`));const[i,o,u,c]=t,h=Op(e,u,l);ie(ac(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const d=[Oc(o.shape,h,i,n,s),Dp(o,h,i.shape,n,s)];if(null!=c){const e=Mp(c,h);d.push(e)}return d},w={x:p,filter:d,bias:y,preluActivationWeights:b},v={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};if(null==o){const e=Uo(((e,t,n)=>{let s=za.runKernel(yr,w,v);return n([t,e,s]),f&&(s=cc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(p,d)}{const e=Uo(((e,t,n,s)=>{let r=za.runKernel(yr,w,v);return s([t,e,r,n]),f&&(r=cc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(p,d,y)}}});const Bp=Za({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,s,r,a=[1,1],i){let o=e;3===e.rank&&(o=cc(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=cc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:o,dy:l},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,filterShape:n};return za.runKernel(Gt,u,c)}});const Wp=Za({depthwiseConv2dNativeBackpropInput_:function(e,t,n,s,r,a=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=cc(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:o,filter:n},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,inputShape:e},h=za.runKernel(Ht,u,c);return l?cc(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Vp=Za({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(!1===zp(za.state.gradientDepth,l)){let h=jc(e,t,n,s,r,a,i);return null!=o&&(h=Ao(h,o)),Lp(h,l,u,c)}const h=Ka(e,"x","depthwiseConv2d","float32"),d=Ka(t,"filter","depthwiseConv2d","float32");let p=h,f=!1;3===h.rank&&(f=!0,p=cc(h,[1,h.shape[0],h.shape[1],h.shape[2]])),ie(4===p.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`)),ie(4===d.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`)),ie(p.shape[3]===d.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`)),null==a&&(a=[1,1]),ie(ic(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),uc("fused depthwiseConv2d",s,i);const m=Ju(p.shape,d.shape,n,a,s,i,!0);let g,y;null!=o&&(g=Ka(o,"bias","fused conv2d"),[g]=Ea(g,h),ll(m.outShape,g.shape)),null!=u&&(y=Ka(u,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{ie(ac(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[r,o,u,c]=t,h=Op(e,u,l),d=Wp(o.shape,h,r,n,s,a,i),p=Bp(o,h,r.shape,n,s,a,i);if(null!=c){return[d,p,Mp(g,h)]}return[d,p]},x={x:p,filter:d,bias:g,preluActivationWeights:y},w={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:c};if(null==o){const e=Uo(((e,t,n)=>{let s=za.runKernel(br,x,w);return n([t,e,s]),f&&(s=cc(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}));return e(p,d)}{const e=Uo(((e,t,n,s)=>{let r=za.runKernel(br,x,w);return s([t,e,r,n]),f&&(r=cc(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(p,d,g)}}});const Up=Za({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===zp(za.state.gradientDepth,a)){let l=Ol(e,t,n,s);return null!=r&&(l=Ao(l,r)),Lp(l,a,i,o)}let l=Ka(e,"a","fused matMul"),u=Ka(t,"b","fused matMul");[l,u]=Ea(l,u);const c=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?u.shape[u.rank-1]:u.shape[u.rank-2],d=n?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=ue(f),y=ue(m);ie(c===h,(()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`));const b=ll(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,p]),x=cc(l,n?[g,c,d]:[g,d,c]),w=cc(u,s?[y,p,h]:[y,h,p]);let v,k;null!=r&&(v=Ka(r,"bias","fused matMul"),[v]=Ea(v,l),ll(b,v.shape)),null!=i&&(k=Ka(i,"prelu weights","fused matMul"));const I=(e,t)=>{const[i,o,l,u]=t,c=Op(cc(e,l.shape),l,a);let h,d;if(n||s?!n&&s?(h=Ol(c,o,!1,!1),d=Ol(c,i,!0,!1)):n&&!s?(h=Ol(o,c,!1,!0),d=Ol(i,c,!1,!1)):(h=Ol(o,c,!0,!0),d=Ol(c,i,!0,!0)):(h=Ol(c,o,!1,!0),d=Ol(i,c,!0,!1)),null!=r){return[h,d,Mp(u,c)]}return[h,d]},N={a:x,b:w,bias:v,preluActivationWeights:k},S={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:o};if(null==r){const e=Uo(((e,t,n)=>{const s=za.runKernel(gr,N,S);return n([e,t,s]),{value:cc(s,b),gradFunc:I}}));return e(x,w)}{const e=Uo(((e,t,n,s)=>{const r=za.runKernel(gr,N,S);return s([e,t,r,n]),{value:cc(r,b),gradFunc:I}}));return e(x,w,v)}}});const Gp=Za({hammingWindow_:function(e){return _p(e,.54,.46)}});const Hp=Za({hannWindow_:function(e){return _p(e,.5,.5)}});const jp=Za({frame_:function(e,t,n,s=!1,r=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(mc(e,a,t)),a+=n;if(s)for(;a<e.size;){const s=a+t-e.size,o=pc([mc(e,a,t-s),el([s],r)]);i.push(o),a+=n}return 0===i.length?hp([],[0,t]):cc(pc(i),[i.length,t])}});const qp=Za({stft_:function(e,t,n,s,r=Hp){null==s&&(s=Ap(t));const a=jp(e,t,n),i=Do(a,r(t));return sp(i,s)}});const Kp=Za({cropAndResize_:function(e,t,n,s,r="bilinear",a=0){const i=Ka(e,"image","cropAndResize"),o=Ka(t,"boxes","cropAndResize","float32"),l=Ka(n,"boxInd","cropAndResize","int32"),u=o.shape[0];ie(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),ie(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`)),ie(1===l.rank&&l.shape[0]===u,(()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`)),ie(2===s.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`)),ie(s[0]>=1&&s[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${s}`)),ie("bilinear"===r||"nearest"===r,(()=>`method must be bilinear or nearest, but was ${r}`));const c={image:i,boxes:o,boxInd:l},h={method:r,extrapolationValue:a,cropSize:s};return za.runKernel(Bt,c,h)}});const Xp=Za({flipLeftRight_:function(e){const t=Ka(e,"image","flipLeftRight","float32");ie(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return za.runKernel(un,n,{})}});const Yp=Za({grayscaleToRGB_:function(e){const t=Ka(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];ie(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),ie(1===s,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`));const r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,wh(t,r)}});const Zp=Za({rgbToGrayscale_:function(e){const t=Ka(e,"image","RGBToGrayscale"),n=t.rank-1,s=t.shape[n];ie(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),ie(3===s,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`));const r=t.dtype,a=$o(t,"float32"),i=cp([.2989,.587,.114]);let o;switch(t.rank){case 2:o=Qc("ij,j->i",a,i);break;case 3:o=Qc("ijk,k->ij",a,i);break;case 4:o=Qc("ijkl,l->ijk",a,i);break;case 5:o=Qc("ijklm,m->ijkl",a,i);break;case 6:o=Qc("ijklmn,n->ijklm",a,i);break;default:throw new Error("Not a valid tensor rank.")}return o=bh(o,-1),$o(o,r)}});const Jp=Za({rotateWithOffset_:function(e,t,n=0,s=.5){const r=Ka(e,"image","rotateWithOffset","float32");ie(4===r.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`));const a={image:r},i={radians:t,fillValue:n,center:s};return za.runKernel(mr,a,i)}});function Qp(e,t,n,s,r,a){null==s&&(s=.5),null==r&&(r=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),ie(0<=s&&s<=1,(()=>`iouThreshold must be in [0, 1], but was '${s}'`)),ie(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),ie(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),ie(1===t.rank,(()=>"scores must be a 1D tensor")),ie(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),ie(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}const ef=Za({nonMaxSuppression_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Ka(e,"boxes","nonMaxSuppression","float32"),i=Ka(t,"scores","nonMaxSuppression","float32"),o=Qp(a,i,n,s,r),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:r=o.scoreThreshold};return za.runKernel(es,{boxes:a,scores:i},l)}});function tf(e,t,n){const s=function(e,t,n){return function(e,t,n){let s=0,r=e.length,a=0,i=!1;for(;s<r;){a=s+(r-s>>>1);const o=n(t,e[a]);o>0?s=a+1:(r=a,i=!o)}return i?s:-s-1}(e,t,n||nf)}(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function nf(e,t){return e>t?1:e<t?-1:0}function sf(e,t,n,s,r){return of(e,t,n,s,r,0)}function rf(e,t,n,s,r,a){return of(e,t,n,s,r,0,!1,a,!0)}function af(e,t,n,s,r,a){return of(e,t,n,s,r,a,!0)}function of(e,t,n,s,r,a,i=!1,o=!1,l=!1){const u=[];for(let e=0;e<t.length;e++)t[e]>r&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(cf);const c=a>0?-.5/a:0,h=[],d=[];for(;h.length<n&&u.length>0;){const t=u.pop(),{score:n,boxIndex:a,suppressBeginIndex:i}=t;if(n<r)break;let o=!1;for(let n=h.length-1;n>=i;--n){const i=lf(e,a,h[n]);if(i>=s){o=!0;break}if(t.score=t.score*uf(s,c,i),t.score<=r)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),d.push(t.score)):t.score>r&&tf(u,t,cf))}const p=h.length,f=n-p;o&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=d),l&&(m.validOutputs=p),m}function lf(e,t,n){const s=e.subarray(4*t,4*t+4),r=e.subarray(4*n,4*n+4),a=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),o=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(o-a)*(l-i),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;const m=Math.max(a,u),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(l,d),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(p+f-x)}function uf(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function cf(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const hf=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Ka(e,"boxes","nonMaxSuppressionAsync"),i=Ka(t,"scores","nonMaxSuppressionAsync"),o=Qp(a,i,n,s,r);n=o.maxOutputSize,s=o.iouThreshold,r=o.scoreThreshold;const l=await Promise.all([a.data(),i.data()]),u=l[0],c=l[1],{selectedIndices:h}=sf(u,c,n,s,r);return a!==e&&a.dispose(),i!==t&&i.dispose(),cp(h,"int32")};const df=Za({nonMaxSuppressionWithScore_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Ka(e,"boxes","nonMaxSuppression"),o=Ka(t,"scores","nonMaxSuppression"),l=Qp(i,o,n,s,r,a),u={boxes:i,scores:o},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:s=l.iouThreshold,scoreThreshold:r=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},h=za.runKernel(ns,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const pf=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Ka(e,"boxes","nonMaxSuppressionAsync"),o=Ka(t,"scores","nonMaxSuppressionAsync"),l=Qp(i,o,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;const u=await Promise.all([i.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:d,selectedScores:p}=af(c,h,n,s,r,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:cp(d,"int32"),selectedScores:cp(p)}};const ff=Za({nonMaxSuppressionPadded_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Ka(e,"boxes","nonMaxSuppression"),o=Ka(t,"scores","nonMaxSuppression"),l=Qp(i,o,n,s,r,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=za.runKernel(ts,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const mf=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Ka(e,"boxes","nonMaxSuppressionAsync"),o=Ka(t,"scores","nonMaxSuppressionAsync"),l=Qp(i,o,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,p]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=rf(d,p,u,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:cp(f,"int32"),validOutputs:Ho(m,"int32")}};const gf=Za({resizeBilinear_:function(e,t,n=!1,s=!1){const r=Ka(e,"images","resizeBilinear");ie(3===r.rank||4===r.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`)),ie(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),ie(!1===s||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=cc(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=za.runKernel(vs,o,l);return i?cc(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const yf=Za({resizeNearestNeighbor_:function(e,t,n=!1,s=!1){const r=Ka(e,"images","resizeNearestNeighbor");ie(3===r.rank||4===r.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`)),ie(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),ie("float32"===r.dtype||"int32"===r.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),ie(!1===s||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=cc(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=za.runKernel(xs,o,l);return i?cc(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const bf=Za({threshold_:function(e,t="binary",n=!1,s=.5){const r=Ka(e,"image","threshold"),a=r.shape[0]*r.shape[1];let i,o,l,u,c=Do(cp([s]),255);if(ie(3===r.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`)),ie(3===r.shape[2]||1===r.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`)),ie("int32"===r.dtype||"float32"===r.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`)),ie("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===r.shape[2]){[i,o,l]=np(r,[1,1,1],-1);const e=Do(i,.2989),t=Do(o,.587),n=Do(l,.114);u=Ao(Ao(e,t),n)}else u=e;if("otsu"===t){c=function(e,t){let n,s,r,a,i,o,l=cp([-1]),u=cp([0]),c=cp([0]);for(let h=0;h<e.size-1;h++){n=mc(e,0,h+1),s=mc(e,h+1),i=Fo(ph(n),t),o=Fo(ph(s),t);const d=ph(Do(n,Ad(0,n.size)));r=Fo(d,ph(n));const p=el(s.shape,n.size),f=Ao(Ad(0,s.size),p),m=Do(s,f);a=Fo(ph(m),ph(s));const g=sl(r,a),y=sl(r,a),b=Do(i,o);c=Do(Do(b,g),y);const x=Nh(c,u);u=Yc(x,c,u),l=Yc(x,cp([h]),l)}return l}(Ic($o(Bd(u),"int32"),ei([]),256),a)}const h=n?Ah(u,c):Nh(u,c);return $o(Do(h,255),"int32")}});const xf=Za({transform_:function(e,t,n="nearest",s="constant",r=0,a){const i=Ka(e,"image","transform","float32"),o=Ka(t,"transforms","transform","float32");ie(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),ie(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),ie(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const l={image:i,transforms:o},u={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return za.runKernel(ir,l,u)}});const wf=Za({bandPart_:function(e,t,n){const s=Ka(e,"a","bandPart");ie(s.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`));const r=s.shape,[a,i]=s.shape.slice(-2);let o,l;"number"==typeof t?(ie(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),ie(t<=a,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`)),o=Ka(t<0?a:t,"numLower","bandPart")):(ie("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),o=Yc(Rh(t,0),a,ed(t,a))),"number"==typeof n?(ie(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),ie(n<=i,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`)),l=Ka(n<0?i:n,"numUpper","bandPart")):(ie("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),l=Yc(Rh(n,0),i,ed(n,i)));const u=cc(Ad(0,a,1,"int32"),[-1,1]),c=Ad(0,i,1,"int32"),h=sl(u,c),d=Bh(Ah(h,o),Sh(h,zl(l))),p=Zh([a,i],s.dtype);return cc(ip(wp(cc(s,[-1,a,i])).map((e=>Yc(d,e,p)))),r)}});const vf=Za({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,ie(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)ie(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=np(e,e.shape[0],0).map((e=>ap(e,[0])));ie(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],s=e;for(let t=0;t<e.length;++t)n.push(za.tidy((()=>{let e=s[t];if(t>0)for(let s=0;s<t;++s){const t=Do(ph(Do(n[s],e)),n[s]);e=sl(e,t)}return Fo(e,mh(e,"euclidean"))})));return t?ip(n,0):n}});function kf(e,t=!1){return za.tidy((()=>{ie(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],s=e.shape[1];let r=vh(n),a=Eo(e);const i=hp([[1]],[1,1]);let o=Eo(i);const l=n>=s?s:n;for(let e=0;e<l;++e){const t=a,l=o,u=r;[o,a,r]=za.tidy((()=>{const t=mc(a,[e,e],[n-e,1]),l=mh(t),u=mc(a,[e,e],[1,1]),c=Yc(Nh(u,0),hp([[-1]]),hp([[1]])),h=sl(u,Do(c,l)),d=Fo(t,h);o=1===d.shape[0]?Eo(i):pc([i,mc(d,[1,0],[d.shape[0]-1,d.shape[1]])],0);const p=zl(Fo(Ol(c,h),l)),f=mc(a,[e,0],[n-e,s]),m=Do(p,o),g=Bl(o);if(0===e)a=sl(f,Ol(m,Ol(g,f)));else{const t=sl(f,Ol(m,Ol(g,f)));a=pc([mc(a,[0,0],[e,s]),t],0)}const y=Bl(m),b=mc(r,[0,e],[n,r.shape[1]-e]);if(0===e)r=sl(b,Ol(Ol(b,o),y));else{const t=sl(b,Ol(Ol(b,o),y));r=pc([mc(r,[0,0],[n,e]),t],1)}return[o,a,r]})),di([t,l,u])}return!t&&n>s&&(r=mc(r,[0,0],[n,s]),a=mc(a,[0,0],[s,s])),[r,a]}))}const If=Za({qr_:function(e,t=!1){if(ie(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return kf(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),s=wp(cc(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach((e=>{const[n,s]=kf(e,t);r.push(n),a.push(s)}));return[cc(ip(r,0),e.shape),cc(ip(a,0),e.shape)]}}});var Nf;!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"}(Nf||(Nf={}));const Sf=Za({computeWeightedLoss_:function(e,t,n=Nf.SUM_BY_NONZERO_WEIGHTS){const s=Ka(e,"losses","computeWeightedLoss");let r=null;null!=t&&(r=Ka(t,"weights","computeWeightedLoss"));const a=null==r?s:Do(s,r);if(n===Nf.NONE)return a;if(n===Nf.SUM)return ph(a);if(n===Nf.MEAN){if(null==r)return Yh(a);{const e=s.size/r.size,t=Fo(ph(a),ph(r));return e>1?Fo(t,Ho(e)):t}}if(n===Nf.SUM_BY_NONZERO_WEIGHTS){if(null==r)return Fo(ph(a),Ho(s.size));{const e=Do(r,Jh(s.shape)),t=$o(ph(id(e,Ho(0))),"float32");return Fo(ph(a),t)}}throw Error(`Unknown reduction: ${n}`)}});const Tf=Za({absoluteDifference_:function(e,t,n,s=Nf.SUM_BY_NONZERO_WEIGHTS){const r=Ka(e,"labels","absoluteDifference"),a=Ka(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=Ka(n,"weights","absoluteDifference")),oe(r.shape,a.shape,"Error in absoluteDifference: ");const o=al(sl(r,a));return Sf(o,i,s)}});const Cf=Za({cosineDistance_:function(e,t,n,s,r=Nf.SUM_BY_NONZERO_WEIGHTS){const a=Ka(e,"labels","cosineDistance"),i=Ka(t,"predictions","cosineDistance");let o=null;null!=s&&(o=Ka(s,"weights","cosineDistance")),oe(a.shape,i.shape,"Error in cosineDistance: ");const l=Ho(1),u=sl(l,ph(Do(a,i),n,!0));return Sf(u,o,r)}});const $f=Za({hingeLoss_:function(e,t,n,s=Nf.SUM_BY_NONZERO_WEIGHTS){let r=Ka(e,"labels","hingeLoss");const a=Ka(t,"predictions","hingeLoss");let i=null;null!=n&&(i=Ka(n,"weights","hingeLoss")),oe(r.shape,a.shape,"Error in hingeLoss: ");const o=Ho(1);r=sl(Do(Ho(2),r),o);const l=Fd(sl(o,Do(r,a)));return Sf(l,i,s)}});const Ef=Za({huberLoss_:function(e,t,n,s=1,r=Nf.SUM_BY_NONZERO_WEIGHTS){const a=Ka(e,"labels","huberLoss"),i=Ka(t,"predictions","huberLoss");let o=null;null!=n&&(o=Ka(n,"weights","huberLoss")),oe(a.shape,i.shape,"Error in huberLoss: ");const l=Ho(s),u=al(sl(i,a)),c=ed(u,l),h=sl(u,c),d=Ao(Do(Ho(.5),Mo(c)),Do(l,h));return Sf(d,o,r)}});const Rf=Za({logLoss_:function(e,t,n,s=1e-7,r=Nf.SUM_BY_NONZERO_WEIGHTS){const a=Ka(e,"labels","logLoss"),i=Ka(t,"predictions","logLoss");let o=null;null!=n&&(o=Ka(n,"weights","logLoss")),oe(a.shape,i.shape,"Error in logLoss: ");const l=Ho(1),u=Ho(s),c=zl(Do(a,Dh(Ao(i,u)))),h=Do(sl(l,a),Dh(Ao(sl(l,i),u))),d=sl(c,h);return Sf(d,o,r)}});const Af=Za({meanSquaredError_:function(e,t,n,s=Nf.SUM_BY_NONZERO_WEIGHTS){const r=Ka(e,"labels","meanSquaredError"),a=Ka(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=Ka(n,"weights","meanSquaredError")),oe(r.shape,a.shape,"Error in meanSquaredError: ");const o=rp(r,a);return Sf(o,i,s)}});const _f=Za({sigmoidCrossEntropy_:function(e,t,n,s=0,r=Nf.SUM_BY_NONZERO_WEIGHTS){let a=Ka(e,"multiClassLabels","sigmoidCrossEntropy");const i=Ka(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=Ka(n,"weights","sigmoidCrossEntropy")),oe(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),s>0){const e=Ho(s),t=Ho(1),n=Ho(.5);a=Ao(Do(a,sl(t,e)),Do(n,e))}const l=function(e,t){const n=Ka(e,"labels","sigmoidCrossEntropyWithLogits"),s=Ka(t,"logits","sigmoidCrossEntropyWithLogits");oe(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=Fd(s),a=Do(s,n),i=Oh(yh(zl(al(s))));return Ao(sl(r,a),i)}(a,i);return Sf(l,o,r)}});const Ff=Za({softmaxCrossEntropy_:function(e,t,n,s=0,r=Nf.SUM_BY_NONZERO_WEIGHTS){let a=Ka(e,"onehotLabels","softmaxCrossEntropy");const i=Ka(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=Ka(n,"weights","softmaxCrossEntropy")),oe(a.shape,i.shape,"Error in softmaxCrossEntropy: "),s>0){const e=Ho(s),t=Ho(1),n=Ho(a.shape[1]);a=Ao(Do(a,sl(t,e)),Fo(e,n))}const l=function(e,t,n=-1){if(-1===n&&(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}`);const s=Uo(((e,t,s)=>{const r=Ph(t,[n],!0),a=sl($o(t,"float32"),r);s([e,a]);const i=zl(Do(a,e));return{value:ph(i,[n]),gradFunc:(e,t)=>{const[s,r]=t,a=ih(e.shape,[n]);return[Do(cc(e,a),sl($o(s,"float32"),yh(r))),Do(cc(e,a),sl(yh(r),$o(s,"float32")))]}}}));return s(e,t)}(a,i);return Sf(l,o,r)}});const Df=Za({sparseFillEmptyRows_:function(e,t,n,s){const r=Ka(e,"indices","sparseFillEmptyRows","int32"),a=Ka(t,"values","sparseFillEmptyRows"),i=Ka(n,"denseShape","sparseFillEmptyRows","int32"),o=Ka(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==r.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const l={indices:r,values:a,denseShape:i,defaultValue:o},u=za.runKernel(Us,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const Of=Za({sparseReshape_:function(e,t,n){const s=Ka(e,"inputIndices","sparseReshape","int32"),r=Ka(t,"inputShape","sparseReshape","int32"),a=Ka(n,"newShape","sparseReshape","int32");if(2!==s.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${s.shape}`);if(1!==r.rank)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:s,inputShape:r,newShape:a},o=za.runKernel(Gs,i);return{outputIndices:o[0],outputShape:o[1]}}});const Mf=Za({sparseSegmentMean_:function(e,t,n){const s=Ka(e,"data","sparseSegmentMean"),r=Ka(t,"indices","sparseSegmentMean","int32"),a=Ka(n,"segmentIds","sparseSegmentMean","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return za.runKernel(Hs,i)}});const Lf=Za({sparseSegmentSum_:function(e,t,n){const s=Ka(e,"data","sparseSegmentSum"),r=Ka(t,"indices","sparseSegmentSum","int32"),a=Ka(n,"segmentIds","sparseSegmentSum","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return za.runKernel(js,i)}});const zf=Za({stringNGrams_:function(e,t,n,s,r,a,i,o){const l=Ka(e,"data","stringNGrams","string");if("string"!==l.dtype)throw new Error("Data must be of datatype string");if(1!==l.shape.length)throw new Error(`Data must be a vector, saw: ${l.shape}`);const u=Ka(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},d=za.runKernel(Js,h,c);return{nGrams:d[0],nGramsSplits:d[1]}}});const Pf=Za({stringSplit_:function(e,t,n=!0){const s=Ka(e,"input","stringSplit","string"),r=Ka(t,"delimiter","stringSplit","string");if(1!==s.rank)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(0!==r.rank)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);const a={skipEmpty:n},i={input:s,delimiter:r},o=za.runKernel(Qs,i,a);return{indices:o[0],values:o[1],shape:o[2]}}});const Bf=Za({stringToHashBucketFast_:function(e,t){const n=Ka(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const r={input:n};return za.runKernel(er,r,s)}});const Wf=Za({staticRegexReplace_:function(e,t,n,s=!0){const r=Ka(e,"input","staticRegexReplace","string"),a={pattern:t,rewrite:n,replaceGlobal:s};return za.runKernel(Ys,{x:r},a)}}),Vf={fft:Qd,ifft:ep,rfft:sp,irfft:tp},Uf={hammingWindow:Gp,hannWindow:Hp,frame:jp,stft:qp},Gf={flipLeftRight:Xp,grayscaleToRGB:Yp,resizeNearestNeighbor:yf,resizeBilinear:gf,rgbToGrayscale:Zp,rotateWithOffset:Jp,cropAndResize:Kp,nonMaxSuppression:ef,nonMaxSuppressionAsync:hf,nonMaxSuppressionWithScore:df,nonMaxSuppressionWithScoreAsync:pf,nonMaxSuppressionPadded:ff,nonMaxSuppressionPaddedAsync:mf,threshold:bf,transform:xf},Hf={bandPart:wf,gramSchmidt:vf,qr:If},jf={absoluteDifference:Tf,computeWeightedLoss:Sf,cosineDistance:Cf,hingeLoss:$f,huberLoss:Ef,logLoss:Rf,meanSquaredError:Af,sigmoidCrossEntropy:_f,softmaxCrossEntropy:Ff},qf={sparseFillEmptyRows:Df,sparseReshape:Of,sparseSegmentMean:Mf,sparseSegmentSum:Lf},Kf={stringNGrams:zf,stringSplit:Pf,stringToHashBucketFast:Bf,staticRegexReplace:Wf},Xf=Mu,Yf="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function Zf(){return new Promise((e=>Yf((()=>e()))))}function Jf(e,t){const n=e[0].length;e.forEach(((e,t)=>{ie(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),ie(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const s=e[0];e.forEach(((e,r)=>{for(let a=0;a<n;a++)ie(a===t||e[a]===s[a],(()=>`Error in concat${n}D: Shape of tensors[${r}] (${e}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`))}))}function Qf(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}var em;function tm(e,t,n){let s=new Array;if(null==n&&null==t)return s;if(null==t)for(;s.length<e+n.length;)s.push(-1);else s=t.slice();if(null==n)return s;if(e+n.length!==s.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${s.length}`);for(let r=1;r<n.length;++r){const a=n[r],i=s[s.length-n.length+r],o=s[i];if(a>=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${a} but shape[${r+e}] = ${o}`)}else s[i]=a}return s}function nm(e){const t={FIRST_DIM_SIZE:em.FIRST_DIM_SIZE,VALUE_ROWIDS:em.VALUE_ROWIDS,ROW_LENGTHS:em.ROW_LENGTHS,ROW_SPLITS:em.ROW_SPLITS,ROW_LIMITS:em.ROW_LIMITS,ROW_STARTS:em.ROW_STARTS},n=[];for(const s of e){if(!(s in t))break;n.push(t[s])}return n}function sm(e){return 0===e.length?0:e[0]===em.FIRST_DIM_SIZE?e.length-1:e.length}function rm(e,t){if(null==e||null==t)return;const n=e.length,s=t.length;if(n>=s)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 = ${s})`);for(let r=0;r<Math.min(n,s-1);++r){const n=e[r],s=t[r+1];if(n>=0&&s>=0&&1!==n&&n!==s)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${n} but ragged tensor input.flatValues.shape[${r-e.length}] = ${s}`)}}!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"}(em||(em={}));const am=30;function im(e){return e<=am?e:De(e,Math.floor(Math.sqrt(e)))}function om(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function lm(e,t,n,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);const n=t.length;for(let s=0;s<n;++s)r=r.concat([e[s+1]/t[s],t[s]]);r=r.concat(e.slice(n+1))}return r}function um(e,t,n=!0){const s=[];if(n){s.push(t);for(let n=t+1;n<e;++n)n<=2*t?(s.push(n),s.push(n-(t+1))):s.push(n)}else{const n=[],r=[];for(let s=1;s<e;++s)s>=2*t+1||s%2==1?r.push(s):n.push(s);s.push(...n),s.push(0),s.push(...r)}return s}function cm(e,t,n,s=!0){const r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?s?r.push(t[n-1]*e[n]):r.push(e[n]/t[n-1]):r.push(e[n]);return r}function hm(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function dm(e,t,n){const s=e.slice(0,1);for(let r=0;r<n;++r)s.push(e[r+1]-t[r][0]-t[r][1]);return s}const pm=1.7580993408473768,fm=1.0507009873554805,mm=.3275911,gm=.254829592,ym=-.284496736,bm=1.421413741,xm=-1.453152027,wm=1.061405429;function vm(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}.`);const n=new Float32Array(2*e.length);for(let s=0;s<n.length;s+=2)n[s]=e[s/2],n[s+1]=t[s/2];return n}function km(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let s=0;s<e.length;s+=2)t[s/2]=e[s],n[s/2]=e[s+1];return{real:t,imag:n}}function Im(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],s[Math.floor(t/4)]=e[t+1];return{real:n,imag:s}}function Nm(e){const t=Math.floor(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],s[Math.floor(t/4)]=e[t+1];return{real:n,imag:s}}function Sm(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Tm(e,t,n,s){e[2*s]=t,e[2*s+1]=n}function Cm(e,t){const n=new Float32Array(e/2),s=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){const a=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(a),s[r]=Math.sin(a)}return{real:n,imag:s}}function $m(e,t,n){const s=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(s),imag:Math.sin(s)}}const Em="->",Rm=/->/g,Am=",",_m="...";function Fm(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Rm,"").length)/Em.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 ("${Em}").`);const[s,r]=e.split(Em);ie(-1===s.indexOf(_m),(()=>`The ellipsis notation ("${_m}") is not supported yet.`));const a=s.split(Am),i=a.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.");const o=[];for(let e=0;e<r.length;++e){const t=r[e];if(!a.some((e=>-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===o.indexOf(t)&&o.push(t)}for(let e=0;e<s.length;++e){const t=s[e];-1===o.indexOf(t)&&t!==Am&&o.push(t)}const l=new Array(a.length);for(let e=0;e<i;++e){if(new Set(a[e].split("")).size!==a[e].length)throw new Error(`Found duplicate axes in input component ${a[e]}. Support for duplicate axes in input is not implemented yet.`);l[e]=[];for(let t=0;t<a[e].length;++t)l[e].push(o.indexOf(a[e][t]))}const u=o.length,c=[];for(let e=r.length;e<u;++e)c.push(e);return{allDims:o,summedDims:c,idDims:l}}function Dm(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const s=[];for(let t=0;t<e;++t)-1===n[t]&&s.push(t);return n=n.filter((e=>-1!==e)),{permutationIndices:n,expandDims:s}}function Om(e,t,n){const s=new Array(e);for(let e=0;e<n.length;++e){const r=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===s[t[e][n]]?s[t[e][n]]=r[n]:ie(s[t[e][n]]===r[n],(()=>`Expected dimension ${s[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(r)}, but got dimension ${r[n]}`))}}function Mm(e,t){const n=e,s=[];let r=0;0===e.length&&n.push(-1),r=e.length+1;for(let e=0;e<r;++e)s.push([]);const a=[];for(let e=0;e<n.length;++e){const r=zm(t,n[e]);for(const t of r)-1===a.indexOf(t)&&(s[e].push(t),a.push(t))}return{path:n,steps:s}}function Lm(e){return e.every(((e,t)=>e===t))}function zm(e,t){const n=[];for(let s=0;s<e.length;++s)0!==e[s].length&&-1===e[s].indexOf(t)&&-1!==t||n.push(s);return n}function Pm(e,t,n=0){let s=[];if("number"==typeof t)ie(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),s=new Array(t).fill(e.shape[n]/t);else{const r=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);ie(r<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const s=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-s}ie(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),s=t}return s}function Bm(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Wm(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Vm(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Um(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Gm(e,t){return`size ${e} must be non-negative, not ${t}`}function Hm(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function jm(e,t){return`Input to reshape is a SparseTensor with ${ue(e)}\n dense values, but the requested shape requires a multiple of ${ue(t)}. inputShape=${e} outputShape= ${t}`}function qm(e,t){return`Input to reshape is a tensor with ${ue(e)} dense values, but the requested shape has ${ue(t)}. inputShape=${e} outputShape=${t}`}function Km(){return"segment ids must be >= 0"}function Xm(){return"segment ids are not increasing"}function Ym(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Zm(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Jm(e,t){let n,s=!1;for(e<=am?(n=e,s=!0):n=De(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=De(e,n+1);return n}function Qm(e,t,n){const s=[],r=e.length;for(let a=0;a<r;a++)a!==t?s.push(e[a]):s.push(n);return s}function eg(e,t,n,s){const r=t.shape.length,a=e.shape.length;if(0!==s&&(s<-r||s>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) (\n ${a}).`);if(n<s)throw new Error(`batchDims (${s}) must be less than or equal to axis (${n}).`);for(let n=0;n<s;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const i=e.shape[n],o=[];let l=1,u=1,c=1;for(let t=0;t<s;++t)o.push(e.shape[t]),l*=e.shape[t];for(let t=s;t<n;t++)o.push(e.shape[t]),u*=e.shape[t];for(let e=s;e<r;e++)o.push(t.shape[e]);for(let t=n+1;t<a;t++)o.push(e.shape[t]),c*=e.shape[t];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:i,outputShape:o}}function tg(e){try{return e.map((e=>Jr(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function ng(e){return e.map((e=>Zr(e)))}!function(){for(const e of fl)Yo(e)}();const sg={kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,op($o(n,"float32"),-1))}}},rg={kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Mo($o(n,"float32")),s=Oo(sl(Ho(1),t));return zl(Fo(e,s))}}}},ag={kernelName:nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Oo(sl(Mo($o(n,"float32")),1));return Fo(e,t)}}}},ig={kernelName:st,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{let t=e;const s=ol(n.shape,r);return s.length>0&&(t=ph(t,s)),cc(t,n.shape)},b:()=>{let t=e;const n=ol(s.shape,r);return n.length>0&&(t=ph(t,n)),cc(t,s.shape)}}}},og={kernelName:rt,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,s)=>{n[s]=()=>e.clone()})),n}},lg={kernelName:ot,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Lo(n)}}},ug={kernelName:lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Lo(n)}}},cg={kernelName:ut,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,Oo(sl(Ho(1),Mo($o(n,"float32")))))}}},hg={kernelName:ct,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Oo(Ao(Ho(1),Mo($o(n,"float32"))));return Fo(e,t)}}}},dg={kernelName:pt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{const t=Ao(Mo(n),Mo(s));let a=Do(e,Fo(s,t));const i=ol(n.shape,r);return i.length>0&&(a=ph(a,i)),cc(a,n.shape)},b:()=>{const t=Ao(Mo(n),Mo(s));let a=zl(Do(e,Fo(n,t)));const i=ol(s.shape,r);return i.length>0&&(a=ph(a,i)),cc(a,s.shape)}}}},pg={kernelName:ht,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,Ao(Mo($o(n,"float32")),1))}}},fg={kernelName:dt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,sl(Ho(1),Mo($o(n,"float32"))))}}};const mg=Za({avgPool3dGrad_:function(e,t,n,s,r,a){const i=Ka(e,"dy","avgPool3dGrad"),o=Ka(t,"input","avgPool3dGrad");let l=i,u=o,c=!1;4===o.rank&&(c=!0,l=cc(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=cc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),ie(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),ie(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),uc("avgPool3dGrad",r,a);const h={dy:l,input:u},d={filterSize:n,strides:s,pad:r,dimRoundingMode:a},p=za.runKernel(yt,h,d);return c?cc(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),gg={kernelName:gt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>mg(e,s,r,a,i,o)}}};const yg=Za({avgPoolGrad_:function(e,t,n,s,r){const a=Ka(e,"dy","avgPoolGrad"),i=Ka(t,"input","avgPoolGrad");ie(i.rank===a.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`));let o=i,l=a,u=!1;3===i.rank&&(u=!0,o=cc(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=cc(a,[1,a.shape[0],a.shape[1],a.shape[2]])),ie(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),ie(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const c={dy:l,input:o},h={filterSize:n,strides:s,pad:r},d=za.runKernel(mt,c,h);return u?cc(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),bg={kernelName:ft,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i}=n;return{x:()=>yg(e,s,r,a,i)}}},xg={kernelName:bt,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,r]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>Ol(e,r,!1,!1),b:()=>Ol(e,s,!0,!1)}:a&&!i?{a:()=>Ol(r,e,!1,!0),b:()=>Ol(s,e,!1,!1)}:{a:()=>Ol(r,e,!0,!0),b:()=>Ol(e,s,!0,!0)}:{a:()=>Ol(e,r,!1,!0),b:()=>Ol(s,e,!0,!1)}}},wg={kernelName:xt,gradFunc:(e,t,n)=>{const{blockShape:s,crops:r}=n;return{x:()=>fd(e,s,r)}}},vg={kernelName:kt,gradFunc:(e,t,n)=>{const s=n,r=s.inputShape,a=s.shape,i=Array.from(a);for(let e=r.length-1;e>=0;e--)if(r[e]===a[e])i[e]=1;else if(1!==r[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e<i.length;e++)i[e]>1&&o.push(e);return{x:()=>ph(e,o,!0)}}},kg={kernelName:Nt,gradFunc:e=>({x:()=>e.clone()})},Ig={kernelName:St,gradFunc:e=>({x:()=>Lo(e)})},Ng={kernelName:Tt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Yc(Bh(Sh(s,r),Ah(s,a)),e,Lo(e))}}},Sg={kernelName:$t,inputsToSave:["x"],gradFunc:sg.gradFunc},Tg={kernelName:Et,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map((e=>e.shape)),{axis:r}=n,a=we(r,t[0].shape)[0],i=s.map((e=>e[a]));return np(e,i,a).map((e=>()=>e))}},Cg={kernelName:Rt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{dilations:a,strides:i,pad:o,dataFormat:l}=n;return ie(ac(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>Oc(s.shape,e,r,i,o,l),filter:()=>Dp(s,e,r.shape,i,o,l)}}},$g={kernelName:_t,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Fc(e,r,a,i,o,1,l),filter:()=>Dp(e,s,r.shape,a,i,o,l)}}};const Eg=Za({conv3DBackpropFilter_:function(e,t,n,s,r){let a=e;4===e.rank&&(a=cc(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=cc(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),ie(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),ie(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),ie(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),ie(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),ie(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:a,dy:i},l={strides:s,pad:r,filterShape:n};return za.runKernel(Dt,o,l)}}),Rg={kernelName:Ft,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a}=n;ie(ac(s),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const[i,o]=t;return{x:()=>zc(i.shape,e,o,r,a),filter:()=>Eg(i,e,o.shape,r,a)}}},Ag={kernelName:Mt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(zl(jd($o(n,"float32"))),e)}}},_g={kernelName:Lt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(qd($o(n,"float32")),e)}}},Fg={kernelName:Pt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r,exclusive:a,reverse:i}=n;return{x:()=>{const t=lh([r],s.rank);let n=Uc(e,r,a,!i);return null!=t&&(n=Bl(n,t)),n}}}},Dg={kernelName:Ut,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a,dimRoundingMode:i}=n,o=null==s?[1,1]:s;ie(ac(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=t;return ie(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),ie(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),ie(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]}.`)),ie(ic(r,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`)),uc("depthwiseConv2d",a,i),{x:()=>Wp(l.shape,e,u,r,a,o,i),filter:()=>Bp(l,e,u.shape,r,a,o,i)}}},Og={kernelName:qt,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,a={x:s,filter:r,dy:e},i={x:s,filter:r,dy:e};return{x:()=>za.runKernel(Kt,a,n),filter:()=>za.runKernel(Xt,i,n)}}},Mg={kernelName:Qt,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s={dy:e,y:n};return{x:()=>za.runKernel(en,s)}}},Lg={kernelName:tn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Do(yh(zl(Mo(n))),2/Math.sqrt(Math.PI));return{x:()=>Do(e,s)}}},zg={kernelName:sn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,n)}}},Pg={kernelName:rn,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>cc(e,n.shape)}}},Bg={kernelName:an,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,yh(n))}}},Wg={kernelName:cn,gradFunc:e=>({x:()=>Lo(e)})},Vg={kernelName:hn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{const t=Fo(e,$o(s,"float32")),a=ol(n.shape,r);return a.length>0?cc(ph(t,a),n.shape):t},b:()=>{let t=Do(e,$o(n,"float32"));const a=ol(s.shape,r);a.length>0&&(t=cc(ph(t,a),s.shape));const i=Mo(s);return zl(Fo(t,$o(i,"float32")))}}}},Ug={kernelName:dn,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[r,a,i,o]=t,l=null==o?Ho(1):o,u=ol(a.shape,r.shape),c=[];if(1===a.rank){for(let e=0;e<r.shape.length-1;++e)c.push(r.shape[e]);c.push(1)}const h=sl(r,a),d=Do(e,l),p=Wd(Ao(i,Ho(s))),f=Do(Do(Do(p,p),p),Ho(-.5));return{x:()=>1===a.rank?cc(Do(Do(e,wh(cc(p,[1,1,1,a.shape[0]]),c)),l),r.shape):cc(Do(Do(e,p),l),r.shape),mean:()=>{let e=Do(Do(p,Ho(-1)),d);return 1===a.rank&&(e=ph(e,u)),cc(e,a.shape)},variance:()=>{let e=Do(Do(f,h),d);return 1===a.rank&&(e=ph(e,u)),cc(e,a.shape)},scale:()=>{const t=Do(h,p);let n=Do(e,t);return 1===a.rank&&(n=ph(n,u)),cc(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=ph(t,u)),cc(t,a.shape)}}}},Gg={kernelName:pn,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,r]=t,{axis:a,batchDims:i}=n,o=we(a,s.shape)[0],l=(e,t,n)=>()=>{const s=e.shape,r=t.size,i=s.slice(0,o),l=i.length,u=s.slice(a,s.length).slice(1),c=u.length,h=Hg(0,l),d=Hg(l+1,l+1+c),p=jg([i,[r],u]),f=cc(n,p),m=cc(t,[r]),g=jg([[l],h,d]),y=Bl(f,g);let b=xp(y,m,e.shape[o]);const x=uh(g);return b=Bl(b,x),b};if(1===i){const t=s.shape[0],n=s.split(t,0);return{x:()=>{const t=ip(n.map(((t,n)=>l(t,r.slice(n,1),e.slice(n,1))())));return t.reshape(s.shape)},indices:()=>r}}return{x:l(s,r,e),indices:()=>r}}};function Hg(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function jg(e){const t=[];for(let n=0;n<e.length;++n)for(let s=0;s<e[n].length;++s)t.push(e[n][s]);return t}const qg={kernelName:gn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Lo(n),b:()=>Lo(s)}}},Kg={kernelName:yn,gradFunc:e=>({x:()=>$o(e,"float32")})},Xg={kernelName:wn,gradFunc:e=>({x:()=>Lo(e)})},Yg={kernelName:vn,gradFunc:e=>({x:()=>Lo(e)})},Zg={kernelName:kn,gradFunc:e=>({x:()=>Lo(e)})},Jg={kernelName:In,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{alpha:r}=n,a=Nh(s,0);return{x:()=>Yc(a,e,Do(e,r))}}},Qg={kernelName:$n,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,Ao(n,1))}}},ey={kernelName:Cn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,$o(n,"float32"))}}},ty={kernelName:Fn,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;return{logits:()=>{const t=yh(s);return sl(e,Do(ph(e,r,!0),t))}}}};const ny=Za({localResponseNormalizationBackprop_:function(e,t,n,s=5,r=1,a=1,i=.5){const o={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:i};return za.runKernel(Mn,o,l)}}),sy={kernelName:On,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{depthRadius:a,bias:i,alpha:o,beta:l}=n;return{x:()=>ny(s,r,e,a,i,o,l)}}};function ry(e,t,n,s){return t.rank<n.rank&&(t=cc(t,ih(t.shape,s))),e.rank<n.rank&&(e=cc(e,ih(e.shape,s))),{x:()=>Do(e,$o(Xc(n,t),e.dtype))}}const ay={kernelName:zn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:r}=s,a=t[0],i=ry(e,t[1],a,we(r,a.shape));return{x:()=>i.x()}}},iy={kernelName:Pn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Do(e,$o(Sh(n,s),"float32")),b:()=>Do(e,$o(Rh(n,s),"float32"))}}};const oy=Za({maxPool3dGrad_:function(e,t,n,s,r,a,i){const o=Ka(e,"dy","maxPool3dGrad"),l=Ka(t,"input","maxPool3dGrad"),u=Ka(n,"output","maxPool3dGrad");let c=o,h=l,d=u,p=!1;4===l.rank&&(p=!0,c=cc(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=cc(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=cc(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),ie(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),ie(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),ie(5===d.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`)),uc("maxPool3dGrad",a,i);const f={dy:c,input:h,output:d},m={filterSize:s,strides:r,pad:a,dimRoundingMode:i},g=za.runKernel(Un,f,m);return p?cc(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),ly={kernelName:Vn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>oy(e,s,r,a,i,o,l)}}};const uy=Za({maxPoolGrad_:function(e,t,n,s,r,a,i){const o=Ka(e,"dy","maxPoolGrad"),l=Ka(t,"input","maxPoolGrad"),u=Ka(n,"output","maxPoolGrad");ie(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),ie(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),ie(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),uc("maxPoolGrad",a,i);const c={dy:o,input:l,output:u},h={filterSize:s,strides:r,pad:a,dimRoundingMode:i};return za.runKernel(Wn,c,h)}}),cy={kernelName:Bn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>uy(e,s,r,a,i,o)}}},hy={kernelName:Kn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>mc(e,a,s.shape)}}},dy={kernelName:is,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>mc(e,a,s.shape)}}},py={kernelName:ls,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,r]=t,a=n,i=s,o=ll(a.shape,i.shape);return{a:()=>{const t=$o(i,"float32");let n=Do(e,Do(t,nl(a,sl(t,Ho(1)))));const s=ol(a.shape,o);return s.length>0&&(n=ph(n,s)),cc(n,a.shape)},b:()=>{const t=Nh(a,0),n=Yc(t,Dh(a),Lo(a));let s=Do(e,Do(r,n));const l=ol(i.shape,o);return l.length>0&&(s=ph(s,l)),cc(s,i.shape)}}}};function fy(e,t,n){const s=e.shape.length,r=s-n.length,a=lh(n,s);let i=e;null!=a&&(i=Bl(e,a));const o=i.shape.slice(),l=o.splice(s-n.length,n.length).reduce(((e,t)=>e*t),1);o.push(l);let u=function(e,t,n){const s=e.shape.slice();s[n]=1;const r=cc(t,s),a=Vc(e,n,!0,!1),i=Vc(e,n,!0,!0),o=Do(a,i);return Do(r,o)}(i.reshape(o),t,r);if(u=u.reshape(i.shape),null!=a){const e=uh(a);u=Bl(u,e)}return u}const my={kernelName:As,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Nh(n,Ho(0)),s=Ho(pm),r=Ho(fm),a=Do(e,r),i=Do(Do(e,s),yh($o(n,"float32")));return Yc(t,a,i)}}}},gy={kernelName:Bs,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:r}=n;return{x:()=>bc(e,s,r)}}},yy={kernelName:Ws,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>pc(e,s)}}};const by=[sg,rg,ag,ig,og,lg,ug,cg,hg,dg,pg,fg,gg,bg,xg,wg,vg,kg,Ig,Ng,Sg,Tg,$g,Cg,Rg,Ag,_g,Fg,Dg,Og,{kernelName:Zt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{const t=Fo(e,$o(s,"float32")),a=ol(n.shape,r);return a.length>0?cc(ph(t,a),n.shape):t},b:()=>{let t=Do(e,$o(n,"float32"));const a=ol(s.shape,r);a.length>0&&(t=cc(ph(t,a),s.shape));const i=Mo(s);return zl(Fo(t,$o(i,"float32")))}}}},Mg,Lg,zg,Pg,Bg,Vg,Wg,Ug,Gg,qg,Kg,Xg,Yg,Zg,Jg,Qg,ey,ty,sy,ay,ay,iy,ly,cy,{kernelName:Hn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n,a=we(r,s.shape),i=ue(ah(s.shape,a)[1]);return{x:()=>{const t=s.shape.slice();a.forEach((e=>{t[e]=1}));const n=cc(e,t);return Fo(Do(n,Jh(s.shape,"float32")),i)}}}},{kernelName:jn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:r}=s,[a,i]=t,o=ry(e,i,a,we(r,a.shape));return{x:()=>o.x()}}},{kernelName:qn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Do(e,$o(Ah(n,s),"float32")),b:()=>Do(e,$o(Nh(n,s),"float32"))}}},hy,{kernelName:Xn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{const t=ol(n.shape,r);return t.length>0?cc(ph(e,t),n.shape):e},b:()=>{const t=Do(e,zl(kh(Fo(n,s)))),a=ol(s.shape,r);return a.length>0?cc(ph(t,a),s.shape):t}}}},{kernelName:Zn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{const t=Do(e,$o(s,"float32")),a=ol(n.shape,r);return a.length>0?cc(ph(t,a),n.shape):t},b:()=>{const t=Do(e,$o(n,"float32")),a=ol(s.shape,r);return a.length>0?cc(ph(t,a),s.shape):t}}}},{kernelName:Jn,gradFunc:e=>({x:()=>zl(e)})},{kernelName:rs,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Zh(n.shape,"float32")}}},{kernelName:ss,gradFunc:e=>({x:()=>Lo(e)})},{kernelName:as,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:s}=n;return wp(e,s).map((e=>()=>e))}},dy,dy,py,{kernelName:us,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,r=Nh(n,0);return{x:()=>Yc(r,e,Do(e,s)),alpha:()=>{let t=Yc(r,Lo(e),Do(e,n));const a=ol(s.shape,e.shape);return a.length>0&&(t=ph(t,a)),cc(t,s.shape)}}}},{kernelName:cs,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;let a=[];return a=null==r?s.shape.map(((e,t)=>t)):"number"==typeof r?[r]:r,{x:()=>fy(s,e,a)}}},{kernelName:gs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,zl(Mo(n)))}}},{kernelName:Is,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Do(Ah(n,6),op(n));return{x:()=>Do(e,$o(s,"float32"))}}},{kernelName:ys,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,$o(op(n),"float32"))}}},{kernelName:bs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>cc(e,n.shape)}}},{kernelName:vs,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>za.runKernel(ks,r,n)}}},{kernelName:xs,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>za.runKernel(ws,r,n)}}},{kernelName:Ns,gradFunc:(e,t,n)=>{const{dims:s}=n,r=we(s,e.shape);return{x:()=>Od(e,r)}}},{kernelName:Ss,gradFunc:e=>({x:()=>Lo(e)})},{kernelName:Ts,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zl(Fo(e,Do(nl(n,1.5),2)))}}},{kernelName:Rs,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>$o(Lo(n),"float32"),t:()=>Do(e,$o(n,e.dtype)),e:()=>Do(e,$o(Wh(n),e.dtype))}}},my,{kernelName:Ms,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,Do(n,sl(Ho(1),n)))}}},{kernelName:Os,gradFunc:e=>({x:()=>Lo(e)})},{kernelName:Fs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(Bc($o(n,"float32")),e)}}},{kernelName:Ds,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(Wc($o(n,"float32")),e)}}},{kernelName:_s,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:r,size:a}=n,i=s.shape,[o,l]=bu(s,r,a),u=[];for(let t=0;t<e.rank;t++)u.push([o[t],i[t]-o[t]-l[t]]);return{x:()=>ud(e,u)}}},{kernelName:Vs,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:r}=n,a=Do(e,s);return{logits:()=>sl(a,Do(ph(a,[r],true),s))}}},{kernelName:Ls,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,fc(n))}}},gy,gy,yy,yy,{kernelName:zs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,Do(Oo($o(n,"float32")),2))}}},{kernelName:Ks,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Ho(2);return{a:()=>Do(e,Do(r,sl(n,s))),b:()=>Do(e,Do(r,sl(s,n)))}}},{kernelName:Xs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(e,Do($o(n,"float32"),2))}}},{kernelName:pr,gradFunc:e=>({x:()=>Lo(e)})},{kernelName:tr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=ll(n.shape,s.shape);return{a:()=>{let t=e;const s=ol(n.shape,r);return s.length>0&&(t=ph(t,s)),cc(t,n.shape)},b:()=>{let t=e;const n=ol(s.shape,r);return n.length>0&&(t=ph(t,n)),cc(zl(t),s.shape)}}}},{kernelName:Ps,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,r=s.shape.slice(),{axis:a}=n;we(a,s.shape).forEach((e=>{r[e]=1}));const i=cc(e,r),o=Do(i,Jh(s.shape,"float32"));return{x:()=>o}}},{kernelName:nr,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Fo(e,Mo(Bc(n)))}}},{kernelName:sr,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Do(sl(Ho(1),Mo(n)),e)}}},{kernelName:rr,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:r}=n;return{x:()=>{let t=Lo(s);if(1===s.rank)for(let n=0;n<r[0];++n)t=Ao(t,mc(e,[n*s.shape[0]],[s.shape[0]]));else if(2===s.rank)for(let n=0;n<r[0];++n)for(let a=0;a<r[1];++a)t=Ao(t,mc(e,[n*s.shape[0],a*s.shape[1]],[s.shape[0],s.shape[1]]));else if(3===s.rank)for(let n=0;n<r[0];++n)for(let a=0;a<r[1];++a)for(let i=0;i<r[2];++i)t=Ao(t,mc(e,[n*s.shape[0],a*s.shape[1],i*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else{if(4!==s.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);for(let n=0;n<r[0];++n)for(let a=0;a<r[1];++a)for(let i=0;i<r[2];++i)for(let o=0;o<r[3];++o)t=Ao(t,mc(e,[n*s.shape[0],a*s.shape[1],i*s.shape[2],o*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]))}return t}}}},{kernelName:or,gradFunc:(e,t,n)=>{const s=n,{perm:r}=s,a=uh(r);return{x:()=>Bl(e,a)}}},{kernelName:ur,gradFunc:(e,t,n)=>{const s=n,{axis:r}=s;return{value:()=>ip(e,r)}}},{kernelName:cr,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=ul(t,Lo(t)),s=Ih(e,n);let r=Sh(t,Ho(0,"int32"));const a=s.rank-r.rank;for(let e=0;e<a;++e)r=bh(r,e+1);r=Bh(r,Jh(s.shape,"bool"));const i=Lo(s);return Yc(r,s,i)}(e,n)}}},{kernelName:dr,gradFunc:e=>({x:()=>Lo(e)})}];for(const e of by)Cr(e);ya().prototype.abs=function(){return this.throwIfDisposed(),al(this)},ya().prototype.acos=function(){return this.throwIfDisposed(),Lu(this)},ya().prototype.acosh=function(){return this.throwIfDisposed(),zu(this)},ya().prototype.add=function(e){return this.throwIfDisposed(),Ao(this,e)},ya().prototype.all=function(e,t){return this.throwIfDisposed(),Bu(this,e,t)},ya().prototype.any=function(e,t){return this.throwIfDisposed(),Wu(this,e,t)},ya().prototype.argMax=function(e){return this.throwIfDisposed(),Vu(this,e)},ya().prototype.argMin=function(e){return this.throwIfDisposed(),Uu(this,e)},ya().prototype.asScalar=function(){return this.throwIfDisposed(),ie(1===this.size,(()=>"The array must have only 1 element.")),cc(this,[])},ya().prototype.asType=function(e){return this.throwIfDisposed(),$o(this,e)},ya().prototype.as1D=function(){return this.throwIfDisposed(),cc(this,[this.size])},ya().prototype.as2D=function(e,t){return this.throwIfDisposed(),cc(this,[e,t])},ya().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),cc(this,[e,t,n])},ya().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),cc(this,[e,t,n,s])},ya().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),cc(this,[e,t,n,s,r])},ya().prototype.asin=function(){return this.throwIfDisposed(),Gu(this)},ya().prototype.asinh=function(){return this.throwIfDisposed(),Hu(this)},ya().prototype.atan=function(){return this.throwIfDisposed(),ju(this)},ya().prototype.atan2=function(e){return this.throwIfDisposed(),qu(this,e)},ya().prototype.atanh=function(){return this.throwIfDisposed(),Ku(this)},ya().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),hc(this,e,t,n,s)},ya().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),bc(this,e,t)},ya().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),xc(this,e,t,n,s,r)},ya().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Tc(this,e)},ya().prototype.cast=function(e){return this.throwIfDisposed(),$o(this,e)},ya().prototype.ceil=function(){return this.throwIfDisposed(),Cc(this)},ya().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),$c(this,e,t)},ya().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof ga&&(e=[e]),pc([this,...e],t)},ya().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Dc(this,e,t,n,s,r,a)},ya().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),Mc(this,e,t,n,s,r)},ya().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Fc(this,e,t,n,s,r,a)},ya().prototype.cos=function(){return this.throwIfDisposed(),Bc(this)},ya().prototype.cosh=function(){return this.throwIfDisposed(),Wc(this)},ya().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Vc(this,e,t,n)},ya().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Uc(this,e,t,n)},ya().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Hc(this,e,t)},ya().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),jc(this,e,t,n,s,r,a)},ya().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),Kc(this,e,t,n,s,r)},ya().prototype.divNoNan=function(e){return this.throwIfDisposed(),Zc(this,e)},ya().prototype.div=function(e){return this.throwIfDisposed(),Fo(this,e)},ya().prototype.dot=function(e){return this.throwIfDisposed(),Jc(this,e)},ya().prototype.elu=function(){return this.throwIfDisposed(),eh(this)},ya().prototype.equal=function(e){return this.throwIfDisposed(),Xc(this,e)},ya().prototype.erf=function(){return this.throwIfDisposed(),nh(this)},ya().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),gh(this,e,t)},ya().prototype.exp=function(){return this.throwIfDisposed(),yh(this)},ya().prototype.expandDims=function(e){return this.throwIfDisposed(),bh(this,e)},ya().prototype.expm1=function(){return this.throwIfDisposed(),xh(this)},ya().prototype.fft=function(){return this.throwIfDisposed(),Qd(this)},ya().prototype.flatten=function(){return this.throwIfDisposed(),cc(this,[this.size])},ya().prototype.floor=function(){return this.throwIfDisposed(),kh(this)},ya().prototype.floorDiv=function(e){return this.throwIfDisposed(),_o(this,e)},ya().prototype.gather=function(e,t,n){return this.throwIfDisposed(),Ih(this,e,t,n)},ya().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Sh(this,e)},ya().prototype.greater=function(e){return this.throwIfDisposed(),Nh(this,e)},ya().prototype.ifft=function(){return this.throwIfDisposed(),ep(this)},ya().prototype.irfft=function(){return this.throwIfDisposed(),tp(this)},ya().prototype.isFinite=function(){return this.throwIfDisposed(),Th(this)},ya().prototype.isInf=function(){return this.throwIfDisposed(),Ch(this)},ya().prototype.isNaN=function(){return this.throwIfDisposed(),$h(this)},ya().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Eh(this,e)},ya().prototype.lessEqual=function(e){return this.throwIfDisposed(),Ah(this,e)},ya().prototype.less=function(e){return this.throwIfDisposed(),Rh(this,e)},ya().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),Fh(this,e,t,n,s)},ya().prototype.logSigmoid=function(){return this.throwIfDisposed(),Lh(this)},ya().prototype.logSoftmax=function(e){return this.throwIfDisposed(),zh(this,e)},ya().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Ph(this,e,t)},ya().prototype.log=function(){return this.throwIfDisposed(),Dh(this)},ya().prototype.log1p=function(){return this.throwIfDisposed(),Oh(this)},ya().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Bh(this,e)},ya().prototype.logicalNot=function(){return this.throwIfDisposed(),Wh(this)},ya().prototype.logicalOr=function(e){return this.throwIfDisposed(),Vh(this,e)},ya().prototype.logicalXor=function(e){return this.throwIfDisposed(),Uh(this,e)},ya().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Ol(this,e,t,n)},ya().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),qh(this,e,t,n,s)},ya().prototype.max=function(e,t){return this.throwIfDisposed(),hh(this,e,t)},ya().prototype.maximum=function(e){return this.throwIfDisposed(),ul(this,e)},ya().prototype.mean=function(e,t){return this.throwIfDisposed(),Yh(this,e,t)},ya().prototype.min=function(e,t){return this.throwIfDisposed(),dh(this,e,t)},ya().prototype.minimum=function(e){return this.throwIfDisposed(),ed(this,e)},ya().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),td(this,e,t)},ya().prototype.mod=function(e){return this.throwIfDisposed(),nd(this,e)},ya().prototype.mul=function(e){return this.throwIfDisposed(),Do(this,e)},ya().prototype.neg=function(){return this.throwIfDisposed(),zl(this)},ya().prototype.norm=function(e,t,n){return this.throwIfDisposed(),mh(this,e,t,n)},ya().prototype.notEqual=function(e){return this.throwIfDisposed(),id(this,e)},ya().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Ml(this,e,t,n)},ya().prototype.onesLike=function(){return this.throwIfDisposed(),od(this)},ya().prototype.pad=function(e,t){return this.throwIfDisposed(),ud(this,e,t)},ya().prototype.pool=function(e,t,n,s,r,a){return this.throwIfDisposed(),md(this,e,t,n,s,r,a)},ya().prototype.pow=function(e){return this.throwIfDisposed(),nl(this,e)},ya().prototype.prelu=function(e){return this.throwIfDisposed(),gd(this,e)},ya().prototype.prod=function(e,t){return this.throwIfDisposed(),yd(this,e,t)},ya().prototype.reciprocal=function(){return this.throwIfDisposed(),_d(this)},ya().prototype.relu=function(){return this.throwIfDisposed(),Fd(this)},ya().prototype.relu6=function(){return this.throwIfDisposed(),Dd(this)},ya().prototype.reshapeAs=function(e){return this.throwIfDisposed(),cc(this,e.shape)},ya().prototype.reshape=function(e){return this.throwIfDisposed(),cc(this,e)},ya().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),gf(this,e,t,n)},ya().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),yf(this,e,t,n)},ya().prototype.reverse=function(e){return this.throwIfDisposed(),Od(this,e)},ya().prototype.rfft=function(){return this.throwIfDisposed(),sp(this)},ya().prototype.round=function(){return this.throwIfDisposed(),Bd(this)},ya().prototype.rsqrt=function(){return this.throwIfDisposed(),Wd(this)},ya().prototype.selu=function(){return this.throwIfDisposed(),Vd(this)},ya().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Ud(this,e,t,n,s,r,a)},ya().prototype.sigmoid=function(){return this.throwIfDisposed(),fc(this)},ya().prototype.sign=function(){return this.throwIfDisposed(),Hd(this)},ya().prototype.sin=function(){return this.throwIfDisposed(),jd(this)},ya().prototype.sinh=function(){return this.throwIfDisposed(),qd(this)},ya().prototype.slice=function(e,t){return this.throwIfDisposed(),mc(this,e,t)},ya().prototype.softmax=function(e){return this.throwIfDisposed(),Jd(this,e)},ya().prototype.softplus=function(){return this.throwIfDisposed(),Mh(this)},ya().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),fd(this,e,t)},ya().prototype.split=function(e,t){return this.throwIfDisposed(),np(this,e,t)},ya().prototype.sqrt=function(){return this.throwIfDisposed(),Oo(this)},ya().prototype.square=function(){return this.throwIfDisposed(),Mo(this)},ya().prototype.squaredDifference=function(e){return this.throwIfDisposed(),rp(this,e)},ya().prototype.squeeze=function(e){return this.throwIfDisposed(),ap(this,e)},ya().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof ga?[this,e]:[this,...e];return ip(n,t)},ya().prototype.step=function(e){return this.throwIfDisposed(),op(this,e)},ya().prototype.stridedSlice=function(e,t,n,s,r,a,i,o){return this.throwIfDisposed(),lp(this,e,t,n,s,r,a,i,o)},ya().prototype.sub=function(e){return this.throwIfDisposed(),sl(this,e)},ya().prototype.sum=function(e,t){return this.throwIfDisposed(),ph(this,e,t)},ya().prototype.tan=function(){return this.throwIfDisposed(),up(this)},ya().prototype.tanh=function(){return this.throwIfDisposed(),gc(this)},ya().prototype.tile=function(e){return this.throwIfDisposed(),wh(this,e)},ya().prototype.toBool=function(){return this.throwIfDisposed(),$o(this,"bool")},ya().prototype.toFloat=function(){return this.throwIfDisposed(),$o(this,"float32")},ya().prototype.toInt=function(){return this.throwIfDisposed(),$o(this,"int32")},ya().prototype.topk=function(e,t){return this.throwIfDisposed(),gp(this,e,t)},ya().prototype.transpose=function(e){return this.throwIfDisposed(),Bl(this,e)},ya().prototype.unique=function(e){return this.throwIfDisposed(),bp(this,e)},ya().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),xp(this,e,t)},ya().prototype.unstack=function(e){return this.throwIfDisposed(),wp(this,e)},ya().prototype.where=function(e,t){return this.throwIfDisposed(),Yc(e,this,t)},ya().prototype.zerosLike=function(){return this.throwIfDisposed(),Lo(this)};class xy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,xy.prototype)}}class wy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,wy.prototype)}}class vy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,vy.prototype)}}class ky extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ky.prototype)}}class Iy extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Iy.prototype)}}Error;class Ny{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){const e=this.cache.keys().next().value;this.cache.delete(e)}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++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}function Sy(e,t){if(Array.isArray(e)){let n=[];for(let s=0;s<t;s++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Ty(e,t){if(!e)throw new Iy(t)}function Cy(e,t){let n=0;for(const s of e)s===t&&n++;return n}function $y(e){return 1===e.length?e[0]:e}function Ey(e){return Array.isArray(e)?e:[e]}function Ry(e){const 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 Ay(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let _y={};function Fy(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Dy(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>Dy(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?Dy(t):e[n]=t.value)}}}function Oy(e,t={},n={},s="object",r=!1){if("string"==typeof e){const r=e;let a;if(r in n)a=n[r];else if(r in _y)a=_y[r];else if(a=t[r],null==a)throw new vy(`Unknown ${s}: ${e}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}{const a=e;if(null==a.className||null==a.config)throw new vy(`${s}: Improper config format: ${JSON.stringify(a)}.\n'className' and 'config' must set.`);const i=a.className;let o,l;if(i in n?[o,l]=n[i]:i in _y?[o,l]=_y.className:i in t&&([o,l]=t[i]),null==o)throw new vy(`Unknown ${s}: ${i}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(_y))e[t]=_y[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},_y);for(const e of Object.keys(n))_y[e]=n[e];Dy(a.config);const s=l(o,a.config,n,r);return _y=Object.assign({},t),s}{const e=Object.assign({},_y);for(const e of Object.keys(n))_y[e]=n[e];const t=new o(a.config);return _y=Object.assign({},e),t}}}function My(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Ly(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function zy(e){if(null==e)throw new vy(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Py(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new vy(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function By(e,t,n=0,s=1/0){return Ty(n>=0),Ty(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every((e=>typeof e===t))}function Wy(e,t){Array.isArray(e)?(ie(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Wy(e,`element ${n+1} of ${t}`)))):ie(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${Vy(e)}.`))}function Vy(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>Vy(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function Uy(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let Gy=0;function Hy(){return Gy++}const jy={};function qy(e=""){return e in jy||(jy[e]=0),jy[e]+=1,e+jy[e].toString()}const Ky=["channelsFirst","channelsLast"],Xy=["nearest","bilinear"],Yy=["valid","same","causal"],Zy=["max","avg"],Jy=["sum","mul","concat","ave"],Qy=new Map;function eb(e){Py(Ky,"DataFormat",e)}function tb(e){Py(Yy,"PaddingMode",e)}function nb(e){Py(Zy,"PoolMode",e)}const sb=[],rb="/";function ab(e,t){sb.push(e);try{const e=t();return sb.pop(),e}catch(e){throw sb.pop(),e}}function ib(e){if(!ub(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===sb.length?"":sb.join(rb)+rb)+e}function ob(e){if(!ub(e))throw new Error("Not a valid tensor name: '"+e+"'");Qy.has(e)||Qy.set(e,0);const t=Qy.get(e);if(Qy.set(e,Qy.get(e)+1),t>0){const n=`${e}_${t}`;return Qy.set(n,1),n}return e}const lb=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function ub(e){return!!e.match(lb)}function cb(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let s=1;for(let r=t;r<n;++r)s*=e[r];return s}function hb(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const s=e[n];s<t&&(t=s)}return t}function db(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const s=e[n];s>t&&(t=s)}return t}function pb(e,t){if(t<e)throw new vy(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let fb;function mb(){return null==fb&&(fb=ki().epsilon()),fb}function gb(e,t){return $o(e,t)}function yb(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),cc(e,n)}function bb(e,t,n){return hi((()=>{switch(e.rank){case 1:return Kd(e,t,n);case 2:return Xd(e,[t,0],[n,e.shape[1]]);case 3:return Yd(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Zd(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return mc(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return mc(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 vy(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function xb(e,t,n){return hi((()=>{switch(e.rank){case 1:return Kd(e,t,n);case 2:return Xd(e,[0,t],[e.shape[0],n]);case 3:return Yd(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Zd(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new vy(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function wb(e,t,n,s){return hi((()=>{switch(e.rank){case 1:return Kd(e,t,n);case 2:switch(s){case 1:return bb(e,t,n);case 2:return xb(e,t,n);default:throw new vy(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return bb(e,t,n);case 2:return Yd(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return xb(e,t,n);default:throw new vy(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return bb(e,t,n);case 2:return Zd(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Zd(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return xb(e,t,n);default:throw new vy(`The axis is not within the rank of the tensor ${s}`)}default:throw new vy(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function vb(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),pc(e,t)}function kb(e,t){switch(e.rank){case 1:return Ec([e,t]);case 2:return Rc([e,t],0);case 3:return Ac([e,t],0);case 4:return _c([e,t],0);default:throw new vy(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ib(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new vy(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return wh(e,t)}function Nb(e,t=0,n=1,s,r){return Cd(e,t,n,s,r)}function Sb(e,t,n,s){if(e.rank<2||t.rank<2)throw new ky(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new ky(`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(2===e.rank&&2===t.rank){return Up({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?$b(e.rank,s,"channelsLast"):null,activation:n})}{const r=e.shape.slice(),a=r.pop();e=cc(e,[-1,a]);const i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=cc(Bl(t,c),[l,-1]);const h=[...r,...u];return cc(Up({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?$b(e.rank,s,"channelsLast"):null,activation:n}),h)}}function Tb(e,t,n){return hi((()=>(t=Array.isArray(t)?cp(t,"int32"):$o(t,"int32"),Ih(e,t,n))))}function Cb(e){return Do(e,e)}function $b(e,t,n){const s=t.shape;if(1!==t.rank&&t.rank!==e)throw new vy(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===s.length?cc(t,[1,s[0],1,1,1]):cc(t,[1,s[3],s[0],s[1],s[2]]);if("channelsLast"===n)return 1===s.length?cc(t,[1,1,1,1,s[0]]):cc(t,[1].concat(s))}else if(4===e){if("channelsFirst"===n)return 1===s.length?cc(t,[1,s[0],1,1]):cc(t,[1,s[2],s[0],s[1]]);if("channelsLast"===n)return 1===s.length?cc(t,[1,1,1,s[0]]):cc(t,[1].concat(s))}else if(3===e){if("channelsFirst"===n)return 1===s.length?cc(t,[1,s[0],1]):cc(t,[1,s[1],s[0]]);if("channelsLast"===n)return 1===s.length?cc(t,[1,1,s[0]]):cc(t,[1].concat(s))}else if(e<3)return t;throw new vy(`Unsupported input rank by biasAdd: ${t.rank}`)}function Eb(e,t,n){return hi((()=>(null==n&&(n="channelsLast"),eb(n),Ao(e,$b(e.rank,t,n)))))}function Rb(e,t,n,s){return hi((()=>Rp(e,t,n,s)))}function Ab(e,t,n=!1){return n?e():t()}const _b=["fanIn","fanOut","fanAvg"],Fb=["normal","uniform","truncatedNormal"];class Db extends Ko{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Ob extends Db{apply(e,t){return Zh(e,t)}}Ob.className="Zeros",Yo(Ob);class Mb extends Db{apply(e,t){return Jh(e,t)}}Mb.className="Ones",Yo(Mb);class Lb extends Db{constructor(e){if(super(),"object"!=typeof e)throw new vy(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new vy(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return hi((()=>Do(Ho(this.value),Jh(e,t))))}getConfig(){return{value:this.value}}}Lb.className="Constant",Yo(Lb);class zb extends Db{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 Ed(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}zb.className="RandomUniform",Yo(zb);class Pb extends Db{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("float32"!==(t=t||"float32")&&"int32"!==t)throw new ky(`randomNormal does not support dType ${t}.`);return Nb(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Pb.className="RandomNormal",Yo(Pb);class Bb extends Db{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("float32"!==(t=t||"float32")&&"int32"!==t)throw new ky(`truncatedNormal does not support dType ${t}.`);return yp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Bb.className="TruncatedNormal",Yo(Bb);class Wb extends Db{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return hi((()=>{if(2!==e.length||e[0]!==e[1])throw new vy("Identity matrix initializer can only be used for 2D square matrices.");return Do(this.gain,vh(e[0]))}))}getConfig(){return{gain:this.gain}}}Wb.className="Identity",Yo(Wb);class Vb extends Db{constructor(e){if(super(),e.scale<0)throw new vy(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Py(_b,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Py(Fb,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,s;if(eb(t),2===e.length)n=e[0],s=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=cb(e,2);n=e[1]*t,s=e[0]*t}else if("channelsLast"===t){const t=cb(e,0,e.length-2);n=e[e.length-2]*t,s=e[e.length-1]*t}}else{const t=cb(e);n=Math.sqrt(t),s=Math.sqrt(t)}return[n,s]}(e),s=n[0],r=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,s):"fanOut"===this.mode?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new ky(`${this.getClassName()} does not support dType ${t}.`);return yp(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return Ed(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Vb.className="VarianceScaling",Yo(Vb);class Ub extends Vb{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}Ub.className="GlorotUniform",Yo(Ub);class Gb extends Vb{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}Gb.className="GlorotNormal",Yo(Gb);class Hb extends Vb{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}Hb.className="HeNormal",Yo(Hb);class jb extends Vb{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}jb.className="HeUniform",Yo(jb);class qb extends Vb{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}qb.className="LeCunNormal",Yo(qb);class Kb extends Vb{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Vb.className}}Kb.className="LeCunUniform",Yo(Kb);class Xb extends Db{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return hi((()=>{if(e.length<2)throw new ky("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=ue(e.slice(0,-1)),s=e[e.length-1],r=n*s;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.`);const a=Nb([Math.max(s,n),Math.min(s,n)],0,1,t,this.seed),i=Hf.qr(a,!1);let o=i[0];const l=i[1].flatten().stridedSlice([0],[Math.min(s,n)*Math.min(s,n)],[Math.min(s,n)+1]);return o=Do(o,l.sign()),n<s&&(o=o.transpose()),Do(Ho(this.gain),o.reshape(e))}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Xb.className="Orthogonal",Yo(Xb);const Yb={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 Zb(e,t={}){return Oy(e,Xo.getMap().classNameMap,t,"initializer")}function Jb(e){return Fy(e)}function Qb(e){if("string"==typeof e){const t=e in Yb?Yb[e]:e;if("GlorotNormal"===t)return new Gb;if("GlorotUniform"===t)return new Ub;if("HeNormal"===t)return new Hb;if("HeUniform"===t)return new jb;if("LeCunNormal"===t)return new qb;if("LeCunUniform"===t)return new Kb;{const e={};return e.className=t,e.config={},Zb(e)}}return e instanceof Db?e:Zb(e)}function ex(e){return Array.isArray(e)&&Array.isArray(e[0])}function tx(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function nx(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new vy(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function sx(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new vy(`Expected exactly 1 Shape; got ${e.length}`)}return e}function rx(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}const ax="Variable";class ix{constructor(e,t="float32",n=ax,s=!0,r=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Hy(),n=null==n?ax:n,this.originalName=ib(n),this.name=ob(this.originalName),this.trainable_=s,this.constraint=r,this.val=kp(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&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 ox(e){return e.map((e=>e.read()))}function lx(e){e.forEach((e=>{e[0].write(e[1])}))}class ux{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class cx{constructor(e,t,n,s,r,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=i,this.id=Hy(),null!=a&&(this.originalName=ib(a),this.name=ob(this.originalName)),this.rank=t.length}}let hx=0;class dx{constructor(e,t){this.callArgs=t,this.id=hx++,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(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let px=0;class fx extends Ko{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=px++,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){const e=this.getClassName();t=Ry(e)+"_"+qy(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?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(0===this.inboundNodes.length)throw new wy(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new vy(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return $y(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return $y(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new xy(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new xy(`Layer ${this.name} is not connected, no input to return.`);return $y(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new xy(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new xy(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return $y(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){const t=Ey(e);if(null==this.inputSpec||0===this.inputSpec.length)return;const n=Ey(this.inputSpec);if(t.length!==n.length)throw new vy(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let e=0;e<t.length;e++){const s=t[e],r=n[e];if(null==r)continue;const a=s.rank;if(null!=r.ndim&&a!==r.ndim)throw new vy(`Input ${e} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${a}`);if(null!=r.maxNDim&&a>r.maxNDim)throw new vy(`Input ${e} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(null!=r.minNDim&&a<r.minNDim)throw new vy(`Input ${e} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${a}.`);if(null!=r.dtype&&s.dtype!==r.dtype)throw new vy(`Input ${e} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${s.dtype}.`);if(r.axes){const t=s.shape;for(const n in r.axes){const s=Number(n),a=r.axes[n],i=s>=0?t[s]:t[t.length+s];if(null!=a&&-1===[a,null].indexOf(i))throw new vy(`Input ${e} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${a} but got shape ${t}.`)}}if(null!=r.shape)for(let t=0;t<r.shape.length;++t){const n=r.shape[t],a=s.shape[t];if(null!=n&&null!=a&&n!==a)throw new vy(`Input ${e} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${s.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Ey(e),s=function(e){let t=!0;for(const n of Ey(e))if(!(n instanceof cx)){t=!1;break}return t}(e),r=function(e){let t=!0;for(const n of Ey(e))if(n instanceof cx){t=!1;break}return t}(e);if(s===r)throw new vy("Arguments to apply() must be all SymbolicTensors or all Tensors");return ab(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Ey(e))t.push(n.shape);this.build($y(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,s);const r=Ey(s),a=[];for(let e of r)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(s=$y(a),null!=this.activityRegularizer)throw new ky("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(e){e=Ey(e);const t=[];for(const n of e)t.push(n.shape);return $y(t)}(e),s=this.computeOutputShape(n);let r;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),r=null!=s&&s.length>0&&Array.isArray(s[0])?s.map(((n,s)=>new cx(a,n,this,Ey(e),t,this.name,s))):new cx(a,s,this,Ey(e),t,this.name),this.addInboundNode(e,r,null,null,n,s,t),this._refCount++,null!=this.activityRegularizer)throw new ky("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)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,s)=>{null!=n&&null!=e[s]&&e[s]!==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(null==this.inboundNodes||0===this.inboundNodes.length)throw new xy(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new xy(`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 wy(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return rx(this.weights)}build(e){this.built=!0}getWeights(e=!1){return ox(e?this.trainableWeights:this.weights)}setWeights(e){hi((()=>{const t=this.weights;if(t.length!==e.length)throw new vy(`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(0===t.length)return;const n=[],s=ox(t);for(let r=0;r<s.length;++r){const a=s[r],i=t[r],o=e[r];if(!de(a.shape,o.shape))throw new vy(`Layer weight shape ${a.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}lx(n)}))}addWeight(e,t,n,s,r,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new vy(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(s=null!=o?o():Qb("zeros"));const l=s.apply(t,n),u=new ix(l,n,e,a,i);return l.dispose(),null!=r&&this.addLoss((()=>r.apply(u.read()))),null==a&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Ey(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)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;const s=this.computeMask(e,n),r=Ey(t),a=Ey(s);if(r.length!==a.length)throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);for(let e=0;e<r.length;e++)r[e].kerasMask=a[e]}addInboundNode(e,t,n,s,r,a,i=null){const o=Ey(e);t=Ey(t),n=Ey(n),s=Ey(s),r=tx(r),a=tx(a);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new dx({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},i);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)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(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function mx(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const s=mx(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of s)-1===t.indexOf(e)&&t.push(e)}return t}}}class gx extends fx{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:qy("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new vy("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new vy("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new vy("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const s=new cx(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new dx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new vy(`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}}}function yx(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new vy("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;null==n&&(n="float32");return new gx({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}gx.className="InputLayer",Yo(gx);class bx{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof bx)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new vy(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return $o(t,e.dtype)}catch(n){throw new vy(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof cx){if(null==this.id2Value[e.id])throw new vy(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new vy(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof cx){if(null==this.id2Value[e.id])throw new vy(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new vy(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&di(this.id2Mask)}}const xx=new Ny,wx=new Ny;function vx(e,t,n,s){const r=null!=n&&n.training,a=Array.isArray(e),i=a?e:[e],o=i.map((e=>e.name)),l=[],u=t.names();for(const e of o)-1!==u.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=s&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let h,d=xx.get(c);if(null==d){const e=function(e,t){ie(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],s={};if(1===e.length){const r=Ix(e[0],t);n=r.sorted,s=r.recipientMap}else{const r=new Set;for(const a of e){const{sorted:e,recipientMap:i}=Ix(a,t);for(const t of e)r.has(t.name)||(n.push(t),r.add(t.name));for(const e in i)null==s[e]&&(s[e]=new Set),i[e].forEach((t=>s[e].add(t)))}}return{sorted:n,recipientCounts:kx(s)}}(i,t);d=e.sorted,h=e.recipientCounts,xx.put(c,d),wx.put(c,h)}h={},r||Object.assign(h,wx.get(c));const p=new bx(t);for(let e=0;e<d.length;++e){if(null!=s){const e=ui().numTensors;e>s.maxNumTensors&&(s.maxNumTensors=e),e<s.minNumTensors&&(s.minNumTensors=e)}const a=d[e],i=a.sourceLayer;if(i instanceof gx)continue;const u=[],c=[],f=[];let m=!1;for(const e of a.inputs){const n=p.getValue(e),s=p.getMask(e);u.push(n),c.push(s),null!=s&&(m=!0),r||(h[e.name]--,0!==h[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||f.push(n))}m&&((n=n||{}).mask=c[0]);const g=Ey(i.apply(u,n));let y=null;i.supportsMasking&&(y=i.computeMask(u,c));const b=Nx(a),x=Array.isArray(b)?b:[b];for(let e=0;e<x.length;++e){p.hasKey(x[e])||p.add(x[e],g[e],Array.isArray(y)?y[0]:y);const t=o.indexOf(x[e].name);-1!==t&&(l[t]=g[e])}r||di(f)}return p.disposeMasks(),a?l:l[0]}function kx(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Ix(e,t){const n=new Set,s=[],r={};for(const e of t.names())n.add(e);const a=[],i=[];for(a.push(e);a.length>0;){const e=a[a.length-1];if(n.has(e.name)){a.pop();continue}const t=i[i.length-1]===a.length-1;if(0===e.inputs.length||t)a.pop(),s.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==r[t.name]&&(r[t.name]=new Set),r[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:s,recipientMap:r}}function Nx(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const s of e.sourceLayer.inboundNodes[t].outputTensors)if(s.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}function Sx(e,t){return hi((()=>Oo(ph(Do(e,e),t,!0))))}Xe().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=xx&&xx.setMaxEntries(e),null!=wx&&wx.setMaxEntries(e)}));class Tx extends Ko{getConfig(){return{}}}class Cx extends Tx{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return hi((()=>{const t=Sx(e,this.axis),n=$c(t,0,this.maxValue);return Do(e,Fo(n,Ao(mb(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Cx.className="MaxNorm",Yo(Cx);class $x extends Tx{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return hi((()=>Fo(e,Ao(mb(),Sx(e,this.axis)))))}getConfig(){return{axis:this.axis}}}$x.className="UnitNorm",Yo($x);class Ex extends Tx{apply(e){return Fd(e)}}Ex.className="NonNeg",Yo(Ex);class Rx extends Tx{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return hi((()=>{const t=Sx(e,this.axis),n=Ao(Do(this.rate,$c(t,this.minValue,this.maxValue)),Do(1-this.rate,t));return Do(e,Fo(n,Ao(mb(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Rx.className="MinMaxNorm",Yo(Rx);const Ax={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function _x(e){return Fy(e)}function Fx(e,t={}){return Oy(e,Xo.getMap().classNameMap,t,"constraint")}function Dx(e){if(null==e)return null;if("string"==typeof e){return Fx({className:e in Ax?Ax[e]:e,config:{}})}return e instanceof Tx?e:Fx(e)}function Ox(e){return new Cx(e)}function Mx(e){return new $x(e)}function Lx(){return new Ex}function zx(e){return new Rx(e)}function Px(){return new Ob}function Bx(){return new Mb}function Wx(e){return new Lb(e)}function Vx(e){return new zb(e)}function Ux(e){return new Pb(e)}function Gx(e){return new Bb(e)}function Hx(e){return new Wb(e)}function jx(e){return new Vb(e)}function qx(e){return new Ub(e)}function Kx(e){return new Gb(e)}function Xx(e){return new Hb(e)}function Yx(e){return new jb(e)}function Zx(e){return new qb(e)}function Jx(e){return new Kb(e)}function Qx(e){return new Xb(e)}async function ew(e){if(null==e)return;const t=[],n=[],s=[];for(const r in e){const a=e[r];if("number"!=typeof a){const e=a;t.push(e.data()),n.push(r),s.push(e)}}if(t.length>0){const r=await Promise.all(t);for(let t=0;t<r.length;++t)e[n[t]]=r[t][0];di(s)}}function tw(e){if(null!=e)for(const t in e){const n=e[t];"number"!=typeof n&&n.dispose()}}var nw;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(nw||(nw={}));class sw{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){}}class rw{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class aw extends sw{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const s=t[e];if("number"==typeof s)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+s*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const r=hi((()=>Ao(this.totals[e],Do(s,n))));this.totals[e]=r,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:hi((()=>{const n=Do(Fo(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),pi(t[e])})))}}class iw extends sw{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const s in this.history){const r=this.history[s];for(let a=0;a<r.length;++a)if("number"!=typeof r[a]){const i=r[a];e.push(i.data()),t.push(s),n.push(a)}}const s=await Promise.all(e);for(let e=0;e<s.length;++e){this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=s[e][0]}}}class ow extends sw{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Zf,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");Ae(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let s,r=null!=n?n():Xr();return(...a)=>{const i=null!=n?n():Xr();return i-r<t||(r=i,s=e(...a)),s}}(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){const s=[];null!=this.yield&&(await ew(n),s.push(this.yield(e,t,n))),s.push(this.nextFrameFunc()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await ew(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await ew(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await ew(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await ew(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):Ae(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await ew(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await ew(e),await this.trainEnd(e))}}function lw(e,t){if(null==e&&(e={}),e instanceof sw)return[e];if(Array.isArray(e)&&e[0]instanceof sw)return e;return Ey(e).map((e=>new ow(e,t)))}class uw{constructor(){}static registerCallbackConstructor(e,t){ie(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),uw.checkForDuplicate(t),null==uw.constructors[e]&&(uw.constructors[e]=[]),uw.constructors[e].push(t)}static checkForDuplicate(e){for(const t in uw.constructors){uw.constructors[+t].forEach((t=>{if(t===e)throw new vy("Duplicate callback constructor.")}))}}static clear(){uw.constructors={}}static createCallbacks(e){const t=[];for(const n in uw.constructors){const s=+n;e>=s&&t.push(...uw.constructors[s])}return t.map((e=>new e))}}function cw(e,t,n,s,r,a,i,o,l){const u=new iw,c=[new aw,...uw.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new rw(c);return h.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function hw(e,t={},n=!1){return Oy(e,Xo.getMap().classNameMap,t,"layer",n)}function dw(e,t){return hi((()=>{"float32"!==e.dtype&&(e=$o(e,"float32"));const n=ph(Cb(e),t,!0),s=el(n.shape,mb()),r=Oo(ul(n,s));return Fo(e,r)}))}function pw(e,t){return hi((()=>Yh(Cb(sl(t,e)),-1)))}function fw(e,t){return hi((()=>Yh(al(sl(t,e)),-1)))}function mw(e,t){return hi((()=>{const n=sl(e,t),s=$c(al(e),mb(),Number.MAX_VALUE),r=al(Fo(n,s));return Do(100,Yh(r,-1))}))}function gw(e,t){return hi((()=>{const n=$c(t,mb(),Number.MAX_VALUE),s=Dh(Ao(1,n)),r=$c(e,mb(),Number.MAX_VALUE),a=Dh(Ao(1,r));return Yh(Cb(sl(s,a)),-1)}))}function yw(e,t,n=!1){return hi((()=>{if(n)t=Jd(t);else{const e=ph(t,t.shape.length-1,!0);t=Fo(t,e)}return t=$c(t,mb(),1-mb()),zl(ph(Do($o(e,"float32"),Dh(t)),t.shape.length-1))}))}function bw(e,t,n=!1){return hi((()=>{const s=$o(kh(function(e){const t=[cb(e.shape)];return cc(e,t)}(e)),"int32"),r=(t=$c(t,mb(),1-mb())).shape;return yw(cc(Ml(s,r[r.length-1]),r),t,n)}))}function xw(e,t){return hi((()=>{let n;return n=$c(t,mb(),1-mb()),n=Dh(Fo(n,sl(1,n))),Yh(function(e,t){if(!de(e.shape,t.shape))throw new vy(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return hi((()=>{const n=Fd(t),s=zl(al(t));return Ao(sl(n,Do(t,e)),Oh(yh(s)))}))}(e,n),-1)}))}function ww(e,t){return hi((()=>{const n=$c(e,mb(),1),s=$c(t,mb(),1);return ph(Do(e,Dh(Fo(n,s))),-1)}))}function vw(e,t){return hi((()=>{const n=dw(e,-1),s=dw(t,-1),r=Do(n,s);return zl(ph(r,-1))}))}uw.constructors={};const kw={meanSquaredError:pw,meanAbsoluteError:fw,meanAbsolutePercentageError:mw,meanSquaredLogarithmicError:gw,squaredHinge:function(e,t){return hi((()=>{const n=ul(0,sl(1,Do(e,t)));return Yh(Cb(n),-1)}))},hinge:function(e,t){return hi((()=>{const n=ul(0,sl(1,Do(e,t)));return Yh(n,-1)}))},categoricalHinge:function(e,t){return hi((()=>{const n=ph(Do(e,t),-1),s=hh(Do(sl(1,e),t),-1);return ul(0,Ao(1,sl(s,n)))}))},logcosh:function(e,t){return hi((()=>{const n=Math.log(2),s=sl(t,e),r=sl(Ao(s,Mh(Do(-2,s))),n);return Yh(r,-1)}))},categoricalCrossentropy:yw,sparseCategoricalCrossentropy:bw,binaryCrossentropy:xw,kullbackLeiblerDivergence:ww,poisson:function(e,t){return hi((()=>{const n=Dh(Ao(mb(),t));return Yh(sl(t,Do(e,n)),-1)}))},cosineProximity:vw};function Iw(e){if("string"==typeof e){if(e in kw)return kw[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 vy(t)}return e}function Nw(e,t){return hi((()=>{const n=Do(.5,od(t)),s=gb(Nh(t,n),e.dtype);return Yh(Xc(e,s),-1)}))}function Sw(e,t){return hi((()=>gb(Xc(Vu(e,-1),Vu(t,-1)),"float32")))}function Tw(e,t){return hi((()=>$o(ph(Bh(Xc(e,1),Xc(t,1))),"float32")))}function Cw(e,t){return hi((()=>{const n=Tw(e,t),s=function(e,t){return hi((()=>$o(ph(Bh(Xc(e,0),Xc(t,1))),"float32")))}(e,t),r=Ao(n,s);return $o(Yc(Nh(r,0),Fo(n,r),0),"float32")}))}function $w(e,t){return hi((()=>{const n=Tw(e,t),s=function(e,t){return hi((()=>$o(ph(Bh(Xc(e,1),Xc(t,0))),"float32")))}(e,t),r=Ao(n,s);return $o(Yc(Nh(r,0),Fo(n,r),0),"float32")}))}function Ew(e,t){return xw(e,t)}function Rw(e,t){return e.rank===t.rank&&(e=ap(e,[e.rank-1])),(t=Vu(t,-1)).dtype!==e.dtype&&(t=$o(t,e.dtype)),$o(Xc(e,t),"float32")}const Aw=yw,_w=bw,Fw={binaryAccuracy:Nw,categoricalAccuracy:Sw,precision:Cw,categoricalCrossentropy:Aw,sparseCategoricalCrossentropy:_w,mse:pw,MSE:pw,mae:fw,MAE:fw,mape:mw,MAPE:mw,cosine:vw};function Dw(e){if("string"==typeof e&&e in Fw)return Fw[e];if("string"!=typeof e&&null!=e)return e;throw new vy(`Unknown metric ${e}`)}function Ow(e){if(Ty(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(kw))if(kw[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Fw))if(Fw[n]===e){t=n;break}return void 0!==t?t:e.name}}const Mw=1048576;function Lw(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!zw(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>Mw&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.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 zw(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!zw(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!zw(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Pw(e,t,n,s=console.log){const r=function(e){let t=!0;const n=[],s=[];for(const t in e.nodesByDepth)n.push(e.nodesByDepth[t]);for(const e of n){if(e.length>1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}s.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const r of n.inboundNodes)if(-1!==s.indexOf(r)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(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((e=>Math.floor(t*e)))),!r){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}s("_".repeat(t)),Bw(a,n,s),s("=".repeat(t));const o=e.layers;for(let e=0;e<o.length;++e)r?Ww(o[e],n,s):Vw(o[e],n,i,s),s((e===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=function(e){let t;t=null!=e.collectedTrainableWeights?rx(e.collectedTrainableWeights):rx(e.trainableWeights);return t}(e),u=rx(e.nonTrainableWeights);s(`Total params: ${l+u}`),s(`Trainable params: ${l}`),s(`Non-trainable params: ${u}`),s("_".repeat(t))}function Bw(e,t,n=console.log){let s="";for(let n=0;n<e.length;++n)n>0&&(s=s.slice(0,s.length-1)+" "),s+=e[n],s=s.slice(0,t[n]),s+=" ".repeat(t[n]-s.length);n(s)}function Ww(e,t,n){let s,r;try{r=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){r="multiple"}try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}Bw([`${e.name} (${e.getClassName()})`,r,s,e.countParams().toString()],t,n)}function Vw(e,t,n,s){let r,a;try{a=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){a="multiple"}try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}const i=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;e<t.inboundLayers.length;++e){const n=t.inboundLayers[e].name,s=t.nodeIndices[e],r=t.tensorIndices[e];i.push(`${n}[${s}][${r}]`)}const o=e.name,l=e.getClassName(),u=0===i.length?"":i[0];Bw([`${o} (${l})`,a,r,e.countParams().toString(),u],t,s);for(let e=1;e<i.length;++e)Bw(["","","","",i[e]],t,s)}function Uw(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function Gw(e,t){if(null===e)return null;if("string"==typeof e)return Ay(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],s=e.length;for(let r=0;r<s;++r){const s=e[r];Uw(t,r,s)?n.push(s):n.push(Gw(s,t))}return n}{const t={};for(const n of Object.keys(e)){const s=e[n];if("name"===n&&"string"==typeof s)t[n]=s;else{const e=Ay(n);t[e]=Gw(s,e)}}return t}}function Hw(e,t){if(null==e)return null;if("string"==typeof e)return Ry(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],s=e.length;for(let r=0;r<s;++r){const s=e[r];Uw(t,r,s)?n.push(s):n.push(Hw(s,t))}return n}{const t={};for(const n of Object.keys(e)){const s=e[n],r=Ry(n);t[r]="name"!==n&&"className"!==n||"string"!=typeof s?Hw(s,n):s}return t}}const jw="4.20.0";class qw extends fx{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=qy(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Ly(this.inputs).length!==this.inputs.length)throw new vy(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);Ly(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((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(s)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;Ty(0===n,"input layer has >1 nodes"),Ty(0===s,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(s)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof gx))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},s={},r={},a={},i=[],o=(e,t,n,s,r,l)=>{null!=s&&null!=r&&null!=l||(s=e.sourceLayer,r=e.nodeIndex,l=e.tensorIndex);const u=s.inboundNodes[r];if(-1!==n.indexOf(u))throw new wy(`The tensor ${e.name} at layer "${s.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(qw.nodeKey(s,r)),s.id in a||(a[s.id]=Object.keys(a).length),-1===n.indexOf(u)&&n.push(u);const c=u.inboundLayers.length;for(let e=0;e<c;e++){const s=u.inputTensors[e],r=u.inboundLayers[e],a=u.nodeIndices[e],i=u.tensorIndices[e];o(s,t,n,r,a,i)}for(t.push(u);n.indexOf(u)>=0;)n.splice(n.indexOf(u),1);i.push(u)},l=[],u=[];for(const e of this.outputs)o(e,l,u);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let a=t[e.id];const i=null==s[e.outboundLayer.id]?0:s[e.outboundLayer.id];a=Math.max(a,i),s[e.outboundLayer.id]=a,r[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let s=0;s<e.inboundLayers.length;s++){const r=e.inboundLayers[s],i=e.nodeIndices[s],o=r.inboundNodes[i],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(a+1,l),n[o.id]=o}}const h={};for(const e in t){const s=t[e];s in h||(h[s]=[]),h[s].push(n[e])}const d={};for(const e in s){const t=s[e];t in d||(d[t]=[]),d[t].push(r[e])}let p=Object.keys(d).map((e=>parseInt(e,10))).sort(My);this.layers=[];for(const e of p){const t=d[e];t.sort(((e,t)=>{const n=a[e.id],s=a[t.id];return n<s?-1:n>s?1:0}));for(const e of t)e instanceof qw&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=d,p=Object.keys(h).map((e=>parseInt(e,10))).sort(My);const f=this.inputs.slice(),m=[];for(const e of p)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new wy(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new wy(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new dx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new vy("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let s=0;const r=(e=>{const t=Object.keys(e);if(0===t.length)return!1;const n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))})(e);r&&this.parseWeights(e);for(const e of this.layers)for(const[t,a]of e.weights.entries()){const e=r?`${a.name.split("/").slice(0,-1).join("/")+"/"}${t}`:a.originalName;if(null!=n[e])throw new vy(`Duplicate weight name: ${e}`);n[e]=a,s++}const a=[];for(const s in e){let r=s;if(null==n[s]){const e=s.split("/");r=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[r])a.push([n[r],e[s]]);else if(t)throw new vy(`Provided weight data has no target variable: ${s}`);delete n[r]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new vy(`${e.length} of ${s} weights are not set: ${e}`)}lx(a)}parseWeights(e){for(const t in Object.keys(e)){const n=t.split("/"),s=["vars","layer_checkpoint_dependencies"],r=n.map((e=>e.startsWith("_")?e.slice(1):e)).filter((e=>!s.includes(e))).join("/");r!==t&&(e[r]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${jw}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Hw(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return hi((()=>{e=Ey(e);const n=new bx;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return vx(this.outputs,n,t)}))}computeMask(e,t){return hi((()=>{let n;return e=Ey(e),n=null==t?Sy(null,e.length):Ey(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=tx(e);if(t.length!==this.inputLayers.length)throw new vy(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const s=this.inputLayers[e],r=t[e];n[s.name+"_0_0"]=r}const s=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(My);if(s.length>1)for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const s=[];for(let t=0;t<e.inboundLayers.length;t++){const r=e.inboundLayers[t],a=e.nodeIndices[t],i=e.tensorIndices[t],o=n[`${r.name}_${a}_${i}`];s.push(o)}const r=tx(t.computeOutputShape($y(s))),a=t.inboundNodes.indexOf(e);for(let e=0;e<r.length;e++){n[`${t.name}_${a}_${e}`]=r[e]}}}const r=[],a=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],s=this.outputLayersTensorIndices[e],r=`${t.name}_${n}_${s}`;a.push(r)}for(let e=0;e<a.length;e++){const t=a[e];Ty(t in n),r.push(n[t])}return $y(r)}runInternalGraph(e,t){null==t&&(t=Sy(null,e.length));const n={};for(let s=0;s<this.inputs.length;++s){const r=this.inputs[s],a=e[s],i=t[s];n[r.id]=[a,i]}const s=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(My);for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,s=e.inputTensors,r=e.outputTensors,a=new Array;for(const e of s)e.id in n&&a.push(n[e.id]);if(a.length===s.length){let s,i,o,l,u={};if(null!=e.callArgs&&(u=e.callArgs),1===a.length){const[e,n]=a[0];null==u.mask&&(u.mask=n),o=Ey(t.call(e,u)),l=Ey(t.computeMask(e,n)),s=[e],i=[n]}else s=a.map((e=>e[0])),i=a.map((e=>e[1])),null==u.mask&&(u.mask=i),o=Ey(t.call(s,u)),l=Ey(t.computeMask(s,i));if(t.activityRegularizer)throw new ky("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<r.length;++e){const t=r[e],s=o[e],a=l[e];n[t.id]=[s,a]}}}}const r=[],a=[],i=[];for(const e of this.outputs){Ty(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,s]=n[e.id];i.push(t.shape),r.push(t),a.push(s)}return[r,a,i]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof qw?1:0;for(let s=0;s<e.inboundNodes.length;s++){const r=qw.nodeKey(e,s);this.containerNodes.has(r)&&(t[r]=n,n+=1)}}return t}getLayer(e,t){if(null!=t)return this.findLayer(t);if(null==e)throw new vy("Provide either a layer name or layer index");if("number"==typeof e)return this.findLayer(e);for(const t of this.layers)if(t.name===e)return t;throw new vy(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new vy(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return hi((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=qw.nodeKey(t,n);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const s=e.getClassName(),r=e.getConfig(),a=[];for(let n=0;n<e.inboundNodes.length;n++){const s=e.inboundNodes[n],r=qw.nodeKey(e,n);let i={};if(this.containerNodes.has(r)){if(s.callArgs)try{JSON.stringify(s.callArgs),i=s.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${s.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),i={}}if(s.inboundLayers.length>0){const e=[];for(let n=0;n<s.inboundLayers.length;n++){const r=s.inboundLayers[n],a=s.nodeIndices[n],o=s.tensorIndices[n];let l=t[qw.nodeKey(r,a)];null==l&&(l=0),e.push([r.name,l,o,i])}a.push(e)}}}const i={};i.name=e.name,i.className=s,i.config=r,i.inboundNodes=a,n.push(i)}e.layers=n;const s=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],r=this.inputLayersNodeIndices[e],a=qw.nodeKey(n,r);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.inputLayersTensorIndices[e];s.push([n.name,i,o])}e.inputLayers=s;const r=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],s=this.outputLayersNodeIndices[e],a=qw.nodeKey(n,s);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.outputLayersTensorIndices[e];r.push([n.name,i,o])}return e.outputLayers=r,e}static fromConfig(e,t,n={},s=!1){const r={},a={};function i(e,t){e.name in a?a[e.name].push(t):a[e.name]=[t]}function o(e,t){const n=[];let s;for(const a of t){const o=a[0],l=a[1],u=a[2];if(s=null==a[3]?{}:a[3],!(o in r))return void i(e,t);const c=r[o];if(c.inboundNodes.length<=l)return void i(e,t);const h=c.inboundNodes[l];n.push(h.outputTensors[u])}n.length>0&&e.apply($y(n),s)}function l(e){const n=e.name,a=hw(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(s),r[n]=a;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new vy(`Corrupted configuration, expected array for nodeData: ${e}`);i(a,e)}))}const u=t.name,c=t.layers;for(const e of c)l(e);for(;!zy(a);)for(const e of c){const t=r[e.name];if(t.name in a){const e=a[t.name];delete a[t.name];for(const n of e)o(t,n)}}const h=[],d=[],p=t.inputLayers;for(const e of p){const t=e[0],n=e[1],s=e[2];Ty(t in r);const a=r[t].inboundNodes[n].outputTensors;h.push(a[s])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],s=e[2];Ty(t in r);const a=r[t].inboundNodes[n].outputTensors;d.push(a[s])}return new e({inputs:h,outputs:d,name:u})}get stateful(){if(this._stateful)throw new vy("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(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){hi((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function Kw(e,t,n){const s=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===s)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Xw(e,t){return Kw(e,t,"classWeight")}async function Yw(e,t,n,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=hi((()=>{if(1===e.shape.length)return Eo(e);if(2===e.shape.length){if(e.shape[1]>1){return Vu(e,1)}if(1===e.shape[1])return cc(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.`)}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 t.data());di(t);const r=[];return s.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);r.push(n[e])})),cp(r,"float32")}return null}function Zw(e,t){return Do(e,t)}function Jw(e,t){let n,s;const r=t;n=r.xs,s=r.ys,ie(null!=n&&null!=s,(()=>`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}`));const a=Qw("input",e.inputNames,n),i=Qw("output",e.outputNames,s),o=a[0].shape[0];ie(a.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),ie(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 t=0;t<a.length;t++)ie(a[t].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[t]} has ${a[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t<i.length;t++)ie(i[t].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:a,ys:i}}function Qw(e,t,n){if(n instanceof ga)return[n];if(Array.isArray(n))return ie(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const s=[];for(const r of t){if(null==n[r])throw new vy(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}async function ev(e,t,n){const s=null!=n.batchesPerEpoch;if(ie(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),ie(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),ie(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),ie(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),ie(null==n.validationSplit,(()=>"`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{const r=null!=n.validationData;let a,i;if(r)if(tv(n.validationData))ie(null==n.validationBatches||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{const e=function(e){if(3===e.length)throw new ky("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);a=e.xs,i=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let u;u=r?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const c=lw(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:d,history:p}=cw(c,h,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,r,u);d.setModel(e),e.history=p,await d.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){const u={};await d.onEpochBegin(f);let c=0,h=0;for(s||(m=await t.iterator());!s||c<n.batchesPerEpoch;){const t=await m.next();if(s&&t.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${c} 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(null!=t.value){const{xs:s,ys:r}=Jw(e,t.value),a={};a.batch=h,a.size=s[0].shape[0],await d.onBatchBegin(h,a);const i=[];if(null!=n.classWeight){const t=Xw(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await Yw(r[e],null,t[e]))}const u=s.concat(r).concat(i),p=o(u);di(u);for(let e=0;e<l.length;++e){const t=l[e],n=p[e];a[t]=n,pi(n)}await d.onBatchEnd(h,a),tw(a),h++,c++}if(s?c>=n.batchesPerEpoch:t.done){if(r){let t;t=tv(n.validationData)?Ey(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Ey(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)u[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await d.onEpochEnd(f,u),f++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function tv(e){return"function"==typeof e.iterator}function nv(e){ie(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function sv(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>bb(e,t,n-t))):bb(e,t,n-t)}function rv(e,t){return hi((()=>null==e?null:Array.isArray(e)?e.map((e=>rv(e,t))):Tb(e,"int32"===t.dtype?t:$o(t,"int32"))))}function av(e,t){const n=[];let s=0,r=null;for(;s<e;)r=s+t,r>=e&&(r=e),n.push([s,r]),s=r;return n}function iv(e){const t=[];e instanceof ga&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(1===s.rank)t.push(yb(s,1));else{if(0===s.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function ov(e,t){if(null==e)return;const n=[];if(t instanceof ga)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const e in t){const s=t[e];n.push(s.id)}const s=[];if(e instanceof ga)-1===n.indexOf(e.id)&&s.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&s.push(e)}));else if(null!=e)for(const t in e){const r=e[t];-1===n.indexOf(r.id)&&s.push(r)}s.forEach((e=>{e.isDisposed||e.dispose()}))}function lv(e){return Array.isArray(e)}function uv(e){return!function(e){return e instanceof ga}(e)&&!lv(e)}function cv(e,t,n,s=!0,r=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(lv(e)&&e.length>0)t=!0;else if(uv(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new vy(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(uv(e)){a=[];for(const n of t){if(null==e[n])throw new vy(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(lv(e)){if(e.length!==t.length)throw new vy(`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}`);a=e}else{if(t.length>1)throw new vy(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=iv(a),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new vy(`Error when checking ${r}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${i.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!s)continue;const a=i.shape[t],o=n[e][t];if(null!=o&&o>=0&&a!==o)throw new vy(`${r} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function hv(e,t,n,s=!0,r=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new vy(`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).`);a=e}else{if(t.length>1)throw new vy(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new vy(`Error when checking ${r}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let a=0;a<n[e].length;++a){if(0===a&&!s)continue;const o=i.shape[a],l=n[e][a];if(null!=l&&l!==o)throw new vy(`Error when checking ${r}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}class dv extends qw{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new vy("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");Pw(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Xf.adagrad(.01),Adadelta:()=>Xf.adadelta(1,.95,mb()),Adam:()=>Xf.adam(.001,.9,.999,mb()),Adamax:()=>Xf.adamax(.002,.9,.999,mb(),0),RMSProp:()=>Xf.rmsprop(.001,.9,0,mb()),SGD:()=>Xf.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 vy(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Jo))throw new vy("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new vy(`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}.`);const n=e.loss;t=n.map((e=>Iw(e)))}else{const n=Iw(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new vy(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Iw(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ab("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const s=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const s of t){let t=n.hasOwnProperty(s)?n[s]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),r=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};ab("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,s,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let r;1===t[t.length-1]||this.lossFunctions[e]===xw?-1!==["accuracy","acc"].indexOf(i)?s=Nw:-1!==["crossentropy","ce"].indexOf(i)&&(s=Ew):this.lossFunctions[e]===bw?-1!==["accuracy","acc"].indexOf(i)?s=Rw:-1!==["crossentropy","ce"].indexOf(i)&&(s=_w):-1!==["accuracy","acc"].indexOf(i)?s=Sw:-1!==["crossentropy","ce"].indexOf(i)&&(s=Aw),-1!==["accuracy","acc"].indexOf(i)?r="acc":-1!==["crossentropy","ce"].indexOf(i)&&(r="ce"),a=s,n=""+r}else{const e=Dw(i);a=e,n=""+Ow(i)}let t;ab(n,(()=>{t=a})),r(e,n,t)}})(s[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&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={}){const s=null==n.batchSize?32:n.batchSize;nv(s);const r=this.standardizeUserDataXY(e,t,!0,s);try{const e=r[0].concat(r[1]);this.makeTestFunction();const t=this.testFunction;return $y(this.testLoop(t,e,s,n.verbose,n.steps))}finally{ov(r[0],e),ov(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const s=null!=(n=n||{}).batches,r=e.testFunction;let a=[];if(n.verbose>0)throw new ky("Verbose mode is not implemented yet.");ie(!s||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!s||l<n.batches;){const t=await i.next();if(a=hi((()=>{if(t.value){const{xs:n,ys:s}=Jw(e,t.value),i=n.concat(s),u=hi((()=>r(i)));if(di(i),0===l)for(let e=0;e<u.length;++e)a.push(Ho(0));const c=i[0].shape[0];for(let e=0;e<u.length;++e){const t=u[e],n=a[e];a[e]=hi((()=>Ao(a[e],Do(c,t)))),l>0&&di(n)}di(u),o+=c,++l}return a})),t.done){s&&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 e=0;e<a.length;++e){const t=a[e];a[e]=Fo(a[e],o),di(t)}return $y(a)}(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(null!=n){if(r=null,null!=t)throw new vy(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new vy(`Either the input data should have a defined shape, or ${s} shoud be specified.`);r=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return r}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new vy("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new bx;if(e instanceof ga&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new vy(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)a.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new vy(`No value is provided for the model's input ${t.name}`);a.add(t,n)}const i=vx(r,a);return n?i:i[0]}retrieveSymbolicTensors(e){const t=Sy(null,e.length);let n=e.length;for(const s of this.layers){const r=Array.isArray(s.output)?s.output:[s.output],a=r.map((e=>e.name));for(let s=0;s<e.length;++s){const i=a.indexOf(e[s]);if(-1!==i&&(t[s]=r[i],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,s)=>{null==t&&n.push(e[s])})),new vy(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return hi((()=>{const s=this.checkNumSamples(e);if(n)throw new ky("Verbose predictLoop() is not implemented yet.");const r=av(s,t),a=this.outputs.map((e=>[]));for(let t=0;t<r.length;++t){hi((()=>{const n=r[t][0],s=r[t][1],a=sv(e,n,s),i=[];if(Array.isArray(a))for(let e=0;e<a.length;++e)i.push({key:this.inputs[e],value:a[e]});else i.push({key:this.inputs[0],value:a});const o=new bx(i);return vx(this.outputs,o)})).forEach(((e,t)=>a[t].push(e)))}return $y(a.map((e=>pc(e,0))))}))}predict(e,t={}){const n=iv(e);hv(n,this.inputNames,this.feedInputShapes,!1);try{const e=null==t.batchSize?32:t.batchSize;return nv(e),this.predictLoop(n,e)}finally{ov(n,e)}}predictOnBatch(e){hv(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(null==this.optimizer_)throw new wy("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===bw?r.push(t.slice(0,t.length-1).concat([1])):r.push(t)}if(function(e,t,n){const s=Ly(e.map((e=>e.shape[0])));s.sort();const r=Ly(t.map((e=>e.shape[0])));if(r.sort(),s.length>1)throw new vy(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(r.length>1)throw new vy(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(s.length>0&&r.length>0&&!de(s,r))throw new vy(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}(e=cv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=cv(t,this.feedOutputNames,r,!1,"target")),function(e,t,n){const s=[pw,xw,yw];for(let r=0;r<e.length;++r){const a=e[r],i=t[r],o=n[r];if(null!=i){if(i===yw&&1===a.shape[a.shape.length-1])throw new vy(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==s.indexOf(i)){const e=a.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const s=e[n],r=t[n];if(null!=r&&s!==r)throw new vy(`A target Tensor with shape ${a.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.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=s&&s>0&&e[0].shape[0]%s!=0)throw new vy(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,r,a);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=s){const e=Xw(s,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await Yw(o[t],null,e[t]))}return[i,o,l]}testLoop(e,t,n,s=0,r){return hi((()=>{const a=this.checkNumSamples(t,n,r,"steps"),i=[];if(s>0)throw new ky("Verbose mode is not implemented yet.");if(null!=r)throw new ky("steps mode in testLoop() is not implemented yet");{const s=av(a,n),r=cp(pb(0,a));for(let n=0;n<s.length;++n){const a=s[n][0],o=s[n][1],l=bb(r,a,o-a),u=rv(t,l),c=e(u);if(0===n)for(let e=0;e<c.length;++e)i.push(Ho(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=Ao(i[e],Do(o-a,t))}}for(let e=0;e<i.length;++e)i[e]=Fo(i[e],a)}return i}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const s=e[n];let r=s;if(Cy(e,s)>1){r+=`_${Cy(e.slice(0,n),s)}`}t.push(r)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),a=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const i=new bx(e),o=vx(this.outputs,i,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(s[e],o[e]);null!=r[e]&&(n=Zw(n,r[e]));const a=Yh(n);t.push(a),l=0===e?n:Ao(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],r=this.metricsTensors[e][1];n=Yh(t(s[r],o[r]))}pi(n),a.push(n)}return l=Yh(l),this.calculateLosses().forEach((e=>{l=Ao(l,e)})),l}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>hi((()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;e<this.inputs.length;++e)a.push({key:this.inputs[e],value:s[e]});const i=new bx(a),o=vx(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const s=this.lossFunctions[e],a=Yh(s(r[e],o[e]));n=0===e?a:Ao(n,a),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],s=this.metricsTensors[e][1],a=Yh(n(r[s],o[s]));t.push(a)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let s,r,a,i,o,l,u,c,h;this.isTraining=!0;try{const d=null==n.batchSize?32:n.batchSize;nv(d);const p=!1,f=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,p,d);s=f[0],r=f[1],h=f[2];let m,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new ky("validationData including sample weights is not supported yet."):new vy(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,d);u=t[0],c=t[1],m=u.concat(c)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(s[0].shape[0]*(1-n.validationSplit)),t=s[0].shape[0];u=sv(s,e,t),a=s,s=sv(s,0,e),c=sv(r,e,t),i=r,r=sv(r,0,e),m=u.concat(c)}else null!=n.validationSteps&&(g=!0);const y=s.concat(r).concat(h);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let w,v;g?(this.makeTestFunction(),w=this.testFunction,v=x.slice().concat(x.map((e=>"val_"+e)))):(w=null,m=[],v=x.slice());const k=lw(n.callbacks,n.yieldEvery);return await this.fitLoop(b,y,x,d,n.epochs,n.verbose,k,w,m,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,ov(s,e),ov(r,t),ov(a,e),ov(i,t),ov(u,o),ov(c,l),null!=h&&di(h)}}async fitLoop(e,t,n,s,r,a,i,o,l,u,c,h,d,p){null==s&&(s=32),null==r&&(r=1),null==u&&(u=!0),null==h&&(h=0);let f=!1;if(null!=o&&null!=l&&(f=!0),null!=p&&(f=!0,null==d))throw new vy("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,s,d,"steps_per_epoch");let g;null!=m&&(g=pb(0,m)),null==a&&(a=1);const{callbackList:y,history:b}=cw(i,a,r,h,m,d,s,f,c);y.setModel(this),this.history=b,await y.onTrainBegin(),this.stopTraining_=!1;for(let a=h;a<r;++a){await y.onEpochBegin(a);const r={};if(null!=d)throw new ky("stepsPerEpoch mode is not implemented yet.");{if("batch"===u)throw new ky("batch shuffling is not implemneted yet");u&&J(g);const a=cp(g),i=av(m,s);for(let u=0;u<i.length;++u){const c={};if(await y.onBatchBegin(u,c),hi((()=>{const h=i[u][0],d=i[u][1],p=bb(a,h,d-h);c.batch=u,c.size=d-h;const m=rv(t,p),g=e(m);for(let e=0;e<n.length;++e){const t=n[e],s=g[e];c[t]=s,pi(s)}if(u===i.length-1&&f){const e=this.testLoop(o,l,s);for(let t=0;t<n.length;++t){const s=n[t],a=e[t];pi(a),r["val_"+s]=a}}})),await y.onBatchEnd(u,c),tw(c),this.stopTraining_)break}a.dispose()}if(await y.onEpochEnd(a,r),this.stopTraining_)break}return await y.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return ev(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),s=n[0],r=n[1],a=this.makeTrainFunction()(s.concat(r)),i=[];for(const e of a){const t=await e.data();i.push(t[0])}return di(a),ov(n[0],e),ov(n[1],t),$y(i)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,s=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let e=0;e<s.length;++e)n&&!s[e].trainable||t.push({name:s[e].originalName,tensor:r[e]});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(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ui().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ui().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Ry(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Ry(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t){if("string"!=typeof n[s])throw new Error("Serialization of non-string loss is not supported.");e[s]=Ry(n[s])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Ry(Ow(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Ry(Ow(e))));{const e={};for(const t in this.metrics)e[t]=Ry(Ow(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(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=hw(Gw(e.optimizer_config));let n,s;if("string"==typeof e.loss)n=Ay(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Ay(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Ay(e.loss[t])}if(Array.isArray(e.metrics))s=e.metrics.map((e=>Ay(e)));else if(null!=e.metrics){s={};for(const t in e.metrics)s[t]=Ay(e.metrics[t])}this.compile({loss:n,metrics:s,optimizer:t})}async save(e,t){if("string"==typeof e){const t=Hi(e);if(0===t.length)throw new vy(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new vy(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new vy("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Si(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${jw}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:r}=await Si(await this.optimizer.getWeights(),e);n.specs.push(...r),n.data=Oi([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Lw(this.userDefinedMetadata,this.name,e),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){Lw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}dv.className="Model",Yo(dv);class pv extends dv{}async function fv(e,t){"modelTopology"in e||(e={modelTopology:e});let n=e.modelTopology;null!=n.model_config&&(n=n.model_config);const s=hw(Gw(n),t);if(null!=e.weightsManifest){const t=await vl(e.weightsManifest,e.pathPrefix,s.weights.map((e=>e.originalName))),n={};for(const e of s.weights)n[e.originalName]=t[e.originalName];s.loadWeights(n),di(t)}return s}async function mv(e,t){if(null==t&&(t={}),"string"==typeof e){const n=ji(e,t);if(0===n.length)n.push(Cl(e,t));else if(n.length>1)throw new vy(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new vy("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await e.load();let r=s.modelTopology;null!=r.model_config&&(r=r.model_config);const a=null==n.strict||n.strict,i=null!=s.weightData&&null!=s.weightSpecs&&a,o=hw(Gw(r),t,i),l=s.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=s.userDefinedMetadata&&o.setUserDefinedMetadata(s.userDefinedMetadata);if(null!=s.weightData){if(null==s.weightSpecs)throw new vy("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=Ti(e,t),s={},r=[];return t.forEach((e=>{"optimizer"===e.group?r.push({name:e.name,tensor:n[e.name]}):s[e.name]=n[e.name]})),{modelWeights:s,optimizerWeights:r}}(s.weightData,s.weightSpecs);o.loadWeights(e,a),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),di(e),di(t.map((e=>e.tensor)))}return o}(e,void 0,t)}pv.className="Functional",Yo(pv);class gv extends dv{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:qy("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new vy(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof gv||e instanceof dv;let n;if(t){if(n=e,1!==n.outputs.length)throw new vy("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new vy("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new vy("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=yx({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new vy(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new vy("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=mx(this.outputs[0])}this.inboundNodes=[],new dx({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Sy(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(sx(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new dv({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new wy("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new wy("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new wy("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new wy("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new vy("Legacy serialization format not supported yet.");r=t}else ie(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),r=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof gv))throw new ky(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of r){const t=hw(e,void 0,s);s&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new vy("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new vy("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function yv(e){return new dv(e)}function bv(e){return new gv(e)}function xv(e){return yx(e)}function wv(e,t){uw.registerCallbackConstructor(e,t)}gv.className="Sequential",Yo(gv);class vv extends Ko{getConfig(){return{}}}class kv extends vv{apply(e,t=1){return function(e,t=1){if(1!==t)throw new ky(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return eh(e)}(e,t)}}kv.className="elu",Yo(kv);class Iv extends vv{apply(e){return Vd(e)}}Iv.className="selu",Yo(Iv);class Nv extends vv{apply(e){return Fd(e)}}Nv.className="relu",Yo(Nv);class Sv extends vv{apply(e){return hi((()=>ed(6,Fd(e))))}}Sv.className="relu6",Yo(Sv);class Tv extends vv{apply(e){return e}}Tv.className="linear",Yo(Tv);class Cv extends vv{apply(e){return fc(e)}}Cv.className="sigmoid",Yo(Cv);class $v extends vv{apply(e){return function(e){return hi((()=>{const t=Ao(.5,Do(.2,e));return $c(t,0,1)}))}(e)}}$v.className="hardSigmoid",Yo($v);class Ev extends vv{apply(e){return Mh(e)}}Ev.className="softplus",Yo(Ev);class Rv extends vv{apply(e){return function(e){return hi((()=>Fo(e,Ao(al(e),1))))}(e)}}Rv.className="softsign",Yo(Rv);class Av extends vv{apply(e){return gc(e)}}Av.className="tanh",Yo(Av);class _v extends vv{apply(e,t=-1){return Jd(e,t)}}_v.className="softmax",Yo(_v);class Fv extends vv{apply(e,t=-1){return zh(e,t)}}Fv.className="logSoftmax",Yo(Fv);class Dv extends vv{apply(e){return hi((()=>hi((()=>{const t=Math.sqrt(2),n=Do(.5,Ao(1,nh(Fo(e,t))));return Do(e,n)}))))}}Dv.className="gelu",Yo(Dv);class Ov extends vv{apply(e){return hi((()=>Do(.5,Do(e,Ao(1,gc(Do(Oo(Fo(2,Math.PI)),Ao(e,Do(.044715,nl(e,3))))))))))}}Ov.className="gelu_new",Yo(Ov);class Mv extends vv{apply(e){return hi((()=>Do(e,gc(Mh(e)))))}}Mv.className="mish",Yo(Mv);class Lv extends vv{apply(e,t=1){return hi((()=>Do(fc(Do(e,t)),e)))}}function zv(e){return e.getClassName()}function Pv(e,t={}){return Oy(e,Xo.getMap().classNameMap,t,"activation")}function Bv(e){if(null==e){const e={className:"linear",config:{}};return Pv(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Pv(t)}return e instanceof vv?e:Pv(e)}function Wv(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}Lv.className="swish",Yo(Lv);class Vv extends Ko{}class Uv extends Vv{constructor(e){super(),Wv(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return hi((()=>{let t=Zh([1]);return this.hasL1&&(t=Ao(t,ph(Do(this.l1,al(e))))),this.hasL2&&(t=Ao(t,ph(Do(this.l2,Cb(e))))),cc(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Uv.className="L1L2",Yo(Uv);const Gv={l1l2:"L1L2"};function Hv(e){return Fy(e)}function jv(e,t={}){return Oy(e,Xo.getMap().classNameMap,t,"regularizer")}function qv(e){if(null==e)return null;if("string"==typeof e){return jv({className:e in Gv?Gv[e]:e,config:{}})}return e instanceof Vv?e:jv(e)}class Kv extends fx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=nx(e);let n=Fd(e);return null!=this.maxValue&&(n=$c(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Kv.className="ReLU",Yo(Kv);class Xv extends fx{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=nx(e);return Eh(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Xv.className="LeakyReLU",Yo(Xv);class Yv extends fx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Qb(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=qv(e.alphaRegularizer),this.alphaConstraint=Dx(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new vy(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=sx(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new ux({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=nx(e),gd(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Jb(this.alphaInitializer),alphaRegularizer:Hv(this.alphaRegularizer),alphaConstraint:_x(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Yv.className="PReLU",Yo(Yv);class Zv extends fx{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new ky(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=nx(e);return eh(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Zv.className="ELU",Yo(Zv);class Jv extends fx{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=nx(e);return Do(n,$o(Nh(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Jv.className="ThresholdedReLU",Yo(Jv);class Qv extends fx{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new _v).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return hi((()=>{let n=nx(e);const s=t.mask;if(null!=s){const e=Do(sl(Jh(n.shape),$o(s,n.dtype)),Ho(-1e9));n=Ao(n,e)}return this.axis instanceof Array?this.axis.length>1?yh(sl(n,Ph(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)}))}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function ek(e,t,n){if("number"==typeof e)return Sy(e,t);if(e.length!==t)throw new vy(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let r=0;r<t;++r){const a=e[r];if((s=a)!==parseInt(s.toString(),10))throw new vy(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e;var s}function tk(e,t,n,s,r=1){if(null==e)return e;let a;return a="same"===n?e:e-(t+(t-1)*(r-1))+1,Math.floor((a+s-1)/s)}function nk(e,t,n,s){if(null==e)return null;if("valid"===s)e=e*t+db([n-t,0]);else{if("same"!==s)throw new vy(`Unsupport padding mode: ${s}.`);e*=t}return e}function sk(e,t){return hi((()=>(eb(t),"channelsFirst"===t?Bl(e,[0,2,3,1]):e)))}function rk(e,t){return hi((()=>(eb(t),"channelsFirst"===t?Bl(e,[0,2,3,4,1]):e)))}function ak(e,t,n,s=1,r="valid",a,i=1){return hi((()=>{if(null==a&&(a="channelsLast"),eb(a),3!==e.shape.length)throw new vy(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new vy(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new vy(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===a&&(e=Bl(e,[0,2,1])),"causal"===r)throw new ky("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Dc(e,t,s,"same"===r?"same":"valid","NWC",i);return null!=n&&(o=Eb(o,n)),o}))}function ik(e,t,n,s=[1,1],r="valid",a,i,o=null){return hi((()=>{if(null==a&&(a="channelsLast"),eb(a),3!==e.rank&&4!==e.rank)throw new vy(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new vy(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=sk(e,a);if("causal"===r)throw new ky("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Pp({x:l,filter:t,strides:s,pad:"same"===r?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(l=Bl(l,[0,3,1,2])),l}))}function ok(e,t,n,s=[1,1,1],r="valid",a,i){return hi((()=>{if(null==a&&(a="channelsLast"),eb(a),4!==e.rank&&5!==e.rank)throw new vy(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new vy(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=rk(e,a);if("causal"===r)throw new ky("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Lc(o,t,s,"same"===r?"same":"valid","NDHWC",i),null!=n&&(o=Eb(o,n)),"channelsFirst"===a&&(o=Bl(o,[0,4,1,2,3])),o}))}Qv.className="Softmax",Yo(Qv);class lk extends fx{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",lk.verifyArgs(t),this.rank=e,Wy(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new ky(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=ek(t.kernelSize,e,"kernelSize"),this.strides=ek(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,tb(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,eb(this.dataFormat),this.activation=Bv(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=Qb(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Dx(t.biasConstraint),this.biasRegularizer=qv(t.biasRegularizer),this.activityRegularizer=qv(t.activityRegularizer),this.dilationRate=ek(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new vy(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new vy(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new vy(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ty("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!By(e.kernelSize,"number",1,3))throw new vy(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:zv(this.activation),useBias:this.useBias,biasInitializer:Jb(this.biasInitializer),biasRegularizer:Hv(this.biasRegularizer),activityRegularizer:Hv(this.activityRegularizer),biasConstraint:_x(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class uk extends lk{constructor(e,t){super(e,t),this.kernel=null,uk.verifyArgs(t),this.filters=t.filters,Wy(this.filters,"filters"),this.kernelInitializer=Qb(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Dx(t.kernelConstraint),this.kernelRegularizer=qv(t.kernelRegularizer)}build(e){e=sx(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new vy(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return hi((()=>{let t;e=nx(e);const n=null==this.bias?null:this.bias.read(),s=Uy(this.activation.getClassName());if(null!=s&&2===this.rank)t=ik(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(1===this.rank)t=ak(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ik(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new ky("convolutions greater than 3D are not implemented yet.");t=ok(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=sx(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const s=tk(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(s)}let s=[e[0]];return"channelsLast"===this.dataFormat?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){const e={filters:this.filters,kernelInitializer:Jb(this.kernelInitializer),kernelRegularizer:Hv(this.kernelRegularizer),kernelConstraint:_x(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new vy(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class ck extends uk{constructor(e){super(2,e),ck.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!By(e.kernelSize,"number",1,2))throw new vy(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}ck.className="Conv2D",Yo(ck);class hk extends uk{constructor(e){super(3,e),hk.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new vy(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}hk.className="Conv3D",Yo(hk);class dk extends ck{constructor(e){if(super(e),this.inputSpec=[new ux({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new vy(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=sx(e)).length)throw new vy("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new vy("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"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 ux({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return hi((()=>{let t=nx(e);if(4!==t.shape.length)throw new vy(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a;"channelsFirst"===this.dataFormat?(r=2,a=3):(r=1,a=2);const i=n[r],o=n[a],l=this.kernelSize[0],u=this.kernelSize[1],c=this.strides[0],h=this.strides[1],d=[s,nk(i,c,l,this.padding),nk(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Bl(t,[0,2,3,1]));let p=Mc(t,this.kernel.read(),d,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(p=Bl(p,[0,3,1,2])),null!=this.bias&&(p=Eb(p,this.bias.read(),this.dataFormat)),null!=this.activation&&(p=this.activation.apply(p)),p}))}computeOutputShape(e){const t=(e=sx(e)).slice();let n,s,r;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3):(n=3,s=1,r=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=nk(t[s],o,a,this.padding),t[r]=nk(t[r],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}dk.className="Conv2DTranspose",Yo(dk);class pk extends hk{constructor(e){if(super(e),this.inputSpec=[new ux({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new vy(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=sx(e)).length)throw new vy("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new vy("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"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 ux({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return hi((()=>{let t=nx(e);if(5!==t.shape.length)throw new vy(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a,i;"channelsFirst"===this.dataFormat?(i=2,r=3,a=4):(i=1,r=2,a=3);const o=n[i],l=n[r],u=n[a],c=this.kernelSize[0],h=this.kernelSize[1],d=this.kernelSize[2],p=this.strides[0],f=this.strides[1],m=this.strides[2],g=[s,nk(o,p,c,this.padding),nk(l,f,h,this.padding),nk(u,m,d,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Bl(t,[0,2,3,4,1]));let y=Pc(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=Bl(y,[0,4,1,2,3])),null!==this.bias&&(y=Eb(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=sx(e)).slice();let n,s,r,a;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);const i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],c=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[s]=nk(t[s],u,i,this.padding),t[r]=nk(t[r],c,o,this.padding),t[a]=nk(t[a],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}pk.className="Conv3DTranspose",Yo(pk);class fk extends uk{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new vy("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new vy("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new vy(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=Qb(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=qv(t.depthwiseRegularizer),this.depthwiseConstraint=Dx(t.depthwiseConstraint),this.pointwiseInitializer=Qb(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=qv(t.pointwiseRegularizer),this.pointwiseConstraint=Dx(t.pointwiseConstraint)}build(e){if((e=sx(e)).length<this.rank+2)throw new vy(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new vy(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],s=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let e=0;e<this.rank;++e)r.push(1);r.push(n*this.depthMultiplier,this.filters);const a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new ux({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return hi((()=>{let t;if(e=nx(e),1===this.rank)throw new ky("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=Bl(e,[0,2,3,1])),t=Ud(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Eb(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=Bl(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Jb(this.depthwiseInitializer),e.pointwiseInitializer=Jb(this.pointwiseInitializer),e.depthwiseRegularizer=Hv(this.depthwiseRegularizer),e.pointwiseRegularizer=Hv(this.pointwiseRegularizer),e.depthwiseConstraint=_x(this.depthwiseConstraint),e.pointwiseConstraint=_x(this.pointwiseConstraint),e}}fk.className="SeparableConv";class mk extends fk{constructor(e){super(2,e)}}mk.className="SeparableConv2D",Yo(mk);class gk extends uk{constructor(e){super(1,e),gk.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!By(e.kernelSize,"number",1,1))throw new vy(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}gk.className="Conv1D",Yo(gk);class yk extends fx{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[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 hi((()=>{if(e=nx(e),"channelsLast"===this.dataFormat){const t=wb(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return wb(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=wb(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return wb(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}yk.className="Cropping2D",Yo(yk);class bk extends fx{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,eb(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Py(Xy,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return hi((()=>{let t=nx(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=Bl(t,[0,2,3,1]);const e=this.size[0]*n[2],s=this.size[1]*n[3],r="nearest"===this.interpolation?Gf.resizeNearestNeighbor(t,[e,s]):Gf.resizeBilinear(t,[e,s]);return Bl(r,[0,3,1,2])}{const e=this.size[0]*n[1],s=this.size[1]*n[2];return"nearest"===this.interpolation?Gf.resizeNearestNeighbor(t,[e,s]):Gf.resizeBilinear(t,[e,s])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}bk.className="UpSampling2D",Yo(bk);class xk extends lk{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Qb(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Dx(e.depthwiseConstraint),this.depthwiseRegularizer=qv(e.depthwiseRegularizer)}build(e){if((e=sx(e)).length<4)throw new vy(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new vy(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,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 hi((()=>{let t=function(e,t,n=[1,1],s="valid",r,a){return hi((()=>{null==r&&(r="channelsLast"),eb(r);let i=sk(e,r);if(4!==e.rank)throw new vy(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new vy(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=jc(i,t,n,"same"===s?"same":"valid","NHWC",a),"channelsFirst"===r&&(i=Bl(i,[0,3,1,2])),i}))}(e=nx(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Eb(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=sx(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=tk(t,this.kernelSize[0],this.padding,this.strides[0]),a=tk(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Jb(this.depthwiseInitializer),e.depthwiseRegularizer=Hv(this.depthwiseRegularizer),e.depthwiseConstraint=_x(this.depthwiseRegularizer),e}}function wk(e,t,n,s){if(Array.isArray(e)){if(null!=t||null!=n)throw new vy("When inputs is an array, neither initialState or constants should be provided");null!=s&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=r(t),constants:n=r(n)}}function vk(e,t,n,s=!1,r,a,i=!1,o=!1){return hi((()=>{const l=t.shape.length;if(l<3)throw new vy(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(pb(2,l));if(t=Bl(t,u),null!=a)throw new ky("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."),null!=r&&((r=$o($o(r,"bool"),"float32")).rank===l-1&&(r=bh(r,-1)),r=Bl(r,u)),s&&(t=Od(t,0),null!=r&&(r=Od(r,0)));const c=[];let h,d=n;const p=t.shape[0],f=wp(t);let m,g;null!=r&&(m=wp(r));for(let t=0;t<p;++t){const n=f[t],s=hi((()=>e(n,d)));if(null==r)h=s[0],d=s[1];else{const e=hi((()=>{const e=m[t],n=sl(od(e),e);return{output:Ao(Do(s[0],e),Do(d[0],n)),newStates:d.map(((t,r)=>Ao(Do(s[1][r],e),Do(t,n))))}}));h=e.output,d=e.newStates}o&&c.push(h)}if(o){g=ip(c,1)}return[h,g,d]}))}xk.className="DepthwiseConv2D",Yo(xk);class kk extends fx{constructor(e){let t;if(super(e),null==e.cell)throw new vy("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Rk({cells:e.cell}):e.cell,null==t.stateSize)throw new vy("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new ux({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return pb(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){ex(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(s=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const s of t)n.push([e[0],s]);return[s].concat(n)}return s}computeMask(e,t){return hi((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new ky("Constants support is not implemented in RNN yet.");ex(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new ux({shape:[t,null,...n]});const s=[e[0]].concat(e.slice(2));let r;if(this.cell.build(s),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!de(this.stateSpec.map((e=>e.shape[e.shape.length-1])),r))throw new vy(`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=r.map((e=>new ux({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){hi((()=>{if(!this.stateful)throw new xy("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new vy("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(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Zh([n,e]))):this.states_=[Zh([n,this.cell.stateSize])];else if(null==e)di(this.states_),null!=this.keptStates&&(di(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Zh([n,e]))):this.states_[0]=Zh([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new vy(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):di(this.states_);for(let t=0;t<this.states_.length;++t){const s=e[t],r=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,a=[n,r];if(!de(s.shape,a))throw new vy(`State ${t} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${s.shape}`);this.states_[t]=s}}this.states_=this.states_.map((e=>pi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=wk(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],i=[];if(null!=n){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new ux({shape:e.shape}));i=i.concat(this.stateSpec)}null!=s&&(t.constants=s,a=a.concat(s),this.numConstants=s.length);if(a[0]instanceof cx){const n=[e].concat(a),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return hi((()=>{const n=null==t?null:t.mask,s=null==t?null:t.training;let r=null==t?null:t.initialState;e=nx(e),null==r&&(r=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new vy(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:s},o=vk(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],c=o[2];this.stateful&&this.resetStates(c,s);const h=this.returnSequences?u:l;return this.returnState?[h].concat(c):h}))}getInitialState(e){return hi((()=>{let t=Zh(e.shape);return t=ph(t,[1,2]),t=yb(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ib(t,[1,e]):t)):this.cell.stateSize>1?[Ib(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===kk.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const s=hw(t.cell,n);return new e(Object.assign(t,{cell:s}))}}kk.className="RNN",Yo(kk);class Ik extends fx{}class Nk extends Ik{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,Wy(this.units,"units"),this.activation=Bv(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Qb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Qb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Qb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=qv(e.kernelRegularizer),this.recurrentRegularizer=qv(e.recurrentRegularizer),this.biasRegularizer=qv(e.biasRegularizer),this.kernelConstraint=Dx(e.kernelConstraint),this.recurrentConstraint=Dx(e.recurrentConstraint),this.biasConstraint=Dx(e.biasConstraint),this.dropout=hb([1,db([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hb([1,db([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=sx(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 hi((()=>{if(2!==e.length)throw new vy(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=null!=t.training&&t.training;let r;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ak({ones:()=>od(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ak({ones:()=>od(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;r=Sb(null!=a?Do(e,a):e,this.kernel.read()),null!=this.bias&&(r=Eb(r,this.bias.read())),null!=i&&(n=Do(n,i));let o=Ao(r,Sb(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:zv(this.activation),useBias:this.useBias,kernelInitializer:Jb(this.kernelInitializer),recurrentInitializer:Jb(this.recurrentInitializer),biasInitializer:Jb(this.biasInitializer),kernelRegularizer:Hv(this.kernelRegularizer),recurrentRegularizer:Hv(this.recurrentRegularizer),biasRegularizer:Hv(this.biasRegularizer),activityRegularizer:Hv(this.activityRegularizer),kernelConstraint:_x(this.kernelConstraint),recurrentConstraint:_x(this.recurrentConstraint),biasConstraint:_x(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}Nk.className="SimpleRNNCell",Yo(Nk);class Sk extends kk{constructor(e){e.cell=new Nk(e),super(e)}call(e,t){return hi((()=>{null!=this.cell.dropoutMask&&(di(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(di(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return new e(t)}}Sk.className="SimpleRNN",Yo(Sk);class Tk extends Ik{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 vy("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Wy(this.units,"units"),this.activation=Bv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Bv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Qb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Qb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Qb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=qv(e.kernelRegularizer),this.recurrentRegularizer=qv(e.recurrentRegularizer),this.biasRegularizer=qv(e.biasRegularizer),this.kernelConstraint=Dx(e.kernelConstraint),this.recurrentConstraint=Dx(e.recurrentConstraint),this.biasConstraint=Dx(e.biasConstraint),this.dropout=hb([1,db([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hb([1,db([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=sx(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return hi((()=>{if(2!==e.length)throw new vy(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ak({ones:()=>od(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ak({ones:()=>od(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,l;0<this.dropout&&this.dropout<1&&(e=Do(e,r[0]));let u=Sb(e,this.kernel.read());this.useBias&&(u=Eb(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=Do(s,a[0]));const c=this.recurrentKernel.read(),[h,d]=np(c,[2*this.units,this.units],c.rank-1),p=Sb(s,h),[f,m,g]=np(u,3,u.rank-1),[y,b]=np(p,2,p.rank-1);i=this.recurrentActivation.apply(Ao(f,y)),o=this.recurrentActivation.apply(Ao(m,b));const x=Sb(Do(o,s),d);l=this.activation.apply(Ao(g,x));const w=Ao(Do(i,s),Do(Ao(1,zl(i)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:zv(this.activation),recurrentActivation:zv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Jb(this.kernelInitializer),recurrentInitializer:Jb(this.recurrentInitializer),biasInitializer:Jb(this.biasInitializer),kernelRegularizer:Hv(this.kernelRegularizer),recurrentRegularizer:Hv(this.recurrentRegularizer),biasRegularizer:Hv(this.biasRegularizer),activityRegularizer:Hv(this.activityRegularizer),kernelConstraint:_x(this.kernelConstraint),recurrentConstraint:_x(this.recurrentConstraint),biasConstraint:_x(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Tk.className="GRUCell",Yo(Tk);class Ck extends kk{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Tk(e),super(e)}call(e,t){return hi((()=>{null!=this.cell.dropoutMask&&(di(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(di(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Ck.className="GRU",Yo(Ck);class $k extends Ik{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,Wy(this.units,"units"),this.activation=Bv(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Bv(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Qb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Qb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Qb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=qv(e.kernelRegularizer),this.recurrentRegularizer=qv(e.recurrentRegularizer),this.biasRegularizer=qv(e.biasRegularizer),this.kernelConstraint=Dx(e.kernelConstraint),this.recurrentConstraint=Dx(e.recurrentConstraint),this.biasConstraint=Dx(e.biasConstraint),this.dropout=hb([1,db([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hb([1,db([0,null==e.recurrentDropout?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;const n=(e=sx(e))[e.length-1];let s;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;s=new((t=class extends Db{apply(t,s){const r=e.apply([n]),a=(new Mb).apply([n]),i=e.apply([2*n]);return kb(kb(r,a),i)}}).className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return hi((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new vy(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ak({ones:()=>od(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ak({ones:()=>od(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,l,u,c;0<this.dropout&&this.dropout<1&&(e=Do(e,a[0]));let h=Sb(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=Do(s,i[0])),h=Ao(h,Sb(s,this.recurrentKernel.read())),this.useBias&&(h=Eb(h,this.bias.read()));const[d,p,f,m]=np(h,4,h.rank-1);o=this.recurrentActivation.apply(d),l=this.recurrentActivation.apply(p),u=Ao(Do(l,r),Do(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=Do(c,this.activation.apply(u));return[g,g,u]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:zv(this.activation),recurrentActivation:zv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Jb(this.kernelInitializer),recurrentInitializer:Jb(this.recurrentInitializer),biasInitializer:Jb(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Hv(this.kernelRegularizer),recurrentRegularizer:Hv(this.recurrentRegularizer),biasRegularizer:Hv(this.biasRegularizer),activityRegularizer:Hv(this.activityRegularizer),kernelConstraint:_x(this.kernelConstraint),recurrentConstraint:_x(this.recurrentConstraint),biasConstraint:_x(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}$k.className="LSTMCell",Yo($k);class Ek extends kk{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new $k(e),super(e)}call(e,t){return hi((()=>{null!=this.cell.dropoutMask&&(di(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(di(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Ek.className="LSTM",Yo(Ek);class Rk extends Ik{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return hi((()=>{let n=e.slice(1);const s=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?s.push(n.splice(0,e.stateSize.length)):s.push(n.splice(0,1));s.reverse();const r=[];let a;for(let i=0;i<this.cells.length;++i){const o=this.cells[i];n=s[i],a=0===i?[e[0]].concat(n):[a[0]].concat(n),a=o.call(a,t),r.push(a.slice(1))}n=[];for(const e of r.slice().reverse())n.push(...e);return[a[0]].concat(n)}))}build(e){let t;ex(e)&&(e=e[0]),this.cells.forEach(((n,s)=>{ab(`RNNCell_${s}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const s=[];for(const e of t.cells)s.push(hw(e,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return ox(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,r=e.splice(s);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],r[e]])}lx(t)}}function Ak(e){const{ones:t,rate:n,training:s=!1,count:r=1,dropoutFunc:a}=e,i=()=>null!=a?a(t(),n):Rb(t(),n),o=()=>Ab(i,t,s);if(!r||r<=1)return pi(o().clone());return Array(r).fill(void 0).map(o).map((e=>pi(e.clone())))}Rk.className="StackedRNNCells",Yo(Rk);var _k=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]])}return n};class Fk extends kk{constructor(e){if(e.unroll)throw new ky("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ky("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new ux({ndim:5})]}call(e,t){return hi((()=>{if(null!=this.cell.dropoutMask&&(di(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(di(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new vy("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,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 hi((()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=Zh([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(r):[r]}))}resetStates(e,t=!1){hi((()=>{if(!this.stateful)throw new xy("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(null==n[0])throw new vy("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(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Zh(r))):this.states_=[Zh(r)];else if(null==e)di(this.states_),null!=this.keptStates&&(di(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Zh(r))):this.states_[0]=Zh(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new vy(`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()):di(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],s=r;if(!de(n.shape,s))throw new vy(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>pi(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,l=e[o?3:2],u=e[o?4:3],c=tk(l,s[0],r,a[0],i[0]),h=tk(u,s[1],r,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}Fk.className="ConvRNN2D";class Dk extends $k{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Wy(this.filters,"filters"),this.kernelSize=ek(n,2,"kernelSize"),this.kernelSize.forEach((e=>Wy(e,"kernelSize"))),this.strides=ek(s||1,2,"strides"),this.strides.forEach((e=>Wy(e,"strides"))),this.padding=r||"valid",tb(this.padding),this.dataFormat=a||"channelsLast",eb(this.dataFormat),this.dilationRate=ek(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Wy(e,"dilationRate")))}build(e){var t;e=sx(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new vy(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],r=this.kernelSize.concat([s,4*this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,s=this.filters;e=new((t=class extends Db{apply(e,t){return vb([n.apply([s]),Jh([s]),n.apply([2*s])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return hi((()=>{if(3!==e.length)throw new vy(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],r=e[1],a=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ak({ones:()=>od(s),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?Do(t[n],e):e;let l=o(s,i,0),u=o(s,i,1),c=o(s,i,2),h=o(s,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ak({ones:()=>od(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const d=this.recurrentDropoutMask;let p=o(r,d,0),f=o(r,d,1),m=o(r,d,2),g=o(r,d,3);const[y,b,x,w]=np(this.kernel.read(),4,3),[v,k,I,N]=this.useBias?np(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,y,v,this.padding),u=this.inputConv(u,b,k,this.padding),c=this.inputConv(c,x,I,this.padding),h=this.inputConv(h,w,N,this.padding);const[S,T,C,$]=np(this.recurrentKernel.read(),4,3);p=this.recurrentConv(p,S),f=this.recurrentConv(f,T),m=this.recurrentConv(m,C),g=this.recurrentConv(g,$);const E=this.recurrentActivation.apply(Ao(l,p)),R=this.recurrentActivation.apply(Ao(u,f)),A=Ao(Do(R,a),Do(E,this.activation.apply(Ao(c,m)))),_=Do(this.recurrentActivation.apply(Ao(h,g)),this.activation.apply(A));return[_,_,A]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=_k(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),s)}inputConv(e,t,n,s){const r=Fc(e,t,this.strides,s||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Eb(r,n,this.dataFormat):r}recurrentConv(e,t){return Fc(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Dk.className="ConvLSTM2DCell",Yo(Dk);class Ok extends Fk{constructor(e){const t=new Dk(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}Ok.className="ConvLSTM2D",Yo(Ok);class Mk extends fx{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(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,s=this.getNoiseShape(n);return Ab((()=>Rb(n,this.rate,s,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Mk.className="Dropout",Yo(Mk);class Lk extends Mk{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Lk.className="SpatialDropout1D",Yo(Lk);class zk extends fx{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",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Wy(this.units,"units"),this.activation=Bv(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=Qb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Qb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Dx(e.kernelConstraint),this.biasConstraint=Dx(e.biasConstraint),this.kernelRegularizer=qv(e.kernelRegularizer),this.biasRegularizer=qv(e.biasRegularizer),this.activityRegularizer=qv(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=sx(e))[e.length-1];null==this.kernel&&(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){const t=(e=sx(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e),s=Uy(this.activation.getClassName());let r;return null!=s?r=Sb(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Sb(n,this.kernel.read()),null!=this.bias&&(r=Eb(r,this.bias.read())),null!=this.activation&&(r=this.activation.apply(r))),r}))}getConfig(){const e={units:this.units,activation:zv(this.activation),useBias:this.useBias,kernelInitializer:Jb(this.kernelInitializer),biasInitializer:Jb(this.biasInitializer),kernelRegularizer:Hv(this.kernelRegularizer),biasRegularizer:Hv(this.biasRegularizer),activityRegularizer:Hv(this.activityRegularizer),kernelConstraint:_x(this.kernelConstraint),biasConstraint:_x(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}zk.className="Dense",Yo(zk);class Pk extends fx{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=sx(e);for(const t of e.slice(1))if(null==t)throw new vy(`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],cb(e,1)]}call(e,t){return hi((()=>{this.invokeCallHook(e,t);let n=nx(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=Bl(n,e)}return function(e){if(e.rank<=1)throw new vy(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],cb(e.shape,1)];return cc(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Pk.className="Flatten",Yo(Pk);class Bk extends fx{constructor(e){super(e),this.supportsMasking=!0,this.activation=Bv(e.activation)}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e);return this.activation.apply(n)}))}getConfig(){const e={activation:zv(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Bk.className="Activation",Yo(Bk);class Wk extends fx{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 hi((()=>{return e=nx(e),t=e,n=this.n,hi((()=>{if(2!==t.shape.length)throw new vy(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ib(yb(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Wk.className="RepeatVector",Yo(Wk);class Vk extends fx{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",s=t.slice();let r=1,a=null;for(let e=0;e<s.length;++e){const t=s[e];if(this.isUnknown(t)){if(null!==a)throw new vy("Can only specifiy one unknown dimension.");a=e}else r*=t}const i=cb(e);if(null!==a){if(0===r||i%r!=0)throw new vy(n);s[a]=i/r}else if(i!==r)throw new vy(n);return s}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 hi((()=>{this.invokeCallHook(e,t);const n=nx(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return cc(n,r)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Vk.className="Reshape",Yo(Vk);class Uk extends fx{constructor(e){if(super(e),null==e.dims)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.`);const t=pb(1,e.dims.length+1);if(!de(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 ux({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=sx(e)).slice();return this.dims.forEach(((n,s)=>{t[s+1]=e[n]})),t}call(e,t){return Bl(nx(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Uk.className="Permute",Yo(Uk);class Gk extends fx{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=nx(e);return Wu(id(n,this.maskValue),-1)}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e),s=Wu(id(n,this.maskValue),-1,!0);return Do(n,$o(s,n.dtype))}))}}Gk.className="Masking",Yo(Gk);class Hk extends fx{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Ey(e.inputLength))}this.inputDim=e.inputDim,Wy(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Wy(this.outputDim,"outputDim"),this.embeddingsInitializer=Qb(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=qv(e.embeddingsRegularizer),this.activityRegularizer=qv(e.activityRegularizer),this.embeddingsConstraint=Dx(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 hi((()=>this.maskZero?(e=nx(e),id(e,Lo(e))):null))}computeOutputShape(e){if(e=sx(e),null==this.inputLength)return[...e,this.outputDim];const t=Ey(this.inputLength);if(t.length!==e.length-1)throw new vy(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s<t.length;++s){const r=t[s],a=e[s+1];if(null!=r&&null!=a&&r!==a)throw new vy(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==r&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return hi((()=>{this.invokeCallHook(e,t);let n=nx(e);"int32"!==n.dtype&&(n=gb(n,"int32"));const s=Tb(this.embeddings.read(),cc(n,[n.size]));return cc(s,sx(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Jb(this.embeddingsInitializer),embeddingsRegularizer:Hv(this.embeddingsRegularizer),activityRegularizer:Hv(this.activityRegularizer),embeddingsConstraint:_x(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Hk.className="Embedding",Yo(Hk);class jk extends fx{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new ky}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){const r=e[e.length-t.length+s],a=t[s];if(null==r||null==a||r<0||a<0)n.push(null);else if(1===r)n.push(a);else if(1===a)n.push(r);else{if(r!==a)throw new vy("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=[sx(e)]),e.length<2)throw new vy(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=Ly(t),t.length>1)throw new vy(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const s=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}const s=e.map((e=>e.length));-1===e.indexOf(null)&&1===Ly(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return hi((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const s=db(n);for(let n of e){const e=n.rank;for(let t=0;t<s-e;++t)n=yb(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const s of e){const e=s.rank;if(null==e){const e=s.shape,r=e[0],a=e.slice(1).concat([r]);let i=cc(s,[r].concat(cb(e.slice(1))));i=Bl(i,[1,0]),i=cc(i,a),t.push(i),n=!0}else if(e>1){const r=pb(1,e).concat([0]);t.push(Bl(s,r)),n=!0}else t.push(s)}let s=this.mergeFunction(t);const r=s.rank;if(n)if(null==r){const e=s.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));s=cc(Bl(cc(s,[-1,t]),[1,0]),n)}else if(r>1){const e=[r-1].concat(pb(0,r-1));s=Bl(s,e)}return s}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const s=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=Ly(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return hi((()=>{if(null==t)return null;if(!Array.isArray(t))throw new vy("`mask` should be an Array");if(!Array.isArray(e))throw new vy("`inputs` should be an Array");if(t.length!==e.length)throw new vy(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:bh(e,0))))[0];for(let e=1;e<t.length-1;++e)n=Bh(n,t[e]);return n}))}}class qk extends jk{constructor(e){super(e)}mergeFunction(e){return hi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Ao(t,e[n]);return t}))}}qk.className="Add",Yo(qk);class Kk extends jk{constructor(e){super(e)}mergeFunction(e){return hi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Do(t,e[n]);return t}))}}Kk.className="Multiply",Yo(Kk);class Xk extends jk{constructor(e){super(e)}mergeFunction(e){return hi((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Ao(t,e[n]);return Do(1/e.length,t)}))}}Xk.className="Average",Yo(Xk);class Yk extends jk{constructor(e){super(e)}mergeFunction(e){return hi((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ul(t,e[n]);return t}))}}Yk.className="Maximum",Yo(Yk);class Zk extends jk{constructor(e){super(e)}mergeFunction(e){return hi((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ed(t,e[n]);return t}))}}Zk.className="Minimum",Yo(Zk);class Jk extends jk{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new vy("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const s=e[t].slice();s.splice(this.axis,1);let r=!1;for(const e of n)if(de(e,s)){r=!0;break}r||n.push(s)}if(n.length>1)throw new vy("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return hi((()=>vb(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new vy("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[s]||null==e[s]){n[s]=null;break}n[s]+=e[s]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new vy("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new vy("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new vy(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return hi((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const s=[];for(let n=0;n<e.length;++n)null==t[n]?s.push($o(od(e[n]),"bool")):t[n].rank<e[n].rank?s.push(bh(t[n],-1)):s.push(t[n]);const r=pc(s,this.axis);return Bu(r,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Qk(e,t){for(;e<0;)e+=t;return e}Jk.className="Concatenate",Yo(Jk);class eI extends jk{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new ky("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new vy(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(2!==e.length)throw new vy(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],s=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>Qk(t,e[n].shape.length))):[Qk(this.axes,n.shape.length),Qk(this.axes,s.shape.length)],this.normalize&&(n=dw(n,t[0]),s=dw(s,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new ky("batchDot is not implemented for tensors of 4D or higher rank yet");if(ie(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),ie(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new ky("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,r=t.shape.length;null==n&&(n=[s-1,r-2]);const a=n;return hi((()=>{let n,i;if(s>r){n=s-r;const e=[];for(let t=0;t<n;++t)e.push(1);t=cc(t,t.shape.concat(e))}else if(r>s){n=r-s;const t=[];for(let e=0;e<n;++e)t.push(1);e=cc(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=a[0]===a[1]?ph(Do(e,t),a[0]):ph(Do(Bl(e,[1,0]),t),a[1]);else{const n=a[0]!==e.shape.length-1,s=a[1]===t.shape.length-1;i=Ol(e,t,n,s)}if(n>0){let e;e=s>r?s+r-3:s-1;const t=[];for(let s=e;s<e+n;++s)t.push(s);i=ap(i,t)}return 1===i.shape.length&&(i=bh(i,1)),i}))}(n,s,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[Qk(this.axes,e.length),Qk(this.axes,t.length)],n}computeOutputShape(e){ie(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new ky("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const r=t.concat(n);return 1===r.length&&r.push(1),r}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}eI.className="Dot",Yo(eI);class tI extends fx{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e);return Ab((()=>Ao(Nb(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}tI.className="GaussianNoise",Yo(tI);class nI extends fx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return hi((()=>{this.invokeCallHook(e,t);const n=nx(e);if(this.rate>0&&this.rate<1){return Ab((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return Do(n,Nb(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}nI.className="GaussianDropout",Yo(nI);class sI extends fx{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||nx(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return hi((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const t=nx(e),s=-1.7580993408473766;let r=Sh(Ed(n),this.rate);r=gb(r,"float32");const a=((1-this.rate)*(1+this.rate*s**2))**-.5,i=-a*s*this.rate,o=Ao(Do(t,r),Do(Ao(r,-1),s));return Ao(Do(o,a),i)};return Ab(s,(()=>nx(e)),t.training||!1)}return e}))}}function rI(e,t,n,s,r,a=.001){let i;if(2===e.rank)i=wc(e,t,n,s,r,a);else if(3===e.rank)i=vc(e,t,n,s,r,a);else{if(4!==e.rank)throw new ky(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=kc(e,t,n,s,r,a)}return i}function aI(e,t,n,s,r=.001){return de(s.slice().sort(),pb(0,e.rank-1))?function(e,t,n,s,r=.001){return hi((()=>{const a=sd(e,s),i=a.mean,o=a.variance;return[rI(e,i,o,n,t,r),i,o]}))}(e,t,n,s,r):function(e,t,n,s,r=.001){return hi((()=>{const a=sd(e,s),i=a.mean,o=a.variance,l=[];for(const t of pb(0,e.rank))-1!==s.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=cc(i,l),c=cc(o,l),h=null==t?null:cc(t,l),d=null==n?null:cc(n,l);return[rI(e,u,c,d,h,r),i,o]}))}(e,t,n,s,r)}sI.className="AlphaDropout",Yo(sI);class iI extends fx{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Qb(e.betaInitializer||"zeros"),this.gammaInitializer=Qb(e.gammaInitializer||"ones"),this.movingMeanInitializer=Qb(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Qb(e.movingVarianceInitializer||"ones"),this.betaConstraint=Dx(e.betaConstraint),this.gammaConstraint=Dx(e.gammaConstraint),this.betaRegularizer=qv(e.betaRegularizer),this.gammaRegularizer=qv(e.gammaRegularizer)}build(e){e=sx(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new vy(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new ux({ndim:e.length,axes:{[t]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return hi((()=>{const n=null!=t.training&&t.training,s=nx(e),r=s.shape,a=r.length,i=pb(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const l=Sy(1,a);l[o]=r[o];const u=i.slice();u.sort();const c=!de(u,pb(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=cc(this.movingMean.read(),l),t=cc(this.movingVariance.read(),l),n=this.center?cc(this.beta.read(),l):null,r=this.scale?cc(this.gamma.read(),l):null;return rI(s,e,t,n,r,this.epsilon)}return rI(s,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,d,p]=aI(s,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{hi((()=>{const s=1-n,r=e.read(),a=Do(sl(r,t),s);e.write(sl(r,a))}))};return(()=>{f(this.movingMean,d,this.momentum),f(this.movingVariance,p,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Jb(this.betaInitializer),gammaInitializer:Jb(this.gammaInitializer),movingMeanInitializer:Jb(this.movingMeanInitializer),movingVarianceInitializer:Jb(this.movingVarianceInitializer),betaRegularizer:Hv(this.betaRegularizer),gammaRegularizer:Hv(this.gammaRegularizer),betaConstraint:_x(this.betaConstraint),gammaConstraint:_x(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}iI.className="BatchNormalization",Yo(iI);class oI extends fx{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=Qb(e.betaInitializer||"zeros"),this.gammaInitializer=Qb(e.gammaInitializer||"ones"),this.betaRegularizer=qv(e.betaRegularizer),this.gammaRegularizer=qv(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=sx(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==Ly(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t])),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){const n=nx(e),s=n.shape,r=s.length;return hi((()=>{let{mean:e,variance:t}=sd(n,this.axis,!0);const a=Sy(1,r);for(const e of this.axis)a[e]=s[e];const i=e=>null!=e&&e.shape.length!==r?cc(e,a):e;let o=this.scale?i(this.gamma.read()):null,l=this.center?i(this.beta.read()):null;const u=[],c=[];for(let e=0;e<r;++e)-1!==this.axis.indexOf(e)?(u.push(s[e]),c.push(1)):(u.push(1),c.push(s[e]));return e=wh(e,u),t=wh(t,u),null!=o&&(o=wh(o,c)),null!=l&&(l=wh(l,c)),rI(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Jb(this.betaInitializer),gammaInitializer:Jb(this.gammaInitializer),betaRegularizer:Hv(this.betaRegularizer),gammaRegularizer:Hv(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}oI.className="LayerNormalization",Yo(oI);class lI extends fx{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new vy(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new vy(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new vy(`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 ux({ndim:4})]}computeOutputShape(e){let t,n;return e=sx(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return hi((()=>{return t=nx(e),n=this.padding,s=this.dataFormat,hi((()=>{if(4!==t.rank)throw new vy(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new vy("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==s&&(s="channelsLast"),"channelsLast"!==s&&"channelsFirst"!==s)throw new vy(`Unknown data format: ${s}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===s?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],ud(t,e)}));var t,n,s}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function uI(e,t,n,s,r,a){return hi((()=>{let i;eb(r),nb(a),tb(s),null==n&&(n=[1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=sk(e,r);const o="same"===s?"same":"valid";return i="max"===a?qh(e,t,n,o):hc(e,t,n,o),"channelsFirst"===r&&(i=Bl(i,[0,3,1,2])),i}))}function cI(e,t,n,s,r,a){return hi((()=>{let i;eb(r),nb(a),tb(s),null==n&&(n=[1,1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=rk(e,r);const o="same"===s?"same":"valid";return i="max"===a?Kh(e,t,n,o):dc(e,t,n,o),"channelsFirst"===r&&(i=Bl(i,[0,4,1,2,3])),i}))}lI.className="ZeroPadding2D",Yo(lI);class hI extends fx{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new vy(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Wy(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new vy(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Wy(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,tb(this.padding),this.inputSpec=[new ux({ndim:3})]}computeOutputShape(e){const t=tk((e=sx(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return hi((()=>{this.invokeCallHook(e,t),e=yb(nx(e),2);const n=this.poolingFunction(nx(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return ap(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class dI extends hI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),uI(e,t,n,s,r,"max")}}dI.className="MaxPooling1D",Yo(dI);class pI extends hI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),uI(e,t,n,s,r,"avg")}}pI.className="AveragePooling1D",Yo(pI);class fI extends fx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new vy(`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];Wy(this.poolSize,"poolSize"),Wy(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,eb(this.dataFormat),tb(this.padding),this.inputSpec=[new ux({ndim:4})]}computeOutputShape(e){e=sx(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=tk(t,this.poolSize[0],this.padding,this.strides[0]),n=tk(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return hi((()=>(this.invokeCallHook(e,t),this.poolingFunction(nx(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class mI extends fI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),uI(e,t,n,s,r,"max")}}mI.className="MaxPooling2D",Yo(mI);class gI extends fI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),uI(e,t,n,s,r,"avg")}}gI.className="AveragePooling2D",Yo(gI);class yI extends fx{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new vy(`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];Wy(this.poolSize,"poolSize"),Wy(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,eb(this.dataFormat),tb(this.padding),this.inputSpec=[new ux({ndim:5})]}computeOutputShape(e){e=sx(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[4]:e[3];return t=tk(t,this.poolSize[0],this.padding,this.strides[0]),n=tk(n,this.poolSize[1],this.padding,this.strides[1]),s=tk(s,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return hi((()=>(this.invokeCallHook(e,t),this.poolingFunction(nx(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class bI extends yI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),cI(e,t,n,s,r,"max")}}bI.className="MaxPooling3D",Yo(bI);class xI extends yI{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return eb(r),tb(s),cI(e,t,n,s,r,"avg")}}xI.className="AveragePooling3D",Yo(xI);class wI extends fx{constructor(e){super(e),this.inputSpec=[new ux({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ky}}class vI extends wI{constructor(e){super(e||{})}call(e,t){return hi((()=>{const t=nx(e);return Yh(t,1)}))}}vI.className="GlobalAveragePooling1D",Yo(vI);class kI extends wI{constructor(e){super(e||{})}call(e,t){return hi((()=>{const t=nx(e);return hh(t,1)}))}}kI.className="GlobalMaxPooling1D",Yo(kI);class II extends fx{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,eb(this.dataFormat),this.inputSpec=[new ux({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ky}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class NI extends II{call(e,t){return hi((()=>{const t=nx(e);return"channelsLast"===this.dataFormat?Yh(t,[1,2]):Yh(t,[2,3])}))}}NI.className="GlobalAveragePooling2D",Yo(NI);class SI extends II{call(e,t){return hi((()=>{const t=nx(e);return"channelsLast"===this.dataFormat?hh(t,[1,2]):hh(t,[2,3])}))}}SI.className="GlobalMaxPooling2D",Yo(SI);class TI extends fx{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(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(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const s=hw(t.layer,n);delete t.layer;const r={layer:s};return Object.assign(r,t),new e(r)}}class CI extends TI{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=sx(e)).length<3)throw new vy(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=sx(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return hi((()=>vk(((e,n)=>[nx(this.layer.call(e,t)),[]]),e=nx(e),[],!1,null,null,!1,!0)[1]))}}CI.className="TimeDistributed",Yo(CI);class $I extends TI{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=hw(n),t.goBackwards=!0!==t.goBackwards;const s={};var r;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=hw(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,r=this.mergeMode,Py(Jy,"BidirectionalMergeMode",r),e.weights)throw new ky("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,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const 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,n,s,r=this.forwardLayer.computeOutputShape(e);return Array.isArray(r)&&Array.isArray(r[0])||(r=[r]),this.returnState?(s=r.slice(1),t=r[0]):t=r[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(s).concat(s.slice()):[t].concat(s).concat(s.slice()):$y(n)}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=wk(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==s)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new vy("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);const s=n.map((e=>new ux({shape:e.shape})));this.forwardLayer.stateSpec=s.slice(0,e/2),this.backwardLayer.stateSpec=s.slice(e/2),i.push(...s)}if(null!=s)throw new ky("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof cx;for(const e of a)if(e instanceof cx!==o)throw new vy("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(a),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return hi((()=>{const n=t.initialState;let s,r,a,i;if(null==n)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=Od(r,1)),"concat"===this.mergeMode?i=vb([s,r]):"sum"===this.mergeMode?i=Ao(s,r):"ave"===this.mergeMode?i=Do(.5,Ao(s,r)):"mul"===this.mergeMode?i=Do(s,r):null==this.mergeMode&&(i=[s,r]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){ab(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),ab(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}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),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=hw(t.layer);if(delete t.layer,null!=t.numConstants)throw new ky("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}$I.className="Bidirectional",Yo($I);class EI extends fx{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return hi((()=>("float32"!==(e=nx(e)).dtype&&(e=gb(e,"float32")),Ao(Do(e,this.scale),this.offset))))}}EI.className="Rescaling",Yo(EI);const{resizeBilinear:RI,cropAndResize:AI}=Gf;class _I extends fx{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,s,r,a,i,o){return hi((()=>{let l,u=!1;const c=[t/a,n/i,(s+t)/a,(r+n)/i],h=[];3===e.rank?(u=!0,l=ip([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(c);const d=ei(h,[h.length,4]),p=Ad(0,h.length,1,"int32"),f=AI(l,d,p,[s,r],"nearest");return gb(u?nx(wp(f)):f,o)}))}upsize(e,t,n,s){return hi((()=>gb(RI(e,[t,n]),s)))}call(e,t){return hi((()=>{const t=nx(e),n=t.dtype,s=t.shape,r=s[s.length-3],a=s[s.length-2];let i=0;r!==this.height&&(i=Math.floor((r-this.height)/2));let o=0;return a!==this.width&&(o=Math.floor((a-this.width)/2),0===o&&(o=1)),i>=0&&o>=0?this.centerCrop(t,i,o,this.height,this.width,r,a,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=sx(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}_I.className="CenterCrop",Yo(_I);class FI extends fx{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=sx(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return hi((()=>{let n;if("int32"!==(e=nx(e)).dtype&&(e=gb(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new vy(`countWeights is not used when outputMode !== count.\n Received countWeights=${t.countWeights}`);n=nx(t.countWeights)}const s=hh(e),r=dh(e),a=Nh(this.numTokens,s).bufferSync().get(0),i=Sh(r,0).bufferSync().get(0);if(!a||!i)throw new vy(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,s){let r=nx(e);if("int32"!==r.dtype&&(r=gb(r,"int32")),"int"===t)return r;const a=r.shape;if(0===r.rank&&(r=bh(r,-1)),"oneHot"===t&&1!==r.shape[r.shape.length-1]&&(r=bh(r,-1)),r.rank>2)throw new vy(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${a} which would result in output rank ${r.rank}.`);const i=["multiHot","oneHot"].includes(t),o=r;let l;if(l=Gc(o,void 0!==s&&"count"===t?s:[],n,i),"tfIdf"!==t)return l;if(s)return Do(l,s);throw new vy("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,n)}))}}FI.className="CategoryEncoding",Yo(FI);const DI=new Set(["bilinear","nearest"]);class OI extends fx{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!DI.has(e.interpolation))throw new vy(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){const t=(e=sx(e))[2];return[this.height,this.width,t]}getConfig(){const 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 hi((()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return Gf.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return Gf.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...DI]} are supported`)}))}}OI.className="Resizing",Yo(OI);class MI{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}MI.className="RandomSeed";class LI extends fx{constructor(e){super(e),this.randomGenerator=new MI(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}LI.className="BaseRandomLayer";const zI=new Set(["bilinear","nearest"]);class PI extends LI{constructor(e){super(e);const{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&2===this.factor.length)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new vy(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new vy(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new vy(`factor cannot have upper bound less than lower bound.\n Got upper bound: ${this.widthUpper}.\n Got lower bound: ${this.widthLower}\n `);if(n){if(!zI.has(n))throw new vy(`Invalid interpolation parameter: ${n} is not implemented`);this.interpolation=n}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=sx(e))[2];return[this.imgHeight,-1,t]}call(e,t){return hi((()=>{const t=nx(e);this.imgHeight=t.shape[t.shape.length-3];const n=t.shape[t.shape.length-2];this.widthFactor=Ed([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let s=this.widthFactor.dataSync()[0]*n;s=Math.round(s);const r=[this.imgHeight,s];switch(this.interpolation){case"bilinear":return Gf.resizeBilinear(e,r);case"nearest":return Gf.resizeNearestNeighbor(e,r);default:throw new Error(`Interpolation is ${this.interpolation}\n but only ${[...zI]} are supported`)}}))}}function BI(e){return new gx(e)}function WI(e){return new Zv(e)}function VI(e){return new Kv(e)}function UI(e){return new Xv(e)}function GI(e){return new Yv(e)}function HI(e){return new Qv(e)}function jI(e){return new Jv(e)}function qI(e){return new gk(e)}function KI(e){return new ck(e)}function XI(e){return new dk(e)}function YI(e){return new hk(e)}function ZI(e){return new pk(e)}function JI(e){return new mk(e)}function QI(e){return new yk(e)}function eN(e){return new bk(e)}function tN(e){return new xk(e)}function nN(e){return new Bk(e)}function sN(e){return new zk(e)}function rN(e){return new Mk(e)}function aN(e){return new Lk(e)}function iN(e){return new Pk(e)}function oN(e){return new Wk(e)}function lN(e){return new Vk(e)}function uN(e){return new Uk(e)}function cN(e){return new Hk(e)}function hN(e){return new qk(e)}function dN(e){return new Xk(e)}function pN(e){return new Jk(e)}function fN(e){return new Yk(e)}function mN(e){return new Zk(e)}function gN(e){return new Kk(e)}function yN(e){return new eI(e)}function bN(e){return new iI(e)}function xN(e){return new oI(e)}function wN(e){return new lI(e)}function vN(e){return new pI(e)}function kN(e){return vN(e)}function IN(e){return vN(e)}function NN(e){return new gI(e)}function SN(e){return NN(e)}function TN(e){return NN(e)}function CN(e){return new xI(e)}function $N(e){return CN(e)}function EN(e){return CN(e)}function RN(e){return new vI(e)}function AN(e){return new NI(e)}function _N(e){return new kI(e)}function FN(e){return new SI(e)}function DN(e){return new dI(e)}function ON(e){return new mI(e)}function MN(e){return new bI(e)}function LN(e){return new Ck(e)}function zN(e){return new Tk(e)}function PN(e){return new Ek(e)}function BN(e){return new $k(e)}function WN(e){return new Sk(e)}function VN(e){return new Nk(e)}function UN(e){return new Ok(e)}function GN(e){return new Dk(e)}function HN(e){return new kk(e)}function jN(e){return new Rk(e)}function qN(e){return new $I(e)}function KN(e){return new CI(e)}PI.className="RandomWidth",Yo(PI);const XN=_N,YN=FN,ZN=DN,JN=ON;function QN(e){return new tI(e)}function eS(e){return new nI(e)}function tS(e){return new sI(e)}function nS(e){return new Gk(e)}function sS(e){return new EI(e)}function rS(e){return new _I(e)}function aS(e){return new OI(e)}function iS(e){return new FI(e)}function oS(e){return new PI(e)}function lS(e,t){return Nw(e,t)}function uS(e,t){return Ew(e,t)}function cS(e,t){return Rw(e,t)}function hS(e,t){return Sw(e,t)}function dS(e,t){return Aw(e,t)}function pS(e,t){return Cw(e,t)}function fS(e,t){return $w(e,t)}function mS(e,t){return vw(e,t)}function gS(e,t){return fw(e,t)}function yS(e,t){return mw(e,t)}function bS(e,t){return mw(e,t)}function xS(e,t){return mw(e,t)}function wS(e,t){return pw(e,t)}function vS(e,t){return pw(e,t)}function kS(e,t){return pw(e,t)}function IS(e){return new Uv(e)}function NS(e){return Wv(t=e),new Uv({l1:null!=t?t.l1:null,l2:0});var t}function SS(e){return Wv(t=e),new Uv({l2:null!=t?t.l2:null,l1:0});var t}class TS extends sw{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof dv))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function CS(e,t){return e<t}function $S(e,t){return e>t}class ES extends TS{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new ky("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,-1===["auto","min","max"].indexOf(this.mode)&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),"min"===this.mode?this.monitorFunc=CS:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=$S:this.monitorFunc=CS,this.monitorFunc===CS&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===CS?1/0:-1/0}async onEpochEnd(e,t){await ew(t);const n=this.getMonitorValue(t);null!=n&&(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){null==e&&(e={});const t=e[this.monitor];return null==t&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const RS={earlyStopping:function(e){return new ES(e)}};var AS,_S;Xe().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.")})),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"}(AS||(AS={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(_S||(_S={}));const FS={};function DS(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};FS[e]=n}function OS(e){return FS[e]}function MS(e){delete FS[e]}function LS(e,t,n,s,r){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===a.type)return zS(t.inputNames[o],n,s,r);if("tensors"===a.type){const a=t.inputs.slice(e,i);return t.inputNames.slice(e,i).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=a[t])||void 0===n?void 0:n.op)})).map((e=>zS(e,n,s,r)))}const l=zS(t.inputNames[o],n,s,r),u=l.dataSync();return"number"===a.type?u[0]:Le(l.shape,u)}const i=t.attrParams[e];return i&&i.value}function zS(e,t,n,s){const[r,a]=VS(e,n);if(null!=s){const e=s.getHashTableHandleByName(r);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[WS(r,e)]));return void 0!==i?t[WS(r,i)][a]:void 0}function PS(e,t,n){return t[WS(e,n.currentContextId)]}function BS(e,t){const[n,s,r]=VS(e,t);return[WS(n,t&&t.currentContextId),s,r]}function WS(e,t){return t?`${e}-${t}`:e}function VS(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const s=e.split(":");let r;if(1===s.length)r=[e,0,void 0];else{const e=s[0],t=3===s.length?s[1]:void 0;r=[e,Number(s[s.length-1]),t]}return n&&t.parseNodeNameCache.set(e,r),r}function US(e,t,n){let s=LS("pad",e,t,n);if("explicit"===s){s=LS("explicitPaddings",e,t,n);const r=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)r[e][0]=s[2*e],r[e][1]=s[2*e+1];return r}return s}function GS(e){return e.kept?e:Eo(e)}const HS=[{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}]}],jS=[{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}]}],qS=[{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"}]}],KS=[{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"}]}],XS=[{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"}]}],YS=[{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}]}],ZS=[{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"}]}],JS=[{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"}]}],QS=[{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"}]}],eT=[{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"}]}],tT=[{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"}]}],nT=[{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"}]}],sT=[{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"}]}],rT=[{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"}]}],aT=[{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"}]}],iT=[{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"}]}],oT=[{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}]}],lT=[{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"}]}],uT=[{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:[]}];class cT{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[S,T,C,$,E,R,A,_,F,D,O,M,L,z,P,B,W,V,U].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,s=[],r=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?s.push(e[t.name]):"Const"===t.op?r.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e)),{});let o=[];const l=[];let u={},c={};null!=t&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[s,,r]=BS(e),a=i[s];if(null!=a.outputs){const e=a.outputs.indexOf(r);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(a),a.children.push(t)}))})),0===Object.keys(c).length?h.forEach((e=>{const t=i[e];0===t.children.length&&l.push(t)})):Object.keys(c).forEach((e=>{const[t]=BS(e),n=i[t];null!=n&&(n.signatureKey=c[e],l.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((e=>{const[t]=BS(e),n=i[t];n&&(n.signatureKey=u[e],o.push(n))})):o=s;let d={};null!=e.library&&null!=e.library.function&&(d=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const p={nodes:i,inputs:o,outputs:l,weights:r,placeholders:s,signature:t,functions:d};return a.length>0&&(p.initNodes=a),p}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=OS(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const s=n.type;let r;switch(n.type){case"string":r=dT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=dT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":r=kT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=kT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":r=fT(e.attr,n.tfName,n.defaultValue||0),void 0===r&&n.tfDeprecatedName&&(r=fT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":r=vT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=vT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":r=pT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=pT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":r=NT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=NT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":r=wT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=wT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":r=IT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=IT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":r=yT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=yT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":r=bT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=bT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":r=gT(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=gT(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:r,type:s},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let s={};null!=t&&(s=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const r=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=BS(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:mT(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,r.push(n),s[t]=n}));Object.keys(s).forEach((e=>{const t=s[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=BS(e),i=s[r];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=BS(i[e.name]),r=s[t];null!=r&&(r.defaultOutput=n,a.push(r))}));const o=this.mapArgsToSignature(e);return{nodes:s,inputs:r,outputs:a,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function hT(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Xe().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function dT(e,t,n,s=!1){const r=e[t];return null!=r?hT(r.s,s):n}function pT(e,t,n){const s=e[t];return s?s.b:n}function fT(e,t,n){const s=e[t]||{},r=null!=s.i?s.i:null!=s.f?s.f:n;return"number"==typeof r?r:parseInt(r,10)}function mT(e){switch("string"==typeof e&&(e=AS[e]),e){case AS.DT_FLOAT:case AS.DT_HALF:return"float32";case AS.DT_INT32:case AS.DT_INT64:case AS.DT_INT8:case AS.DT_UINT8:return"int32";case AS.DT_BOOL:return"bool";case AS.DT_DOUBLE:return"float32";case AS.DT_STRING:return"string";case AS.DT_COMPLEX64:case AS.DT_COMPLEX128:return"complex64";default:return null}}function gT(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function yT(e,t,n){const s=e[t];return s&&s.type?mT(s.type):n}function bT(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map((e=>mT(e))):n}function xT(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function wT(e,t,n){const s=e[t];return s&&s.shape?xT(s.shape):n}function vT(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function kT(e,t,n,s=!1){const r=e[t];return r&&r.list&&r.list.s?r.list.s.map((e=>hT(e,s))):n}function IT(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map((e=>xT(e))):n}function NT(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class ST{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return zS(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return zS(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return fT(this.node.rawAttrs,e,t);if(null!=n.s)return dT(this.node.rawAttrs,e,t);if(null!=n.b)return pT(this.node.rawAttrs,e,t);if(null!=n.shape)return wT(this.node.rawAttrs,e,t);if(null!=n.type)return yT(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return vT(this.node.rawAttrs,e,t);if(null!=n.list.s)return kT(this.node.rawAttrs,e,t);if(null!=n.list.shape)return IT(this.node.rawAttrs,e,t);if(null!=n.list.b)return NT(this.node.rawAttrs,e,t);if(null!=n.list.type)return bT(this.node.rawAttrs,e,t)}return t}}function TT(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){ie(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let s=0;s<e.length;s++){const r=e[s],a=t[s];ie(r<0||a<0||r===a,(()=>n+` Shapes ${e} and ${t} must match`))}}}function CT(e){return"number"!=typeof e&&!e.some((e=>e<0))}function $T(e,t,n){let s=ET(e,n);const r=!CT(s);if(r&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach((e=>{s=ET(e.shape,s)})),!CT(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function ET(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let s=0;s<e.length;++s){const r=e[s],a=t[s];if(r>=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}class RT{constructor(e,t,n,s,r,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Ho(0),pi(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&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()}`);const 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((e=>this.read(e)))}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}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),TT(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,pi(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(((e,n)=>this.write(e,t[n])))}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 t=0;t<this.size();t++)e.push(t)}if(0===e.length)return ei([],[0].concat(this.elementShape));const n=this.readMany(e);return TT(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ip(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return ei([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return TT(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),pc(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]}`);const 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,wp(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;const s=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${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`);const r=0===n?0:t.size/n,a=[];hi((()=>{t=cc(t,[1,n,r]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:s[n-1],0],o=[1,e[n],r];a[n]=cc(mc(t,i,o),this.elementShape)}return a}));const i=[];for(let t=0;t<e.length;t++)i[t]=t;this.writeMany(i,a)}}class AT{get id(){return this.idTensor.id}constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach((e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);TT(t,e.shape,"TensorList shape mismatch: "),pi(e)})),this.idTensor=Ho(0),this.maxNumElements=s,pi(this.idTensor)}copy(){return new AT([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);TT(e,this.elementShape,"TensorList shape mismatch: ");const s=$T(this.elementShape,this.tensors,e);return hi((()=>{const e=this.tensors.map((e=>cc(e,s)));return ip(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=$T(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,TT(s.shape,e,"TensorList shape mismatch: "),cc(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(TT(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");pi(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new AT([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);TT(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=$T(this.elementShape,this.tensors,t);return cc(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);TT(this.elementShape,t.shape,"TensorList shape mismatch: "),pi(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);TT(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=$T(this.elementShape,this.tensors,n);return 0===e.length?ei([],[0].concat(s)):hi((()=>{const t=e.map((e=>cc(this.tensors[e],s)));return ip(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);TT(this.elementShape,t,"TensorList shape mismatch: ");const n=$T(this.elementShape,this.tensors,t);return 0===this.size()?ei([],[0].concat(n)):hi((()=>{const e=this.tensors.map((e=>cc(e,n)));return pc(e,0)}))}}const _T=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=LS("thenBranch",e,t,n),r=LS("elseBranch",e,t,n),a=LS("cond",e,t,n),i=LS("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=LS("body",e,t,n),r=LS("cond",e,t,n),a=LS("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map((e=>e.id));let l=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let u=a;for(;l[0];){const e=u;u=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);const t=u.map((e=>e.id));e.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const a=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await a[0].data(),a.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return u}case"LoopCond":return[GS(LS("pred",e,t,n))];case"Switch":{const s=LS("pred",e,t,n);let r=LS("data",e,t,n);return r.kept||(r=GS(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{const s=e.inputNames.find((e=>void 0!==zS(e,t,n)));if(s){return[GS(zS(s,t,n))]}return}case"Enter":{const s=LS("frameName",e,t,n),r=LS("tensor",e,t,n);return n.enterFrame(s),[GS(r)]}case"Exit":{const s=LS("tensor",e,t,n);return n.exitFrame(),[GS(s)]}case"NextIteration":{const s=LS("tensor",e,t,n);return n.nextIteration(),[GS(s)]}case"TensorArrayV3":{const s=LS("size",e,t,n),r=LS("dtype",e,t,n),a=LS("elementShape",e,t,n),i=LS("dynamicSize",e,t,n),o=LS("clearAfterRead",e,t,n),l=LS("identicalElementShapes",e,t,n),u=LS("name",e,t,n),c=new RT(u,r,s,a,l,i,o);return n.addTensorArray(c),[c.idTensor,Ho(1)]}case"TensorArrayWriteV3":{const s=LS("tensorArrayId",e,t,n),r=LS("index",e,t,n),a=LS("tensor",e,t,n),i=n.getTensorArray(s.id);return i.write(r,a),[i.idTensor]}case"TensorArrayReadV3":{const s=LS("tensorArrayId",e,t,n),r=LS("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{const s=LS("tensorArrayId",e,t,n),r=LS("indices",e,t,n),a=LS("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{const s=LS("tensorArrayId",e,t,n),r=LS("indices",e,t,n),a=LS("tensor",e,t,n),i=n.getTensorArray(s.id);return i.scatter(r,a),[i.idTensor]}case"TensorArrayConcatV3":{const s=LS("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=LS("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{const s=LS("tensorArrayId",e,t,n),r=LS("tensor",e,t,n),a=LS("lengths",e,t,n),i=n.getTensorArray(s.id);return i.split(a,r),[i.idTensor]}case"TensorArraySizeV3":{const s=LS("tensorArrayId",e,t,n);return[Ho(n.getTensorArray(s.id).size(),"int32")]}case"TensorArrayCloseV3":{const s=LS("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{const s=LS("tensorListId",e,t,n),r=LS("index",e,t,n),a=LS("tensor",e,t,n),i=n.getTensorList(s.id);return i.setItem(r,a),[i.idTensor]}case"TensorListGetItem":{const s=LS("tensorListId",e,t,n),r=LS("index",e,t,n),a=LS("elementShape",e,t,n),i=LS("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const s=LS("indices",e,t,n),r=function(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const r=Math.max(...t);if(null!=s&&-1!==s&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);const a=new AT([],n,e.dtype,s),i=wp(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(LS("tensor",e,t,n),s,LS("elementShape",e,t,n),LS("numElements",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=LS("elementShape",e,t,n),r=LS("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=LS(a,e,t,n),o=function(e,t,n,s){return new AT([],e,t,s)}(s,r,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const s=LS("tensorListId",e,t,n),r=LS("indices",e,t,n),a=LS("elementShape",e,t,n),i=LS("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,i,a)]}case"TensorListStack":{const s=LS("tensorListId",e,t,n),r=LS("elementShape",e,t,n),a=LS("elementDType",e,t,n),i=LS("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,i)]}case"TensorListFromTensor":{const s=function(e,t,n){const s=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}`);TT(e.shape.slice(1),t,"TensorList shape mismatch: ");const r=wp(e);return new AT(r,t,s)}(LS("tensor",e,t,n),LS("elementShape",e,t,n),LS("elementDType",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const s=LS("tensorListId",e,t,n),r=n.getTensorList(s.id),a=LS("dtype",e,t,n),i=LS("elementShape",e,t,n);return[r.concat(a,i)]}case"TensorListPushBack":{const s=LS("tensorListId",e,t,n),r=LS("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{const s=LS("tensorListId",e,t,n),r=LS("elementShape",e,t,n),a=LS("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{const s=LS("tensor",e,t,n),r=LS("elementShape",e,t,n),a=function(e,t,n){let s=0;const r=t.map((e=>(s+=e,s)));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${s}, and tensor's shape is: ${e.shape}`);const a=ET(e.shape.slice(1),n),i=0===s?0:e.size/s,o=hi((()=>{const n=[];e=cc(e,[1,s,i]);for(let s=0;s<t.length;++s){const o=[0,0===s?0:r[s-1],0],l=[1,t[s],i];n[s]=cc(mc(e,o,l),a)}return e.dispose(),n})),l=new AT([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)l.setItem(e,o[e]);return l}(s,LS("lengths",e,t,n),r);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const s=LS("tensorListId",e,t,n);return[Ho(n.getTensorList(s.id).size(),"int32")]}case"TensorListResize":{const s=LS("tensorListId",e,t,n),r=LS("size",e,t,n),a=n.getTensorList(s.id).resize(r);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function FT(e,t,n){const[s,r]=LS("fusedOps",e,t,n),a="biasadd"===s,i=!a,o="prelu"===r,l="fusedbatchnorm"===s,u=LS("numArgs",e,t,n);if(a){if(o&&2!==u)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&1!==u)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");const c=LS("strides",e,t,n),h=US(e,t,n),d=LS("dataFormat",e,t,n).toUpperCase(),p=LS("dilations",e,t,n);let[f,m]=LS("args",e,t,n);i&&(m=f,f=void 0);return{stride:c,pad:h,dataFormat:d,dilations:p,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:LS("leakyreluAlpha",e,t,n)}}function DT(e,t,n){return{boxes:LS("boxes",e,t,n),scores:LS("scores",e,t,n),maxOutputSize:LS("maxOutputSize",e,t,n),iouThreshold:LS("iouThreshold",e,t,n),scoreThreshold:LS("scoreThreshold",e,t,n),softNmsSigma:LS("softNmsSigma",e,t,n)}}class OT{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ho(0),this.tensorMap=new Map,pi(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ho(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),hi((()=>{const e=wp(t),s=n.length,r=e.length;ie(s===r,(()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${r} elements.`));for(let t=0;t<s;t++){const s=n[t],r=e[t];pi(r),this.tensorMap.set(s,r)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return hi((()=>{const e=[];for(let s=0;s<n.length;s++){const r=n[s],a=this.findWithDefault(r,t);e.push(a)}return ip(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?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}`)}}function MT(e,t,n,s,r=hi){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(LS("a",e,t,n),LS("b",e,t,n))];case"AddN":return[s.addN(LS("tensors",e,t,n))];case"FloorMod":case"Mod":return[s.mod(LS("a",e,t,n),LS("b",e,t,n))];case"Mul":return[s.mul(LS("a",e,t,n),LS("b",e,t,n))];case"RealDiv":case"Div":return[s.div(LS("a",e,t,n),LS("b",e,t,n))];case"DivNoNan":return[s.divNoNan(LS("a",e,t,n),LS("b",e,t,n))];case"FloorDiv":return[s.floorDiv(LS("a",e,t,n),LS("b",e,t,n))];case"Sub":return[s.sub(LS("a",e,t,n),LS("b",e,t,n))];case"Minimum":return[s.minimum(LS("a",e,t,n),LS("b",e,t,n))];case"Maximum":return[s.maximum(LS("a",e,t,n),LS("b",e,t,n))];case"Pow":return[s.pow(LS("a",e,t,n),LS("b",e,t,n))];case"SquaredDifference":return[s.squaredDifference(LS("a",e,t,n),LS("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Abs":case"ComplexAbs":return[s.abs(LS("x",e,t,n))];case"Acos":return[s.acos(LS("x",e,t,n))];case"Acosh":return[s.acosh(LS("x",e,t,n))];case"Asin":return[s.asin(LS("x",e,t,n))];case"Asinh":return[s.asinh(LS("x",e,t,n))];case"Atan":return[s.atan(LS("x",e,t,n))];case"Atan2":return[s.atan2(LS("x",e,t,n),LS("y",e,t,n))];case"Atanh":return[s.atanh(LS("x",e,t,n))];case"Ceil":return[s.ceil(LS("x",e,t,n))];case"Complex":return[s.complex(LS("real",e,t,n),LS("imag",e,t,n))];case"Cos":return[s.cos(LS("x",e,t,n))];case"Cosh":return[s.cosh(LS("x",e,t,n))];case"Elu":return[s.elu(LS("x",e,t,n))];case"Erf":return[s.erf(LS("x",e,t,n))];case"Exp":return[s.exp(LS("x",e,t,n))];case"Expm1":return[s.expm1(LS("x",e,t,n))];case"Floor":return[s.floor(LS("x",e,t,n))];case"Log":return[s.log(LS("x",e,t,n))];case"Log1p":return[s.log1p(LS("x",e,t,n))];case"Imag":return[s.imag(LS("x",e,t,n))];case"Neg":return[s.neg(LS("x",e,t,n))];case"Reciprocal":return[s.reciprocal(LS("x",e,t,n))];case"Real":return[s.real(LS("x",e,t,n))];case"Relu":return[s.relu(LS("x",e,t,n))];case"Round":return[s.round(LS("x",e,t,n))];case"Selu":return[s.selu(LS("x",e,t,n))];case"Sigmoid":return[s.sigmoid(LS("x",e,t,n))];case"Sin":return[s.sin(LS("x",e,t,n))];case"Sign":return[s.sign(LS("x",e,t,n))];case"Sinh":return[s.sinh(LS("x",e,t,n))];case"Softplus":return[s.softplus(LS("x",e,t,n))];case"Sqrt":return[s.sqrt(LS("x",e,t,n))];case"Square":return[s.square(LS("x",e,t,n))];case"Tanh":return[s.tanh(LS("x",e,t,n))];case"Tan":return[s.tan(LS("x",e,t,n))];case"ClipByValue":return[s.clipByValue(LS("x",e,t,n),LS("clipValueMin",e,t,n),LS("clipValueMax",e,t,n))];case"Relu6":return[s.relu6(LS("x",e,t,n))];case"Rsqrt":return[s.rsqrt(zS(e.inputNames[0],t,n))];case"LeakyRelu":return[s.leakyRelu(LS("x",e,t,n),LS("alpha",e,t,n))];case"Prelu":return[s.prelu(LS("x",e,t,n),LS("alpha",e,t,n))];case"IsNan":return[s.isNaN(zS(e.inputNames[0],t,n))];case"IsInf":return[s.isInf(zS(e.inputNames[0],t,n))];case"IsFinite":return[s.isFinite(zS(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return _T(e,t,n);case"convolution":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Conv1D":{const r=LS("stride",e,t,n),a=LS("pad",e,t,n),i=LS("dataFormat",e,t,n).toUpperCase(),o=LS("dilation",e,t,n);return[s.conv1d(LS("x",e,t,n),LS("filter",e,t,n),r,a,i,o)]}case"Conv2D":{const r=LS("strides",e,t,n),a=US(e,t,n),i=LS("dataFormat",e,t,n).toUpperCase(),o=LS("dilations",e,t,n);return[s.conv2d(LS("x",e,t,n),LS("filter",e,t,n),[r[1],r[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=FT(e,t,n);return[s.fused.conv2d({x:LS("x",e,t,n),filter:LS("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=FT(e,t,n);return[s.fused.depthwiseConv2d({x:LS("x",e,t,n),filter:LS("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const r=LS("outputShape",e,t,n),a=LS("strides",e,t,n),i=US(e,t,n);return[s.conv2dTranspose(LS("x",e,t,n),LS("filter",e,t,n),r,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=LS("strides",e,t,n),a=US(e,t,n),i=LS("dilations",e,t,n),o=LS("dataFormat",e,t,n).toUpperCase();return[s.depthwiseConv2d(LS("input",e,t,n),LS("filter",e,t,n),[r[1],r[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("dataFormat",e,t,n).toUpperCase(),o=LS("dilations",e,t,n);return[s.conv3d(LS("x",e,t,n),LS("filter",e,t,n),[r[1],r[2],r[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("kernelSize",e,t,n);return[s.avgPool(LS("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPool":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("kernelSize",e,t,n);return[s.maxPool(LS("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPoolWithArgmax":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("kernelSize",e,t,n),o=LS("includeBatchInIndex",e,t,n),{result:l,indexes:u}=s.maxPoolWithArgmax(LS("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a,o);return[l,u]}case"AvgPool3D":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("kernelSize",e,t,n);return[s.avgPool3d(LS("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"MaxPool3D":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("kernelSize",e,t,n);return[s.maxPool3d(LS("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"Dilation2D":{const r=LS("strides",e,t,n),a=LS("pad",e,t,n),i=LS("dilations",e,t,n),o=r[1],l=r[2],u=i[1],c=i[2];return[s.dilation2d(LS("x",e,t,n),LS("filter",e,t,n),[o,l],a,[u,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Fill":{const r=LS("shape",e,t,n),a=LS("dtype",e,t,n),i=LS("value",e,t,n);return[s.fill(r,i,a)]}case"LinSpace":{const r=LS("start",e,t,n),a=LS("stop",e,t,n),i=LS("num",e,t,n);return[s.linspace(r,a,i)]}case"Multinomial":{const r=LS("logits",e,t,n),a=LS("numSamples",e,t,n),i=LS("seed",e,t,n);return[s.multinomial(r,a,i)]}case"OneHot":{const r=LS("indices",e,t,n),a=LS("depth",e,t,n),i=LS("onValue",e,t,n),o=LS("offValue",e,t,n),l=LS("dtype",e,t,n);return[s.oneHot(r,a,i,o,l)]}case"Ones":return[s.ones(LS("shape",e,t,n),LS("dtype",e,t,n))];case"OnesLike":return[s.onesLike(LS("x",e,t,n))];case"RandomStandardNormal":return[s.randomStandardNormal(LS("shape",e,t,n),LS("dtype",e,t,n),LS("seed",e,t,n))];case"RandomUniform":return[s.randomUniform(LS("shape",e,t,n),LS("minval",e,t,n),LS("maxval",e,t,n),LS("dtype",e,t,n))];case"RandomUniformInt":return[s.randomUniformInt(LS("shape",e,t,n),LS("minval",e,t,n),LS("maxval",e,t,n),LS("seed",e,t,n))];case"Range":{const r=LS("start",e,t,n),a=LS("stop",e,t,n),i=LS("step",e,t,n);return[s.range(r,a,i,LS("dtype",e,t,n))]}case"TruncatedNormal":{const r=LS("shape",e,t,n),a=LS("mean",e,t,n),i=LS("stdDev",e,t,n),o=LS("seed",e,t,n);return[s.truncatedNormal(r,a,i,LS("dtype",e,t,n),o)]}case"Zeros":return[s.zeros(LS("shape",e,t,n),LS("dtype",e,t,n))];case"ZerosLike":return[s.zerosLike(LS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,s,r=G)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=DT(e,t,n),c=await r.image.nonMaxSuppressionWithScoreAsync(s,a,i,o,l,u);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=DT(e,t,n),u=LS("padToMaxOutputSize",e,t,n),c=await r.image.nonMaxSuppressionPaddedAsync(s,a,i,o,l,u);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=DT(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,a,i,o,l)]}case"Where":{const s=r.cast(LS("condition",e,t,n),"bool"),a=[await r.whereAsync(s)];return s.dispose(),a}case"ListDiff":return r.setdiff1dAsync(LS("x",e,t,n),LS("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"LowerBound":{const r=LS("sortedSequence",e,t,n),a=LS("values",e,t,n);return[s.lowerBound(r,a)]}case"TopKV2":{const r=LS("x",e,t,n),a=LS("k",e,t,n),i=LS("sorted",e,t,n),o=s.topk(r,a,i);return[o.values,o.indices]}case"UpperBound":{const r=LS("sortedSequence",e,t,n),a=LS("values",e,t,n);return[s.upperBound(r,a)]}case"Unique":{const r=LS("x",e,t,n),a=s.unique(r);return[a.values,a.indices]}case"UniqueV2":{const r=LS("x",e,t,n),a=LS("axis",e,t,n),i=s.unique(r,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"ResizeBilinear":{const r=LS("images",e,t,n),a=LS("size",e,t,n),i=LS("alignCorners",e,t,n),o=LS("halfPixelCenters",e,t,n);return[s.image.resizeBilinear(r,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const r=LS("images",e,t,n),a=LS("size",e,t,n),i=LS("alignCorners",e,t,n),o=LS("halfPixelCenters",e,t,n);return[s.image.resizeNearestNeighbor(r,[a[0],a[1]],i,o)]}case"CropAndResize":{const r=LS("image",e,t,n),a=LS("boxes",e,t,n),i=LS("boxInd",e,t,n),o=LS("cropSize",e,t,n),l=LS("method",e,t,n),u=LS("extrapolationValue",e,t,n);return[s.image.cropAndResize(r,a,i,o,l,u)]}case"ImageProjectiveTransformV3":{const r=LS("images",e,t,n),a=LS("transforms",e,t,n),i=LS("outputShape",e,t,n),o=LS("fillValue",e,t,n),l=LS("interpolation",e,t,n),u=LS("fillMode",e,t,n);return[s.image.transform(r,a,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const r=LS("default",e,t,n);return[zS(e.name,t,n)||r];case"Placeholder":return[zS(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[GS(LS("x",e,t,n))];case"IdentityN":return LS("x",e,t,n).map((e=>GS(e)));case"Shape":return[s.tensor1d(LS("x",e,t,n).shape,"int32")];case"ShapeN":return LS("x",e,t,n).map((e=>s.tensor1d(e.shape)));case"Size":return[s.scalar(LS("x",e,t,n).size,"int32")];case"Rank":return[s.scalar(LS("x",e,t,n).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":const a=LS("x",e,t,n),i=LS("data",e,t,n),o=LS("message",e,t,n),l=LS("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let e=0;e<i.length;e++)console.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,l));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Equal":return[s.equal(LS("a",e,t,n),LS("b",e,t,n))];case"NotEqual":return[s.notEqual(LS("a",e,t,n),LS("b",e,t,n))];case"Greater":return[s.greater(LS("a",e,t,n),LS("b",e,t,n))];case"GreaterEqual":return[s.greaterEqual(LS("a",e,t,n),LS("b",e,t,n))];case"Less":return[s.less(LS("a",e,t,n),LS("b",e,t,n))];case"LessEqual":return[s.lessEqual(LS("a",e,t,n),LS("b",e,t,n))];case"LogicalAnd":return[s.logicalAnd(LS("a",e,t,n),LS("b",e,t,n))];case"LogicalNot":return[s.logicalNot(LS("a",e,t,n))];case"LogicalOr":return[s.logicalOr(LS("a",e,t,n),LS("b",e,t,n))];case"Select":case"SelectV2":return[s.where(LS("condition",e,t,n),LS("a",e,t,n),LS("b",e,t,n))];case"BitwiseAnd":return[s.bitwiseAnd(LS("a",e,t,n),LS("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(LS("a",e,t,n),LS("b",e,t,n),LS("transposeA",e,t,n),LS("transposeB",e,t,n))];case"Einsum":return[s.einsum(LS("equation",e,t,n),...LS("tensors",e,t,n))];case"Transpose":return[s.transpose(LS("x",e,t,n),LS("perm",e,t,n))];case"_FusedMatMul":const[r,a]=LS("fusedOps",e,t,n),i="biasadd"===r,o="prelu"===a,l=LS("numArgs",e,t,n),u=LS("leakyreluAlpha",e,t,n);if(i){if(o&&2!==l)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==l)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=LS("args",e,t,n);return[s.fused.matMul({a:LS("a",e,t,n),b:LS("b",e,t,n),transposeA:LS("transposeA",e,t,n),transposeB:LS("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:u})];case"MatrixBandPart":return[s.linalg.bandPart(LS("a",e,t,n),LS("numLower",e,t,n),LS("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"EuclideanNorm":return[s.euclideanNorm(LS("x",e,t,n),LS("axis",e,t,n),LS("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[s.batchNorm(LS("x",e,t,n),LS("mean",e,t,n),LS("variance",e,t,n),LS("offset",e,t,n),LS("scale",e,t,n),LS("epsilon",e,t,n))];case"LRN":return[s.localResponseNormalization(LS("x",e,t,n),LS("radius",e,t,n),LS("bias",e,t,n),LS("alpha",e,t,n),LS("beta",e,t,n))];case"Softmax":return[s.softmax(LS("x",e,t,n))];case"LogSoftmax":return[s.logSoftmax(LS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:r,outputDenseValues:a}=s.raggedGather(LS("paramsNestedSplits",e,t,n),LS("paramsDenseValues",e,t,n),LS("indices",e,t,n),LS("outputRaggedRank",e,t,n));return r.concat(a)}case"RaggedRange":{const{rtNestedSplits:r,rtDenseValues:a}=s.raggedRange(LS("starts",e,t,n),LS("limits",e,t,n),LS("splits",e,t,n));return[r,a]}case"RaggedTensorToTensor":return[s.raggedTensorToTensor(LS("shape",e,t,n),LS("values",e,t,n),LS("defaultValue",e,t,n),LS("rowPartitionTensors",e,t,n),LS("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Max":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.max(LS("x",e,t,n),r,a)]}case"Mean":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.mean(LS("x",e,t,n),r,a)]}case"Min":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.min(LS("x",e,t,n),r,a)]}case"Sum":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.sum(LS("x",e,t,n),r,a)]}case"All":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.all(LS("x",e,t,n),r,a)]}case"Any":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.any(LS("x",e,t,n),r,a)]}case"ArgMax":{const r=LS("axis",e,t,n);return[s.argMax(LS("x",e,t,n),r)]}case"ArgMin":{const r=LS("axis",e,t,n);return[s.argMin(LS("x",e,t,n),r)]}case"Prod":{const r=LS("axis",e,t,n),a=LS("keepDims",e,t,n);return[s.prod(LS("x",e,t,n),r,a)]}case"Cumprod":{const r=LS("axis",e,t,n),a=LS("exclusive",e,t,n),i=LS("reverse",e,t,n);return[s.cumprod(LS("x",e,t,n),r,a,i)]}case"Cumsum":{const r=LS("axis",e,t,n),a=LS("exclusive",e,t,n),i=LS("reverse",e,t,n);return[s.cumsum(LS("x",e,t,n),r,a,i)]}case"Bincount":const r=LS("x",e,t,n),a=LS("weights",e,t,n),i=LS("size",e,t,n);return[s.bincount(r,a,i)];case"DenseBincount":{const r=LS("x",e,t,n),a=LS("weights",e,t,n),i=LS("size",e,t,n),o=LS("binaryOutput",e,t,n);return[s.denseBincount(r,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"ConcatV2":case"Concat":{const r=LS("n",e,t,n),a=LS("axis",e,t,n);let i=LS("tensors",e,t,n);return i=i.slice(0,r),[s.concat(i,a)]}case"Gather":{const r=LS("x",e,t,n),a=LS("indices",e,t,n);return[s.gather(r,s.cast(a,"int32"),0)]}case"GatherV2":{const r=LS("axis",e,t,n),a=LS("batchDims",e,t,n),i=LS("x",e,t,n),o=LS("indices",e,t,n);return[s.gather(i,s.cast(o,"int32"),r,a)]}case"Reverse":{const r=LS("dims",e,t,n),a=[];for(let e=0;e<r.length;e++)r[e]&&a.push(e);const i=LS("x",e,t,n);return[s.reverse(i,a)]}case"ReverseV2":{const r=LS("axis",e,t,n),a=LS("x",e,t,n);return[s.reverse(a,r)]}case"Slice":{const r=LS("begin",e,t,n),a=LS("size",e,t,n);return[s.slice(LS("x",e,t,n),r,a)]}case"StridedSlice":{const r=LS("begin",e,t,n),a=LS("end",e,t,n),i=LS("strides",e,t,n),o=LS("beginMask",e,t,n),l=LS("endMask",e,t,n),u=LS("ellipsisMask",e,t,n),c=LS("newAxisMask",e,t,n),h=LS("shrinkAxisMask",e,t,n),d=LS("x",e,t,n);return[s.stridedSlice(d,r,a,i,o,l,u,c,h)]}case"Pack":return hi((()=>{const r=LS("axis",e,t,n),a=LS("tensors",e,t,n),i=a[0].shape,o=s.squeeze(a[0]).shape,l=a.map((e=>{const t=de(e.shape,i);if(!t&&!de(s.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:s.reshape(e,i)}));return[s.stack(l,r)]}));case"Unpack":{const r=LS("axis",e,t,n),a=LS("tensor",e,t,n);return s.unstack(a,r)}case"Tile":{const r=LS("reps",e,t,n);return[s.tile(LS("x",e,t,n),r)]}case"Split":case"SplitV":{const r=LS("axis",e,t,n),a=LS("numOrSizeSplits",e,t,n),i=LS("x",e,t,n);return s.split(i,a,r)}case"ScatterNd":{const r=LS("indices",e,t,n),a=LS("values",e,t,n),i=LS("shape",e,t,n);return[s.scatterND(r,a,i)]}case"GatherNd":{const r=LS("x",e,t,n),a=LS("indices",e,t,n);return[s.gatherND(r,a)]}case"SparseToDense":{const r=LS("sparseIndices",e,t,n),a=LS("outputShape",e,t,n),i=LS("sparseValues",e,t,n),o=LS("defaultValue",e,t,n);return[s.sparseToDense(r,i,a,i.dtype===o.dtype?o:s.cast(o,i.dtype))]}case"TensorScatterUpdate":{const r=LS("indices",e,t,n),a=LS("values",e,t,n),i=LS("tensor",e,t,n);return[s.tensorScatterUpdate(i,r,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=s.sparse.sparseFillEmptyRows(LS("indices",e,t,n),LS("values",e,t,n),LS("denseShape",e,t,n),LS("defaultValue",e,t,n));return[r,a,i,o]}case"SparseReshape":{const{outputIndices:r,outputShape:a}=s.sparse.sparseReshape(LS("inputIndices",e,t,n),LS("inputShape",e,t,n),LS("newShape",e,t,n));return[r,a]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(LS("data",e,t,n),LS("indices",e,t,n),LS("segmentIds",e,t,n))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(LS("data",e,t,n),LS("indices",e,t,n),LS("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"FFT":return[s.fft(LS("x",e,t,n))];case"IFFT":return[s.ifft(LS("x",e,t,n))];case"RFFT":return[s.rfft(LS("x",e,t,n))];case"IRFFT":return[s.irfft(LS("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"StaticRegexReplace":return[s.string.staticRegexReplace(LS("input",e,t,n),LS("pattern",e,t,n),LS("rewrite",e,t,n),LS("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:r,nGramsSplits:a}=s.string.stringNGrams(LS("data",e,t,n),LS("dataSplits",e,t,n),LS("separator",e,t,n),LS("nGramWidths",e,t,n),LS("leftPad",e,t,n),LS("rightPad",e,t,n),LS("padWidth",e,t,n),LS("preserveShortSequences",e,t,n));return[r,a]}case"StringSplit":{const{indices:r,values:a,shape:i}=s.string.stringSplit(LS("input",e,t,n),LS("delimiter",e,t,n),LS("skipEmpty",e,t,n));return[r,a,i]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(LS("input",e,t,n),LS("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return r((()=>((e,t,n,s=G)=>{switch(e.op){case"Cast":return[s.cast(LS("x",e,t,n),LS("dtype",e,t,n))];case"ExpandDims":{const r=LS("axis",e,t,n);return[s.expandDims(LS("x",e,t,n),r)]}case"Squeeze":{const r=LS("axis",e,t,n);return[s.squeeze(LS("x",e,t,n),r)]}case"Reshape":return[s.reshape(LS("x",e,t,n),LS("shape",e,t,n))];case"EnsureShape":return[s.ensureShape(LS("x",e,t,n),LS("shape",e,t,n))];case"MirrorPad":return[s.mirrorPad(LS("x",e,t,n),LS("padding",e,t,n),LS("mode",e,t,n))];case"PadV2":case"Pad":return[s.pad(LS("x",e,t,n),LS("padding",e,t,n),LS("constantValue",e,t,n))];case"SpaceToBatchND":{const r=LS("blockShape",e,t,n),a=LS("paddings",e,t,n);return[s.spaceToBatchND(LS("x",e,t,n),r,a)]}case"BatchToSpaceND":{const r=LS("blockShape",e,t,n),a=LS("crops",e,t,n);return[s.batchToSpaceND(LS("x",e,t,n),r,a)]}case"DepthToSpace":{const r=LS("blockSize",e,t,n),a=LS("dataFormat",e,t,n).toUpperCase();return[s.depthToSpace(LS("x",e,t,n),r,a)]}case"BroadcastTo":return[s.broadcastTo(LS("x",e,t,n),LS("shape",e,t,n))];case"BroadcastArgs":return[s.broadcastArgs(LS("s0",e,t,n),LS("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const r=s.getHashTableHandleByName(e.name);if(null!=r)return[r];{const r=LS("keyDType",e,t,n),a=LS("valueDType",e,t,n),i=new OT(r,a);return s.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const r=LS("tableHandle",e,t,n,s),a=LS("keys",e,t,n),i=LS("values",e,t,n),o=s.getHashTableById(r.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const r=LS("tableHandle",e,t,n,s),a=LS("keys",e,t,n),i=LS("defaultValue",e,t,n),o=s.getHashTableById(r.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const r=LS("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,s);case"custom":const a=OS(e.op);if(a&&a.customExecutor)return a.customExecutor(new ST(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.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 He(a)?a.then((e=>[].concat(e))):[].concat(a)}class LT{constructor(e={},t={},n={},s={},r){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,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(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const 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((e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.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))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const 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))}}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(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function zT(e,t,n,s){const r=new Set,a=[];let i=null,o=null;const l=new Set,u=new Set(Object.keys(e).map((e=>VS(e)[0])));s=s||[];const c=new Set(s.map((e=>VS(e.name)[0]))),h=[...t];for(;h.length>0;){const e=h.pop();(GT(e)||HT(e)||jT(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>r.has(e)))),r.add(e.name),null==n[e.name]&&(u.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach((e=>{l.has(e.name)||(l.add(e.name),h.push(e))})):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:i,syncInputs:o}}function PT(e,t){const{usedNodes:n,inputs:s}=t,r=Object.keys(s).map((e=>VS(e)[0])).map((t=>e.nodes[t])),a=e.initNodes||[],i=e=>n.has("string"==typeof e?e:e.name);function o(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const l=o([...r,...e.weights,...a]).filter(i),u=o([...l,...Object.values(e.nodes)]).filter(i),c=new Map(u.map((e=>[e.name,e]))),h={};for(const e of u){h[e.name]=h[e.name]||0;for(const t of e.children)i(t)||(h[t.name]=Number.POSITIVE_INFINITY),h[t.name]=(h[t.name]||0)+1}const d=Object.entries(h).filter((([,e])=>0===e)).map((([e])=>e)),p=[...d];for(;d.length>0;){const e=d.pop(),t=c.get(e);for(const e of t.children.filter(i))0==--h[e.name]&&(p.push(e.name),d.push(e.name))}const f=function(e,t){const n=new Map(e.map((e=>[e.name,e]))),s=t.map((e=>e.name)),r=new Set(s);for(;s.length>0;){const e=s.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!r.has(e.name)&&(r.add(e.name),s.push(e.name))}const a=e.filter((e=>r.has(e.name)));return a}(p.map((e=>c.get(e))),l);return function(e,t){const n=new Map(e.map(((e,t)=>[e.name,t]))),s=new Set(t.map((e=>e.name))),r=e=>s.has("string"==typeof e?e:e.name),a=new Set(e.map((e=>e.name))),i=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(i)){if(!n.has(e.name))throw new BT(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new BT(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!r(t))for(const e of t.inputs){if(!n.has(e.name))throw new BT(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new BT(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,l),f}class BT extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const WT=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),VT=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),UT=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function GT(e){return WT.has(e.op)}function HT(e){return VT.has(e.op)}function jT(e){return UT.has(e.op)}class qT{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new qT(e.functions[t],this)}))}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),s=t.map((e=>e.name)).sort();return n.join(this.SEPARATOR)+"--"+s.join(this.SEPARATOR)}compile(e,t){const n=zT(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(null!=r)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){const n=t.map((e=>e.name)),r=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${r}]. Missing the following inputs: [${s}]`)}const i=PT(this.graph,n),o=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,s=e.map(((e,t)=>GT(e)?n:t)),r=e=>{const n=s[t.get(e.name)];return null==n?-1:n},a=e.map(((e,t)=>e.children.map(r).reduce(((e,t)=>Math.max(e,t)),s[t]))),i=new Map;for(let t=0;t<e.length;++t){const s=a[t];if(s===n)continue;const r=e[t],o=e[s];i.has(o.name)||i.set(o.name,[]),i.get(o.name).push(r)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return pi(t),t}cloneTensorList(e){if(!e)return null;const t=e.map((e=>this.cloneAndKeepTensor(e)));return t}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=n.map((e=>this.graph.nodes[VS(e)[0]])),r=t.map((e=>VS(e)[0])),a=new Set(r);let i=r.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const o=this.getCompilationKey(s,i);let l=this.compiledMap.get(o);null==l&&(l=this.compile(e,i),this.compiledMap.set(o,l));try{this.keepIntermediateTensors=Xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const u={},c={};return hi((()=>{const n=new LT(this.weightMap,u,c,this.functionExecutorMap,this.parseNodeNameCache),s=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[r,a]=VS(t,n),i=[];i[a]=e[t],s[r]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[r]=this.cloneTensorList(i))}));const r=this.getFrozenTensorIds(s),{orderedNodes:i,nodeLiveUntilMap:o}=l;for(const e of i){if(s[e.name])continue;const t=MT(e,s,n,this._resourceManager);if(He(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);s[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,s,n,r,a,o.get(e.name))}return null==this.parent&&n.dispose(r),t.map((e=>zS(e,s,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,i){if(!GT(t)&&!a.has(e)){for(const s of n[e])null!=s&&(i[s.id]=(i[s.id]||0)+t.children.length);for(const e of t.inputs){if(GT(e))continue;const t=PS(e.name,n,s);if(null!=t)for(const e of t){if(!e||e.kept||r.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,s,r,a){function i(e){return GT(e)||r.has(e.name)}if(!GT(e)&&null!=a)for(const e of a){if(i(e))continue;const r=PS(e.name,t,n);for(const e of r)!e||e.kept||s.has(e.id)||e.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach((e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()})),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,s={},r={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Xe().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const a=new LT(this.weightMap,s,r,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map((e=>zS(e,i,a))),l=o.map((e=>e.id)),u=Object.keys(e).map((t=>e[t].id)),c=new Set([...l,...u,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&a.dispose(c),o}async executeFunctionAsync(e,t,n){const s=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const r=Object.keys(e),a=r.map((e=>this.graph.nodes[VS(e)[0]])),i=n.map((e=>VS(e)[0])),o=new Set(i);let l=i.map((e=>this.graph.nodes[e]));0===l.length&&(l=this._outputs);const{usedNodes:u,missingInputs:c,dynamicNode:h,syncInputs:d}=zT(e,l,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),f=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,s]=VS(t),r=[];r[s]=e[t],f[n]=r}));const m={},g=this.getFrozenTensorIds(f),y={};for(;p.length>0;){const e=this.processStack(a,p,t,f,y,g,o,m,u);await Promise.all(e)}null!=h||s||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=l.filter((e=>!GT(e)&&!zS(e.name,f,t))).map((e=>e.name));if(b.length>0){let e="";throw null!=h&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,s,r,a,i,o,l){const u=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&LS("isConstant",e.node,s,n)&&([c]=BS(e.node.name,n)),null==s[e.node.name]){const h=MT(e.node,s,n,this._resourceManager);c||([c]=BS(e.node.name,n));const d=n.currentContext;He(h)?u.push(h.then((u=>(s[c]=u,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(u)),n.currentContext=d,this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l),u)))):(s[c]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(h)),this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l))}else this.processChildNodes(e.node,t,n,s,r,l)}return u}processChildNodes(e,t,n,s,r,a){e.children.forEach((e=>{const[i]=BS(e.name,n);!r[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!zS(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!zS(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[s]=VS(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){const e=r.attrParams.shape.value;ie(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}r.attrParams.dtype&&r.attrParams.dtype.value&&ie(n.dtype===r.attrParams.dtype.value,(()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const s={};for(const r in e){const a=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[r];null!=a?s[a.name]=e[r]:s[r]=e[r]}return s}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=VS(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>{var t,n;const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=s?s.name:e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=VS(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class KT{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(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const XT="?tfjs-format=file",YT="model.json";class ZT{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=l){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new KT}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)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(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return He(e)?e.then((e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e))):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Ai(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let s=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(s=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=s,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new qT(cT.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=cT.Instance.transformGraph(e.modelInitializer);this.initializer=new qT(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)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){const t={};return(e instanceof ga?[e]:e).forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e)),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof ga||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const s=n[t];null!=s.resourceId&&(e[t]=this.resourceIdToCapturedInput[s.resourceId])}return e}e=Array.isArray(e)?e:[e];const 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 s=0;return this.inputNodes.reduce(((t,n)=>{var r,a,i;const o=null===(i=null===(a=null===(r=this.signature)||void 0===r?void 0:r.inputs)||void 0===a?void 0:a[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]:e[s++],t}),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let s=0;s<n.length;s++){const r=t[n[s]];this.resourceIdToCapturedInput[r.resourceId]=e[s]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const 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&&di(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function JT(e,t={},n=l){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}${YT}${XT}`}(e));const s=new ZT(e,t,n);return await s.load(),s}function QT(e){if(null==e)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){const[n,s]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!(s&&s instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");t=_l(zi(n,Wi(n.weightsManifest),s))}else if("load"in e)t=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");t=_l(e)}const n=new ZT(t);return n.load(),n}const eC="4.20.0";function tC(e,t,n=new Map,s=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse){if(iC(e)){const r=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const i=tC(e[a],t,n,s);r[a]=i}return s.delete(e),e.__proto__&&(r.__proto__=e.__proto__),r}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,r.value),r.value}function nC(e,t=rC){return sC(e,t)}function sC(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse){if(iC(s)){const r=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const s=sC(e.map((e=>e[a])),t,n);r[a]=s}return n.delete(s),r}throw new Error(`Can't recurse into non-iterable type: ${s}`)}return r.value}function rC(e){return null===e?null:iC(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function aC(e,t){const n=new Map;tC(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(He(t)){const s=await t;n.set(e,s)}}return tC(e,t,n)}function iC(e){let t=!1;if(Xe().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:s}=n(551);t=e instanceof s}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof ga)&&!(e instanceof Promise)&&!t)}function oC(e){return function(e,t){return tC(e,t)}(e,lC)}function lC(e){return e instanceof ga?{value:e.clone(),recurse:!1}:iC(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class uC{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)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 0===this.length()}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(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const 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.");const 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.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class cC extends uC{constructor(){super(cC.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e<n;e++)t[e]=this.get(this.wrap(this.begin+e));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}function hC(e){return new mC(e)}function dC(e){return new gC(e)}function pC(e,t){return new CC(e,t)}cC.INITIAL_CAPACITY=32;class fC{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let 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 IC(this,e)}filter(e){return new vC(this,e)}map(e){return new kC(this,e)}mapAsync(e){return new NC(this,e)}serialMapAsync(e){return new NC(this,e).serial()}flatmap(e){return new TC(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile((e=>!0===e))}rowMajorBatch(e,t=!0){return new wC(this,e,t)}columnMajorBatch(e,t=!0,n=rC){return this.rowMajorBatch(e,t).map((e=>nC(e,n)))}concatenate(e,t){return new CC(hC([this,e]),t)}take(e){return e<0||null==e?this:new xC(this,e)}skip(e){return e<0||null==e?this:new bC(this,e)}prefetch(e){return new RC(this,e)}shuffle(e,t){return new AC(this,e,t)}serial(){return new yC(this)}}class mC extends fC{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};const e=this.items[this.trav];return this.trav++,{value:oC(e),done:!1}}}class gC extends fC{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}}}class yC extends fC{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()}}class bC extends fC{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;){const e=await this.upstream.next();if(e.done)return e;di(e.value)}return this.upstream.next()}}class xC extends fC{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()}}class wC extends fC{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(){const e=[];for(;e.length<this.batchSize;){const 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}}}class vC extends fC{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(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;di(e.value)}}}class kC extends fC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=_a(e.value),n=this.transform(e.value),s=_a(n);for(const e of t)Aa(e,s)||e.dispose();return{value:n,done:!1}}}class IC extends fC{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}}}}class NC extends fC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=_a(e.value),n=await this.transform(e.value),s=_a(n);for(const e of t)Aa(e,s)||e.dispose();return{value:n,done:!1}}}class SC extends fC{constructor(){super(),this.outputQueue=new cC,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class TC extends SC{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=_a(e.value),n=this.transform(e.value),s=_a(n);this.outputQueue.pushAll(n);for(const e of t)Aa(e,s)||e.dispose();return!0}}class CC extends fC{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,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var $C;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}($C||($C={}));class EC extends fC{constructor(e,t=$C.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;const s=await aC(this.iterators,(function(e){if(e instanceof fC){return{value:e.next().then((e=>(t++,e.done&&n++,e.value))),recurse:!1}}return{value:null,recurse:!0}}));if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case $C.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case $C.SHORTEST:return{value:null,done:!0};case $C.LONGEST:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class RC extends fC{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new uC(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class AC extends RC{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=kd.alea(n||Xr().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();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class _C{constructor(){this.size=null}batch(e,t=!0){const n=this;let s;return ie(e>0,(()=>`batchSize needs to be positive, but it is\n ${e}`)),s=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),FC((async()=>(await n.iterator()).columnMajorBatch(e,t,MC)),s)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,FC((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,FC((async()=>(await t.iterator()).filter((t=>hi((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return FC((async()=>(await t.iterator()).map((t=>hi((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return FC((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return FC((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,FC((async()=>pC(dC((async()=>({value:await t.iterator(),done:!1}))).take(e))),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size<e||void 0===e||e<0)?0:null,FC((async()=>(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?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)`);const s=this,r=kd.alea(t||Xr().toString());return FC((async()=>{let t=r.int32();return n&&(t+=r.int32()),(await s.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,FC((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()}}function FC(e,t=null){return new class extends _C{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function DC(e){return FC((async()=>hC(e)),e.length)}function OC(e){if(!iC(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=null==t?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=null==t?e[n].size:Math.min(t,e[n].size);return FC((async()=>function(e,t=$C.FAIL){return new EC(e,t)}(await aC(e,(e=>{if(e instanceof _C)return{value:e.iterator(),recurse:!1};if(iC(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),$C.SHORTEST)),t)}function MC(e){if(null===e)return null;const t=e[0];if(null==(n=t)||null===(s=n)||"object"!=typeof s&&"function"!=typeof s||Array.isArray(n)||"object"==typeof n&&n instanceof ga||Qr(n)){return{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ga?ip(e):ei(e)}(e),recurse:!1}}var n,s;return{value:null,recurse:!0}}_C.MAX_BUFFER_SIZE=1e4;class LC extends _C{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\n").map((e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e)))}}const zC='"',PC=Symbol("out"),BC=Symbol("field"),WC=Symbol("quote"),VC=Symbol("quoteafterquote"),UC=Symbol("quoteinquote");class GC extends _C{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const 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&&ie(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);const t=this.fullColumnNames.reduce(((e,t)=>(e[t]=e[t]+1||1,e)),{}),n=Object.keys(t).filter((e=>t[e]>1));if(ie(0===n.length,(()=>"Duplicate column names found: "+n.toString())),this.columnConfigs)for(const e of Object.keys(this.columnConfigs)){if(-1===this.fullColumnNames.indexOf(e))throw new Error('The key "'+e+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}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 LC(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(ie(null==t.delimiter,(()=>"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((e=>this.makeDataElement(e)))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let r=0;r<this.fullColumnNames.length;r++){const a=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[a]:null;if(!this.configuredColumnsOnly||i){const o=t[r];let l=null;if(""===o)if(i&&void 0!==i.default)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);l=void 0}else{const e=Number(o);if(isNaN(e))l=i&&"bool"===i.dtype?this.getBoolean(o):o;else if(i&&i.dtype)switch(i.dtype){case"float32":default:l=e;break;case"int32":l=Math.floor(e);break;case"bool":l=this.getBoolean(o)}else l=e}i&&i.isLabel?s[a]=l:n[a]=l}}return 0===Object.keys(s).length?n:{xs:n,ys:s}}getBoolean(e){return"1"===e||"true"===e.toLowerCase()?1:0}parseRow(e,t=!0){const n=[];let s=0;const r=e.length;let a=PC;for(let t=0;t<r;t++)switch(a){case PC:switch(e.charAt(t)){case zC:s=t+1,a=WC;break;case this.delimiter:if(s=t+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=PC;break;default:a=BC,s=t}break;case BC:if(e.charAt(t)===this.delimiter)n.push(e.substring(s,t)),a=PC,s=t+1;break;case WC:if(e.charAt(t)===zC)a=VC;break;case VC:switch(e.charAt(t)){case this.delimiter:n.push(e.substring(s,t-1)),a=PC,s=t+1;break;case zC:a=WC;break;default:a=UC}break;case UC:if(e.charAt(t)===zC)a=WC}if(a===VC?n.push(e.substring(s,r-1)):n.push(e.substring(s)),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}}class HC extends fC{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!Xe().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new HC(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(e){throw new Error(`Error thrown while initializing video stream: ${e.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise((s=>{const r=setInterval((()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))}),this.fftSize/this.sampleRateHz*1e3)}))}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach(((e,s)=>n.set(e,s*t))),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(ue(t));return n.set(e,n.length-e.length),ei(n,t)}}class jC extends fC{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=cp([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,s=(1-t)/2,r=n+e,a=t+s;this.cropBox=hp([s,n,a,r],[1,4])}else this.cropBox=hp([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!Xe().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new jC(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&ie("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`));try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise((e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}}))}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Zl(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return hi((()=>{const t=bh($o(e,"float32"),0);let n;n=Gf.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=n.shape;return cc(n,s.slice(1))}))}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach((e=>e.stop()));try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class qC{}class KC extends fC{split(e){return new XC(this,e)}}class XC extends KC{constructor(e,t){super(),this.upstream=e,this.impl=new YC(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class YC extends SC{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const e of t.slice(0,-1))this.outputQueue.push(e);return this.carryover=t[t.length-1],!0}}class ZC extends fC{decodeUTF8(){return new JC(this)}}class JC extends KC{constructor(e){super(),this.upstream=e,this.impl=new QC(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class QC extends SC{constructor(e){if(super(),this.upstream=e,Xe().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=n(530);this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=Xe().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class e$ extends ZC{constructor(e,t={}){super(),this.file=e,this.options=t,ie(e instanceof Uint8Array||!!Xe().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(()=>"FileChunkIterator only supports File, Blob and Uint8Array right now.")),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise(((e,t)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const s=new FileReader;s.onload=n=>{let r=s.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(r)},s.onabort=e=>t(new Error("Aborted")),s.onerror=e=>t(new Error(e.type));const r=this.file.slice(this.offset,n);s.readAsArrayBuffer(r)}this.offset=n}));return{value:await e,done:!1}}}const t$=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 n$(e){return"string"==typeof e&&"file://"===e.slice(0,7)}class s$ extends qC{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(n$(this.input)&&Xe().get("IS_NODE")){const e=n(108);this.input=e.readFileSync(this.input.slice(7))}return new e$(this.input,this.options)}}class r$ extends qC{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return n$(this.url)?new s$(this.url,this.fileOptions).iterator():async function(e,t={},n){let s,r;"string"==typeof e?s=e:(s=e.url,r=t$(e));const a=await(n||Yr)(s,r);if(a.ok){const e=new Uint8Array(await a.arrayBuffer());return new e$(e,t)}throw new Error(a.statusText)}(this.url,this.fileOptions)}}function a$(e,t={}){return new GC(new r$(e),t)}function i$(e){const t=dC(e);return FC((async()=>t))}function o$(e){return FC((async()=>{const t=await e();return dC((()=>t.next()))}))}async function l$(e,t){return jC.create(e,t)}async function u$(e){return HC.create(e)}const c$="4.20.0";function h$(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&ie("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const d$=Ip;class p$ extends Y{nextDataId(){return p$.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new X(this,li())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Xe().get("IS_NODE")&&xr("\n============================\nHi, 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. \n============================"));const s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&Ee(n[0])){const r=n.map((e=>Zr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return vm(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return ze(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Jr(e)));return Co(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Co(e.shape,e.dtype,t)}makeOutput(e,t,n){return li().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Xr();e();return{kernelMs:Xr()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){h$([e],"where");const t=this.readSync(e.dataId);return d$(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function f$(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}p$.nextDataId=0;const m$={kernelName:et,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;h$(t,"abs");let s=new Float32Array(ue(t.shape));return s=f$(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,t.dtype)}};function g$(e){return(t,n,s,r,a)=>{const i=ll(t,n),o=i.length,l=Oe(i),u=ke(a,ue(i)),c=t.length,h=n.length,d=Oe(t),p=Oe(n),f=il(t,i),m=il(n,i);if(f.length+m.length===0)for(let t=0;t<u.length;++t)u[t]=e(s[t%s.length],r[t%r.length]);else for(let t=0;t<u.length;++t){const n=Ge(t,o,l),a=n.slice(-c);f.forEach((e=>a[e]=0));const i=Ue(a,c,d),g=n.slice(-h);m.forEach((e=>g[e]=0));const y=Ue(g,h,p);u[t]=e(s[i],r[y])}return[u,i]}}function y$(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(s.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",i)},o}const b$={kernelName:Ct,backendName:"cpu",kernelFunc:y$};function x$(e,t,n="float32"){if("complex64"===n){return y$({inputs:{real:x$(e,t,"float32"),imag:x$(e,t,"float32")},backend:e})}const s=Be(ue(t),n);return e.makeTensorInfo(t,n,s)}function w$(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const v$={kernelName:yn,backendName:"cpu",kernelFunc:w$};function k$(e){const{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}const I$={kernelName:ms,backendName:"cpu",kernelFunc:k$};function N$(e,t,n,s){if("int32"===s){return[t,"int32",Int32Array.from(e)]}if("bool"===s){const s=Kr([0],n),[r,a]=g$(((e,t)=>e!==t?1:0))(t,[],e,s,"bool");return[a,"bool",r]}throw new Error(`Error in Cast: failed to cast ${n} to ${s}`)}function S$(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if("complex64"===a){if("complex64"===r.dtype)return w$({inputs:{x:r},backend:n});const e=x$(n,r.shape,r.dtype),t=S$({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),s=y$({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),s}if("complex64"===r.dtype){const e=k$({inputs:{input:r},backend:n}),t=S$({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!Te(r.dtype,a)){const e=w$({inputs:{x:r},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}const i=n.data.get(r.dataId).values,[o,l,u]=N$(i,r.shape,r.dtype,a);return n.makeTensorInfo(o,l,u)}const T$={kernelName:Nt,backendName:"cpu",kernelFunc:S$};function C$(e,t,n,s){return null==n?({inputs:n,backend:r})=>{const{a,b:i}=n,o=r;h$([a,i],e);const l=o.data.get(a.dataId).values,u=o.data.get(i.dataId).values,c="string"===a.dtype?tg(l):l,h="string"===a.dtype?tg(u):u,d=s||a.dtype,[p,f]=t(a.shape,i.shape,c,h,d);return o.makeTensorInfo(f,d,p)}:({inputs:e,backend:r})=>{const{a,b:i}=e,o=r;if("complex64"===a.dtype||"complex64"===i.dtype){const e=S$({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,l=o.data.get(s.dataId).values,u=o.data.get(r.dataId).values,c=S$({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),d=h.complexTensorInfos.real,p=h.complexTensorInfos.imag,f=o.data.get(d.dataId).values,m=o.data.get(p.dataId).values,[g,y,b]=n(a.shape,i.shape,l,u,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=y$({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(a.dataId).values,n=o.data.get(i.dataId).values,r=s||a.dtype,[l,u]=t(a.shape,i.shape,e,n,r);return o.makeTensorInfo(u,r,l)}}}function $$(e){return(t,n,s,r,a,i)=>{const o=ll(t,n),l=ue(o),u=o.length,c=Oe(o),h=ke("float32",l),d=ke("float32",l),p=il(t,o),f=il(n,o),m=vm(s,r),g=vm(a,i),y=t.length,b=Oe(t),x=n.length,w=Oe(n);if(p.length+f.length===0)for(let t=0;t<h.length;t++){const n=t%m.length,s=t%g.length,r=e(m[2*n],m[2*n+1],g[2*s],g[2*s+1]);h[t]=r.real,d[t]=r.imag}else for(let t=0;t<h.length;t++){const n=Ge(t,u,c),s=n.slice(-y);p.forEach((e=>s[e]=0));const r=Ue(s,y,b),a=n.slice(-x);f.forEach((e=>a[e]=0));const i=Ue(a,x,w),o=e(m[2*r],m[2*r+1],g[2*i],g[2*i+1]);h[t]=o.real,d[t]=o.imag}return[h,d,o]}}const E$=g$(((e,t)=>e+t)),R$=$$(((e,t,n,s)=>({real:e+n,imag:t+s}))),A$=C$(st,E$,R$),_$={kernelName:st,backendName:"cpu",kernelFunc:A$};function F$(e,t,n,s,r){const a=ue(s),i=Be(r,n);for(let n=0;n<e.length;n++){const s=e[n];if(s<0)throw new Error("Input x must be non-negative!");s>=r||(i[s]+=a>0?t[n]:1)}return i}function D$(e,t,n,s=!1){const r=e.shape[0],a=e.shape[1],i=Co([r,n],t.dtype);for(let o=0;o<r;o++)for(let r=0;r<a;r++){const a=e.get(o,r);if(a<0)throw new Error("Input x must be non-negative!");a>=n||(s?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,r),o,a):i.set(i.get(o,a)+1,o,a))}return i}const O$=g$(((e,t)=>e&t)),M$=C$(vt,O$),L$={kernelName:vt,backendName:"cpu",kernelFunc:M$};function z$(e){return(t,n,s)=>{const r=Ie(n,t.length);for(let n=0;n<t.length;++n)r[n]=e(t[n],s);return r}}function P$(e,t,n){return B$(e,z$(t),n)}function B$(e,t,n){return({inputs:s,attrs:r,backend:a})=>{const{x:i}=s;h$(i,e);const o=a,l=o.data.get(i.dataId).values;let u;if("string"===i.dtype){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=tg(l)}else u=l;const c=n||i.dtype,h=t(u,c,r);return o.makeTensorInfo(i.shape,c,h)}}const W$=z$((e=>Math.ceil(e))),V$=B$(St,W$),U$={kernelName:St,backendName:"cpu",kernelFunc:V$};function G$(e,t,n,s){const r=Ie(n,ue(t));if(s&&"string"!==n){let t=0;e.forEach((e=>{const n=ue(e.shape);r.set(e.vals,t),t+=n}))}else{let s=0;e.forEach((e=>{const a="string"===n?tg(e.vals):e.vals;let i=0;for(let n=0;n<e.shape[0];++n){const o=n*t[1]+s;for(let t=0;t<e.shape[1];++t)r[o+t]=a[i++]}s+=e.shape[1]}))}return r}const H$=g$(((e,t)=>e===t?1:0)),j$=C$(nn,H$,null,"bool"),q$={kernelName:nn,backendName:"cpu",kernelFunc:j$},K$=z$((e=>Math.exp(e))),X$=B$(sn,K$,"float32"),Y$={kernelName:sn,backendName:"cpu",kernelFunc:X$},Z$=z$((e=>Math.expm1(e))),J$=B$(an,Z$),Q$={kernelName:an,backendName:"cpu",kernelFunc:J$},eE=z$((e=>Math.floor(e))),tE=B$(cn,eE),nE={kernelName:cn,backendName:"cpu",kernelFunc:tE},sE=g$(((e,t)=>Math.floor(e/t))),rE=C$(hn,sE,null,"int32"),aE={kernelName:hn,backendName:"cpu",kernelFunc:rE};function iE(e,t,n,s,r,a,i,o,l){const u=Co([s,a],n);for(let n=0;n<s;n++){const s=[];let c=0;for(let t=0;t<r;t++){const a=e[n*r+t];c+=a*i[t],s.push(a)}if(c<0||c>=l/a)throw new Error(`Invalid indices: ${s} does not index into ${o}`);for(let e=0;e<a;e++)u.values[n*a+e]=t.get(...t.indexToLoc(c*a+e))}return u}function oE(e,t,n){const s=Co(n,e.dtype);for(let n=0;n<s.size;++n){const r=s.indexToLoc(n).slice(),a=r[0],i=r[2],o=t.locToIndex([a,i]);r[2]=t.values[o];const l=e.locToIndex(r);0<=l&&l<e.values.length&&(s.values[n]=e.values[l])}return s}const lE=g$(((e,t)=>e>t?1:0)),uE=C$(mn,lE,null,"bool"),cE={kernelName:mn,backendName:"cpu",kernelFunc:uE},hE=g$(((e,t)=>e>=t?1:0)),dE=C$(gn,hE,null,"bool"),pE={kernelName:gn,backendName:"cpu",kernelFunc:dE},fE=g$(((e,t)=>e<t?1:0)),mE=C$(Nn,fE,null,"bool"),gE={kernelName:Nn,backendName:"cpu",kernelFunc:mE},yE=g$(((e,t)=>e<=t?1:0)),bE=C$(Sn,yE,null,"bool"),xE={kernelName:Sn,backendName:"cpu",kernelFunc:bE};function wE(e,t,n){const s=(t-e)/(n-1),r=Be(n,"float32");r[0]=e;for(let e=1;e<r.length;e++)r[e]=r[e-1]+s;return r}const vE=z$((e=>Math.log(e))),kE=B$(Cn,vE),IE={kernelName:Cn,backendName:"cpu",kernelFunc:kE};function NE(e,t,n,s){const r=ke(s,ue(n));for(let n=0;n<r.length;++n){const s=n*t;let a=e[s];for(let n=0;n<t;++n){const t=e[s+n];(Number.isNaN(t)||t>a)&&(a=t)}r[n]=a}return r}const SE=g$(((e,t)=>Math.max(e,t))),TE=C$(Pn,SE),CE={kernelName:Pn,backendName:"cpu",kernelFunc:TE},$E=g$(((e,t)=>Math.min(e,t))),EE=C$(qn,$E),RE={kernelName:qn,backendName:"cpu",kernelFunc:EE},AE=g$(((e,t)=>e*t)),_E=$$(((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n}))),FE=C$(Zn,AE,_E),DE={kernelName:Zn,backendName:"cpu",kernelFunc:FE};function OE(e,t,n){const s=qr(-1,n);return AE([],t,s,e,n)}const ME={kernelName:Jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;h$(s,"neg");const r=n.data.get(s.dataId).values,[a,i]=OE(r,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,a)}},LE=g$(((e,t)=>e!==t?1:0)),zE=C$(Qn,LE,null,"bool"),PE={kernelName:Qn,backendName:"cpu",kernelFunc:zE};function BE(e,t,n,s,r){const a=t.length,i=ue(t),o=Oe(t),l=Oe(r),u=ke(n,ue(r));for(let t=0;t<i;++t){const n=Ge(t,a,o),r=new Array(n.length);for(let e=0;e<r.length;e++)r[e]=n[s[e]];u[Ue(r,a,l)]=e[t]}return u}function WE(e){const{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{perm:a}=n;h$(r,"transpose");const i=r.shape.length,o=new Array(i);for(let e=0;e<o.length;e++)o[e]=r.shape[a[e]];const l=BE(s.data.get(r.dataId).values,r.shape,r.dtype,a,o);return{dataId:s.write(l,o,r.dtype),shape:o,dtype:r.dtype}}const VE={kernelName:or,backendName:"cpu",kernelFunc:WE};function UE(e,t,n,s){const[r,a]=ah(e,s),i=Sa(t,"int32"),o=Be(ue(r),i),l=ue(a);for(let e=0;e<o.length;++e){const t=e*l;let s=1;for(let e=0;e<l;++e)s*=n[t+e];o[e]=s}return{outVals:o,outShape:r,outDtype:i}}const GE={kernelName:cs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;h$(r,"prod");const o=r.shape.length,l=we(a,r.shape),u=lh(l,o);let c=l,h=r;const d=[];null!=u&&(h=WE({inputs:{x:r},backend:n,attrs:{perm:u}}),d.push(h),c=ch(c.length,o));const p=n.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=UE(h.shape,h.dtype,p,c);let y=m;return i&&(y=ih(m,l)),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function HE(e,t,n,s){const r=[];let a=0;const i=t.length-1+n.length,o=new Array(i).fill(null).map((()=>[0]));!function(e,t){for(let n=0;n<e.length;++n){const s=e[n],r=n===e.length-1?t:e[n+1].length;if(0===s.length)throw new Error("Ragged splits may not be empty");if(s[0]<0)throw new Error("Ragged splits must be non-negative");if(s[s.length-1]>r)throw new Error("Ragged splits must not point past values");for(let e=1;e<s.length;++e)if(s[e-1]>s[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,s);let l=1;for(let e=0;e<t.length-1;++e){l*=t[e];const n=t[e+1];for(let t=1;t<l+1;++t)o[e].push(t*n)}for(let s=0;s<e.length;++s){let i=e[s],l=e[s]+1;for(let e=0;e<n.length;++e){const s=n[e],r=e+t.length-1;if(r>=0){const e=o[r],t=e[e.length-1]-s[i];for(let e=i;e<l;++e)o[r].push(s[e+1]+t)}i=s[i],l=s[l]}l!==i&&(r.push([i,l]),a+=l-i)}return{outSplits:o,valueSlices:r,numValues:a}}function jE(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let s=t;s<e.length;s++)n[t-1]*=e[s];return n}function qE(e,t,n,s,r){const a=t.slice();a[0]=r;const i=Ie(n,ue(a)),o=e.length;return function(e,t,n,s,r,a){const i=jE(t,2)[1],o=jE(a,2)[1];let l=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<s;++t)r[l*o+t]=e[n*i+t];++l}}(e,t,s,0===o?0:o/t[0],i,a),[i,a]}function KE(e,t,n,s,r,a,i,o){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach(((e,s)=>{if(e<0||e>=n){const r=Ge(s,t.length,Oe(t)).join(",");throw new Error(`indices[${r}] = ${e} is not in [0, ${n})`)}}))}(a,i,t[0][0]-1),0===s.length)throw new Error("params.rank must be nonzero");const l=s[0],{outSplits:u,valueSlices:c,numValues:h}=HE(a,i,e,l),d=function(e){const t=[];for(let n=0;n<e.length;++n){const s=Ie("int32",e[n].length);t.push(s),e[n].forEach(((e,t)=>s[t]=e))}return t}(u),p=qE(n,s,r,c,h);return[d,p[0],p[1]]}const XE=2147483647;function YE(e,t,n,s,r,a,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");const o=0===t.length,l=0===r.length,u=0===i.length,c=[];o||c.push(t[0]),l||c.push(r[0]),u||c.push(i[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const h=0===c.length?1:c[0],d=Ie("int32",h+1);d[0]=0;for(let t=0;t<h;++t){const n=o?e[0]:e[t],r=l?s[0]:s[t],i=u?a[0]:a[t];if(0===i)throw new Error("Requires delta != 0");let c;if(i>0&&r<n||i<0&&r>n)c=0;else if(c=Math.ceil(Math.abs((r-n)/i)),c>XE)throw new Error(`Requires ((limit - start) / delta) <= ${XE}`);d[t+1]=d[t]+c}const p=Ie(n,d[h]);let f=0;for(let t=0;t<h;++t){const n=d[t+1]-d[t];let s=o?e[0]:e[t];const r=u?a[0]:a[t];for(let e=0;e<n;++e)p[f++]=s,s+=r}return[d,p]}var ZE=em;class JE{constructor(e,t,n,s,r,a,i,o,l,u){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=s,this.valuesDType=r,this.defaultValue=a,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=nm(u),this.raggedRank=sm(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===ZE.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===ZE.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case ZE.VALUE_ROWIDS:return JE.getMaxWidthValueRowID(t);case ZE.ROW_SPLITS:return JE.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${ZE[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let s=0;s<t-1;++s){const t=e[s+1]-e[s];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,s=e[0],r=0;for(let a=1;a<t;++a){const t=e[a];t!==s&&(s=t,r=Math.max(a-n,r),n=a)}return Math.max(t-n,r)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return eR(e,n)}calculateOutputSize(e){const t=this.valuesShape;rm(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=tm(this.raggedRank,n,t);s[0]<0&&(s[0]=e);for(let e=1;e<=this.raggedRank;++e)s[e]<0&&(s[e]=this.getMaxWidth(e));return s}calculateFirstParentOutputIndex(e,t,n){const s=Math.min(e,n),r=[];let a=0;for(let e=0;e<s;++e,a+=t)r.push(a);for(let t=s;t<e;++t)r.push(-1);return ie(r.length===e,(()=>"Final length of result must be equal to firstDimension.")),r}calculateOutputIndexRowSplit(e,t,n,s){const r=e.length,a=[];for(let i=0;i<r-1;++i){const r=e[i+1]-e[i];let o=Math.min(s,r),l=t[i];-1===l&&(o=0);for(let e=0;e<o;++e)a.push(l),l+=n;for(let e=0;e<r-o;++e)a.push(-1)}if(r>0&&a.length!==e[r-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,s){const r=e.length,a=[];if(0===r)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let l=t[o];a.push(l);for(let u=1;u<r;++u){const r=e[u];if(r===o)l>=0&&(++i,i<s?l+=n:l=-1);else{if(i=0,o=r,r>=t.length)throw new Error(`Got nextValueRowId=${r} which is not less than ${t.length}`);l=t[r]}a.push(l)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,s){const r=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case ZE.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,s);case ZE.ROW_SPLITS:if(r.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(r,t,n,s);default:throw new Error(`Unsupported partition type: ${ZE[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case ZE.FIRST_DIM_SIZE:return e[0];case ZE.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case ZE.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${ZE[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const s=eR(t,!1),r=Ie(this.valuesDType,ue(s));if(n[0]*t[0]>0){let a=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e){a=this.calculateOutputIndex(e-1,a,n[e],t[e])}this.setOutput(this.raggedRank,a,r,s)}return[s,r]}setOutput(e,t,n,s){if(0===n.length)return;const r=this.values,a=n;let i=s.slice();i=i.slice(e+1);const o=ue(i),l=t.length;let u=this.defaultValue;if(u.length!==o&&1!==u.length){const e=this.defaultValueShape;hi((()=>{const t=cc(u,e),n=Tc(t,i);u=n.dataSync()}))}let c=0,h=0,d=0;for(let e=0;e<=l;++e){let s=e<l?t[e]:-1;if(s!==d){if(h<d){const e=r.subarray(c*o);QE(a.subarray(h*o),e,(d-h)*o)}if(e>=l){const e=n.length;s=Math.floor(e/o)}if(s>d)if(1===this.defaultValue.length)a.subarray(d*o,s*o).fill(this.defaultValue[0]),d=s;else for(;s>d;){QE(a.slice(d*o),u,o),++d}s<0?(c=e+1,h=d):(c=e,h=d,d=h+1)}else++d}}}function QE(e,t,n){for(let s=0;s<n;s++)e[s]=t[s]}function eR(e,t){const n=[];for(let s of e){if(s<0){if(!t)throw new Error(`Dimension ${s} must be >= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}n.push(s)}return n}function tR(e,t,n,s,r,a,i,o,l,u){return new JE(e,t,n,s,r,a,i,o,l,u).compute()}function nR(e,t,n,s){if(e===t||e<t&&n<0||t<e&&n>1)return Be(0,s);const r=Be(Math.abs(Math.ceil((t-e)/n)),s);t<e&&1===n&&(n=-1),r[0]=e;for(let e=1;e<r.length;e++)r[e]=r[e-1]+n;return r}const sR=z$((e=>1/Math.sqrt(e))),rR=B$(Ts,sR),aR={kernelName:Ts,backendName:"cpu",kernelFunc:rR};function iR(e,t,n,s,r,a,i,o,l,u){const c=[s/r,r],h=e.values,d=t.values;if(0===s)return Co(n,t.dtype);const p=l instanceof da?l:Co(c,t.dtype);"string"==typeof l||"number"==typeof l?p.values.fill(l):"boolean"==typeof l&&p.values.fill(+l);for(let e=0;e<a;e++){const a=[];let l=0;for(let t=0;t<i;t++){const n=h[e*i+t];a.push(n),l+=n*o[t]}if(l<0||l>=s/r)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n<r;n++)u?p.values[l*r+n]+=d[e*r+n]:p.values[l*r+n]=0===t.rank?d[0]:d[e*r+n]}return p}const oR=z$((e=>1/(1+Math.exp(-e)))),lR=P$(Ms,(e=>1/(1+Math.exp(-e)))),uR={kernelName:Ms,backendName:"cpu",kernelFunc:lR};function cR(e,t,n,s,r){const a=gu(s,t,n),i=ue(n),o=Oe(s);if(a){const n=yu(t,o);return"string"===r?e.slice(n,n+i):e.subarray(n,n+i)}const l=Co(s,r,"string"===r?tg(e):e),u=Co(n,r);for(let e=0;e<u.size;++e){const n=u.indexToLoc(e),s=n.map(((e,n)=>e+t[n]));u.set(l.get(...s),...n)}return"string"===r?ng(u.values):u.values}function hR(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s;h$(r,"slice");const[o,l]=bu(r,a,i);ru(r,o,l);const u=cR(n.data.get(r.dataId).values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}const dR={kernelName:_s,backendName:"cpu",kernelFunc:hR};function pR(e,t,n,s,r,a,i){const o=t[0],l=a[0],u=new Array(l),c=new Array(o),h=t[1];if(0===l){if(0!==o)throw new Error(Bm(o));return[Ie(n,0),[0,h],Ie(r,0),u,c]}let d=!0,p=0;const f=new Array(l).fill(0);for(let t=0;t<o;++t){const n=e[t*h];if(n<0)throw new Error(Wm(t,n));if(n>=l)throw new Error(Vm(t,n,l));++f[n],d=d&&n>=p,p=n}let m=!0;for(let e=0;e<l;++e){const t=0===f[e];u[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&d){const t=e,n=s;for(let e=0;e<o;++e)c[e]=e;return[t,[o,h],n,u,c]}{const t=f[l-1],a=Ie(n,t*h),d=Ie(r,t),p=new Array(l).fill(0);for(let t=0;t<o;++t){const n=e[t*h],r=p[n],i=(0===n?0:f[n-1])+r;p[n]++;for(let n=0;n<h;++n)a[i*h+n]=e[t*h+n];d[i]=s[t],c[t]=i}for(let e=0;e<l;++e){if(0===p[e]){const t=0===e?0:f[e-1];a[t*h+0]=e;for(let e=1;e<h;++e)a[t*h+e]=0;d[t]=i}}return[a,[t,h],d,u,c]}}function fR(e,t,n,s,r){const a=ue(s),i=t[0],o=r.length,l=[];let u=1,c=-1;for(let e=0;e<o;++e){const t=r[e];if(-1===t){if(-1!==c)throw new Error(Um(c,e));c=e,l.push(1)}else{if(t<0)throw new Error(Gm(e,t));u*=t,l.push(t)}}if(-1!==c){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(a/u);if(u*e!==a)throw new Error(jm(s,l));l[c]=e}if(ue(l)!==a)throw new Error(qm(s,l));const h=s.length,d=[];if(h>0){d[h-1]=1;for(let e=h-2;e>=0;--e)d[e]=d[e+1]*s[e+1]}const p=[];if(o>0){p[o-1]=1;for(let e=o-2;e>=0;--e)p[e]=p[e+1]*l[e+1]}const f=Ie(n,i*o);for(let t=0;t<i;++t){let n=0;for(let s=0;s<h;++s)n+=e[t*h+s]*d[s];for(let e=0;e<o;++e)f[t*o+e]=Math.trunc(n/p[e]),n%=p[e]}return[f,[i,o],l]}function mR(e,t,n,s,r,a=!1,i=0){const o=s.length,l=[t[0],e.length/t[0]],u=l[1],c=o>0?r[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const d=Ie(n,h.reduce(((e,t)=>e*t),1));if(0===o)return c>0&&d.fill(i),[d,h];if(c<=0)throw new Error("segment ids must be >= 0");let p=0,f=1,m=0,g=r[p];for(;;){let t=0;if(f<o){if(t=r[f],g===t){++f;continue}if(g>=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Ym(g,c));g>m&&d.fill(i,m*u,g*u);for(let t=p;t<f;++t){const n=s[t];if(n<0||n>=l[0])throw new Error(Zm(t,s[t],l[0]));for(let t=0;t<u;t++)d[g*u+t]+=e[n*u+t]}if(a)for(let e=0;e<u;e++)d[g*u+e]/=f-p;if(p=f,++f,m=g+1,g=t,f>o)break}return m<c&&d.fill(i,m*u,c*u),[d,h]}const gR=z$((e=>Math.sqrt(e))),yR=P$(zs,(e=>Math.sqrt(e))),bR={kernelName:zs,backendName:"cpu",kernelFunc:yR},xR=g$(((e,t)=>{const n=e-t;return n*n})),wR=C$(Ks,xR),vR={kernelName:Ks,backendName:"cpu",kernelFunc:wR},kR=z$(((e,t)=>{const{pattern:n,replaceGlobal:s,rewrite:r}=t;return e.replace(new RegExp(n,s?"g":""),r)})),IR=B$(Ys,kR),NR={kernelName:Ys,backendName:"cpu",kernelFunc:IR};function SR(e,t,n,s){const r=Co(e,t.dtype);for(let e=0;e<r.size;e++){const a=r.indexToLoc(e),i=new Array(a.length);for(let e=0;e<i.length;e++)i[e]=a[e]*n[e]+s[e];r.set(t.get(...i),...a)}return r}class TR{constructor(e,t,n,s,r,a){this.separator=Zr(e),this.nGramWidths=t,this.leftPad=Zr(n),this.rightPad=Zr(s),this.padWidth=r,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,s,r,a){for(let i=0;i<r;++i){const o=this.getPadWidth(a),l=Math.max(0,o-i),u=Math.max(0,o-(r-(i+1))),c=a-(l+u),h=t+(l>0?0:i-o);let d=0;d+=l*this.leftPad.length;for(let t=0;t<c;++t)d+=e[h+t].length;d+=u*this.rightPad.length;d+=(l+u+c-1)*this.separator.length,n[s+i]=new Uint8Array(d);const p=n[s+i];let f=0;const m=e=>e.forEach((e=>p[f++]=e));for(let e=0;e<l;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[h+t]),m(this.separator);if(c>0){m(e[h+c-1]);for(let e=0;e<u;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<u-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,s=t.length;if(s>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let r=1;r<s;++r){let s=t[r]>=e;if(s=s&&t[r]<=n,!s)throw new Error(`Invalid split value ${t[r]}, must be in [${e}, ${n}]`);e=t[r]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const r=s-1,a=Ie("int32",s);if(0===n||0===s){const e=new Array(n);for(let e=0;e<=r;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=r;++e){const n=t[e]-t[e-1];let s=0;this.nGramWidths.forEach((e=>{s+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===s&&(s=1),a[e]=a[e-1]+s}const i=new Array(a[r]);for(let n=0;n<r;++n){const s=t[n];let r=a[n];if(this.nGramWidths.forEach((a=>{const o=t[n+1]-t[n],l=this.getNumNGrams(o,a);this.createNGrams(e,s,i,r,l,a),r+=l})),this.preserveShort&&r===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,l=1;this.createNGrams(e,s,i,r,l,o)}}return[i,a]}}function CR(e,t,n,s,r,a,i,o){return new TR(n,s,r,a,i,o).compute(e,t)}function $R(e,t,n,s){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)s.push(e.subarray(t,t+1));return}if(1===t.length){const r=t[0];let a=e.indexOf(r);for(;-1!==a;){const t=e.subarray(0,a);n&&0===t.length||s.push(t),a=(e=e.subarray(a+1)).indexOf(r)}return void(n&&0===e.length||s.push(e))}let r=0;for(let a=0;a<e.length+1;a++)if(a===e.length||-1!==t.indexOf(e[a])){const t=e.subarray(r,a);n&&0===t.length||s.push(t),r=a+1}}function ER(e,t,n){const s=e.length,r=[];let a=0,i=0;const o=new Array(s);for(let l=0;l<s;++l){const s=r.length;$R(e[l],t,n,r);const u=r.length-s;o[l]=u,a+=u,i=Math.max(i,u)}const l=Ie("int32",2*a),u=new Array(a),c=[s,i];let h=0;for(let e=0;e<s;++e)for(let t=0;t<o[e];++t)l[2*h]=e,l[2*h+1]=t,u[h]=r[h],++h;return[l,u,c]}function RR(e,t){const n=Ie("int32",e.length);for(let s=0;s<e.length;++s)n[s]=jr(e[s]).modulo(t).getLowBitsUnsigned();return n}const AR=g$(((e,t)=>e-t)),_R=$$(((e,t,n,s)=>({real:e-n,imag:t-s}))),FR=C$(tr,AR,_R),DR={kernelName:tr,backendName:"cpu",kernelFunc:FR};function OR(e,t){const n=new Array(e.rank);for(let s=0;s<n.length;s++)n[s]=e.shape[s]*t[s];const s=Co(n,e.dtype);for(let t=0;t<s.values.length;++t){const n=s.indexToLoc(t),r=new Array(e.rank);for(let t=0;t<r.length;t++)r[t]=n[t]%e.shape[t];const a=e.locToIndex(r);s.values[t]=e.values[a]}return s}const MR=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function LR(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){const r=s-n+1,a=t-n+1,i=Math.log(r),o=.5*Math.exp(2*i/3),l=.5*Math.sqrt(i*o*(r-o)/r)*Math.sign(a-r/2);LR(e,t,Math.max(n,Math.floor(t-a*o/r+l)),Math.min(s,Math.floor(t+(r-a)*o/r+l)))}const r=e[t];let a=n,i=s;for(ne(e,n,t),MR(e[s],r)>0&&ne(e,n,s);a<i;){for(ne(e,a,i),a++,i--;MR(e[a],r)<0;)a+=1;for(;MR(e[i],r)>0;)i-=1}0===MR(e[n],r)?ne(e,n,i):(i+=1,ne(e,i,s)),i<=t&&(n=i+1),t<=i&&(s=i-1)}}function zR(e,t,n,s,r){const a=t[t.length-1],[i,o]=[e.length/a,a],l=ke(n,i*s),u=ke("int32",i*s);for(let t=0;t<i;t++){const n=t*o,a=e.subarray(n,n+o);let i=new Array(a.length);a.forEach(((e,t)=>i[t]={value:e,index:t})),s<i.length&&(LR(i,s),i=i.slice(0,s)),r&&i.sort(MR);const c=t*s,h=l.subarray(c,c+s),d=u.subarray(c,c+s);for(let e=0;e<s;e++)h[e]=i[e].value,d[e]=i[e].index}const c=t.slice();return c[c.length-1]=s,[Co(c,n,l),Co(c,"int32",u)]}function PR(e,t,n,s){const r=we(t,n)[0],a=[1,n[0],1];for(let e=0;e<r;e++)a[0]*=n[e];a[1]=n[r];for(let e=r+1;e<n.length;e++)a[2]*=n[e];const i=new Map,o=new Int32Array(n[r]),l=new da(a,s,e),u=[],c=1===a[0]&&1===a[2];for(let t=0;t<n[r];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<a[0];n++)for(let s=0;s<a[2];s++)e.push(l.get(n,t,s));n=e.join(",")}const s=i.get(n);if(null!=s)o[t]=s;else{const e=i.size;i.set(n,e),o[t]=e,u.push(t)}}const h=a.slice();h[1]=i.size;const d=new da(h,s);u.forEach(((e,t)=>{for(let n=0;n<a[0];n++)for(let s=0;s<a[2];s++)d.set(l.get(n,e,s),n,t,s)}));const p=n.slice();return p[r]=h[1],{outputValues:d.values,outputShape:p,indices:o}}const BR="4.20.0";vi("cpu",(()=>new p$),1);const WR=P$(Qt,(e=>e>=0?e:Math.exp(e)-1)),VR={kernelName:Qt,backendName:"cpu",kernelFunc:WR};function UR(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;h$([r],"leakyRelu");const i=ue(r.shape),o=n.data.get(r.dataId).values,l=ke("float32",i);for(let e=0;e<o.length;e++)l[e]=o[e]<0?a*o[e]:o[e];return n.makeTensorInfo(r.shape,"float32",l)}const GR={kernelName:In,backendName:"cpu",kernelFunc:UR},HR=g$(((e,t)=>e<0?t*e:e));function jR(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t;h$([s,r],"prelu");const a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,[o,l]=HR(s.shape,r.shape,a,i,"float32");return n.makeTensorInfo(l,"float32",o)}const qR={kernelName:us,backendName:"cpu",kernelFunc:jR},KR=P$(ys,(e=>Math.max(0,e))),XR={kernelName:ys,backendName:"cpu",kernelFunc:KR},YR=P$(Is,(e=>Math.min(Math.max(0,e),6))),ZR={kernelName:Is,backendName:"cpu",kernelFunc:YR};function JR(e,t,n,s,r){if("linear"===n)return w$({inputs:{x:t},backend:e});if("relu"===n)return KR({inputs:{x:t},backend:e});if("elu"===n)return WR({inputs:{x:t},backend:e});if("relu6"===n)return YR({inputs:{x:t},backend:e});if("prelu"===n)return jR({inputs:{x:t,alpha:s},backend:e});if("leakyrelu"===n)return UR({inputs:{x:t},backend:e,attrs:{alpha:r}});if("sigmoid"===n)return lR({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function QR(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=ue(r.shape),o=xe(a,i),l=ue(o);ie(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);const u=n.data.get(r.dataId);if(null!=u.complexTensorInfos){const e=u.complexTensorInfos.real,t=u.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}const eA={kernelName:bs,backendName:"cpu",kernelFunc:QR};function tA(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;h$([r,a],"matMul");const l=r.shape.length,u=a.shape.length,c=i?r.shape[l-2]:r.shape[l-1],h=o?a.shape[u-1]:a.shape[u-2],d=i?r.shape[l-1]:r.shape[l-2],p=o?a.shape[u-2]:a.shape[u-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=ue(f),y=ue(m),b=ll(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,p]);ie(c===h,(()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,p,h]:[y,h,p],w=QR({inputs:{x:r},backend:n,attrs:{shape:i?[g,c,d]:[g,d,c]}}),v=QR({inputs:{x:a},backend:n,attrs:{shape:x}}),k=i?w.shape[1]:w.shape[2],I=i?w.shape[2]:w.shape[1],N=o?v.shape[1]:v.shape[2],S=Math.max(g,y),T=n.data.get(w.dataId).values,C=n.data.get(v.dataId).values,$=Oe(w.shape),E=Oe(v.shape),[R,A,_]=i?[$[0],1,$[1]]:[$[0],$[1],1],[F,D,O]=o?[1,E[1],E[0]]:[E[1],1,E[0]],M=I*N,L=Co([S,I,N],w.dtype),z=L.values,P=n.blockSize;for(let e=0;e<S;e++){const t=e%g,n=e%y;for(let s=0;s<I;s+=P){const r=Math.min(s+P,I);for(let a=0;a<N;a+=P){const i=Math.min(a+P,N);for(let o=0;o<k;o+=P){const l=Math.min(o+P,k);for(let u=s;u<r;u++)for(let s=a;s<i;s++){let r=0;for(let e=o;e<l;e++){r+=T[t*R+u*A+e*_]*C[e*F+s*D+n*O]}z[e*M+(u*N+s)]+=r}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}const nA={kernelName:bt,backendName:"cpu",kernelFunc:tA};const sA={kernelName:gr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;let d,p,f;const m=[];d=tA({inputs:{a:r,b:a},attrs:{transposeA:l,transposeB:u},backend:n}),i&&(p=A$({inputs:{a:d,b:i},backend:n}),m.push(d),d=p),c&&(f=JR(n,d,c,o,h),m.push(d),d=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return d}},rA=P$(tt,(e=>Math.acos(e))),aA={kernelName:tt,backendName:"cpu",kernelFunc:rA},iA=P$(nt,(e=>Math.acosh(e))),oA={kernelName:nt,backendName:"cpu",kernelFunc:iA};const lA={kernelName:rt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,s=t;h$(t,"addN");const r=s.map((e=>n.data.get(e.dataId).values)),a=Co(s[0].shape,s[0].dtype),i=a.values;for(let e=0;e<s.length;e++){const t=r[e];for(let e=0;e<i.length;e++)i[e]+=t[e]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}};const uA={kernelName:at,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;h$(r,"all");const o=we(a,r.shape);let l=o;const u=lh(l,r.shape.length);let c=r;null!=u&&(c=WE({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ch(l.length,r.shape.length)),oh("all",l,c.shape.length);const[h,d]=ah(c.shape,l),p=ue(d),f=Be(ue(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const s=m[t+e];n=n&&s}f[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=QR({inputs:{x:g},backend:n,attrs:{shape:ih(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const cA={kernelName:it,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;h$(r,"any");const o=we(a,r.shape);let l=o;const u=lh(l,r.shape.length);let c=r;null!=u&&(c=WE({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ch(l.length,r.shape.length)),oh("any",l,c.shape.length);const[h,d]=ah(c.shape,l),p=ue(d),f=Be(ue(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const s=m[t+e];n=n||s}f[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=QR({inputs:{x:g},backend:n,attrs:{shape:ih(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const hA={kernelName:ot,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;h$(r,"argMax");let i=we(a,r.shape);const o=lh(i,r.shape.length);let l=r;const u=[];null!=o&&(l=WE({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ch(i.length,l.shape.length)),i=[i[0]],oh("argMax",i,l.shape.length);const[c,h]=ah(l.shape,i),d=Be(ue(c),"int32"),p=ue(h),f=n.data.get(l.dataId).values;for(let e=0;e<d.length;++e){const t=e*p;let n=f[t],s=0;for(let e=0;e<p;++e){const r=f[t+e];r>n&&(n=r,s=e)}d[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",d)}};const dA={kernelName:lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;h$(r,"argMin");let i=we(a,r.shape);const o=lh(i,r.shape.length);let l=r;const u=[];null!=o&&(l=WE({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ch(i.length,l.shape.length)),i=[i[0]],oh("argMin",i,l.shape.length);const[c,h]=ah(l.shape,i),d=Be(ue(c),"int32"),p=ue(h),f=n.data.get(l.dataId).values;for(let e=0;e<d.length;++e){const t=e*p;let n=f[t],s=0;for(let e=0;e<p;++e){const r=f[t+e];r<n&&(n=r,s=e)}d[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",d)}},pA=P$(ut,(e=>Math.asin(e))),fA={kernelName:ut,backendName:"cpu",kernelFunc:pA},mA=P$(ct,(e=>Math.asinh(e))),gA={kernelName:ct,backendName:"cpu",kernelFunc:mA},yA=P$(ht,(e=>Math.atan(e))),bA={kernelName:ht,backendName:"cpu",kernelFunc:yA},xA=g$(((e,t)=>Math.atan2(e,t))),wA=C$(pt,xA),vA={kernelName:pt,backendName:"cpu",kernelFunc:wA},kA=P$(dt,(e=>Math.atanh(e))),IA={kernelName:dt,backendName:"cpu",kernelFunc:kA};function NA(e,t,n,s,r,a){const i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=r.padInfo.top,p=r.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Co(r.outShape,n),g=m.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],b=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let t=0;t<r.batchSize;++t){const n=t*y,m=t*s[0];for(let t=0;t<r.inChannels;++t)for(let y=0;y<r.outHeight;++y){const w=y*i-d,v=Math.max(0,w),k=Math.min(r.inHeight,c+w),I=n+y*b;for(let n=0;n<r.outWidth;++n){const i=n*o-p,c=Math.max(0,i),d=Math.min(r.inWidth,h+i);let y=f,b=0,w=0;for(let n=v;n<k;n+=l){const r=m+n*s[1];for(let n=c;n<d;n+=u){const i=e[r+n*s[2]+t];"max"===a&&i>y?y=i:"avg"===a&&(b+=i,w++)}if(isNaN(y))break}g[I+n*x+t]="avg"===a?b/w:y}}}return m}function SA(e,t,n,s,r=!1,a=!1){const i=Co(s.outShape,"int32"),o=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,d=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,m=Co(t,n,e);for(let e=0;e<s.batchSize;++e)for(let t=0;t<s.inChannels;++t)for(let n=0;n<s.outHeight;++n){const g=n*o-p;let y=g;for(;y<0;)y+=u;const b=Math.min(s.inHeight,h+g);for(let o=0;o<s.outWidth;++o){const h=o*l-f;let p=h;for(;p<0;)p+=c;const x=Math.min(s.inWidth,d+h);let w=Number.NEGATIVE_INFINITY,v=-1;for(let n=y;n<b;n+=u){const i=n-g;for(let o=p;o<x;o+=c){const l=o-h,u=m.get(e,n,o,t);u>w&&(w=u,v=r?a?((e*s.inHeight+n)*s.inWidth+o)*s.inChannels+t:(n*s.inWidth+o)*s.inChannels+t:i*d+l)}}i.set(v,e,n,o,t)}}return i}function TA(e,t,n,s,r,a){const i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,h=r.dilationWidth,d=r.effectiveFilterDepth,p=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Co(r.outShape,n),w=x.values,v=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],I=r.outShape[3]*r.outShape[4],N=r.outShape[4];for(let t=0;t<r.batchSize;++t){const n=t*v,x=t*s[0];for(let t=0;t<r.inChannels;++t)for(let v=0;v<r.outDepth;++v){const S=v*i-m;let T=S;for(;T<0;)T+=u;const C=Math.min(r.inDepth,d+S),$=n+v*k;for(let n=0;n<r.outHeight;++n){const i=n*o-g;let d=i;for(;d<0;)d+=c;const m=Math.min(r.inHeight,p+i),v=$+n*I;for(let n=0;n<r.outWidth;++n){const i=n*l-y;let o=i;for(;o<0;)o+=h;const p=Math.min(r.inWidth,f+i),g=v+n*N;let k=b,I=0,S=0;for(let n=T;n<C;n+=u){const r=x+n*s[1];for(let n=d;n<m;n+=c){const i=r+n*s[2];for(let n=o;n<p;n+=h){const r=e[i+n*s[3]+t];if("max"===a&&r>k?k=r:"avg"===a&&(I+=r,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?I/Math.max(S,1):k}}}}return x}const CA={kernelName:ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;h$(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;ie(ic(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yu(r.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&de(u.inShape,u.outShape))c=w$({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=Oe(r.shape),s=NA(e,r.shape,r.dtype,t,u,"avg");c=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return c}};const $A={kernelName:gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;h$(r,"avgPool3d");const c=Zu(r.shape,a,i,1,o,l,u),h=TA(n.data.get(r.dataId).values,r.shape,r.dtype,Oe(r.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}};const EA={kernelName:yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;h$([r,a],"avgPool3DGrad");const c=Zu(a.shape,i,o,1,l,u),h=c.strideDepth,d=c.strideHeight,p=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,I=w-1-c.padInfo.front,N=k-1-c.padInfo.left,S=v-1-c.padInfo.top,T=Co(a.shape,"float32"),C=1/(f*m*g),$=n.bufferSync(r);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let s=0;s<c.inHeight;++s)for(let r=0;r<c.inWidth;++r){const a=n-I,i=s-S,o=r-N;let l=0;for(let n=0;n<w;n+=y){const s=(a+n)/h;if(!(s<0||s>=c.outDepth||Math.floor(s)!==s))for(let n=0;n<v;n+=b){const r=(i+n)/d;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let n=0;n<k;n+=x){const a=(o+n)/p;if(a<0||a>=c.outWidth||Math.floor(a)!==a)continue;l+=$.get(e,s,r,a,t)}}}T.set(l*C,e,n,s,r,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}};const RA={kernelName:mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;h$([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Yu(i.shape,o,l,1,u),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,v=Co(i.shape,"float32"),k=1/(p*f),I=n.data.get(r.dataId).values,N=Co(r.shape,"float32",I);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inHeight;++n)for(let s=0;s<c.inWidth;++s){const r=n-w,a=s-x;let i=0;for(let n=0;n<y;n+=m){const s=(r+n)/h;if(!(s<0||s>=c.outHeight||Math.floor(s)!==s))for(let n=0;n<b;n+=g){const r=(a+n)/d;if(r<0||r>=c.outWidth||Math.floor(r)!==r)continue;i+=N.get(e,s,r,t)}}v.set(i*k,e,n,s,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}};const AA={kernelName:dn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:i,mean:o,variance:l}=t;ie(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),h$([r,o,l,a,i],"batchNorm");let{varianceEpsilon:u}=s;null==u&&(u=.001);const c=n.data.get(r.dataId).values,h=n.data.get(o.dataId).values,d=n.data.get(l.dataId).values,p=a?n.data.get(a.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=p.length,b=d.length,x=h.length;let w=0,v=0,k=0,I=0;for(let e=0;e<c.length;++e)m[e]=f[w++]+(c[e]-h[v++])*p[k++]/Math.sqrt(d[I++]+u),w>=g&&(w=0),v>=x&&(v=0),k>=y&&(k=0),I>=b&&(I=0);return n.makeTensorInfo(r.shape,r.dtype,m)}};const _A={kernelName:xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;h$([r],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),l=lm(r.shape,a,o),u=um(l.length,a.length),c=cm(r.shape,a,o),h=hm(i,a.length),d=dm(c,i,a.length),p=QR({inputs:{x:r},backend:n,attrs:{shape:l}}),f=WE({inputs:{x:p},backend:n,attrs:{perm:u}}),m=QR({inputs:{x:f},backend:n,attrs:{shape:c}}),g=hR({inputs:{x:m},backend:n,attrs:{begin:h,size:d}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const FA={kernelName:wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=F$(n.data.get(r.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}};const DA={kernelName:It,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=ll(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},OA=P$(Tt,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),MA={kernelName:Tt,backendName:"cpu",kernelFunc:OA},LA={kernelName:$t,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,s=new Float32Array(ue(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values;for(let e=0;e<o.length;e++){const t=o[e],n=l[e];s[e]=Math.hypot(t,n)}return n.makeOutput(s,t.shape,"float32")}};function zA(e){const{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.imag,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}const PA={kernelName:xn,backendName:"cpu",kernelFunc:zA};function BA(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=we(r,t[0].shape)[0];Jf(t.map((e=>e.shape)),a);let i=Qf(t.map((e=>e.shape)),a);if(0===ue(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>ue(e.shape)>0));if(1===o.length)return w$({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map((e=>k$({inputs:{input:e},backend:n}))),t=o.map((e=>zA({inputs:{input:e},backend:n}))),s=BA({inputs:e,backend:n,attrs:{axis:a}}),r=BA({inputs:t,backend:n,attrs:{axis:a}}),i=y$({inputs:{real:s,imag:r},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(r),i}const l=o.map((e=>{const t=ue(e.shape.slice(a));return QR({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=Qf(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=G$(u,i,t[0].dtype,c),d=Qf(o.map((e=>e.shape)),a),p=n.makeTensorInfo(d,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}const WA={kernelName:Et,backendName:"cpu",kernelFunc:BA};function VA(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s;h$([r,a],"conv2d");const h=lc(l),d=Ju(r.shape,a.shape,i,u,o,c,!1,h),p=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,b=d.padInfo.top,x="channelsLast"===d.dataFormat,w=new da(d.outShape,r.dtype),v=Oe(r.shape),k=Oe(a.shape),I=v[0],N=x?v[1]:v[2],S=x?v[2]:1,T=x?1:v[1],C=w.strides[0],$=x?w.strides[1]:w.strides[2],E=x?w.strides[2]:1,R=x?1:w.strides[1],A=n.data.get(r.dataId).values,_=n.data.get(a.dataId).values,F=w.values;for(let e=0;e<d.batchSize;++e){const t=e*I,n=e*C;for(let e=0;e<d.outHeight;++e){const s=n+e*$,r=e*d.strideHeight-b;for(let e=0;e<p;++e){const n=r+e*m;if(n<0||n>=d.inHeight)continue;const a=e*k[0],i=t+n*N;for(let e=0;e<d.outWidth;++e){const t=s+e*E,n=e*d.strideWidth-y;for(let e=0;e<f;++e){const s=n+e*g;if(s<0||s>=d.inWidth)continue;const r=i+s*S;let o=a+e*k[1];for(let e=0;e<d.inChannels;++e){const n=A[r+e*T];for(let e=0;e<d.outChannels;++e)F[t+e*R]+=n*_[o+e];o+=d.outChannels}}}}}}return n.makeTensorInfo(w.shape,w.dtype,F)}const UA={kernelName:Rt,backendName:"cpu",kernelFunc:VA};const GA={kernelName:At,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s;h$([r,a],"conv2dBackpropFilter");const h=lc(l),d=Ju(r.shape,c,i,1,o,u,!1,h),{strideHeight:p,strideWidth:f,filterHeight:m,filterWidth:g}=d,y="channelsLast"===d.dataFormat,b=new da(d.filterShape,"float32"),x=d.padInfo.left,w=d.padInfo.top,v=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,I=new da(r.shape,r.dtype,v),N=new da(a.shape,a.dtype,k);for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((w-e)/p)),n=Math.min(d.outHeight,(d.inHeight+w-e)/p);for(let s=0;s<g;++s){const r=Math.max(0,Math.ceil((x-s)/f)),a=Math.min(d.outWidth,(d.inWidth+x-s)/f);for(let i=0;i<d.inChannels;++i)for(let o=0;o<d.outChannels;++o){let l=0;for(let u=0;u<d.batchSize;++u)for(let c=t;c<n;++c){const t=e+c*p-w;for(let e=r;e<a;++e){const n=s+e*f-x;l+=y?I.get(u,t,n,i)*N.get(u,c,e,o):I.get(u,i,t,n)*N.get(u,o,c,e)}}b.set(l,e,s,i,o)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const HA={kernelName:_t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s;h$([r,a],"conv2dBackpropInput");const h=Oe(a.shape),d=Oe(r.shape);let p=lc(u);const f=Ju(i,a.shape,o,1,l,c,!1,p),m=new da(f.inShape,"float32"),g=m.values,y=n.data.get(r.dataId).values,b=n.data.get(a.dataId).values,[x,w,v]=h,{batchSize:k,filterHeight:I,filterWidth:N,inChannels:S,inHeight:T,inWidth:C,outChannels:$,outHeight:E,outWidth:R,strideHeight:A,strideWidth:_}=f;p=f.dataFormat;const F=I-1-f.padInfo.top,D=N-1-f.padInfo.left,O="channelsLast"===p,M=m.strides[0],L=O?m.strides[1]:m.strides[2],z=O?m.strides[2]:1,P=O?1:m.strides[1],B=d[0],W=O?d[1]:d[2],V=O?d[2]:1,U=O?1:d[1];for(let e=0;e<k;++e)for(let t=0;t<S;++t)for(let n=0;n<T;++n){const s=n-F,r=Math.max(0,Math.ceil(s/A)),a=Math.min(E,(I+s)/A);for(let i=0;i<C;++i){const o=i-D,l=Math.max(0,Math.ceil(o/_)),u=Math.min(R,(N+o)/_);let c=0;for(let n=r;n<a;++n){const r=n*A-s;for(let s=l;s<u;++s){const a=B*e+W*n+V*s,i=x*(I-1-r)+w*(N-1-(s*_-o))+v*t;for(let e=0;e<$;++e){c+=y[a+U*e]*b[i+e]}}}g[M*e+L*n+z*i+P*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}};const jA={kernelName:Ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s;h$([r,a],"conv3d");const u=Qu(r.shape,a.shape,i,l,o),{filterDepth:c,filterHeight:h,filterWidth:d,dilationDepth:p,dilationHeight:f,dilationWidth:m,padInfo:g}=u,y=g.front,b=g.left,x=g.top,w=new da(u.outShape,r.dtype),v=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,I=w.values,N=Oe(r.shape),S=Oe(a.shape);for(let e=0;e<u.batchSize;++e){const t=e*N[0],n=e*w.strides[0];for(let e=0;e<u.outDepth;++e){const s=n+e*w.strides[1],r=e*u.strideDepth-y;for(let e=0;e<c;++e){const n=r+e*p;if(n<0||n>=u.inDepth)continue;const a=e*S[0],i=t+n*N[1];for(let e=0;e<u.outHeight;++e){const t=s+e*w.strides[2],n=e*u.strideHeight-x;for(let e=0;e<h;++e){const s=n+e*f;if(s<0||s>=u.inHeight)continue;const r=a+e*S[1],o=i+s*N[2];for(let e=0;e<u.outWidth;++e){const n=t+e*u.outChannels,s=e*u.strideWidth-b;for(let e=0;e<d;++e){const t=s+e*m;if(t<0||t>=u.inWidth)continue;const a=r+e*S[2],i=o+t*u.inChannels;let l=a;for(let e=0;e<u.inChannels;++e){const t=v[i+e];for(let e=0;e<u.outChannels;++e)I[n+e]+=t*k[l+e];l+=u.outChannels}}}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}};const qA={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,filterShape:l}=s;h$([r,a],"conv3dBackpropFilterV2");const u=Oe(r.shape),c=Oe(a.shape),h=Qu(r.shape,l,i,1,o),d=h.strideDepth,p=h.strideHeight,f=h.strideWidth,m=h.filterDepth,g=h.filterHeight,y=h.filterWidth,b=new da(h.filterShape,"float32"),x=b.values,[w,v,k,I]=b.strides,N=n.data.get(a.dataId).values,[S,T,C,$]=c,E=n.data.get(r.dataId).values,[R,A,_,F]=u,D=h.padInfo.front,O=h.padInfo.left,M=h.padInfo.top;for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((D-e)/d)),n=Math.min(h.outDepth,(h.inDepth+D-e)/d),s=e*w;for(let r=0;r<g;++r){const a=Math.max(0,Math.ceil((M-r)/p)),i=Math.min(h.outHeight,(h.inHeight+M-r)/p),o=r*v+s;for(let s=0;s<y;++s){const l=Math.max(0,Math.ceil((O-s)/f)),u=Math.min(h.outWidth,(h.inWidth+O-s)/f),c=s*k+o;for(let o=0;o<h.inChannels;++o){const m=o*I+c;for(let c=0;c<h.outChannels;++c){let g=0;for(let m=0;m<h.batchSize;++m){const h=m*R,y=m*S;for(let m=t;m<n;++m){const t=(e+m*d-D)*A+h,n=m*T+y;for(let e=a;e<i;++e){const a=(r+e*p-M)*_+t,i=e*C+n;for(let e=l;e<u;++e){const t=e*$+i;g+=E[(s+e*f-O)*F+a+o]*N[t+c]}}}}x[m+c]=g}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const KA={kernelName:Ot,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:i,strides:o,inputShape:l}=s;h$([r],"conv3dBackpropInputV2");const u=Oe(r.shape),c=Oe(a.shape),h=Qu(l,a.shape,o,1,i),d=new da(h.inShape,"float32"),p=d.values,[f,m,g,y]=d.strides,b=n.data.get(r.dataId).values,[x,w,v,k]=u,I=n.data.get(a.dataId).values,[N,S,T,C]=c,{batchSize:$,filterDepth:E,filterHeight:R,filterWidth:A,inChannels:_,inDepth:F,inHeight:D,inWidth:O,outChannels:M,outDepth:L,outHeight:z,outWidth:P,strideDepth:B,strideHeight:W,strideWidth:V}=h,U=E-1-h.padInfo.front,G=R-1-h.padInfo.top,H=A-1-h.padInfo.left;for(let e=0;e<$;++e)for(let t=0;t<_;++t)for(let n=0;n<F;++n){const s=n-U,r=Math.max(0,Math.ceil(s/B)),a=Math.min(L,(E+s)/B);for(let i=0;i<D;++i){const o=i-G,l=Math.max(0,Math.ceil(o/W)),u=Math.min(z,(R+o)/W);for(let c=0;c<O;++c){const h=c-H,d=Math.max(0,Math.ceil(h/V)),$=Math.min(P,(A+h)/V);let _=0;for(let n=r;n<a;++n){const r=n*B-s;for(let s=l;s<u;++s){const a=s*W-o;for(let i=d;i<$;++i){const o=x*e+w*n+v*s+k*i,l=N*(E-1-r)+S*(R-1-a)+T*(A-1-(i*V-h))+C*t;for(let e=0;e<M;++e){_+=b[o+e]*I[l+e]}}}}p[f*e+m*n+g*i+y*c+t]=_}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}},XA=P$(Mt,(e=>Math.cos(e))),YA={kernelName:Mt,backendName:"cpu",kernelFunc:XA},ZA=P$(Lt,(e=>Math.cosh(e))),JA={kernelName:Lt,backendName:"cpu",kernelFunc:ZA};const QA={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,[c,h,d,p]=r.shape,f=a.shape[0],[m,g]=o,y=Co([f,m,g,p],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(r.dataId).values,v=Oe(r.shape),k=Oe(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],s=b[t+1],r=b[t+2],a=b[t+3],i=x[e];if(i>=c)continue;const o=m>1?(r-n)*(h-1)/(m-1):0,f=g>1?(a-s)*(d-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(h-1)+t*o:.5*(n+r)*(h-1);if(c<0||c>h-1)for(let n=0;n<g;n++)for(let s=0;s<p;s++){const r=s+n*k[2]+t*k[1]+e*k[0];y.values[r]=u}else if("bilinear"===l){const n=Math.floor(c),r=Math.ceil(c),o=c-n;for(let l=0;l<g;l++){const c=g>1?s*(d-1)+l*f:.5*(s+a)*(d-1);if(c<0||c>d-1){for(let n=0;n<p;n++){const s=n+l*k[2]+t*k[1]+e*k[0];y.values[s]=u}continue}const h=Math.floor(c),m=Math.ceil(c),b=c-h;for(let s=0;s<p;s++){let a=s+h*v[2]+n*v[1]+i*v[0];const u=w[a];a=s+m*v[2]+n*v[1]+i*v[0];const c=w[a];a=s+h*v[2]+r*v[1]+i*v[0];const d=w[a];a=s+m*v[2]+r*v[1]+i*v[0];const p=u+(c-u)*b,f=d+(w[a]-d)*b;a=s+l*k[2]+t*k[1]+e*k[0],y.values[a]=p+(f-p)*o}}}else for(let n=0;n<g;++n){const r=g>1?s*(d-1)+n*f:.5*(s+a)*(d-1);if(r<0||r>d-1){for(let s=0;s<p;s++){const r=s+n*k[2]+t*k[1]+e*k[0];y.values[r]=u}continue}const o=Math.round(r),l=Math.round(c);for(let s=0;s<p;s++){const r=s+o*v[2]+l*v[1]+i*v[0],a=s+n*k[2]+t*k[1]+e*k[0];y.values[a]=w[r]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}};const e_={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;h$(r,"cumprod");const l=lh([a],r.shape.length);let u=r;null!=l&&(u=WE({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=ch(1,r.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);const h=Sa(u.dtype,"int32"),d=Pe(ue(u.shape),h),p=n.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<p.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)d[n]=i?1:p[n];else{const s=m(e,t-1);d[n]=i?p[s]*d[s]:p[n]*d[s]}}const g=n.makeTensorInfo(u.shape,h,d);if(null!=l){const e=WE({inputs:{x:g},backend:n,attrs:{perm:uh(l)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),e}return g}};const t_={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;h$(r,"cumsum");const l=lh([a],r.shape.length);let u=r;null!=l&&(u=WE({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=ch(1,r.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);const h=Sa(u.dtype,"int32"),d=Be(ue(u.shape),h),p=n.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let e=0;e<p.length;e+=f)for(let t=0;t<f;t++){const n=m(e,t);if(0===t)d[n]=i?0:p[n];else{const s=m(e,t-1);d[n]=i?p[s]+d[s]:p[n]+d[s]}}const g=n.makeTensorInfo(u.shape,h,d);if(null!=l){const e=WE({inputs:{x:g},backend:n,attrs:{perm:uh(l)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),e}return g}};const n_={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i,binaryOutput:o}=s;if(1===r.shape.length){const e=F$(n.data.get(r.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,e)}if(2===r.shape.length){const e=D$(n.bufferSync(r),n.bufferSync(a),i,o);return n.makeTensorInfo(e.shape,a.dtype,e.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}};const s_={kernelName:Vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s;ie("NHWC"===i,(()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=r.shape[0],l=r.shape[1],u=r.shape[2],c=r.shape[3],h=l*a,d=u*a,p=c/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(o*h*d*p);let g=0;for(let e=0;e<o;++e)for(let t=0;t<h;++t){const n=Math.floor(t/a),s=t%a;for(let t=0;t<d;++t){const r=Math.floor(t/a),i=(s*a+t%a)*p;for(let t=0;t<p;++t){const s=t+i+c*(r+u*(n+l*e));m[g++]=f[s]}}}return n.makeTensorInfo([o,h,d,p],r.dtype,m)}};function r_(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=s;h$([r,a],"depthwiseConv2DNative");const c=Oe(r.shape),h=Oe(a.shape);let d=l;null==d&&(d=[1,1]),ie(ic(i,d),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`));const p=Ju(r.shape,a.shape,i,d,o,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=p,x=b.left,w=b.top,v=p.outChannels/p.inChannels,k=new da(p.outShape,r.dtype),I=n.data.get(r.dataId).values,N=n.data.get(a.dataId).values,S=k.values;for(let e=0;e<p.batchSize;++e){const t=e*c[0],n=e*k.strides[0];for(let e=0;e<p.outHeight;++e){const s=n+e*k.strides[1],r=e*p.strideHeight-w;for(let e=0;e<f;++e){const n=r+e*g;if(n<0||n>=p.inHeight)continue;const a=e*h[0],i=t+n*c[1];for(let e=0;e<p.outWidth;++e){const t=s+e*k.strides[2],n=e*p.strideWidth-x;for(let e=0;e<m;++e){const s=n+e*y;if(s<0||s>=p.inWidth)continue;const r=a+e*h[1],o=i+s*p.inChannels;let l=t,u=r;for(let e=0;e<p.inChannels;++e){const t=I[o+e];for(let e=0;e<v;++e)S[l+e]+=t*N[u+e];l+=v,u+=v}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const a_={kernelName:Ut,backendName:"cpu",kernelFunc:r_};const i_={kernelName:Gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s;h$([r,a],"depthwiseConv2dNativeBackpropFilter");const h=Ju(r.shape,c,i,o,l,u,!0),{strideHeight:d,strideWidth:p,filterHeight:f,filterWidth:m}=h,g=new da(h.filterShape,"float32"),y=h.padInfo.left,b=h.padInfo.top,x=h.outChannels/h.inChannels,w=n.data.get(r.dataId).values,v=new da(r.shape,r.dtype,w),k=n.data.get(a.dataId).values,I=new da(a.shape,a.dtype,k);for(let e=0;e<f;++e){const t=Math.max(0,Math.ceil((b-e)/d)),n=Math.min(h.outHeight,(h.inHeight+b-e)/d);for(let s=0;s<m;++s){const r=Math.max(0,Math.ceil((y-s)/p)),a=Math.min(h.outWidth,(h.inWidth+y-s)/p);for(let i=0;i<h.outChannels;++i){const o=Math.trunc(i/x),l=i%x;let u=0;for(let l=0;l<h.batchSize;++l)for(let c=t;c<n;++c){const t=e+c*d-b;for(let e=r;e<a;++e){const n=s+e*p-y;u+=v.get(l,t,n,o)*I.get(l,c,e,i)}}g.set(u,e,s,o,l)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}};const o_={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s;h$([r,a],"depthwiseConv2DNativeBackpropInput");const h=Oe(r.shape),d=Oe(a.shape),p=Ju(c,a.shape,i,o,l,u,!0),f=new da(p.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(r.dataId).values,[w,v,k]=h,I=n.data.get(a.dataId).values,[N,S,T]=d,{batchSize:C,filterHeight:$,filterWidth:E,inChannels:R,inHeight:A,inWidth:_,outChannels:F,outHeight:D,outWidth:O,strideHeight:M,strideWidth:L}=p,z=$-1-p.padInfo.top,P=E-1-p.padInfo.left,B=F/R;for(let e=0;e<C;++e)for(let t=0;t<R;++t)for(let n=0;n<A;++n){const s=n-z,r=Math.max(0,Math.ceil(s/M)),a=Math.min(D,($+s)/M);for(let i=0;i<_;++i){const o=i-P,l=Math.max(0,Math.ceil(o/L)),u=Math.min(O,(E+o)/L);let c=0;for(let n=r;n<a;++n){const r=n*M-s;for(let s=l;s<u;++s){const a=w*e+v*n+k*s,i=N*($-1-r)+S*(E-1-(s*L-o))+T*t;for(let e=0;e<B;++e){c+=x[a+(t*B+e)]*I[i+e]}}}m[g*e+y*n+b*i+t]=c}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}};const l_={kernelName:jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=ue(s.shape),a=n.data.get(s.dataId).values,i=Co([r,r],s.dtype),o=i.values;for(let e=0;e<a.length;e++)o[e*r+e]=a[e];const l=[...s.shape,...s.shape];return n.makeTensorInfo(l,i.dtype,i.values)}},u_={kernelName:qt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r}=e,{strides:a,pad:i,dilations:o}=n,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:p,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:T}=Xu(s.shape,r.shape,a,i,"NHWC",o),C=ue(T),$=T.length,E=Ie(s.dtype,C);for(let e=0;e<p;++e)for(let t=0;t<y;++t){const n=t*w-x.top;for(let a=0;a<b;++a){const i=a*v-x.left;for(let o=0;o<g;++o){let l=Number.MIN_SAFE_INTEGER;for(let t=0;t<k;++t){const a=n+t*N;if(a>=0&&a<f)for(let n=0;n<I;++n){const p=i+n*S;if(p>=0&&p<m){const i=Ue([e,a,p,o],c,Oe(s.shape)),f=Ue([t,n,o],d,Oe(r.shape)),m=u[i]+h[f];m>l&&(l=m)}}}E[Ue([e,t,a,o],$,Oe(T))]=l}}}return{dataId:l.write(Kr(E,s.dtype),T,s.dtype),shape:T,dtype:s.dtype}}},c_={kernelName:Xt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=Le(s.shape,u.data.get(s.dataId).values),h=Le(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=Xu(s.shape,r.shape,i,o,"NHWC",l);ie(a.rank===S.length,(()=>`Error in ${Xt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=Le(S,u.data.get(a.dataId).values),C=We(r.shape,r.dtype);for(let e=0;e<d;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let s=0;s<y;++s){const r=s*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=0,l=0;for(let t=0;t<v;++t){const s=n+t*I;if(s>=0&&s<p)for(let n=0;n<k;++n){const u=r+n*N;if(u>=0&&u<f){const r=c[e][s][u][a]+h[t][n][a];r>i&&(i=r,o=t,l=n)}}}C[o][l][a]+=T[e][t][s][a]}}}return{dataId:u.write(Kr(C,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},h_={kernelName:Kt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=Le(s.shape,u.data.get(s.dataId).values),h=Le(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:S}=Xu(s.shape,r.shape,i,o,"NHWC",l);ie(a.rank===S.length,(()=>`Error in ${Kt}, dy must have the same rank as output ${S.length}, but got ${a.rank}`));const T=Le(S,u.data.get(a.dataId).values),C=We(s.shape,s.dtype);for(let e=0;e<d;++e)for(let t=0;t<g;++t){const n=t*x-b.top;for(let s=0;s<y;++s){const r=s*w-b.left;for(let a=0;a<m;++a){let i=Number.MIN_SAFE_INTEGER,o=n<0?0:n,l=r<0?0:r;for(let t=0;t<v;++t){const s=n+t*I;if(s>=0&&s<p)for(let n=0;n<k;++n){const u=r+n*N;if(u>=0&&u<f){const r=c[e][s][u][a]+h[t][n][a];r>i&&(i=r,o=s,l=u)}}}C[e][o][l][a]+=T[e][t][s][a]}}}return{dataId:u.write(Kr(C,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};const d_={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{canvas:a,options:i}=s,{contextOptions:o,imageOptions:l}=i||{},u=(null==l?void 0:l.alpha)||1,c=(null==o?void 0:o.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=a.getContext(c,(null==o?void 0:o.contextAttributes)||{});if(null==h)throw new Error(`Could not get the context with ${c} type.`);const[d,p]=r.shape.slice(0,2),f=2===r.shape.length?1:r.shape[2],m=n.data.get(r.dataId).values,g="float32"===r.dtype?255:1,y=new Uint8ClampedArray(p*d*4);for(let e=0;e<d*p;++e){const t=[0,0,0,255*u];for(let n=0;n<f;n++){const s=m[e*f+n];if("float32"===r.dtype){if(s<0||s>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===r.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===f?(t[0]=s*g,t[1]=s*g,t[2]=s*g):t[n]=s*g}const n=4*e;y[n+0]=Math.round(t[0]),y[n+1]=Math.round(t[1]),y[n+2]=Math.round(t[2]),y[n+3]=Math.round(t[3])}a.width=p,a.height=d;const b=new ImageData(y,p,d);return h.putImageData(b,0,0),r}};function p_(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;let o;h$(r,"sum"),o="bool"===r.dtype?S$({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):w$({inputs:{x:r},backend:n});const l=o.shape.length,u=we(a,o.shape),c=lh(u,l);let h=u,d=o;null!=c&&(d=WE({inputs:{x:o},backend:n,attrs:{perm:c}}),h=ch(h.length,l)),oh("sum",h,d.shape.length);const[p,f]=ah(d.shape,h);let m=x$(n,p,Sa(d.dtype,"int32"));const g=ue(f),y=n.data.get(m.dataId).values,b=n.data.get(d.dataId).values;for(let e=0;e<y.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=b[t+e];y[e]=n}if(i){const e=m;m=QR({inputs:{x:m},backend:n,attrs:{shape:ih(m.shape,u)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(d),m}const f_={kernelName:Ps,backendName:"cpu",kernelFunc:p_};const m_={kernelName:Jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Fm(r,a.length);Om(i.length,l,a);const{path:u,steps:c}=Mm(o,l),h=c.length;let d=null,p=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Dm(p,l[t]);let r;Lm(e)?r=a[t]:(r=WE({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);de(r.shape,i)||(r=QR({inputs:{x:r},backend:n,attrs:{shape:i}}),f.push(r)),null===d?d=r:(d=FE({inputs:{a:r,b:d},backend:n}),f.push(d))}e<h-1&&(u[e]>=0&&(d=p_({inputs:{x:d},backend:n,attrs:{axis:u[e]-(i.length-p),keepDims:!1}}),f.push(d)),p--)}for(const e of f)e!==d&&n.disposeIntermediateTensorInfo(e);return d}};const g_={kernelName:en,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:s,y:r}=t;h$([s,r],"eluGrad");const a=new Float32Array(ue(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values;for(let e=0;e<i.length;++e){const t=i[e];a[e]=t>=0?o[e]:o[e]*(t+1)}return n.makeTensorInfo(r.shape,"float32",a)}},y_=mm,b_=gm,x_=ym,w_=bm,v_=xm,k_=wm,I_=P$(tn,(e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+y_*n);return t*(1-((((k_*s+v_)*s+w_)*s+x_)*s+b_)*s*Math.exp(-n*n))})),N_={kernelName:tn,backendName:"cpu",kernelFunc:I_};function S_(e){const{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,i=r.shape.length,o=r.shape.slice();let l=a;return a<0&&(ie(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),QR({inputs:{x:r},backend:n,attrs:{shape:o}})}const T_={kernelName:rn,backendName:"cpu",kernelFunc:S_},C_=g$(((e,t)=>e/t)),$_=C$(Zt,C_),E_={kernelName:Zt,backendName:"cpu",kernelFunc:$_};function R_(e,t,n){const s=e.shape,r=s[0],a=s[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,a],c=ue(u),h=ke("float32",c),d=ke("float32",c);for(let e=0;e<r;e++){const s=hR({inputs:{x:o},backend:n,attrs:{begin:[e,0],size:[1,a]}}),r=hR({inputs:{x:l},backend:n,attrs:{begin:[e,0],size:[1,a]}}),i=y$({inputs:{real:s,imag:r},backend:n}),{real:u,imag:c}=A_(i,t,n),p=vm(u,c);for(let t=0;t<a;t++){const n=Sm(p,t);h[e*a+t]=n.real,d[e*a+t]=n.imag}n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(i)}const p=n.makeTensorInfo(u,"float32",h),f=n.makeTensorInfo(u,"float32",d),m=y$({inputs:{real:p,imag:f},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),m}function A_(e,t,n){const s=ue(e.shape),r=n.data.get(e.dataId),a=n.data.get(r.complexTensorInfos.real.dataId).values,i=n.data.get(r.complexTensorInfos.imag.dataId).values;if((o=s)&o-1){const e=function(e,t,n){const s=new Float32Array(2*t);for(let r=0;r<t;r++){let a=0,i=0;for(let s=0;s<t;s++){const o=$m(r*s,t,n),l=Sm(e,s);a+=l.real*o.real-l.imag*o.imag,i+=l.real*o.imag+l.imag*o.real}n&&(a/=t,i/=t),Tm(s,a,i,r)}return s}(vm(a,i),s,t);return km(e)}{const r=__(a,i,s,t,n),o=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(o,"float32",r.real),t=n.makeTensorInfo(o,"float32",r.imag),a=n.makeTensorInfo([],"float32",qr(s,"float32")),i=w$({inputs:{x:a},backend:n}),l=E_.kernelFunc({inputs:{a:e,b:a},backend:n}),u=E_.kernelFunc({inputs:{a:t,b:i},backend:n}),c=n.data.get(l.dataId).values,h=n.data.get(u.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),{real:c,imag:h}}return r}var o}function __(e,t,n,s,r){if(1===n)return{real:e,imag:t};const a=vm(e,t),i=n/2,o=Im(a),l=o.real,u=o.imag,c=[l.length],h=r.makeTensorInfo(c,"float32",l),d=r.makeTensorInfo(c,"float32",u),p=y$({inputs:{real:h,imag:d},backend:r}),f=Nm(a),m=f.real,g=f.imag,y=[m.length],b=r.makeTensorInfo(y,"float32",m),x=r.makeTensorInfo(y,"float32",g),w=y$({inputs:{real:b,imag:x},backend:r}),v=__(l,u,i,s,r),k=v.real,I=v.imag,N=[k.length],S=r.makeTensorInfo(N,"float32",k),T=r.makeTensorInfo(N,"float32",I),C=y$({inputs:{real:S,imag:T},backend:r}),$=__(m,g,i,s,r),E=$.real,R=$.imag,A=[E.length],_=r.makeTensorInfo(A,"float32",E),F=r.makeTensorInfo(A,"float32",R),D=y$({inputs:{real:_,imag:F},backend:r}),O=Cm(n,s),M=[O.real.length],L=r.makeTensorInfo(M,"float32",O.real),z=r.makeTensorInfo(M,"float32",O.imag),P=y$({inputs:{real:L,imag:z},backend:r}),B=FE({inputs:{a:P,b:D},backend:r}),W=A$({inputs:{a:C,b:B},backend:r}),V=FR({inputs:{a:C,b:B},backend:r}),U=k$({inputs:{input:W},backend:r}),G=k$({inputs:{input:V},backend:r}),H=zA({inputs:{input:W},backend:r}),j=zA({inputs:{input:V},backend:r}),q=BA({inputs:[U,G],backend:r,attrs:{axis:0}}),K=BA({inputs:[H,j],backend:r,attrs:{axis:0}}),X=r.data.get(q.dataId).values,Y=r.data.get(K.dataId).values;return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(w),r.disposeIntermediateTensorInfo(S),r.disposeIntermediateTensorInfo(T),r.disposeIntermediateTensorInfo(C),r.disposeIntermediateTensorInfo(_),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(D),r.disposeIntermediateTensorInfo(L),r.disposeIntermediateTensorInfo(z),r.disposeIntermediateTensorInfo(P),r.disposeIntermediateTensorInfo(B),r.disposeIntermediateTensorInfo(W),r.disposeIntermediateTensorInfo(V),r.disposeIntermediateTensorInfo(U),r.disposeIntermediateTensorInfo(H),r.disposeIntermediateTensorInfo(G),r.disposeIntermediateTensorInfo(j),r.disposeIntermediateTensorInfo(q),r.disposeIntermediateTensorInfo(K),{real:X,imag:Y}}const F_={kernelName:on,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t,r=ue(s.shape),a=s.shape[s.shape.length-1],i=QR({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=R_(i,!1,n),l=QR({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}};function D_(e){const{backend:t,attrs:n}=e,{shape:s,value:r,dtype:a}=n,i=a||_e(r),o=Ie(i,ue(s));return function(e,t,n){e.fill(t)}(o,r),t.makeTensorInfo(s,i,o)}const O_={kernelName:ln,backendName:"cpu",kernelFunc:D_};const M_={kernelName:un,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,r=n,a=ke(s.dtype,ue(s.shape)),[i,o,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let e=0;e<i;e++){const t=e*l*o*u;for(let e=0;e<o;e++){const n=e*(l*u);for(let e=0;e<l;e++){const s=e*u;for(let r=0;r<u;r++){const i=Math.round(l-e-1),o=t+n+s+r;let h=c[o];if(i>=0&&i<l){h=c[t+n+i*u+r]}a[o]=h}}}}return{dataId:r.write(a,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};const L_={kernelName:yr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s;let m=VA({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=QR({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=A$({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=A$({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(p){const e=m;if("NCHW"===c&&"prelu"===p&&1===o.shape.length&&1!==o.shape[0]){const e=QR({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=JR(n,m,p,e,f),n.disposeIntermediateTensorInfo(e)}else m=JR(n,m,p,o,f);n.disposeIntermediateTensorInfo(e)}return m}};const z_={kernelName:br,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s;let m=r_({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d}});if(i){const e=m;m=A$({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(p){const e=m;m=JR(n,m,p,o,f),n.disposeIntermediateTensorInfo(e)}return m}};const P_={kernelName:fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=ue(s.shape),i=r.shape,o=i[i.length-1],[l,u,c,h]=Jl(s,r);if(0===u)return n.makeTensorInfo(l,s.dtype,[]);const d=iE(n.data.get(r.dataId).values,n.bufferSync(s),s.dtype,u,o,c,h,s.shape,a);return n.makeTensorInfo(l,s.dtype,d.values)}};const B_={kernelName:pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s;h$([r,a],"gatherV2");const l=we(i,r.shape)[0],u=n.data.get(a.dataId).values,c=r.shape[l];for(let e=0;e<u.length;++e){const t=u[e];ie(t<=c-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}let h=o;null==o&&(h=0);const d=ue(a.shape),p=eg(r,a,l,h),f=QR({inputs:{x:r},backend:n,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),m=QR({inputs:{x:a},backend:n,attrs:{shape:[p.batchSize,d/p.batchSize]}}),g=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],y=n.bufferSync(m),b=oE(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(p.outputShape,b.dtype,b.values)}};const W_={kernelName:bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t,r=ue(s.shape),a=s.shape[s.shape.length-1],i=QR({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=R_(i,!0,n),l=QR({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},V_=P$(wn,(e=>Number.isFinite(e)?1:0),"bool"),U_={kernelName:wn,backendName:"cpu",kernelFunc:V_},G_=P$(vn,(e=>Math.abs(e)===1/0?1:0),"bool"),H_={kernelName:vn,backendName:"cpu",kernelFunc:G_},j_=P$(kn,(e=>Number.isNaN(e)?1:0),"bool"),q_={kernelName:kn,backendName:"cpu",kernelFunc:j_};const K_={kernelName:Tn,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=wE(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},X_=P$($n,(e=>Math.log1p(e))),Y_={kernelName:$n,backendName:"cpu",kernelFunc:X_},Z_=g$(((e,t)=>e&&t)),J_=C$(En,Z_,null,"bool"),Q_={kernelName:En,backendName:"cpu",kernelFunc:J_},eF=P$(Rn,(e=>e?0:1),"bool"),tF={kernelName:Rn,backendName:"cpu",kernelFunc:eF},nF=g$(((e,t)=>e||t)),sF=C$(An,nF,null,"bool"),rF={kernelName:An,backendName:"cpu",kernelFunc:sF};const aF={kernelName:On,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s;h$(r,"LRN");const u=r.shape[3],c=u-1,h=n.data.get(r.dataId).values,d=ue(r.shape),p=new Float32Array(d);function f(e){const t=e%u;let n=e-t+Math.max(0,t-a);const s=e-t+Math.min(t+a,c);let r=0;for(;n<=s;n++){const e=h[n];r+=e*e}return r}for(let e=0;e<d;e++){const t=f(e),n=h[e]*Math.pow(i+o*t,-l);p[e]=n}return n.makeTensorInfo(r.shape,r.dtype,p)}};const iF={kernelName:Mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s;h$(i,"LRNGrad");const h=ue(i.shape),d=i.shape[3],p=n.data.get(i.dataId).values,f=n.data.get(r.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(h),y=h;for(let e=0;e<y;e++){const t=e%d,n=e-t+Math.max(0,t-o),s=e-t+Math.min(d,t+o+1);let r=0;for(let e=n;e<s;e++)r+=Math.pow(f[e],2);r=u*r+l;for(let t=n;t<s;t++){let n=-2*u*c*f[t]*m[e]/r;e===t&&(n+=Math.pow(r,-c)),n*=p[e],g[t]+=n}}return n.makeTensorInfo(i.shape,r.dtype,g)}};function oF(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=n;let l=r.shape;const u=l.length,c=we(a,l);let h=c;const d=lh(h,u);let p=o.data.get(r.dataId).values;if(null!=d){const e=new Array(u);for(let t=0;t<e.length;t++)e[t]=l[d[t]];p=BE(p,l,r.dtype,d,e),h=ch(h.length,u),l=e}h$(r,"max"),oh("max",h,u);const[f,m]=ah(l,h),g=NE(p,ue(m),f,r.dtype),y=o.write(g,f,r.dtype);let b=f;if(i){b=ih(f,c)}return{dataId:y,shape:b,dtype:r.dtype}}const lF={kernelName:zn,backendName:"cpu",kernelFunc:oF};const uF={kernelName:Bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;h$(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;ie(ic(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yu(r.shape,a,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&de(u.inShape,u.outShape))c=w$({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=Oe(r.shape),s=NA(e,r.shape,r.dtype,t,u,"max");c=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return c}};const cF={kernelName:Vn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;h$(r,"maxPool3d");const c=Zu(r.shape,a,i,1,o,l,u),h=TA(n.data.get(r.dataId).values,r.shape,r.dtype,Oe(r.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}};const hF={kernelName:Un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;h$([r,a],"maxPool3DGrad");const c=Zu(a.shape,i,o,1,l,u),h=function(e,t){const n=Co(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,d=t.padInfo.front,p=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*s-d;let x=b;for(;x<0;)x+=i;const w=Math.min(t.inDepth,u+b);for(let s=0;s<t.outHeight;++s){const u=s*r-p;let d=u;for(;d<0;)d+=o;const v=Math.min(t.inHeight,c+u);for(let r=0;r<t.outWidth;++r){const p=r*a-f;let k=p;for(;k<0;)k+=l;const I=Math.min(t.inWidth,h+p);let N=Number.NEGATIVE_INFINITY,S=-1;for(let t=x;t<w;t+=i){const n=t-b;for(let s=d;s<v;s+=o){const r=s-u;for(let a=k;a<I;a+=l){const i=a-p,o=e.get(m,t,s,a,g);o>=N&&(N=o,S=n*c*h+r*c+i)}}}n.set(S,m,y,s,r,g)}}}return n}(n.bufferSync(a),c),d=c.strideDepth,p=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,I=x-1-c.padInfo.top,N=Co(a.shape,"float32"),S=n.bufferSync(r);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let s=0;s<c.inHeight;++s)for(let r=0;r<c.inWidth;++r){const a=n-v,i=s-I,o=r-k;let l=0;for(let n=0;n<b;n+=m){const s=(a+n)/d;if(!(s<0||s>=c.outDepth||Math.floor(s)!==s))for(let r=0;r<x;r+=g){const a=(i+r)/p;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let i=0;i<w;i+=y){const u=(o+i)/f;if(u<0||u>=c.outWidth||Math.floor(u)!==u)continue;const d=b*x*w-1-h.get(e,s,a,u,t)===n*x*w+r*w+i?1:0;if(0===d)continue;l+=S.get(e,s,a,u,t)*d}}}N.set(l,e,n,s,r,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}};const dF={kernelName:Wn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;h$([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=Yu(o.shape,l,u,1,c,h),p=n.data.get(o.dataId).values,f=Co(d.outShape,o.dtype,SA(p,o.shape,o.dtype,d).values),m=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,b=d.dilationWidth,x=d.effectiveFilterHeight,w=d.effectiveFilterWidth,v=w-1-d.padInfo.left,k=x-1-d.padInfo.top,I=Co(o.shape,"float32"),N=n.data.get(r.dataId).values,S=Co(r.shape,"float32",N);for(let e=0;e<d.batchSize;++e)for(let t=0;t<d.inChannels;++t)for(let n=0;n<d.inHeight;++n)for(let s=0;s<d.inWidth;++s){const r=n-k,a=s-v;let i=0;for(let n=0;n<x;n+=y){const s=(r+n)/m;if(!(s<0||s>=d.outHeight||Math.floor(s)!==s))for(let r=0;r<w;r+=b){const o=(a+r)/g;if(o<0||o>=d.outWidth||Math.floor(o)!==o)continue;const l=x*w-1-f.get(e,s,o,t)===n*w+r?1:0;if(0===l)continue;i+=S.get(e,s,o,t)*l}}I.set(i,e,n,s,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}};const pF={kernelName:Gn,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;h$(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=Yu(s.shape,r,a,[1,1],i),[h,d]=function(e,t,n,s,r){const a=NA(e,0,n,Oe(t),r,"max"),i=SA(e,t,n,r,!0,s);return[a.values,i.values]}(u,s.shape,s.dtype,o,c),p=l.write(h,c.outShape,s.dtype),f=l.write(d,c.outShape,s.dtype);return[{dataId:p,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};const fF={kernelName:Hn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=we(a,r.shape),l=ue(ah(r.shape,o)[1]),u=[],c=n.makeTensorInfo([],"float32",new Float32Array([l]));u.push(c);const h=S$({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(h);const d=$_({inputs:{a:h,b:c},backend:n});u.push(d);const p=p_({inputs:{x:d},backend:n,attrs:{axis:a,keepDims:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}};const mF={kernelName:jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;h$(r,"min");const o=we(a,r.shape);let l=o;const u=lh(l,r.shape.length);let c=r;null!=u&&(c=WE({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ch(l.length,r.shape.length)),oh("min",l,c.shape.length);const[h,d]=ah(c.shape,l),p=ue(d),f=Be(ue(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;e<f.length;++e){const t=e*p;let n=m[t];for(let e=0;e<p;++e){const s=m[t+e];(Number.isNaN(s)||s<n)&&(n=s)}f[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(h,c.dtype,f);if(i){const e=QR({inputs:{x:g},backend:n,attrs:{shape:ih(h,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const gF={kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,mode:i}=s;h$(r,"mirrorPad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=a.map(((e,t)=>e[0]+r.shape[t])),c="reflect"===i?0:1,h=n.data.get(r.dataId).values,d=r.shape.length,p=Oe(r.shape),f=ue(o),m=o.length,g=Oe(o),y=ke(r.dtype,f);for(let e=0;e<f;e++){let t=Ge(e,m,g);for(let e=0;e<m;e++)t[e]<l[e]?t[e]=2*l[e]-t[e]-c:t[e]>=u[e]&&(t[e]=2*(u[e]-1)-t[e]+c);t=t.map(((e,t)=>e-l[t]));const n=Ue(t,d,p);y[e]=h[n]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}},yF=g$(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),bF=C$(Xn,yF),xF={kernelName:Xn,backendName:"cpu",kernelFunc:bF};function wF(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=r.shape.length;let o=a;if(-1===o&&(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}`);const l=we([o],r.shape),u=oF({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=ih(u.shape,l),h=QR({inputs:{x:u},backend:n,attrs:{shape:c}}),d=FR({inputs:{a:r,b:h},backend:n}),p=X$({inputs:{x:d},backend:n}),f=p_({inputs:{x:p},backend:n,attrs:{axis:l,keepDims:!1}}),m=QR({inputs:{x:f},backend:n,attrs:{shape:c}}),g=$_({inputs:{a:p,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const vF={kernelName:Vs,backendName:"cpu",kernelFunc:wF};const kF={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s;h$(r,"multinomial");const l=o?r:wF({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=n.data.get(l.dataId).values,d=[u,a],p=Be(ue(d),"int32");for(let e=0;e<u;++e){const t=e*c,n=new Float32Array(c-1);n[0]=h[t];for(let e=1;e<n.length;++e)n[e]=n[e-1]+h[t+e];const s=kd.alea(i.toString()),r=e*a;for(let e=0;e<a;++e){const t=s();p[r+e]=n.length;for(let s=0;s<n.length;s++)if(t<n[s]){p[r+e]=s;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(d,"int32",p)}},IF=sf;const NF={kernelName:es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s;h$(r,"NonMaxSuppression");const u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:h}=IF(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},SF=rf;const TF={kernelName:ts,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s;h$(r,"NonMaxSuppressionPadded");const c=n.data.get(r.dataId).values,h=n.data.get(a.dataId).values,{selectedIndices:d,validOutputs:p}=SF(c,h,i,o,l,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([p]))]}},CF=af;const $F={kernelName:ns,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s;h$(r,"NonMaxSuppressionWithScore");const c=n.data.get(r.dataId).values,h=n.data.get(a.dataId).values,d=i,p=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=CF(c,h,d,p,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const EF={kernelName:rs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s;h$(r,"oneHot");const u=ue(r.shape),c=new Float32Array(u*i);c.fill(l);const h=n.data.get(r.dataId).values;for(let e=0;e<u;++e)h[e]>=0&&h[e]<i&&(c[e*i+h[e]]=o);return n.makeTensorInfo([...r.shape,i],a,c)}};function RF(e){const{inputs:t,backend:n}=e,{x:s}=t;if("string"===s.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===s.dtype){const e=k$({inputs:{input:s},backend:n}),t=RF({inputs:{x:e},backend:n}),r=zA({inputs:{input:s},backend:n}),a=RF({inputs:{x:r},backend:n}),i=y$({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return D_({backend:n,attrs:{shape:s.shape,value:0,dtype:s.dtype}})}const AF={kernelName:dr,backendName:"cpu",kernelFunc:RF};const _F={kernelName:ss,backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:s}=t,{x:r}=n;if("string"===r.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===r.dtype){const t=k$({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=zA({inputs:{input:r},backend:s}),i=RF({inputs:{x:a},backend:s}),o=y$({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return D_({backend:s,attrs:{shape:r.shape,value:1,dtype:r.dtype}})}};function FF(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return S_({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=BA({inputs:t.map((e=>{const t=S_({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}const DF={kernelName:as,backendName:"cpu",kernelFunc:FF};const OF={kernelName:is,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;h$(r,"pad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=n.data.get(r.dataId).values,c=ue(r.shape),h=r.shape.length,d=Oe(r.shape),p=ue(o),f=o.length,m=Oe(o),g=ke(r.dtype,p);0!==i&&g.fill(i);for(let e=0;e<c;e++){g[Ue(Ge(e,h,d).map(((e,t)=>e+l[t])),f,m)]=u[e]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}},MF=g$(((e,t)=>Math.pow(e,t))),LF=C$(ls,MF),zF={kernelName:ls,backendName:"cpu",kernelFunc:LF};const PF={kernelName:hs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.data.get(e.dataId).values)),u=r.map((e=>e.shape)),c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,[d,p,f]=KE(l,u,c,a.shape,a.dtype,h,i.shape),m=d.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,p);return m.concat([g])}};const BF={kernelName:ds,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:s,limits:r,deltas:a}=t,i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=YE(i,s.shape,s.dtype,o,r.shape,l,a.shape);return[n.makeTensorInfo([u.length],"int32",u),n.makeTensorInfo([c.length],s.dtype,c)]}};const WF={kernelName:ps,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,d=o.map((e=>n.data.get(e.dataId).values)),p=o.map((e=>e.shape)),[f,m]=tR(u,r.shape,c,a.shape,a.dtype,h,i.shape,d,p,l);return n.makeTensorInfo(f,a.dtype,m)}};const VF={kernelName:fs,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:i}=n,o=nR(s,r,i,a);return t.makeTensorInfo([o.length],a,o)}},UF=P$(gs,(e=>1/e)),GF={kernelName:gs,backendName:"cpu",kernelFunc:UF};const HF={kernelName:vs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;h$(r,"resizeBilinear");const l=Oe(r.shape),[u,c]=o,[h,d,p,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(ue([h,u,c,f])),y=[a&&u>1?d-1:d,a&&c>1?p-1:p],b=[a&&u>1?u-1:u,a&&c>1?c-1:c];let x=0;const w=y[0]/b[0],v=y[1]/b[1];for(let e=0;e<h;e++)for(let t=0;t<u;t++){let n;n=i?w*(t+.5)-.5:w*t;const s=Math.max(0,Math.floor(n)),r=n-s,a=Math.min(d-1,Math.ceil(n)),o=e*l[0]+s*l[1],u=e*l[0]+a*l[1];for(let e=0;e<c;e++){let t;t=i?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),s=t-n,a=Math.min(p-1,Math.ceil(t)),c=o+n*l[2],h=u+n*l[2],d=o+a*l[2],y=u+a*l[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[h+e],a=t+(m[d+e]-t)*s,i=a+(n+(m[y+e]-n)*s-a)*r;g[x++]=i}}}return n.makeTensorInfo([h,u,c,f],"float32",g)}};const jF={kernelName:ks,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;h$([a,r],"resizeBilinearGrad");const o=Oe(r.shape),[l,u,c,h]=r.shape,[,d,p]=a.shape,f=new Float32Array(l*u*c*h),m=[i&&d>1?u-1:u,i&&p>1?c-1:c],g=[i&&d>1?d-1:d,i&&p>1?p-1:p],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(a.dataId).values;let w=0;for(let e=0;e<l;e++){const t=e*o[0];for(let e=0;e<d;e++){const n=e*y,s=Math.floor(n),r=Math.min(Math.ceil(n),u-1),a=t+s*o[1],i=t+r*o[1],l=n-s,d=1-l;for(let e=0;e<p;e++){const t=e*b,n=Math.floor(t),s=Math.min(Math.ceil(t),c-1),r=t-n,u=1-r,p=a+n*o[2],m=a+s*o[2],g=i+n*o[2],y=i+s*o[2],v=d*u,k=d*r,I=l*u,N=l*r;for(let e=0;e<h;e++){const t=x[w++];f[p+e]+=t*v,f[m+e]+=t*k,f[g+e]+=t*I,f[y+e]+=t*N}}}}return n.makeTensorInfo([l,c,u,h],"float32",f)}};const qF={kernelName:xs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;h$(r,"resizeNearestNeighbor");const l=Oe(r.shape),[u,c]=o,[h,d,p,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(h*u*c*f),y=[a&&u>1?d-1:d,a&&c>1?p-1:p],b=[a&&u>1?u-1:u,a&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let v=0;for(let e=0;e<h;e++){const t=e*l[0];for(let e=0;e<u;e++){const n=i?x*(e+.5):x*e;let s=Math.min(d-1,a?Math.round(n):Math.floor(n));i&&(s=Math.max(0,s));const r=t+s*l[1];for(let e=0;e<c;e++){const t=i?w*(e+.5):w*e;let n=Math.min(p-1,a?Math.round(t):Math.floor(t));i&&(n=Math.max(0,n));const s=r+n*l[2];for(let e=0;e<f;e++){const t=m[s+e];g[v++]=t}}}}return n.makeTensorInfo([h,u,c,f],r.dtype,g)}};const KF={kernelName:ws,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;h$([a,r],"resizeNearestNeighborGrad");const o=Oe(r.shape),l=Oe(a.shape),[u,c,h,d]=r.shape,[,p,f]=a.shape,m=new Float32Array(u*c*h*d),g=n.data.get(a.dataId).values,y=[i&&p>1?c-1:c,i&&f>1?h-1:h],b=[i&&p>1?p-1:p,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,I=2*Math.ceil(v)+2,N=2*Math.ceil(k)+2;for(let e=0;e<u;e++){const t=e*o[0];for(let e=0;e<c;e++){const n=t+e*o[1],s=Math.floor(e*v),r=Math.floor(s-I/2);for(let s=0;s<h;s++){const a=n+s*o[2],u=Math.floor(s*k),y=Math.floor(u-N/2);for(let n=0;n<d;n++){let o=0;for(let a=0;a<I;a++){const u=a+r;if(u<0||u>=p)continue;const d=t+u*l[1],m=u*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e<N;e++){const t=e+y;if(t<0||t>=f)continue;const r=d+t*l[2],a=t*w;s===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[r+n])}}m[a+n]=o}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}};const XF={kernelName:Ns,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;h$(r,"reverse");const i=r.shape.length,o=we(a,r.shape);if(0===i)return w$({inputs:{x:r},backend:n});const l=new da(r.shape,r.dtype),u=n.bufferSync(r);for(let e=0;e<l.size;e++){const t=l.indexToLoc(e),n=t.slice();o.forEach((e=>n[e]=r.shape[e]-1-n[e])),l.set(u.get(...n),...t)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}},YF={kernelName:mr,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=ke(s.dtype,ue(s.shape)),[u,c,h,d]=s.shape,[p,f]=om(i,c,h),m=Math.sin(r),g=Math.cos(r),y=o.data.get(s.dataId).values;for(let e=0;e<u;e++){const t=e*h*c*d;for(let e=0;e<c;e++){const n=e*(h*d);for(let s=0;s<h;s++){const r=s*d;for(let i=0;i<d;i++){const o=[u,e,s,i],b=o[2],x=o[1];let w=(b-p)*g-(x-f)*m,v=(b-p)*m+(x-f)*g;w=Math.round(w+p),v=Math.round(v+f);let k=a;if("number"!=typeof a&&(k=3===i?255:a[i]),w>=0&&w<h&&v>=0&&v<c){k=y[t+v*(h*d)+w*d+i]}l[t+n+r+i]=k}}}}return{dataId:o.write(l,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},ZF=P$(Ss,(e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),JF={kernelName:Ss,backendName:"cpu",kernelFunc:ZF};const QF={kernelName:Cs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=tu(0,r,i),d=iR(n.bufferSync(r),n.bufferSync(a),i,h,u,l,o,c,0,!0);return n.makeTensorInfo(i,d.dtype,d.values)}};function eD(e,t){let n=0,s=e.length,r=0;for(;n<s;)r=Math.floor((n+s)/2),e[r]<t?n=r+1:s=r;return s}function tD(e,t){let n=0,s=e.length,r=0;for(;n<s;)r=Math.floor((n+s)/2),e[r]<=t?n=r+1:s=r;return s}const nD={kernelName:Es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=function(e,t,n,s,r,a){const i=Ie("int32",n*r);for(let o=0;o<n;++o){const n=e.slice(o*s,(o+1)*s),l=o*r;for(let e=0;e<r;++e)i[l+e]="left"===a?eD(n,t[e+l]):tD(n,t[e+l])}return i}(n.data.get(r.dataId).values,n.data.get(a.dataId).values,r.shape[0],r.shape[1],a.shape[1],i);return n.makeTensorInfo(a.shape,"int32",o)}};const sD={kernelName:Rs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t;h$([s,r,a],"select");const i=s.shape.length,o=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,c=Sa(r.dtype,a.dtype),h=Be(ue(r.shape),c);let d=0;const p=0===i||i>1||1===r.shape.length?1:ue(r.shape.slice(1));for(let e=0;e<o.length;e++)for(let t=0;t<p;t++)1===o[e]?h[d++]=l[e]:h[d++]=u[e];return n.makeTensorInfo(r.shape,c,h)}},rD=pm,aD=fm,iD=P$(As,(e=>e>=0?aD*e:rD*(Math.exp(e)-1))),oD={kernelName:As,backendName:"cpu",kernelFunc:iD},lD=P$(Os,(e=>e<0?-1:e>0?1:0)),uD={kernelName:Os,backendName:"cpu",kernelFunc:lD},cD=P$(Fs,(e=>Math.sin(e))),hD={kernelName:Fs,backendName:"cpu",kernelFunc:cD},dD=P$(Ds,(e=>Math.sinh(e))),pD={kernelName:Ds,backendName:"cpu",kernelFunc:dD},fD=Math.log(1.1920928955078125e-7)+2,mD=P$(Ls,(e=>{const t=e>-fD,n=e<fD,s=Math.exp(e);let r;return r=n?s:t?e:Math.log(1+s),r})),gD={kernelName:Ls,backendName:"cpu",kernelFunc:mD};const yD={kernelName:Bs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;h$([r],"spaceToBatchND");const o=ue(a),l=[[0,0]];l.push(...i);for(let e=1+a.length;e<r.shape.length;++e)l.push([0,0]);const u=OF.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),c=lm(u.shape,a,o,!1),h=um(c.length,a.length,!1),d=cm(u.shape,a,o,!1),p=QR({inputs:{x:u},backend:n,attrs:{shape:c}}),f=WE({inputs:{x:p},backend:n,attrs:{perm:h}}),m=QR({inputs:{x:f},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),m}};const bD={kernelName:Us,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${a.shape}`);if(2!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n ${r.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,c=n.data.get(i.dataId).values[0],[h,d,p,f,m]=pR(o,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(d,s.dtype,h),n.makeTensorInfo([d[0]],r.dtype,p),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}};const xD={kernelName:Gs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.data.get(r.dataId).values),o=n.data.get(s.dataId).values,l=Array.from(n.data.get(a.dataId).values),[u,c,h]=fR(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const wD={kernelName:Hs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=mR(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const vD={kernelName:js,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=mR(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const kD={kernelName:qs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:d}=tu(0,r,o),p=!1,f=n.bufferSync(r);let m;switch(a.dtype){case"bool":m=iR(f,n.bufferSync(a),o,d,c,u,l,h,Boolean(n.data.get(i.dataId).values[0]),p);break;case"float32":m=iR(f,n.bufferSync(a),o,d,c,u,l,h,n.data.get(i.dataId).values[0],p);break;case"int32":m=iR(f,n.bufferSync(a),o,d,c,u,l,h,n.data.get(i.dataId).values[0],p);break;case"string":m=iR(f,n.bufferSync(a),o,d,c,u,l,h,Jr(n.data.get(i.dataId).values[0]),p);break;default:throw new Error(`Unsupported type ${a.dtype}`)}return n.makeTensorInfo(o,m.dtype,m.values)}};const ID={kernelName:Ws,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=we(i,r.shape)[0],l=Pm(r,a,o),u=new Array(r.shape.length).fill(0),c=r.shape.slice();return l.map((e=>{const t=[...c];t[o]=e;const s=hR({inputs:{x:r},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,s}))}},ND={kernelName:Xs,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;h$(n,"square");const r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let e=0;e<r.length;++e){const t=r[e];a[e]=t*t}return{dataId:s.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},SD=P$(pr,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),TD={kernelName:pr,backendName:"cpu",kernelFunc:SD};const CD={kernelName:Zs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=s;h$(r,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=xu(r.shape,a,i,o,l,u,c,h,d);let v;if(m)v=QR({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){ie(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=iu(b,x,w),t=hR({inputs:{x:r},backend:n,attrs:{begin:b,size:e}});v=QR({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=SR(p,n.bufferSync(r),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}};const $D={kernelName:Js,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,d=n.data.get(c.dataId).values,p=n.data.get(h.dataId).values,[f,m]=CR(d,p,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const ED={kernelName:Qs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values[0],[u,c,h]=ER(o,l,r),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}};const RD={kernelName:er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const i=RR(n.data.get(a.dataId).values,r);return n.makeTensorInfo(a.shape,"int32",i)}},AD=P$(nr,(e=>Math.tan(e))),_D={kernelName:nr,backendName:"cpu",kernelFunc:AD},FD=P$(sr,(e=>Math.tanh(e)));const DD={kernelName:$s,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:s,indices:r,updates:a}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:u,outputSize:c}=tu(0,r,s.shape),h=n.bufferSync(r),d=n.bufferSync(a),p=n.bufferSync(s),f=iR(h,d,s.shape,c,l,o,i,u,p,!1);return n.makeTensorInfo(s.shape,f.dtype,f.values)}};const OD={kernelName:rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;h$(r,"tile");const i=OR(n.bufferSync(r),a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}};const MD={kernelName:ar,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s;h$(r,"topk");const o=n.data.get(r.dataId).values,[l,u]=zR(o,r.shape,r.dtype,a,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}};const LD={kernelName:ir,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[c,h,d,p]=r.shape,[f,m]=null!=u?u:[h,d],g=[c,f,m,p],y=Oe(r.shape),b=y[0],x=y[1],w=y[2],v=Oe(g),k=v[0],I=v[1],N=v[2],S=ke(r.dtype,ue(g));S.fill(l);const T=s.data.get(r.dataId).values,C=s.data.get(a.dataId).values;for(let e=0;e<c;++e){const t=1===a.shape[0]?C:C.subarray(8*e,8*e+8);for(let n=0;n<f;++n)for(let s=0;s<m;++s)for(let r=0;r<p;++r){let a;const u=t[6]*s+t[7]*n+1;if(0===u)continue;const c=(t[0]*s+t[1]*n+t[2])/u,p=(t[3]*s+t[4]*n+t[5])/u,f=zD(c,d,o),m=zD(p,h,o);switch(i){case"nearest":a=BD(T,h,d,b,x,w,e,m,f,r,l);break;case"bilinear":a=WD(T,h,d,b,x,w,e,m,f,r,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}S[e*k+n*I+s*N+r]=a}return s.makeTensorInfo(g,r.dtype,S)}return{dataId:s.write(S,g,r.dtype),shape:r.shape,dtype:r.dtype}}};function zD(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return ee(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return ee(0,n,t-1)}(e,t);case"nearest":return function(e,t){return ee(0,e,t-1)}(e,t);default:return function(e,t){return e}(e)}}function PD(e,t,n,s,r,a,i,o,l,u,c){return 0<=o&&o<t&&0<=l&&l<n?e[i*s+o*r+l*a+u]:c}function BD(e,t,n,s,r,a,i,o,l,u,c){return PD(e,t,n,s,r,a,i,Math.round(o),Math.round(l),u,c)}function WD(e,t,n,s,r,a,i,o,l,u,c){const h=Math.floor(o),d=Math.floor(l),p=h+1,f=d+1;return(p-o)*((f-l)*PD(e,t,n,s,r,a,i,h,d,u,c)+(l-d)*PD(e,t,n,s,r,a,i,h,f,u,c))+(o-h)*((f-l)*PD(e,t,n,s,r,a,i,p,d,u,c)+(l-d)*PD(e,t,n,s,r,a,i,p,f,u,c))}const VD={kernelName:lr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;h$(a,"unique");const i=s.data.get(a.dataId).values,{outputValues:o,outputShape:l,indices:u}=PR(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const UD={kernelName:ur,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{value:r}=t;let{axis:a}=s;a<0&&(a+=r.shape.length);const i=r.shape.length,o=r.shape[a],l=new Array(i-1);let u=0;for(let e=0;e<i;e++)e!==a&&(l[u++]=r.shape[e]);const c=new Array(i).fill(0),h=r.shape.slice();h[a]=1;const d=new Array(o);for(let e=0;e<d.length;e++){c[a]=e;const t=hR({inputs:{x:r},backend:n,attrs:{begin:c,size:h}});d[e]=QR({inputs:{x:t},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(t)}return d}};const GD={kernelName:cr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s;h$(r,"unsortedSegmentSum");const o=[],l=[],u=r.shape.length-a.shape.length;let c=a;for(let e=0;e<u;++e){const t=S_({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,l.push(t)}for(let e=0;e<i;++e){const t=qr(e,"int32"),s=n.makeTensorInfo([],"int32",t),a=j$({inputs:{a:s,b:c},backend:n}),i=S$({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),u=FE({inputs:{a:i,b:r},backend:n}),h=p_({inputs:{x:u},backend:n,attrs:{axis:0,keepDims:!1}});o.push(h),l.push(s),l.push(a),l.push(i),l.push(u),l.push(h)}const h=FF({inputs:o,backend:n,attrs:{axis:0}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),h}},HD=[sA,m$,aA,oA,_$,lA,uA,cA,hA,dA,fA,gA,bA,vA,IA,CA,$A,EA,RA,nA,AA,_A,FA,L$,DA,T$,U$,MA,b$,LA,WA,UA,GA,HA,jA,qA,KA,YA,JA,QA,e_,t_,n_,s_,a_,i_,o_,l_,u_,c_,h_,d_,m_,VR,g_,q$,N_,Y$,T_,Q$,F_,O_,M_,nE,aE,L_,z_,P_,B_,cE,pE,v$,W_,PA,U_,H_,q_,GR,gE,xE,K_,IE,Y_,Q_,tF,rF,aF,iF,lF,CE,uF,cF,hF,dF,pF,fF,mF,RE,gF,xF,kF,DE,ME,NF,TF,$F,PE,EF,_F,DF,OF,zF,qR,GE,PF,BF,WF,VF,I$,E_,GF,XR,ZR,eA,HF,jF,qF,KF,XF,YF,JF,aR,QF,nD,sD,oD,uR,uD,hD,pD,dR,vF,gD,yD,bD,xD,wD,vD,kD,ID,bR,ND,vR,NR,TD,CD,$D,ED,RD,DR,f_,_D,{kernelName:sr,backendName:"cpu",kernelFunc:FD},DD,OD,MD,LD,VE,VD,UD,GD,AF];for(const e of HD)Tr(e);const jD={},qD={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function KD(e,t){jD[e]=t}function XD(e,t){if(!(e in jD)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if(Xe().getBool("IS_SAFARI")||"undefined"==typeof OffscreenCanvas||2!==e){if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e):t;n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete jD[e]}),!1),Xe().getBool("SOFTWARE_WEBGL_ENABLED")&&(qD.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",qD)||n.getContext("experimental-webgl",qD);return n.getContext("webgl2",qD)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;jD[e]=n}const n=jD[e];return null==n||n.isContextLost()?(delete jD[e],XD(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),jD[e])}var YD,ZD,JD;function QD(e,t){return[t,e]}function eO(e){const t=ue(e);return me(Math.ceil(t/4))}function tO(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function nO(e,t){const n=e;let s,r,a,i,o,l,u,c,h,d;return 2===Xe().getNumber("WEBGL_VERSION")?(s=n.R32F,r=n.R16F,a=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,c=1,h=n.HALF_FLOAT,d=n.FLOAT,l=n.RGBA8):(s=e.RGBA,r=e.RGBA,a=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,d=e.FLOAT,l=e.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:d}}function sO(e,t){const n=t();return Xe().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+oO(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(YD||(YD={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(ZD||(ZD={})),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"}(JD||(JD={}));const rO=5.96e-8,aO=65504;function iO(e){return!!(Xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||rO<Math.abs(e)&&Math.abs(e)<aO)}function oO(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 lO(e,t){return FO(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}function uO(e,t){const n=FO(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(sO(e,(()=>e.shaderSource(n,t))),sO(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function cO(e,t){const n=FO(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(sO(e,(()=>e.shaderSource(n,t))),sO(e,(()=>e.compileShader(n))),Xe().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw dO(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const hO=/ERROR: [0-9]+:([0-9]+):/g;function dO(e,t){const n=hO.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const s=+n[1],r=e.split("\n"),a=r.length.toString().length+2,i=r.map(((e,t)=>ye((t+1).toString(),a)+e));let o=0;for(let e=0;e<i.length;e++)o=Math.max(i[e].length,o);const l=i.slice(0,s-1),u=i.slice(s-1,s),c=i.slice(s);console.log(l.join("\n")),console.log(t.split("\n")[0]),console.log(`%c ${ye(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function pO(e){return FO(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}function fO(e,t){if(sO(e,(()=>e.linkProgram(t))),!Xe().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function mO(e,t){if(sO(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function gO(e,t){const n=FO(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return sO(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),sO(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function yO(e,t){const n=FO(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return sO(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),sO(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function bO(){return 2===Xe().getNumber("WEBGL_VERSION")?1:4}function xO(e){return FO(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}function wO(e,t){const n=Xe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){throw new Error("Requested texture size "+`[${e}x${t}]`+" is invalid.")}if(e>n||t>n){throw new Error("Requested texture size "+`[${e}x${t}]`+" greater than WebGL maximum on this browser / GPU "+`[${n}x${n}]`+".")}}function vO(e){return FO(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}function kO(e,t,n,s,r,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(sO(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,s))),sO(e,(()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,a,i))),sO(e,(()=>e.enableVertexAttribArray(o))),!0)}function IO(e,t,n){DO(e,n),sO(e,(()=>e.activeTexture(e.TEXTURE0+n))),sO(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}function NO(e,t){DO(e,t),sO(e,(()=>e.activeTexture(e.TEXTURE0+t))),sO(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function SO(e,t,n){return FO(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}function TO(e,t,n){return e.getUniformLocation(t,n)}function CO(e,t,n,s){sO(e,(()=>IO(e,t,s))),sO(e,(()=>e.uniform1i(n,s)))}function $O(e){sO(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),sO(e,(()=>e.viewport(0,0,e.canvas.width,e.canvas.height))),sO(e,(()=>e.scissor(0,0,e.canvas.width,e.canvas.height)))}function EO(e,t,n){sO(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),sO(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function RO(e,t){sO(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),sO(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function AO(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+_O(e,t))}function _O(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 FO(e,t,n){const s=sO(e,(()=>t()));if(null==s)throw new Error(n);return s}function DO(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}function OO(e,t=2){return ue(e.slice(0,e.length-t))}function MO(e){if(0===e.length)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 LO(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[OO(e),...MO(e)]),t}function zO(e,t=!1){let n=Xe().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=Xe().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(s===1/0&&Xe().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=n/2),t&&(n*=2,s*=2,1===(e=e.map(((t,n)=>n>=e.length-2?te(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=ve(e);e=t.newShape}let r=ue(e),a=null;e.length<=1&&r<=n?a=[1,r]:2===e.length&&e[0]<=n&&e[1]<=n?a=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);const i=null!=a&&Math.max(...a)>s&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||i)if(t){const t=OO(e);let n=2,s=2;e.length&&([n,s]=MO(e)),r=t*(n/2)*(s/2),a=me(r).map((e=>2*e))}else a=me(r);return a}function PO(e){return e%2==0}function BO(e,t){if(de(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e[e.length-1],s=t[t.length-1];if(n===s)return!0;if(PO(n)&&PO(s)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&PO(e[0])&&PO(t[0])}let WO,VO;function UO(e){if(null==WO){const t=XD(e);WO=t.getParameter(t.MAX_TEXTURE_SIZE)}return WO}function GO(){WO=null}function HO(){VO=null}function jO(e){if(null==VO){const t=XD(e);VO=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,VO)}function qO(e){if(0===e)return 0;let t;const n=XD(e);return t=KO(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:KO(n,"EXT_disjoint_timer_query")?1:0,t}function KO(e,t){return null!=e.getExtension(t)}function XO(e){try{if(null!=XD(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function YO(e){if(0===e)return!1;const t=XD(e);if(1===e){if(!KO(t,"OES_texture_float"))return!1}else if(!KO(t,"EXT_color_buffer_float"))return!1;return JO(t)}function ZO(e){if(0===e)return!1;const t=XD(e);if(1!==e){if(KO(t,"EXT_color_buffer_float"))return JO(t);const e="EXT_color_buffer_half_float";if(KO(t,e)){const n=t.getExtension(e);return function(e,t){const n=nO(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(i),o}(t,n)}return!1}if(!KO(t,"OES_texture_float"))return!1;if(!KO(t,"WEBGL_color_buffer_float"))return!1;return JO(t)}function JO(e){const t=nO(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);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const 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(s),r}function QO(e){if(2!==e)return!1;return null!=XD(e).fenceSync}function eM(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&ie("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const tM=Xe();function nM(){let e,t,n,s,r,a,i,o,l,u;return 2===Xe().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",i="out vec4 outputColor;",o=Xe().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",l="",u="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",s="varying",r="texture2D",a="gl_FragColor",i="",o="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",u="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:r,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function sM(e,t,n="index"){const s=Oe(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${t}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${t}`:`index -= ${e[r]} * ${t}`};`)).join("")}function rM(e,t,n="index"){const s=Oe(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / outShapeStrides[${r}]`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * outShapeStrides[${r}]`:`index -= ${e[r]} * outShapeStrides[${r}]`};`)).join("")}function aM(e,t,n="index"){const s=function(e,t){const n=e.length,s=e.map((e=>`${t}[${e}]`)),r=new Array(n-1);r[n-2]=s[n-1];for(let e=n-3;e>=0;--e)r[e]=`(${r[e+1]} * ${s[e+1]})`;return r}(e.map(((e,t)=>t)),t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${s[r]}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${s[r]}`:`index -= ${e[r]} * ${s[r]}`};`)).join("")}function iM(e){const t=Oe(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}tM.registerFlag("HAS_WEBGL",(()=>tM.getNumber("WEBGL_VERSION")>0)),tM.registerFlag("WEBGL_VERSION",(()=>XO(2)?2:XO(1)?1:0)),tM.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),tM.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===tM.get("WEBGL_VERSION"))),tM.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),tM.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),tM.registerFlag("WEBGL_PACK",(()=>tM.getBool("HAS_WEBGL"))),tM.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_CLIP",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_REDUCE",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_LAZILY_UNPACK",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_CONV_IM2COL",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>tM.getBool("WEBGL_PACK"))),tM.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>UO(tM.getNumber("WEBGL_VERSION")))),tM.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>jO(tM.getNumber("WEBGL_VERSION")))),tM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=tM.getNumber("WEBGL_VERSION");return 0===e?0:qO(e)})),tM.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>tM.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Va())),tM.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>YO(tM.getNumber("WEBGL_VERSION")))),tM.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!tM.getBool("WEBGL_FORCE_F16_TEXTURES")&&tM.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),tM.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>ZO(tM.getNumber("WEBGL_VERSION")))),tM.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>QO(tM.getNumber("WEBGL_VERSION")))),tM.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>tM.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),tM.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),tM.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>Va()?1:-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),tM.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),tM.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),tM.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),tM.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),tM.registerFlag("WEBGL_EXP_CONV",(()=>!1)),tM.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>tM.getBool("IS_TEST"))),tM.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),tM.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),tM.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),tM.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const oM="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:lM}=y;function uM(e,t,n){const s=[];if(e.forEach((e=>{const t=ue(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?s.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(s.push(`uniform sampler2D ${e.name};`),s.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=wM(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:s.push(`uniform int ${e.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${e.name}Shape;`)}s.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;")}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{s.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const r=s.join("\n"),a=e.map((e=>function(e,t,n=!1,s){let r="";r+=n?hM(e,s):cM(e,s);const a=e.shapeInfo.logicalShape,i=t.logicalShape;a.length<=i.length&&(r+=n?function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=lM(e.shapeInfo.logicalShape,t.logicalShape),l=xM(i),u=i-a;let c;const h=["x","y","z","w","u","v"];c=0===a?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${h[e+u]} = 0;`)).join("\n");let d="";d=i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+u]}`)).join(", ");let p="return outputValue;";const f=1===ue(e.shapeInfo.logicalShape),m=ue(t.logicalShape),g=1===m;if(1!==a||f||g){if(f&&!g)p=1===i?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(o.length){const e=a-2,t=a-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?p="return vec4(outputValue.x);":o.indexOf(e)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}}else p="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${r}() {\n ${l} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${s}(${d});\n ${p}\n }\n `}(e,t):function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&null==e.shapeInfo.flatOffset&&de(i,a))return`\n float ${r}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const u=xM(l),c=lM(e.shapeInfo.logicalShape,t.logicalShape),h=l-o;let d;const p=["x","y","z","w","u","v"];d=0===o?"":l<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${p[e+h]} = 0;`)).join("\n");let f="";f=l<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${p[t+h]}`)).join(", ");return`\n float ${r}() {\n ${u} coords = getOutputCoords();\n ${d}\n return get${s}(${f});\n }\n `}(e,t));return r}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=nM(),l=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(o);let u,c,h=function(e){const t=`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${dM}\n ${pM}\n ${fM}\n `;return t}(o);t.isPacked?(u=function(e,t,n){switch(e.length){case 0:return gM();case 1:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===s[0])return n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${s[1]}.0);\n }\n `;if(1===s[1])return n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${s[0]}.0);\n }\n `;if(n)return"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ";return`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(de(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));\n }\n `;const r=Math.ceil(e[1]/2);if(n)return"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ";return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2);let i=a,o="",l="b, r, c";for(let t=2;t<e.length-1;t++)i*=e[e.length-t-1],o=`\n int b${t} = index / ${i};\n index -= b${t} * ${i};\n `+o,l=`b${t}, `+l;return`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n ${o}\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 2;\n\n return ivec${e.length}(${l});\n }\n `}(e,t,n)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n void setOutput(vec4 val) {\n ${e.output} = val;\n }\n `}(o)):(u=function(e,t,n){switch(e.length){case 0:return gM();case 1:return function(e,t,n){if(1===t[0])return n?"\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.x * ${t[1]}.0);\n }\n `;if(1===t[1])return n?"\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.y * ${t[0]}.0);\n }\n `;if(n)return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n ";return`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.x * ${t[1]} + resTexRC.y;\n }\n `}(0,t,n);case 2:return function(e,t,n){if(de(e,t))return n?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n }\n `;if(1===e[1])return n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `;if(1===e[0])return n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `;if(n)return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n ";return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n){return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${rM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`}const s=sM(["r","c","d"],e);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${s}\n return ivec3(r, c, d);\n }\n `}(e,t,n);case 4:return function(e,t,n){if(n){return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${rM(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `}const s=sM(["r","c","d","d2"],e);return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${s}\n return ivec4(r, c, d, d2);\n }\n `}(e,t,n);case 5:return function(e,t){const n=sM(["r","c","d","d2","d3"],e);return`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n ${t[1]}));\n\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `}(e,t);case 6:return function(e,t){const n=sM(["r","c","d","d2","d3","d4"],e);return`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n void setOutput(float val) {\n ${e.output} = vec4(val, 0, 0, 0);\n }\n `}(o)),n.packedInputs&&(h+=mM);return[h,l,c,r,u,a,n.userCode].join("\n")}function cM(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${n};}`;const[r,a]=e.shapeInfo.texShape;if(1===r&&1===a)return`\n float ${s}() {\n return sampleTexture(${n}, halfCR);\n }\n `;const i=yM(n);if(t)return`\n float ${s}() {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});\n return sampleTexture(${n}, uv);\n }\n `;const[o,l]=e.shapeInfo.texShape;return`\n float ${s}() {\n vec2 uv = uvFromFlat(${o}, ${l}, ${i});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 1:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n float ${s}(int index) {\n ${bM(e)}\n }\n `;const r=e.shapeInfo.texShape,a=r[0],i=r[1];if(1===i&&1===a)return`\n float ${s}(int index) {\n return sampleTexture(${n}, halfCR);\n }\n `;const o=yM(n);if(1===i)return t?`\n float ${s}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${s}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${a}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(1===a)return t?`\n float ${s}(int index) {\n vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${s}(int index) {\n vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);\n return sampleTexture(${n}, uv);\n }\n `;if(t)return`\n float ${s}(int index) {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});\n return sampleTexture(${n}, uv);\n }\n `;return`\n float ${s}(int index) {\n vec2 uv = uvFromFlat(${a}, ${i}, index + ${o});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape;if(null!=a&&de(n,a)){if(t)return`\n float ${r}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n return sampleTexture(${s}, uv);\n }\n `;const e=a[0];return`\n float ${r}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${a[1]}.0, ${e}.0);\n return sampleTexture(${s}, uv);\n }\n `}const{newShape:i,keptDims:o}=ve(n),l=i;if(l.length<n.length){const n=["row","col"];return`\n ${cM(vM(e,l),t)}\n float ${r}(int row, int col) {\n return ${r}(${kM(n,o)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n ${bM(e)}\n }\n `;const u=a[0],c=a[1],h=yM(s);if(1===c)return t?`\n float ${r}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);\n return sampleTexture(${s}, uv);\n }\n `;if(1===u)return t?`\n float ${r}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col) {\n float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n return sampleTexture(${s}, uv);\n }\n `;if(t)return`\n float ${r}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${s}Shape[1] + col + ${h};\n vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);\n return sampleTexture(${s}, uv);\n }\n `;return`\n float ${r}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${n[1]} + col + ${h};\n vec2 uv = uvFromFlat(${u}, ${c}, index);\n return sampleTexture(${s}, uv);\n }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[1]*n[2],i=n[2],{newShape:o,keptDims:l}=ve(n),u=o;if(u.length<n.length){const n=["row","col","depth"];return`\n ${cM(vM(e,u),t)}\n float ${r}(int row, int col, int depth) {\n return ${r}(${kM(n,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${a}, ${i}, 1)));\n ${bM(e)}\n }\n `;const c=e.shapeInfo.texShape,h=c[0],d=c[1],p=e.shapeInfo.flatOffset;if(d===a&&null==p)return t?`\n float ${r}(int row, int col, int depth) {\n int stride1 = ${s}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${s}TexShape[1], ${s}TexShape[0]);\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${i}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${s}, uv);\n }\n `;if(d===i&&null==p)return t?`\n float ${r}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${h}.0);\n return sampleTexture(${s}, uv);\n }\n `;const f=yM(s);if(t)return`\n float ${r}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${s}Shape[1] * ${s}Shape[2];\n int stride1 = ${s}Shape[2];\n int index = row * stride0 + col * stride1 + depth + ${f};\n vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);\n return sampleTexture(${s}, uv);\n }\n `;return`\n float ${r}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${a} + col * ${i} + depth + ${f};\n vec2 uv = uvFromFlat(${h}, ${d}, index);\n return sampleTexture(${s}, uv);\n }\n `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[3],i=n[2]*a,o=n[1]*i,{newShape:l,keptDims:u}=ve(n);if(l.length<n.length){const n=["row","col","depth","depth2"];return`\n ${cM(vM(e,l),t)}\n float ${r}(int row, int col, int depth, int depth2) {\n return ${r}(${kM(n,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${o}, ${i}, ${a}, 1)));\n ${bM(e)}\n }\n `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],p=h[1],f=`int stride2 = ${s}Shape[3];`,m=`int stride1 = ${s}Shape[2] * stride2;`,g=`int stride0 = ${s}Shape[1] * stride1;`;if(p===o&&null==c)return t?`\n float ${r}(int row, int col, int depth, int depth2) {\n ${f}\n ${m}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${s}TexShape[1], ${s}TexShape[0]);\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${i}, ${a}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${d}.0);\n return sampleTexture(${s}, uv);\n }\n `;if(p===a&&null==c)return t?`\n float ${r}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${s}TexShape[1], ${s}TexShape[0]);\n return sampleTexture(${s}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${n[1]*n[2]}, ${n[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${d}.0);\n return sampleTexture(${s}, uv);\n }\n `;const y=yM(s);if(t)return`\n float ${r}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${f}\n ${m}\n ${g}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${y});\n return sampleTexture(${s}, uv);\n }\n `;return`\n float ${r}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${o} + col * ${i} +\n depth * ${a} + depth2;\n vec2 uv = uvFromFlat(${d}, ${p}, index + ${y});\n return sampleTexture(${s}, uv);\n }\n `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],a=t[3]*r,i=t[2]*a,o=t[1]*i,{newShape:l,keptDims:u}=ve(t);if(l.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${cM(vM(e,l))}\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n return ${s}(${kM(t,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${o}, ${i}, ${a}, ${r})) +\n depth3;\n ${bM(e)}\n }\n `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],p=h[1];if(p===o&&null==c)return`\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${i}, ${a}, ${r}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(p===r&&null==c)return`\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]},\n ${t[2]*t[3]}, ${t[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${p}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `;const f=yM(n);return`\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${o} + col * ${i} + depth * ${a} +\n depth2 * ${r} + depth3 + ${f};\n vec2 uv = uvFromFlat(${d}, ${p}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:a}=ve(t);if(r.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${cM(vM(e,r))}\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${s}(${kM(t,a)});\n }\n `}const i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,c=t[1]*u;if(e.shapeInfo.isUniform)return`\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${c}, ${u}, ${l}, ${o})) +\n dot(\n vec2(depth3, depth4),\n vec2(${i}, 1)));\n ${bM(e)}\n }\n `;const h=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],f=d[1];if(f===c&&null==h)return`\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${u}, ${l}, ${o}, ${i})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;if(f===i&&null==h)return`\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]*t[4]},\n ${t[2]*t[3]*t[4]},\n ${t[3]*t[4]},\n ${t[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${p}.0);\n return sampleTexture(${n}, uv);\n }\n `;const m=yM(n);return`\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${c} + col * ${u} + depth * ${l} +\n depth2 * ${o} + depth3 * ${i} + depth4 + ${m};\n vec2 uv = uvFromFlat(${p}, ${f}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function hM(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=nM();return`\n vec4 ${n}() {\n return ${s.texture2D}(${t}, halfCR);\n }\n `}(e);case 1:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,a=nM();if(t)return`\n vec4 ${s}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${a.texture2D}(${n}, uv);\n }\n `;const i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`\n vec4 ${s}(int index) {\n vec2 uv = packedUVfrom1D(\n ${i[0]}, ${i[1]}, index);\n return ${a.texture2D}(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,i=a[0],o=a[1],l=nM();if(null!=a&&de(n,a))return t?`\n vec4 ${r}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n\n return ${l.texture2D}(${s}, uv);\n }\n `:`\n vec4 ${r}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);\n\n return ${l.texture2D}(${s}, uv);\n }\n `;if(t)return`\n vec4 ${r}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${l.texture2D}(${s}, uv);\n }\n `;const u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],c=Math.ceil(n[1]/2);return`\n vec4 ${r}(int row, int col) {\n vec2 uv = packedUVfrom2D(${c}, ${u[0]}, ${u[1]}, row, col);\n return ${l.texture2D}(${s}, uv);\n }\n `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){const s=[1,2],a=["b","row","col"];return`\n ${hM(vM(e,n.slice(1)),t)}\n vec4 ${r}(int b, int row, int col) {\n return ${r}(${kM(a,s)});\n }\n `}const o=nM();if(t)return`\n vec4 ${r}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${o.texture2D}(${s}, uv);\n }\n `;const l=i[0],u=i[1],c=Math.ceil(n[2]/2),h=c*Math.ceil(n[1]/2);return`\n vec4 ${r}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${l}, ${u}, ${h}, ${c}, b, row, col);\n return ${o.texture2D}(${s}, uv);\n }\n `}(e,t);default:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=nM();if(t)return`\n vec4 ${s}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${n}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${r.texture2D}(${n}, uv);\n }\n `;const a=e.shapeInfo.logicalShape,i=a.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],c=l[1],h=Math.ceil(a[i-1]/2);let d=h*Math.ceil(a[i-2]/2),p="int b, int row, int col",f=`b * ${d} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<i-1;e++)p=`int b${e}, `+p,d*=a[i-e-1],f=`b${e} * ${d} + `+f;return`\n vec4 ${s}(${p}) {\n int index = ${f};\n int texR = index / ${c};\n int texC = index - texR * ${c};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${u});\n return ${r.texture2D}(${n}, uv);\n }\n `}(e,t)}}const dM="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",pM="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",fM="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",mM="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function gM(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function yM(e){return`offset${e}`}function bM(e){const t=e.name,n=ue(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n for (int i = 0; i < ${n}; i++) {\n if (i == index) {\n return ${t}[i];\n }\n }\n `}function xM(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function wM(e,t,n){const{newShape:s,keptDims:r}=ve(t),a=t.length,i=e&&3===a&&1===t[0],o=i?t.slice(1):s,l=!e&&a>1&&!de(t,n)&&s.length<a||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function vM(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function kM(e,t){return t.map((t=>e[t])).join(", ")}function IM(e,t,n){const s=[],r=[];let a,i,o,l=null,u=null;u=e.getUniformLocation(n,"NAN",!1),1===Xe().getNumber("WEBGL_VERSION")&&(l=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const r of t.variableNames){const a={name:r,uniform:e.getUniformLocation(n,r,c),offset:e.getUniformLocation(n,`offset${r}`,c)};t.enableShapeUniforms&&(a.shape=e.getUniformLocation(n,`${r}Shape`,c),a.texShape=e.getUniformLocation(n,`${r}TexShape`,c)),s.push(a)}if(t.enableShapeUniforms&&(a=e.getUniformLocation(n,"outShape",c),o=e.getUniformLocation(n,"outShapeStrides",c),i=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const s of t.customUniforms)r.push(e.getUniformLocation(n,s.name,c));return{variablesLocations:s,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:a,outShapeStridesLocation:o,outTexShapeLocation:i}}function NM(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(((e,n)=>{const s=e.logicalShape,r=t[n],a=r.shape;if(!de(s,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${a} must match`);if(e.isUniform&&r.isUniform)return;const i=e.texShape,o=r.isUniform?null:r.texData.texShape;if(!de(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function SM(e){return Xe().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class TM{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=YD.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=nM();this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?rM(["r","c","d"],e):sM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class CM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=YD.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=nM();this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?rM(["r","c","d"],e):sM(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class $M{constructor(e){this.variableNames=["A"],this.outTexUsage=ZD.DOWNLOAD;const t=nM();this.outputShape=e,this.userCode=`\n ${oM}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class EM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ZD.DOWNLOAD;const t=nM();this.outputShape=e,this.userCode=`\n ${oM}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}const RM={R:0,G:1,B:2,A:3};class AM{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const s=nM();this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)");let a="";for(let e=0;e<n.length;e++){const t=n[e];a+=`\n if(offset == ${e}) {\n result = values[${RM[t]}];\n }`}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":iM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${n.length});\n\n flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${s.texture2D}(A, uv);\n ${a}\n }\n ${s.output} = vec4(${r}, 0., 0., 0.);\n }\n `}}class _M{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=nM();this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length);let s="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let r=0;r<=1;r++){const a=2*t+r;s+=`\n localCoords = coords;\n if(localCoords[2] + ${r} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${r};\n if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${a}] = values[0];\n } else if (offset == 1) {\n result[${a}] = values[1];\n } else if (offset == 2) {\n result[${a}] = values[2];\n } else {\n result[${a}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":iM(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${s}\n\n ${n.output} = ${r};\n }\n `}}function FM(e){const t=nM();return uO(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}function DM(e){return gO(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function OM(e){return yO(e,new Uint16Array([0,1,2,2,1,3]))}function MM(e,t,n,s,r,a){wO(t,n);const i=xO(e),o=e.TEXTURE_2D;return sO(e,(()=>e.bindTexture(o,i))),sO(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),sO(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),sO(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),sO(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Xe().getNumber("WEBGL_VERSION")?sO(e,(()=>e.texImage2D(o,0,s,t,n,0,r,a,null))):sO(e,(()=>e.texStorage2D(o,1,s,t,n))),sO(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function LM(e){return e.internalFormatFloat}function zM(e,t,n,s){const[r,a]=QD(t,n);return MM(e,r,a,LM(s),s.textureFormatFloat,e.FLOAT)}function PM(e){return e.internalFormatHalfFloat}function BM(e,t,n,s){const[r,a]=QD(t,n);return MM(e,r,a,PM(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function WM(e){return e.downloadTextureFormat}function VM(e,t,n,s){const[r,a]=QD(t,n);return MM(e,r,a,WM(s),e.RGBA,e.UNSIGNED_BYTE)}function UM(e){return e.internalFormatPackedFloat}function GM(e,t,n,s){const[r,a]=tO(t,n);return MM(e,r,a,UM(s),e.RGBA,e.FLOAT)}function HM(e){return e.internalFormatPackedHalfFloat}function jM(e,t,n,s){const[r,a]=tO(t,n);return MM(e,r,a,HM(s),e.RGBA,s.textureTypeHalfFloat)}function qM(e,t,n){sO(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n)));return kO(e,t,"clipSpacePos",n,3,20,0)&&kO(e,t,"uv",n,2,20,12)}function KM(e,t,n,s,r,a){let i,o,l;sO(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),r instanceof Uint8Array?(i=new Uint8Array(n*s*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*s*4),o=e.FLOAT,l=a.internalFormatPackedFloat),i.set(r),2===Xe().getNumber("WEBGL_VERSION")?sO(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGBA,o,i))):sO(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,o,i))),sO(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function XM(e,t,n){sO(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Xe().getNumber("WEBGL_VERSION")?sO(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):sO(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Xe().getNumber("WEBGL_VERSION")?sO(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):sO(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),sO(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function YM(e,t,n,s){const r=e.createBuffer();sO(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r)));const a=16*t*n;return sO(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ))),sO(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),sO(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),r}function ZM(e,t,n){const s=e,r=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function JM(e,t,n,s){const[r,a]=QD(t,n),i=new Uint8Array(t*n*4);return sO(e,(()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}function QM(e,t,n,s,r,a,i,o){const l=e,u=new Float32Array(function(e,t){const[n,s]=tO(e,t);return n*s*4}(a,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 eL(e,t,n){const s=new Float32Array(t*n*4);return sO(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s))),s}class tL{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Xe().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,KD(t,e)):this.gl=XD(t),e=this.gl,2===Xe().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>sO(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>sO(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>sO(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>sO(t,(()=>t.getParameter(t.VERTEX_ARRAY_BINDING)))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>sO(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>sO(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>sO(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>sO(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Xe().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=lO(this.gl,e),KO(this.gl,t))this.textureHalfFloatExtension=lO(this.gl,t);else if(Xe().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),KO(this.gl,s))this.colorBufferHalfFloatExtension=lO(this.gl,s);else if(Xe().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",KO(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!KO(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=DM(this.gl),this.indexBuffer=OM(this.gl),this.framebuffer=vO(this.gl),this.textureConfig=nO(this.gl,this.textureHalfFloatExtension)}get debug(){return Xe().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&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."),null!=this.outputTexture&&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.");const e=this.gl;sO(e,(()=>e.finish())),sO(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),sO(e,(()=>e.deleteFramebuffer(this.framebuffer))),sO(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),sO(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),sO(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),zM(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),BM(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),VM(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),XM(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),KM(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),jM(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),GM(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(RO(this.gl,this.framebuffer),this.outputTexture=null),sO(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>JM(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return QM(this.gl,e,0,0,0,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return ZM(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=YM(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Xe().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,r=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=s.clientWaitSync(r,0,0);return e===s.ALREADY_SIGNALED||e===s.CONDITION_SATISFIED},t=r}else Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>eL(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=FM(t));const n=pO(t);sO(t,(()=>t.attachShader(n,this.vertexShader))),sO(t,(()=>t.attachShader(n,e))),fO(t,n);const s=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&mO(t,s),s}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;sO(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),qM(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(sO(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&mO(this.gl,this.program),sO(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?SO(this.gl,e,t):TO(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),sO(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(),CO(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,r]=tO(t,n);this.setOutputMatrixTextureDriver(e,s,r)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&mO(this.gl,this.program),AO(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}sO(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),sO(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=lO(this.gl,2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await be((()=>this.disposed||this.isQueryAvailable(e,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length;++t){if(!e[t]())break}return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}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 Xe().platform&&(n=Xe().platform.setTimeoutCustom.bind(Xe().platform)),be((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),EO(this.gl,e,this.framebuffer),this.debug&&AO(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(EO(this.gl,this.outputTexture,this.framebuffer),this.debug&&AO(this.gl)):RO(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;EO(s,e,this.framebuffer),this.debug&&AO(s),this.outputTexture=e,sO(s,(()=>s.viewport(0,0,t,n))),sO(s,(()=>s.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),sO(this.gl,(()=>this.gl.scissor(e,t,n,s)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:nL,bincountImpl:sL,bincountReduceImpl:rL,bitwiseAndImpl:aL,castImpl:iL,ceilImpl:oL,concatImpl:lL,equalImpl:uL,expImpl:cL,expm1Impl:hL,floorImpl:dL,gatherNdImpl:pL,gatherV2Impl:fL,greaterImpl:mL,greaterEqualImpl:gL,lessImpl:yL,lessEqualImpl:bL,linSpaceImpl:xL,logImpl:wL,maxImpl:vL,maximumImpl:kL,minimumImpl:IL,multiplyImpl:NL,negImpl:SL,notEqualImpl:TL,prodImpl:CL,raggedGatherImpl:$L,raggedRangeImpl:EL,raggedTensorToTensorImpl:RL,rangeImpl:AL,rsqrtImpl:_L,scatterImpl:FL,sigmoidImpl:DL,simpleAbsImpl:OL,sliceImpl:ML,sparseFillEmptyRowsImpl:LL,sparseReshapeImpl:zL,sparseSegmentReductionImpl:PL,sqrtImpl:BL,staticRegexReplaceImpl:WL,stridedSliceImpl:VL,stringNGramsImpl:UL,stringSplitImpl:GL,stringToHashBucketFastImpl:HL,subImpl:jL,tileImpl:qL,topKImpl:KL,transposeImpl:XL,uniqueImpl:YL}=j;function ZL(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function JL(e,t){return 1===t?[e]:ZL(e,t)}class QL{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=SM(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=JL("rc",this.rank),t=xM(this.rank),n=this.getOutOfBoundsCondition(e),s=this.getSetup(e),r=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${s}\n\n setOutput(vec4(${r}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let s=0;s<=1;s++){let r=`${0===n?"r":"rp1"}, ${0===s?"c":"cp1"}`;for(let t=2;t<this.rank;t++)r=`${e[e.length-1-t]},`+r;t.push(r)}return t}getOutOfBoundsCondition(e){if(1===this.rank)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(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],s=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n int r = ${t[0]};\n int c = ${t[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${n};\n bool rEdge = rp1 >= ${s};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);if(1===this.rank){return`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`}return`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class ez{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var s,r;this.userCode=`\n ${s=t,r=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${r?aM(["r","c","d"],"inputShape"):sM(["r","c","d"],s)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":iM(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class tz{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){const s=sz(t,n),r=rz(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const a=nz(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[r].pop();return this.usedTextures[r].push(e),e}let i;return s===JD.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===JD.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===JD.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===JD.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===JD.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,s){if(null==this.freeTextures)return;const r=sz(n,s),a=rz(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);const i=nz(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),o=Xe().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const l=this.usedTextures[a],u=l&&l.indexOf(e);if(null==u||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;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const 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(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function nz(e,t,n,s,r){const a=function(e,t){switch(e){case JD.PACKED_2X2_FLOAT32:return UM(t);case JD.PACKED_2X2_FLOAT16:return HM(t);case JD.UNPACKED_FLOAT32:return LM(t);case JD.UNPACKED_FLOAT16:return PM(t);case JD.PACKED_4X1_UNSIGNED_BYTE:return WM(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,s);let i;if(r){const[t,n]=tO(e[0],e[1]);i=t*n}else{const[t,n]=QD(e[0],e[1]);i=t*n}const o=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,a);return i*o}function sz(e,t){if(e===ZD.UPLOAD)return JD.PACKED_2X2_FLOAT32;if(e===ZD.RENDER||null==e)return function(e){return Xe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?JD.PACKED_2X2_FLOAT32:JD.UNPACKED_FLOAT32:e?JD.PACKED_2X2_FLOAT16:JD.UNPACKED_FLOAT16}(t);if(e===ZD.DOWNLOAD||e===ZD.PIXELS)return JD.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function rz(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class az{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const iz="if (isnan(x)) return x;",oz="return x;",lz="return abs(x);";const uz="return (x >= 0.0) ? x : (exp(x) - 1.0);",cz=iz+"\n return (x < 0.0) ? 0.0 : x;\n",hz=iz+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",dz="return x;",pz="return 1.0 / (1.0 + exp(-1.0 * x));",fz="return x;",mz="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",gz="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",yz="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",bz="return 1.0 / (1.0 + exp(-1.0 * x));";class xz{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class wz{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=SM(this.outputShape.length);const t=e.length,n=JL("rc",t),s=xM(t),r=function(e,t){if(1===e)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}(t,n),a=n.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`\n void main() {\n ${s} rc = getOutputCoords();\n vec4 packedInput = getA(${r});\n\n setOutput(getChannel(packedInput, ${i}));\n }\n `}}const vz=Ip,kz={};const Iz=Xe().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class Nz extends Y{nextDataId(){return Nz.nextDataId++}constructor(e){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,!Xe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof tL)t=e;else{const n=XD(Xe().getNumber("WEBGL_VERSION"),e);t=new tL(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=XD(Xe().getNumber("WEBGL_VERSION"));t=new tL(e),this.binaryCache=((n=Xe().getNumber("WEBGL_VERSION"))in kz||(kz[n]={}),kz[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new tz(this.gpgpu),this.numMBBeforeWarning=null==Xe().global.screen?1024:Xe().global.screen.height*Xe().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new X(this,li())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,s,r,a){const i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[s,r]},o.texShape=[s,r];const l=LO(t),u=new AM(l,!1,a),c=this.runWebGLProgram(u,[i],n,[[s,r]]);return c.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,n){if((Xe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Xe().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={id:this.nextDataId()};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:ZD.UPLOAD,refCount:1}),s}refCount(e){if(this.texData.has(e)){return this.texData.get(e).refCount}return 0}incRef(e){this.texData.get(e).refCount++}decRef(e){if(this.texData.has(e)){this.texData.get(e).refCount--}}move(e,t,n,s,r){if(Xe().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===s)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:ZD.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:r,slice:a,shape:i,isPacked:o}=t;if(null!=a){let t;t=o?new xz(i,dz):new az(i,dz);const n=this.runWebGLProgram(t,[{dataId:e,shape:i,dtype:s}],s),r=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===s)return n;const l=null!=this.activeTimers;let u,c;if(l&&(u=Xr()),"complex64"===s){c=vm(this.readSync(r.real.dataId),this.readSync(r.imag.dataId))}else c=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=Xr()-u),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e),{values:n,shape:s,slice:r,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=r){let t;t=o?new xz(s,dz):new az(s,dz);const n=this.runWebGLProgram(t,[{dataId:e,shape:s,dtype:a}],a),r=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if(Xe().getBool("DEBUG")&&!Xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Xe().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l,u,c=null;if("complex64"!==a&&Xe().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...eO(s))}if(this.pendingRead.set(e,[]),"complex64"!==a&&await this.gpgpu.createAndWaitForFence(),"complex64"===a){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);u=vm(e[0],e[1])}else if(null==c)u=this.getValuesFromTexture(e);else{const e=ue(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=l&&this.disposeIntermediateTensorInfo(l),null!=c){const e=this.gpgpu.gl;sO(e,(()=>e.deleteBuffer(c)))}const h=this.convertAndCacheOnCPU(e,u),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&li().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:s,shape:r,slice:a,dtype:i,isPacked:o,texture:l}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=a){let n;n=o?new xz(r,dz):new az(r,dz);const s=this.runWebGLProgram(n,[{dataId:e,shape:r,dtype:i}],i),a=this.readToGPU(s,t);return this.disposeIntermediateTensorInfo(s),a}if(null==l)throw null!=s?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(e,t.customTexShape),c=li().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Jr(e)));return Co(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Co(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!iO(n)){if(Xe().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:s}=this.texData.get(e),r=ue(t);if(Xe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),s=this.texData.get(n.dataId),a=this.gpgpu.downloadMatrixFromPackedTexture(s.texture.texture,...eO(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(n),a}const a=Xe().getBool("WEBGL_PACK")&&!0===s,i=a?LO(t):t,o=a?new EM(i):new $M(i),l=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),u=this.texData.get(l.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),c}timerAvailable(){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let s=!1;null==this.programTimersStack?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const r=ea(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=ea(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,s&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(r);i.kernelMs=se(e),i.getExtraProfileInfo=()=>e.map(((e,t)=>({name:a[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Xr(),endMs:null}}endTimer(e){return Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Xr(),e)}async getQueryTime(e){if(Xe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:s,usage:r,isPacked:a,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,r,a)));const u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Iz){return Xe().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&ue(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){xr("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return vz(e.shape,t)}packedUnaryOp(e,t,n){const s=new xz(e.shape,t),r=this.compileAndRun(s,[e],n);return li().makeTensorFromTensorInfo(r)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=OL(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,lz,e.dtype);const t=new az(e.shape,lz),n=this.compileAndRun(t,[e]);return li().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&Ee(n[0])){const r=n.map((e=>Zr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){return li().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new wz(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new QL(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[OO(e.shape),...MO(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[OO(t),...MO(t)],a=new ez(r,n),i=[n],o=this.runWebGLProgram(a,[s],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:s,shape:r,dtype:a}=n;if(null!=t){ie(ue(r)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."))}const i=LO(r);let o;o=s?new CM(i):new TM(i);const l=[null!=t?t:eO(i)];return{dtype:a,shape:r,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,l,!0,t).dataId}}runWebGLProgram(e,t,n,s,r=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===YD.DENSE){const t=null!=a?a:eO(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===ue(i.shape))return o.values=ke(i.dtype,0),i;const l=[],u=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&ue(t.shape)<=Xe().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),l.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!BO(n.shape,t.shape)){const e=t,s=t.shape;t.shape=n.shape,t=this.packedReshape(t,s),l.push(t),n=this.texData.get(t.dataId),e.shape=s}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},h=function(e,t,n){let s="";t.concat(n).forEach((t=>{const r=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const a=t.texData.texShape,{useSqueezeShape:i,uniformShape:o,keptDims:l}=wM(e.packedInputs,t.shape,a);let u="",c="",h="";if(1===o.length&&e.packedInputs){const e=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];u=`${e[0]>1}_${e[1]>1}`}else if(2!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=Oe(o);h=`${e[0]===a[1]}_${e[e.length-1]===a[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const d=t.shape.length,p=2===o.length&&de(t.shape,a),f=1===ue(t.shape),m=il(t.shape,n.shape),g=!e.packedInputs&&d===n.shape.length&&de(a,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;s+=`${d}_${g}_${i?l:""}_${o.length}_${f}_${m}_${p}_${u}_${c}_${h}_${y}_${r}`}else{const e=t.isUniform?"uniform":t.texData.texShape;s+=`${t.shape}_${e}_${r}`}}));const r=e.userCode;let a=e.constructor.name;return a+="_"+s+"_"+r+`${Xe().getNumber("WEBGL_VERSION")}`,a}(e,u,c),d=this.getAndSaveBinary(h,(()=>function(e,t,n,s){const r=n.map(((e,n)=>{const s={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(s.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:s}})),a=r.map((e=>e.shapeInfo)),i={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},o=uM(r,i,t),l=cO(e.gl,o),u=e.createProgram(l);return Xe().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,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:a,outShapeInfo:i},IM(e,t,u)))}(this.gpgpu,e,u,c))),p=null!=this.activeTimers;let f;p&&(f=this.startTimer()),Xe().get("ENGINE_COMPILE_ONLY")||function(e,t,n,s,r){t.program.enableShapeUniforms||(NM(t.inShapeInfos,n),NM([t.outShapeInfo],[s]));const a=s.texData.texture,i=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===Xe().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let s=0;s<n.length;++s){const r=n[s],{uniform:a,offset:i,shape:o,texShape:l}=t.variablesLocations[s];if(o){const{uniformShape:n}=wM(t.program.packedInputs,r.shape,r.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(o,new Int32Array(n));break;case 2:e.gl.uniform2iv(o,new Int32Array(n));break;case 3:e.gl.uniform3iv(o,new Int32Array(n));break;case 4:e.gl.uniform4iv(o,new Int32Array(n))}}if(l&&e.gl.uniform2i(l,r.texData.texShape[0],r.texData.texShape[1]),null!=a)if(r.isUniform)if(ue(r.shape)<2)e.gl.uniform1f(a,r.uniformValues[0]);else{let t=r.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=r.texData.slice&&null!=i&&e.gl.uniform1i(i,r.texData.slice.flatOffset),e.setInputMatrixTexture(r.texData.texture.texture,a,s)}const o=t.outShapeLocation;if(o)switch(s.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(s.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(s.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(s.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(s.shape))}if(t.outShapeStridesLocation){const n=Oe(s.shape);switch(s.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r)for(let n=0;n<t.program.customUniforms.length;++n){const s=t.program.customUniforms[n],a=t.customUniformLocations[n],i=r[n];if("float"===s.type)e.gl.uniform1fv(a,i);else if("vec2"===s.type)e.gl.uniform2fv(a,i);else if("vec3"===s.type)e.gl.uniform3fv(a,i);else if("vec4"===s.type)e.gl.uniform4fv(a,i);else if("int"===s.type)e.gl.uniform1iv(a,i);else if("ivec2"===s.type)e.gl.uniform2iv(a,i);else if("ivec3"===s.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==s.type)throw Error(`uniform type ${s.type} is not supported yet.`);e.gl.uniform4iv(a,i)}}e.executeProgram()}(this.gpgpu,d,u,c,s),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),p&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=Xe().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Xr();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Xe().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===r){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,s,r=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,s,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!Xe().getBool("IS_TEST")){Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}))}this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=hi((()=>{if(!Xe().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Xe().getBool("DEBUG");Xe().set("DEBUG",!1);const t=this.abs(Ho(1e-8)).dataSync()[0];if(Xe().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:s,values:r,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const l=null!=this.activeTimers;let u;l&&(u=Xr());let c=t.texShape;if(null==c&&(c=zO(n,o),t.texShape=c),null!=r){const e=LO(n);let a,i=c[1],h=c[0];const d=r instanceof Uint8Array||r instanceof Uint8ClampedArray;!o&&d||([i,h]=tO(c[0],c[1])),a=o?new _M(e,d):new AM(e,d);const p=d?[h,i]:c,f=this.makeTensorInfo(p,s),m=this.texData.get(f.dataId);m.usage=d?ZD.PIXELS:ZD.UPLOAD,m.texShape=p,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,r);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],s,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,Xe().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),l&&(this.uploadWaitMs+=Xr()-u)}else{const e=this.acquireTexture(c,i,s,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*Ce(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await Zf(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw dO(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:s,nanLoc:r,outShapeLocation:a,outShapeStridesLocation:i,outTexShapeLocation:o}=IM(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=s,e.nanLoc=r,e.outShapeLocation=a,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:s,height:r,width:a,channels:i}=e,o=li().backend;if(!o.gpgpu.gl.isTexture(s))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)'.");const l=o.writeTexture(s,t,n,r,a,i);return li().makeTensorFromDataId(l,t,n,o)}}Nz.nextDataId=0;const Sz="4.20.0";function Tz(){Xe().set("WEBGL_FORCE_F16_TEXTURES",!0)}Ua()&&vi("webgl",(()=>new Nz),2);const Cz={forceHalfFloat:Tz},$z="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";class Ez{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=ll(t,n),this.enableShapeUniforms=SM(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}const Rz="\n result.r = isNaN.r ? NAN : result.r;\n result.g = isNaN.g ? NAN : result.g;\n result.b = isNaN.b ? NAN : result.b;\n result.a = isNaN.a ? NAN : result.a;\n";class Az{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ll(t,n);const r=this.outputShape.length;this.enableShapeUniforms=SM(r);let a="";if(s)if(0===r||1===ue(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else{if(a=`\n ${xM(r)} coords = getOutputCoords();\n `,1===r)this.enableShapeUniforms?a+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":a+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=JL("coords",r);this.enableShapeUniforms?a+=`\n bool nextRowOutOfBounds =\n (${e[r-2]} + 1) >= outShape[${r} - 2];\n bool nextColOutOfBounds =\n (${e[r-1]} + 1) >= outShape[${r} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:a+=`\n bool nextRowOutOfBounds =\n (${e[r-2]} + 1) >= ${this.outputShape[r-2]};\n bool nextColOutOfBounds =\n (${e[r-1]} + 1) >= ${this.outputShape[r-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${a}\n\n setOutput(result);\n }\n `}}function _z(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const Fz={kernelName:yn,backendName:"webgl",kernelFunc:_z};function Dz(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),i=n.texData.get(a.dataId),o=_z({inputs:{x:s},backend:n}),l=_z({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},a}const Oz={kernelName:Ct,backendName:"webgl",kernelFunc:Dz},Mz="return (a < 0.) ? b * a : a;",Lz="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const zz={kernelName:In,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,i=n.makeTensorInfo([],"float32",qr(a,"float32")),o=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Az(Lz,r.shape,i.shape):new Ez(Mz,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}},Pz="return (a < 0.) ? b * a : a;",Bz="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const Wz={kernelName:us,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Az(Bz,s.shape,r.shape):new Ez(Pz,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}},Vz="if (isnan(x)) return x;";function Uz({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:r,backend:a})=>{const{x:i}=r,o=a,l=s||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,l);return o.makeTensorInfo(i.shape,l,t)}let u;return u=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new xz(i.shape,t):new az(i.shape,e),o.runWebGLProgram(u,[i],l)}}function Gz({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:i,backend:o})=>{const{a:l,b:u}=i,c=o;if(s&&"complex64"===l.dtype){const t=c.texData.get(l.dataId),n=c.texData.get(u.dataId),[s,r]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,s]=t,r={dataId:n.dataId,dtype:n.dtype,shape:l.shape},a={dataId:s.dataId,dtype:s.dtype,shape:u.shape},i=new Ez(e,l.shape,u.shape);return c.runWebGLProgram(i,[r,a],Sa(n.dtype,s.dtype))})),a=Dz({inputs:{real:s,imag:r},backend:c});return c.disposeIntermediateTensorInfo(s),c.disposeIntermediateTensorInfo(r),a}const h=a||Sa(l.dtype,u.dtype);if(("string"===l.dtype||"string"===u.dtype||c.shouldExecuteOnCPU([l,u]))&&null!=r){const e=c.texData.get(l.dataId).values,t=c.texData.get(u.dataId).values,n="string"===l.dtype?tg(e):e,s="string"===l.dtype?tg(t):t,[a,i]=r(l.shape,u.shape,n,s,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let d;return d=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Az(t,l.shape,u.shape,n):new Ez(e,l.shape,u.shape),c.runWebGLProgram(d,[l,u],h)}}function Hz(e,t=!1){if("linear"===e)return t?fz:oz;if("relu"===e)return t?gz:cz;if("elu"===e)return t?mz:uz;if("relu6"===e)return t?yz:hz;if("prelu"===e)return t?Bz:Pz;if("leakyrelu"===e)return t?Lz:Mz;if("sigmoid"===e)return t?bz:pz;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class jz{constructor(e,t,n,s=!1,r=!1,a=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=SM(this.outputShape.length);const u=s?e[1]:e[2],c=Math.ceil(u/2),h=s?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",p=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${i}\n }`:l?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${i}\n }`:`vec4 activation(vec4 x) {\n ${i}\n }`,g="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`\n ${m}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${c}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${b};\n int batchB = ${x};\n for (int i = 0; i < ${c}; i++) {\n vec4 a = getMatrixA(batchA, ${h});\n vec4 b = getMatrixB(batchB, ${d});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${p[0]} * ${f[0]});\n result += (${p[1]} * ${f[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${y}\n\n ${g}\n\n setOutput(result);\n }\n `}}const qz={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class Kz{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ll(t,n),this.userCode=`\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${e}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `}}const Xz="return a * b;";function Yz(e){const{inputs:t,backend:n}=e,{a:s,b:r}=t,a=Sa(s.dtype,r.dtype);if("complex64"===s.dtype){const e=n.texData.get(s.dataId),t=n.texData.get(r.dataId),a=new Kz(qz.REAL,s.shape,r.shape),i=new Kz(qz.IMAG,s.shape,r.shape),o=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:s.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:r.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:r.shape}],l=n.runWebGLProgram(a,o,"float32"),u=n.runWebGLProgram(i,o,"float32"),c=Dz({inputs:{real:l,imag:u},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),c}if(n.shouldExecuteOnCPU([s,r])){const e=n.texData.get(s.dataId),t=n.texData.get(r.dataId),[i,o]=NL(s.shape,r.shape,e.values,t.values,a),l=n.makeTensorInfo(o,a);return n.texData.get(l.dataId).values=i,l}let i;return i=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Az(Xz,s.shape,r.shape):new Ez(Xz,s.shape,r.shape),n.runWebGLProgram(i,[s,r],a)}const Zz={kernelName:Zn,backendName:"webgl",kernelFunc:Yz};function Jz(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=n,o=ue(r.shape),l=xe(a,o),u=ue(l);ie(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.`));const c=i.texData.get(r.dataId);return!c.isPacked||BO(r.shape,l)||null!==c.texture&&BO(c.shape,l)?(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype}):function(e,t,n){const s=[OO(e.shape),...MO(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},a=[OO(t),...MO(t)],i=new ez(a,s),o=[s],l=n.runWebGLProgram(i,[r],e.dtype,o,!0);return{dataId:l.dataId,shape:t,dtype:l.dtype}}(r,l,i)}const Qz={kernelName:bs,backendName:"webgl",kernelFunc:Jz};class eP{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];const i=4*Math.floor(n/4),o=n%4;let l="sumValue += dot(values, ones);";if(null!=t){const e=1/t;l=`sumValue += dot(values * ${pe(e)?e.toPrecision(2):e}, ones);`}let u="";r%n>0&&(u=`\n if (inIdx < 0 || inIdx >= ${r}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${u}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${i}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${l}\n }\n\n int inIdx = inOffset + ${i};\n if (${1===o}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${l}\n } else if (${2===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${l}\n } else if (${3===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${l}\n }\n setOutput(sumValue);\n }\n `}}class tP{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?l="sumValue":"prod"===t?l="prodValue":"all"===t?l="allValue":"any"===t&&(l="anyValue");const u=4*Math.floor(n/4),c=n%4;let h=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${o}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${o}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,d="vec4";"all"===t?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",d="bvec4"):"any"===t&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",d="bvec4");let p="";r%n>0&&(p=`\n if (inIdx < 0 || inIdx >= ${r}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${i};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${p}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${i});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${u}; i += 4) {\n int inIdx = inOffset + i;\n ${d} values = ${d}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${h}\n }\n\n int inIdx = inOffset + ${u};\n if (${1===c}) {\n ${d} values = ${d}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${2===c}) {\n ${d} values = ${d}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${3===c}) {\n ${d} values = ${d}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${h}\n }\n setOutput(${l});\n }\n `}}function nP(e,t,n,s){const r=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],s=im(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}(e.shape);let a=e;for(let i=0;i<r.length;i++){const{inSize:o,windowSize:l,outSize:u}=r[i];let c,h;c="mean"===n?0===i?new eP({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new eP({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):new tP({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},n),h=a,a=s.runWebGLProgram(c,[a],t),h.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(h)}return a}class sP{constructor(e,t){this.variableNames=["A"];const 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;const s=xM(this.rank),r=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let t=0;t<e.length;t++)s[e[t]]=n[t];return s.join()}(t);this.userCode=`\n void main() {\n ${s} resRC = getOutputCoords();\n setOutput(getA(${r}));\n }\n `}}class rP{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=xM(this.rank),r=ZL("rc",this.rank),a=new Array(this.rank);for(let e=0;e<t.length;e++)a[t[e]]=r[e];const i=`vec2(${a.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`\n void main() {\n ${s} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${l};\n if(${o}) {\n result[1] = ${l};\n }\n --${r[this.rank-1]};\n if(++${r[this.rank-2]} < ${n[this.rank-2]}) {\n result[2] = ${l};\n if(${o}) {\n result[3] = ${l};\n }\n }\n setOutput(result);\n }\n `}}function aP(e,t,n){const s=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rP(e.shape,t):new sP(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}function iP(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;return function(e,t,n,s){const r=t,a=e.shape.length,i=we(r,e.shape);let o=i;const l=lh(o,a),u=null!=l;let c=e;u&&(c=aP(e,l,s),o=ch(o.length,a)),oh("sum",o,a);const[h,d]=ah(c.shape,o);let p=h;n&&(p=ih(h,i));const f=ue(d),m=Jz({inputs:{x:c},attrs:{shape:[ue(e.shape)/f,f]},backend:s}),g=nP(m,Ta(e.dtype),"sum",s),y=Jz({inputs:{x:g},attrs:{shape:p},backend:s});return s.disposeIntermediateTensorInfo(m),s.disposeIntermediateTensorInfo(g),u&&s.disposeIntermediateTensorInfo(c),y}(r,a,i,n)}const oP={kernelName:Ps,backendName:"webgl",kernelFunc:iP};function lP(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{perm:a}=s,i=n,o=r.shape.length,l=new Array(o);for(let e=0;e<l.length;e++)l[e]=r.shape[a[e]];let u;if(i.shouldExecuteOnCPU([r])){const e=i.texData.get(r.dataId).values,t=XL(e,r.shape,r.dtype,a,l);u=i.makeTensorInfo(l,r.dtype);i.texData.get(u.dataId).values=t}else u=aP(r,a,i);return u}const uP={kernelName:or,backendName:"webgl",kernelFunc:lP},cP=1e3;function hP({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){const u=e.shape.length,c=t.shape.length,h=n?e.shape[u-2]:e.shape[u-1],d=s?t.shape[c-1]:t.shape[c-2],p=n?e.shape[u-1]:e.shape[u-2],f=s?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=ue(m),b=ue(g),x=ll(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([p,f]);ie(h===d,(()=>`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`));const w=n?[y,h,p]:[y,p,h],v=s?[b,f,d]:[b,d,f],k=Jz({inputs:{x:e},backend:r,attrs:{shape:w}}),I=Jz({inputs:{x:t},backend:r,attrs:{shape:v}}),N=[k,I],S=Math.max(y,b),T=n?k.shape[1]:k.shape[2],C=null!=a,$=null!=i,E="leakyrelu"===l,R=null!=l?Hz(l,!0):null;let A;if((1===p||1===f)&&T>cP&&!1===(C||$||E||null!=R)){let e=k,t=I;n&&(e=lP({inputs:{x:k},backend:r,attrs:{perm:[0,2,1]}}),N.push(e)),s&&(t=lP({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),N.push(t));const a=1===f;let i=e;1!==f&&(i=Jz({inputs:{x:e},backend:r,attrs:{shape:[S,T,1]}}),N.push(i));const o=1===f?2:1;let l=t;a&&(l=Jz({inputs:{x:t},backend:r,attrs:{shape:[S,1,T]}}),N.push(l));const u=Yz({inputs:{a:i,b:l},backend:r});A=iP({inputs:{x:u},backend:r,attrs:{axis:o,keepDims:!0}}),N.push(u)}else{const l=Sa(e.dtype,t.dtype),u=new jz(w,v,[S,p,f],n,s,C,R,$,E),c=[k,I];if(null!=a&&c.push(a),$&&c.push(i),E){const e=r.makeTensorInfo([],"float32",qr(o,"float32"));c.push(e),N.push(e)}A=r.runWebGLProgram(u,c,l)}const _=Jz({inputs:{x:A},backend:r,attrs:{shape:x}});N.push(A);for(const e of N)r.disposeIntermediateTensorInfo(e);return _}const dP={kernelName:gr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return hP({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},pP="return abs(x);";const fP={kernelName:et,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&"complex64"!==s.dtype){const e=n.texData.get(s.dataId),t=OL(e.values);return n.makeTensorInfo(s.shape,s.dtype,t)}let r;return r=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new xz(s.shape,pP):new az(s.shape,pP),n.runWebGLProgram(r,[s],s.dtype)}},mP=Uz({opSnippet:iz+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),gP={kernelName:tt,backendName:"webgl",kernelFunc:mP},yP=Uz({opSnippet:iz+"\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),bP={kernelName:nt,backendName:"webgl",kernelFunc:yP},xP="return a + b;",wP=Gz({opSnippet:xP,packedOpSnippet:xP,supportsComplex:!0,cpuKernelImpl:nL}),vP={kernelName:st,backendName:"webgl",kernelFunc:wP};class kP{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`float v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${s};\n setOutput(result);\n }\n `}}class IP{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${s};\n setOutput(result);\n }\n `}}const NP={kernelName:rt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,r=n;if(1===r.length)return _z({inputs:{x:r[0]},backend:s});if(r.length>Xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(r.length/2),n=e({inputs:r.slice(0,t),backend:s}),a=e({inputs:r.slice(t),backend:s});return e({inputs:[n,a],backend:s})}const a=r.map((e=>e.dtype)).reduce(((e,t)=>Sa(e,t))),i=r.map((e=>e.shape)),o=Xe().getBool("WEBGL_PACK")?new IP(r[0].shape,i):new kP(r[0].shape,i);return s.runWebGLProgram(o,r,a)}};const SP={kernelName:at,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=we(a,r.shape);let u=l;const c=lh(u,o);let h=r;null!=c&&(h=lP({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ch(u.length,o)),oh("all",u,o);const[d,p]=ah(h.shape,u),f=Jz({inputs:{x:h},backend:n,attrs:{shape:[-1,ue(p)]}}),m=nP(f,f.dtype,"all",n);let g;if(i){g=Jz({inputs:{x:m},backend:n,attrs:{shape:ih(d,l)}})}else g=Jz({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};const TP={kernelName:it,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=we(a,r.shape);let u=l;const c=lh(u,o);let h=r;null!=c&&(h=lP({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ch(u.length,o)),oh("any",u,o);const[d,p]=ah(h.shape,u),f=Jz({inputs:{x:h},backend:n,attrs:{shape:[-1,ue(p)]}}),m=nP(f,f.dtype,"any",n);let g;if(i){g=Jz({inputs:{x:m},backend:n,attrs:{shape:ih(d,l)}})}else g=Jz({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};class CP{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:r,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,a];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${s};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${s}; i++) {\n int inIdx = ${o};\n float candidate = getA(batch, inIdx);\n if (candidate ${i} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class $P{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,ie(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const r=e[e.length-1],a=Math.ceil(r/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),s||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,l=xM(o),u=JL("coords",o);let c,h;if(1===a){h=o+1;const e=xM(h);c=`\n ${e} sourceLocR = ${e}(${u.join()}, 0);\n ++${u[o-1]};\n ${e} sourceLocG = ${e}(${u.join()}, 0);\n ++${u[o-2]};\n ${e} sourceLocA = ${e}(${u.join()}, 0);\n --${u[o-1]};\n ${e} sourceLocB = ${e}(${u.join()}, 0);\n --${u[o-2]};`}else h=o,c=`\n ${l} sourceLocR = coords;\n ++${u[o-1]};\n ${l} sourceLocG = coords;\n ++${u[o-2]};\n ${l} sourceLocA = coords;\n --${u[o-1]};\n ${l} sourceLocB = coords;\n --${u[o-2]};`;const d=["x","y","z","w","u","v"].slice(0,h),p="."+d[h-1],f=d.map((e=>"int "+e)),m=JL("sourceLocR",h-1).concat("inIdx.r"),g=JL("sourceLocG",h-1).concat("inIdx.g"),y=JL("sourceLocB",h-1).concat("inIdx.b"),b=JL("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=s?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,k=s?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${d.join()}),\n vec2(${d.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${d.join()}),\n vec2(${d.slice(-2).join()}));\n }\n ${k}\n void main() {\n ${l} coords = getOutputCoords();\n bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};\n bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${p}, sourceLocG${p},\n sourceLocB${p}, sourceLocA${p}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${v};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${v};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function EP(e,t,n,s=null){let r=t.shape[0],a=t.shape[1];null!=s&&(r=s.shape[0],a=s.shape[1]);const i=im(a),o={windowSize:i,inSize:a,batchSize:r,outSize:Math.ceil(a/i)},l=new CP(o,n,null==s),u=[t];null!=s&&u.push(s);const c=e.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=EP(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function RP(e,t,n,s=null){const r=null!=s?s.shape:t.shape,a=im(r[r.length-1]),i=new $P(r,a,n,null==s),o=null==s?[t]:[t,s],l=e.runWebGLProgram(i,o,"int32");if(l.shape.length===t.shape.length){const s=RP(e,t,n,l);return e.disposeIntermediateTensorInfo(l),s}return l}function AP(e,t,n,s){const r=[n];if(oh("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!Xe().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],a=e.texData.get(t.dataId);let i=t;null!==a&&a.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,l]=ah(i.shape,r),u=ue(l),c=Jz({inputs:{x:i},backend:e,attrs:{shape:[-1,u]}});n.push(c);const h=EP(e,c,s);n.push(h);const d=Jz({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),d}return RP(e,t,s)}const _P={kernelName:ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=we(a,r.shape);const o=lh(i,r.shape.length);let l=r;const u=[];null!=o&&(l=lP({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ch(i.length,l.shape.length)),oh("argMax",[i[0]],l.shape.length);const c=AP(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}};const FP={kernelName:lt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=we(a,r.shape);const o=lh(i,r.shape.length);let l=r;const u=[];null!=o&&(l=lP({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ch(i.length,l.shape.length)),oh("argMin",[i[0]],l.shape.length);const c=AP(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},DP=Uz({opSnippet:iz+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),OP={kernelName:ut,backendName:"webgl",kernelFunc:DP},MP=Uz({opSnippet:iz+"return log(x + sqrt(x * x + 1.0));"}),LP={kernelName:ct,backendName:"webgl",kernelFunc:MP},zP=Uz({opSnippet:iz+"\n return atan(x);\n"}),PP={kernelName:ht,backendName:"webgl",kernelFunc:zP},BP=Gz({opSnippet:$z+"\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Rz+"\n return result;\n"}),WP={kernelName:pt,backendName:"webgl",kernelFunc:BP},VP=Uz({opSnippet:iz+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),UP={kernelName:dt,backendName:"webgl",kernelFunc:VP};class GP{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=e.padInfo.top,p=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${d}, ${p});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h};\n wC += ${u}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${s?r?m:g:`wR * ${h} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const x=4*Math.floor(a/4),w=a%4,v=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${d}, ${p});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${x}; wC += 4) {\n int xC = xCCorner + wC * ${u};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n getValue(batch, xR, xC + 3 * ${u}, d)\n );\n\n ${v}\n }\n\n int xC = xCCorner + ${x};\n if (${1===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${2===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${3===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n initializationValue\n );\n\n ${v}\n }\n }\n setOutput(${b});\n }\n `}}class HP{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,d=e.effectiveFilterDepth,p=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${d};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${p};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f};\n wC += ${h}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${s?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 * ${p} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / max(count, 1.0)");const v=4*Math.floor(a/4),k=a%4,I=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n const float initializationValue = ${x};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${x});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${d};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${p};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${v}; wC += 4) {\n int xC = xCCorner + wC * ${h};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n getValue(batch, xD, xR, xC + 3 * ${h}, ch)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${v};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${2===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n initializationValue\n );\n\n ${I}\n }\n }\n }\n setOutput(${w});\n }\n `}}const jP={kernelName:ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;eM(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;ie(ic(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yu(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&de(u.inShape,u.outShape))return _z({inputs:{x:r},backend:n});const c=new GP(u,"avg",!1);return n.runWebGLProgram(c,[r],"float32")}};const qP={kernelName:gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s,c=Zu(r.shape,a,i,[1,1,1],o,l,u),h=new HP(c,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}};class KP{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,c=l-1-e.padInfo.left,h=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${u}, ${c});\n const float avgMultiplier = float(${h});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${o};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${l};\n wC+= ${i}) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class XP{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=d-1-e.padInfo.left,g=1/(t*n*s);this.userCode=`\n const ivec3 pads = ivec3(${p}, ${f}, ${m});\n const float avgMultiplier = float(${g});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${c};\n wD += ${o}) {\n float dyD = float(dyDCorner + wD) / ${r}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${h};\n wR += ${l}) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${d};\n wC += ${u}) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const YP={kernelName:yt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Zu(i.shape,o,l,[1,1,1],u,c),d=new XP(h);return n.runWebGLProgram(d,[r],i.dtype)}};const ZP={kernelName:mt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;eM([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Yu(i.shape,o,l,1,u),h=new KP(c);return n.runWebGLProgram(h,[r],i.dtype)}};const JP={kernelName:bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;return hP({a:r,b:a,transposeA:i,transposeB:o,backend:n})}};class QP{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ll(e,t),ll(e,n);let i="0.0";null!=s&&(ll(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=r&&(ll(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${i};\n float scale = ${o};\n float inv = scale * inversesqrt(variance + float(${a}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class eB{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ll(e,t),ll(e,n);let i="vec4(0.0)";null!=s&&(ll(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=r&&(ll(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${i};\n vec4 scale = ${o};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${a}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const tB={kernelName:dn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:r,variance:a,offset:i,scale:o}=e;ie(r.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),ie(null==i||r.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),ie(null==o||r.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:l}=n;null==l&&(l=.001);const u=[s,r,a];let c=null;null!=i&&(c=i.shape,u.push(i));let h=null;null!=o&&(h=o.shape,u.push(o));const d=Xe().getBool("WEBGL_PACK_NORMALIZATION")?new eB(s.shape,r.shape,a.shape,c,h,l):new QP(s.shape,r.shape,a.shape,c,h,l);return t.runWebGLProgram(d,u,u[0].dtype)}};class nB{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=xM(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return sB.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let s;s=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${sB[t]} = start[${t}] + coords.${sB[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${s}\n setOutput(getSource(${n}));\n }\n `}}const sB=["x","y","z","w","u","v"];class rB{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"}];const t=xM(this.rank),n=JL("coords",this.rank),s=JL("sourceLoc",this.rank),r=1===this.rank?"sourceLoc":`vec2(${s.slice(-2).join()})`,a=`getChannel(getSource(${s.join()}), ${r})`,i=`\n result.x = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[this.rank-1]};\n result.y = ${a};\n --${s[this.rank-1]};\n }\n `,o=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${s[this.rank-2]};\n result.z = ${a};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[this.rank-1]};\n result.w = ${a};\n }\n }\n `,l=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${s[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${l}\n vec4 result = vec4(0.);\n ${i}\n ${o}\n setOutput(result);\n }\n `}}function aB(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s,[o,l]=bu(r,a,i);if(ru(r,o,l),0===ue(l))return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||"string"===r.dtype){const e=n.texData.get(r.dataId),t=ML(e.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,t)}const{isPacked:u}=n.texData.get(r.dataId),c=gu(r.shape,o,l);if(u||!c){const e=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rB(l):new nB(l),t=[o];return n.runWebGLProgram(e,[r],r.dtype,t)}return n.uploadToGPU(r.dataId),function(e,t,n,s){const r=s.texData.get(e.dataId),a=s.makeTensorInfo(n,e.dtype),i=s.texData.get(a.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=yu(t,Oe(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};const l=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,l+1),a}(r,o,l,n)}const iB={kernelName:_s,backendName:"webgl",kernelFunc:aB},oB={kernelName:xt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;ie(r.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=lm(r.shape,a,o),u=um(l.length,a.length),c=cm(r.shape,a,o),h=hm(i,a.length),d=dm(c,i,a.length),p=[],f=Jz({inputs:{x:r},backend:n,attrs:{shape:l}}),m=lP({inputs:{x:f},backend:n,attrs:{perm:u}}),g=Jz({inputs:{x:m},backend:n,attrs:{shape:c}}),y=aB({inputs:{x:g},backend:n,attrs:{begin:h,size:d}});return p.push(f),p.push(m),p.push(g),p.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}};const lB={kernelName:wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=n.readSync(r.dataId),l=n.readSync(a.dataId),u=sL(o,l,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,u)}};const uB={kernelName:vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:s,b:r}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=Xe().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([s,r])||1===i){const e=n.texData.get(s.dataId).values,t=n.texData.get(r.dataId).values,[a,i]=aL(s.shape,r.shape,e,t,s.dtype),o=n.makeTensorInfo(i,s.dtype);return n.texData.get(o.dataId).values=a,o}let o;return o=a?new Az("\n int r = int(a.r) & int(b.r);\n int g = int(a.g) & int(b.g);\n int rb = int(a.b) & int(b.b);\n int ra = int(a.a) & int(b.a);\n return vec4(r, g, rb, ra);\n",s.shape,r.shape,!1):new Ez("\n return float(int(a.r) & int(b.r));\n",s.shape,r.shape),n.runWebGLProgram(o,[s,r],s.dtype)}};const cB={kernelName:It,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.readSync(s.dataId),i=n.readSync(r.dataId),o=ll(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},hB=Gz({opSnippet:"return float(a != b);",cpuKernelImpl:TL,dtype:"bool"}),dB={kernelName:Qn,backendName:"webgl",kernelFunc:hB};function pB(e){const{inputs:t,backend:n}=e,{input:s}=t;return _z({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.real},backend:n})}const fB={kernelName:ms,backendName:"webgl",kernelFunc:pB},mB="return float(int(x));";const gB={kernelName:Nt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s,attrs:r}=t,{x:a}=n,{dtype:i}=r;if("complex64"===i){if("complex64"===a.dtype)return _z({inputs:{x:a},backend:s});const t=Zh(a.shape),n=e({inputs:{x:a},backend:s,attrs:{dtype:"float32"}}),r=Dz({inputs:{real:n,imag:t},backend:s});return t.dispose(),s.disposeIntermediateTensorInfo(n),r}if("complex64"===a.dtype){const t=pB({inputs:{input:a},backend:s}),n=e({inputs:{x:t},backend:s,attrs:{dtype:i}});return s.disposeIntermediateTensorInfo(t),n}if(!Te(a.dtype,i)){const e=_z({inputs:{x:a},backend:s});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(s.shouldExecuteOnCPU([a])){const e=s.texData.get(a.dataId).values,[t,n,r]=iL(e,a.shape,a.dtype,i);return s.makeTensorInfo(t,n,r)}if("int32"===i)return function(e,t){const n=new az(e.shape,mB),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}(a,s);if("bool"===i){const e=s.makeTensorInfo([],"bool",ke("bool",1)),t=hB({inputs:{a,b:e},backend:s});return s.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},yB="return ceil(x);",bB=Uz({opSnippet:yB,packedOpSnippet:yB,cpuKernelImpl:oL}),xB={kernelName:St,backendName:"webgl",kernelFunc:bB};class wB{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class vB{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="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const kB={kernelName:Tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:i}=s;let o;o=Xe().getBool("WEBGL_PACK_CLIP")?new vB(r.shape):new wB(r.shape);const l=[[a],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}};class IB{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function NB(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const SB={kernelName:$t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new IB(s.shape),i=[NB(s,r.complexTensorInfos.real),NB(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class TB{constructor(e){this.outputShape=[],this.outputShape=Qf(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const s=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${s}));`)}const s=t.length,r=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${r}));`),this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${n.join("\n ")}\n }\n `}}class CB{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Qf(e,t);const n=this.outputShape,s=n.length,r=xM(s),a=JL("coords",s),i=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map(((e,t)=>`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n<o.length;n++)o[n]=o[n-1]+e[n][t];const l=i[t],u=i.slice(-2),c=i.join();let h=`if (${l} < ${o[0]}) {\n return getChannel(\n getT0(${c}), vec2(${u.join()}));\n }`;for(let e=1;e<o.length;e++){const t=o[e-1];h+=`\n if (${l} < ${o[e]} && ${l} >= ${o[e-1]}) {\n return getChannel(\n getT${e}(${$B(i,l,t)}),\n vec2(${$B(u,l,t)}));\n }`}const d=o.length,p=o[o.length-1];h+=`\n return getChannel(\n getT${d}(${$B(i,l,p)}),\n vec2(${$B(u,l,p)}));`,this.userCode=`\n float getValue(${i.map((e=>"int "+e))}) {\n ${h}\n }\n\n void main() {\n ${r} coords = getOutputCoords();\n vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n ${a[s-1]} = ${a[s-1]} + 1;\n if (${a[s-1]} < ${n[s-1]}) {\n result.g = getValue(${a});\n }\n\n ${a[s-2]} = ${a[s-2]} + 1;\n if (${a[s-2]} < ${n[s-2]}) {\n result.a = getValue(${a});\n }\n\n ${a[s-1]} = ${a[s-1]} - 1;\n if (${a[s-2]} < ${n[s-2]} &&\n ${a[s-1]} < ${n[s-1]}) {\n result.b = getValue(${a});\n }\n setOutput(result);\n }\n `}}function $B(e,t,n){const s=e.indexOf(t);return e.map(((e,t)=>t===s?`${e} - ${n}`:e)).join()}function EB(e){const{inputs:t,backend:n}=e,{input:s}=t;return _z({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.imag},backend:n})}const RB={kernelName:xn,backendName:"webgl",kernelFunc:EB};function AB(e,t,n){const s=e[0].dtype;if("complex64"===s){const s=e.map((e=>pB({inputs:{input:e},backend:n}))),r=e.map((e=>EB({inputs:{input:e},backend:n}))),a=AB(s,t,n),i=AB(r,t,n),o=Dz({inputs:{real:a,imag:i},backend:n});return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),r.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let r=n.shouldExecuteOnCPU(e);if("string"===s&&(r=!0),r){const r=e.map((e=>{const s=ue(e.shape.slice(t));return Jz({inputs:{x:e},backend:n,attrs:{shape:[-1,s]}})})),a=r.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=Qf(r.map((e=>e.shape)),1),o=1===r[0].shape[0],l=lL(a,i,s,o),u=Qf(e.map((e=>e.shape)),t),c=n.makeTensorInfo(u,s,l);return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const a=e.filter((e=>ue(e.shape)>0)),i=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(1===a.length){const t=i?new az(e[0].shape,dz):new xz(e[0].shape,dz);return n.runWebGLProgram(t,e,s)}const o=Xe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(a.length>o){const e=[];for(let s=0;s<a.length;s+=o){const r=a.slice(s,s+o);e.push(AB(r,t,n))}const s=AB(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return s}if(i){const e=new CB(a.map((e=>e.shape)),t);return n.runWebGLProgram(e,a,s)}const{tensors2D:l,outShape:u}=function(e,t,n){const s=Qf(e.map((e=>e.shape)),t),r=e.map((e=>Jz({inputs:{x:e},attrs:{shape:[-1,ue(e.shape.slice(t))]},backend:n})));return{tensors2D:r,outShape:s}}(a,t,n),c=new TB(l.map((e=>e.shape))),h=n.runWebGLProgram(c,l,s);l.forEach((e=>n.disposeIntermediateTensorInfo(e)));const d=Jz({inputs:{x:h},attrs:{shape:u},backend:n});return n.disposeIntermediateTensorInfo(h),d}function _B(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=we(r,t[0].shape)[0];Jf(t.map((e=>e.shape)),a);const i=Qf(t.map((e=>e.shape)),a);if(0===ue(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>ue(e.shape)>0));return 1===o.length?_z({inputs:{x:o[0]},backend:n}):AB(o,a,n)}const FB={kernelName:Et,backendName:"webgl",kernelFunc:_B};class DB{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,p=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,w="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${x}\n\n const ivec2 strides = ivec2(${o}, ${l});\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${u};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${d}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${p}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${p}) *\n getW(wR, wC, ${p}, d2);\n } else {\n dotProd +=\n getX(batch, ${p}, xR, xC) *\n getW(wR, wC, ${p}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${p}, d2),\n getW(wR, wC, ${p} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${p}),\n getX(batch, xR, xC, ${p} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${p}, xR, xC),\n getX(batch, ${p} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${p}, d2),\n getW(wR, wC, ${p} + 1, d2),\n getW(wR, wC, ${p} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${p}),\n getX(batch, xR, xC, ${p} + 1),\n getX(batch, xR, xC, ${p} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${p}, xR, xC),\n getX(batch, ${p} + 1, xR, xC),\n getX(batch, ${p} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${v}\n ${w}\n setOutput(result);\n }\n `}}class OB{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,d=e.filterWidth,p=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${r}, ${a}, ${i});\n const ivec3 pads = ivec3(${t}, ${n}, ${s});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${c}; wF++) {\n int xF = xFCorner + wF * ${o};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${d}; wC++) {\n int xC = xCCorner + wC * ${u};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${p}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===f}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${p}) *\n getW(wF, wR, wC, ${p}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${p}),\n getX(batch, xF, xR, xC, ${p} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${p}, d2),\n getW(wF, wR, wC, ${p} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${p}),\n getX(batch, xF, xR, xC, ${p} + 1),\n getX(batch, xF, xR, xC, ${p} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${p}, d2),\n getW(wF, wR, wC, ${p} + 1, d2),\n getW(wF, wR, wC, ${p} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class MB{constructor(e,t=!1,n=null,s=!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=SM(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,c=u;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<u;e++)h+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;h+=`\n for (int r = 0; r < ${l}; r++) {\n for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n `;for(let e=0;e<u;e++)h+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;h+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let t=0;t<(c+1)/2;t++){const n=2*t;if(h+=`\n xC = xCCorner + ${n*o};\n `,1===i){if(n<u&&(a%2==1?(h+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n `,h+=1===o&&n>0?`\n xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${n} = vec4(previous.zw, xTexelC${n}.xy);\n } else {\n xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xC${n} = xTexelC${n};\n `,n+1<u)){const e=a%2==0?te(o):o;o%2==0&&a%2==1||o%2!=0&&a%2!=1?(h+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n `,h+=o>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n } else {\n xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n }\n `:`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n `):h+=1===e?`\n xC${n+1} = xTexelC${n};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n+1} = xTexelC${n+1};\n `}}else n<u&&(a%2==1?(h+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `,n+1<u&&(h+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(\n xTexelC${n}.xy, xTexelC${n+1}.xy);\n `,n+1<u&&(h+=`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `)));n<u&&(h+=`\n wTexel = getW(r, ${n}, d1, d2);\n dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `,n+1<u&&(h+=`\n wTexel = getW(r, ${n+1}, d1, d2);\n dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `))}h+="\n }\n ",h+="\n }\n ",h+="\n }\n ";let d="",p="";n&&(d=s?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,p="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${d}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${h}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${f}\n ${p}\n setOutput(result);\n }\n `}}class LB{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=SM(this.outputShape.length);const{dataFormat:n}=t,s=nM(),r="channelsLast"===n,a=r?1:2,i=r?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let l="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)l+=`\n blockIndex = rc.z + ${t};\n pos = rc.y + ${e};\n\n ${o}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${a}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${i}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${r}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${l}\n\n ${s.output} = result;\n }\n `}}function zB(e,t){const 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&&1===n&&e[0]>1?[e[0],1]:null}function PB({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,u=s.texData.get(e.dataId),c=n.inChannels,h=l[0]*l[1]*l[2],d=n.outChannels,p="channelsLast"===n.dataFormat,f=!1;let m;const g=[];if(null!=a){const e=zB(a.shape,p);null!=e&&(a=Jz({inputs:{x:a},backend:s,attrs:{shape:e}}),g.push(a))}if(null!=r){const e=zB(r.shape,p);null!=e&&(r=Jz({inputs:{x:r},backend:s,attrs:{shape:e}}),g.push(r))}if(!((1===h||1===d)&&c>cP)&&u.isPacked&&p&&null!=u.texture&&l[2]%2!=0&&de(u.shape.slice(-3),l.slice(-3))){const c=l[0]*l[1]*(l[2]+1),h={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},d=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,ie(BO(u.shape,h.shape),(()=>`packed reshape ${u.shape} to ${h.shape} isn't free`));const p=Jz({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(p);const y=hP({a:h,b:p,backend:s,transposeA:false,transposeB:f,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),b=s.texData.get(y.dataId);ie(b.isPacked,(()=>"batchMatMul result is expected to be packed")),u.shape=d,b.shape=n.outShape,m=_z({inputs:{x:y},backend:s}),m.shape=n.outShape,g.push(y)}else{const l=n.outHeight*n.outWidth,u=Jz({inputs:{x:e},backend:s,attrs:{shape:p?[n.batchSize,l,n.inChannels]:[n.batchSize,n.inChannels,l]}}),c=Jz({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=hP({a:p?u:c,b:p?c:u,transposeA:!p,transposeB:f,backend:s,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i});m=Jz({inputs:{x:h},backend:s,attrs:{shape:n.outShape}}),g.push(u),g.push(c),g.push(h)}for(const e of g)s.disposeIntermediateTensorInfo(e);return m}function BB({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:d,dataFormat:p}=n,f="channelsLast"===p,m=l*u*c,g=d*h,y=[n.batchSize,m,g],b=[];if(null!=a){const e=zB(a.shape,f);null!=e&&(a=Jz({inputs:{x:a},backend:s,attrs:{shape:e}}),b.push(a))}if(null!=r){const e=zB(r.shape,f);null!=e&&(r=Jz({inputs:{x:r},backend:s,attrs:{shape:e}}),b.push(r))}const x=Jz({inputs:{x:t},backend:s,attrs:{shape:[1,m,ue(t.shape)/m]}});b.push(x);const w=new LB(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],k=s.runWebGLProgram(w,[e],"float32",v),I=Jz({inputs:{x:k},backend:s,attrs:{shape:y}});b.push(k),b.push(I);const N=null!=r,S=null!=a,T="leakyrelu"===o,C=o?Hz(o,!0):null,$=new jz(f?I.shape:x.shape,f?x.shape:I.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,N,C,S,T),E=f?[I,x]:[x,I];if(r&&E.push(r),S&&E.push(a),T){const e=s.makeTensorInfo([],"float32",qr(i,"float32"));E.push(e),b.push(e)}const R=s.runWebGLProgram($,E,"float32"),A=Jz({inputs:{x:R},backend:s,attrs:{shape:n.outShape}});b.push(R);for(const e of b)s.disposeIntermediateTensorInfo(e);return A}const WB={kernelName:Rt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=lc(l),d=Ju(r.shape,a.shape,i,u,o,c,!1,h);let p;if(1!==d.filterHeight||1!==d.filterWidth||1!==d.dilationHeight||1!==d.dilationWidth||1!==d.strideHeight||1!==d.strideWidth||"SAME"!==d.padInfo.type&&"VALID"!==d.padInfo.type)if(d.strideWidth<=2&&"channelsLast"===h&&Xe().getBool("WEBGL_EXP_CONV")){const e=new MB(d),t=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];p=n.runWebGLProgram(e,[r,a],"float32",t)}else if(Xe().getBool("WEBGL_CONV_IM2COL"))p=BB({x:r,filter:a,convInfo:d,backend:n});else{const e=new DB(d);p=n.runWebGLProgram(e,[r,a],"float32")}else p=PB({x:r,filter:a,convInfo:d,backend:n});const f=Jz({inputs:{x:p},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(p),f}};class VB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${s};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${r};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n ${a?"float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);":"float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);"}\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class UB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=a?1:2,u=a?2:3,c=a?3:1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${a}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class GB{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yF = 0; yF < ${e.outDepth}; yF++) {\n int xF = wF + yF * ${t} - ${r};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${n} - ${a};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${s} - ${i};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class HB{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=s-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${o}, ${l}, ${u});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${t}; wF++) {\n float dyF = float(dyFCorner + wF) / ${r}.0;\n\n if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${t} - 1 - wF;\n\n for (int wR = 0; wR < ${n}; wR++) {\n float dyR = float(dyRCorner + wR) / ${a}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${n} - 1 - wR;\n\n for (int wC = 0; wC < ${s}; wC++) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${s} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const jB={kernelName:At,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=lc(l),d=Ju(r.shape,c,i,1,o,u,!1,h),p=new VB(d);return n.runWebGLProgram(p,[r,a],"float32")}};class qB{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=SM(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,s=t-1-e.padInfo.top,r=n-1-e.padInfo.left;this.userCode=`\n const ivec2 pads = ivec2(${s}, ${r});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n vec4 result = vec4(0.);\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n int wCPerm = ${n} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\n && (fract(dyC) == 0.0);\n int idyC = int(dyC);\n\n float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n dySample : getDy(batch, idyR, idyC2, d2);\n\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n\n dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample2.xy : dySample2.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC2, d2);\n vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n }\n }\n }\n setOutput(result);\n }\n `}}const KB={kernelName:_t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=lc(u),d=Ju(i,a.shape,o,1,l,c,!1,h);if(Xe().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===h){const e=[[d.strideHeight,d.strideWidth]],t=new qB(d);return n.runWebGLProgram(t,[r,a],"float32",e)}{const e=new UB(d);return n.runWebGLProgram(e,[r,a],"float32")}}};const XB={kernelName:Ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=Qu(r.shape,a.shape,i,l,o),c=new OB(u);return n.runWebGLProgram(c,[r,a],"float32")}};const YB={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,filterShape:l}=s,u=Qu(r.shape,l,i,1,o),c=new GB(u);return n.runWebGLProgram(c,[r,a],"float32")}};const ZB={kernelName:Ot,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:i,strides:o,inputShape:l}=s,u=Qu(l,a.shape,o,1,i),c=new HB(u);return n.runWebGLProgram(c,[r,a],"float32")}},JB=Uz({opSnippet:Vz+"\n return cos(x);\n",packedOpSnippet:`\n vec4 result = cos(x);\n bvec4 isNaN = isnan(x);\n ${Rz}\n return result;\n`}),QB={kernelName:Mt,backendName:"webgl",kernelFunc:JB},eW=Uz({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),tW={kernelName:Lt,backendName:"webgl",kernelFunc:eW};class nW{constructor(e,t,n,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,o,l]=e,[u]=t,[c,h]=n;this.outputShape=[u,c,h,l];const d="bilinear"===s?1:0,[p,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${p} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${p}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${a}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${x};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${p} ) {\n setOutput(float(${r}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${r}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${d} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const sW={kernelName:Bt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,c=new nW(r.shape,a.shape,o,l,u);return n.runWebGLProgram(c,[r,a,i],"float32")}};var rW;!function(e){e.Prod="*",e.Sum="+"}(rW||(rW={}));class aW{constructor(e,t,n,s){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const r=this.outputShape.length,a=this.op===rW.Prod?"1.0":"0.0",i=n?a:`getX(${iW(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let l="",u="";n?(l=s?"end != "+(o-1):"end != 0",u=s?"end + 1":"end - 1"):(l=s?`end + pow2 < ${o}`:"end >= pow2",u=s?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${xM(r)} coords = getOutputCoords();\n int end = ${oW(r,"coords",this.op)};\n float val = ${i};\n int pow2 = int(pow(2.0, index));\n if (${l}) {\n int idx = ${u};\n ${oW(r,"coords",this.op)} = idx;\n val ${this.op}= getX(${iW(r,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function iW(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function oW(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function lW(e,t,n,s,r,a){const i=t.shape.length,o=lh([s],i);let l=t;null!=o&&(l=lP({inputs:{x:t},backend:n,attrs:{perm:o}}));const u=ch(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=${s}`);const c=l.shape[u];let h=_z({inputs:{x:l},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const s=new aW(e,l.shape,!1,a),r=[[t]],i=h;h=n.runWebGLProgram(s,[h],h.dtype,r),n.disposeIntermediateTensorInfo(i)}if(r){const t=new aW(e,l.shape,r,a),s=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(s)}if(null!=o){const e=lP({inputs:{x:h},backend:n,attrs:{perm:uh(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),e}return h}const uW={kernelName:zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return lW(rW.Prod,r,n,a,i,o)}};const cW={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return lW(rW.Sum,r,n,a,i,o)}};const hW={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i,binaryOutput:o}=s;if(1===r.shape.length){const e=n.readSync(r.dataId),t=n.readSync(a.dataId),s=sL(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,s)}if(2===r.shape.length){const e=n.bufferSync(r),t=n.bufferSync(a),s=rL(e,t,i,o);return n.makeTensorInfo(s.shape,a.dtype,s.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}};class dW{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${t};\n int offset_h = imod(h, ${t});\n int in_w = w / ${t};\n int offset_w = imod(w, ${t});\n int offset_d = (offset_h * ${t} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const pW={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s,o=r.shape[0],l=("NHWC"===i?r.shape[1]:r.shape[2])*a,u=("NHWC"===i?r.shape[2]:r.shape[3])*a,c=("NHWC"===i?r.shape[3]:r.shape[1])/(a*a),h=new dW("NHWC"===i?[o,l,u,c]:[o,c,l,u],a,i);return n.runWebGLProgram(h,[r],r.dtype)}};class fW{constructor(e,t=!1,n=null,s=!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=SM(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let l="",u="";n&&(l=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,u="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${l}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${o};\n int q = d2 - d1 * ${o};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${a}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${i}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${u}\n setOutput(result);\n }\n `}}class mW{constructor(e,t=!1,n=null,s=!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=SM(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,h=c;let d="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)d+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;d+=`\n for (int r = 0; r < ${u}; r++) {\n `;for(let e=0;e<c;e++)d+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;d+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let e=0;e<(h+1)/2;e++){const t=2*e;if(d+=`\n xC = xCCorner + ${t*l};\n `,1===o){if(t<c&&(i%2==1?(d+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,d+=1===l&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):d+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1<c)){const e=i%2==0?te(l):l;l%2==0&&i%2==1||l%2!=0&&i%2!=1?(d+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,d+=l>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):d+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t<c&&(i%2==1?(d+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1<c&&(d+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(d+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1<c&&(d+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `)));t<c&&(d+=`\n wTexel = getW(r, ${t}, d1, q);\n dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\n `,t+1<c&&(d+=`\n wTexel = getW(r, ${t+1}, d1, q);\n dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\n `))}d+="\n }\n ",d+="\n }\n ";let p="",f="";n&&(p=s?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:r?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${p}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${a};\n int q = d2 - d1 * ${a};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${d}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${m}\n ${f}\n setOutput(result);\n }\n `}}const gW={kernelName:Ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=s;let c=l;null==c&&(c=[1,1]),ie(ic(i,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`));const h=Ju(r.shape,a.shape,i,c,o,u,!0);let d;d=Xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new mW(h):new fW(h);const p=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return n.runWebGLProgram(d,[r,a],"float32",p)}};class yW{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${a} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${s};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${r};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class bW{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${a}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${r}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${o}; dm++) {\n int d2 = d1 * ${o} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const xW={kernelName:Gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s,h=Ju(r.shape,c,i,o,l,u,!0),d=new yW(h);return n.runWebGLProgram(d,[r,a],"float32")}};const wW={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s,h=Ju(c,a.shape,i,o,l,u,!0),d=new bW(h);return n.runWebGLProgram(d,[r,a],"float32")}};class vW{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const kW={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=ue(s.shape),i=Jz({inputs:{x:s},backend:n,attrs:{shape:[a]}}),o=new vW(a),l=n.runWebGLProgram(o,[i],i.dtype),u=Jz({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}};class IW{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:s,strideHeight:r,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:c,left:h}=s;this.userCode=`\n const ivec2 strides = ivec2(${r}, ${a});\n const ivec2 pads = ivec2(${c}, ${h});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${i}; h++) {\n int hIn = hBeg + h * ${l};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${o}; w++) {\n int wIn = wBeg + w * ${u};\n\n if (wIn >= 0 && wIn < ${n}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `}}const NW={kernelName:qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=Xu(r.shape,a.shape,i,o,"NHWC",l);let c;const h=new IW(u);c=n.runWebGLProgram(h,[r,a],"float32");const d=Jz({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),d}};const SW={kernelName:Jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Fm(r,a.length);Om(i.length,l,a);const{path:u,steps:c}=Mm(o,l),h=c.length;let d=null,p=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Dm(p,l[t]);let r;Lm(e)?r=a[t]:(r=lP({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);de(r.shape,i)||(r=Jz({inputs:{x:r},backend:n,attrs:{shape:i}}),f.push(r)),null===d?d=r:(d=Yz({inputs:{a:r,b:d},backend:n}),f.push(d))}e<h-1&&(u[e]>=0&&(d=iP({inputs:{x:d},backend:n,attrs:{axis:u[e]-(i.length-p),keepDims:!1}}),f.push(d)),p--)}for(const e of f)e!==d&&n.disposeIntermediateTensorInfo(e);return d}},TW=Uz({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n"}),CW={kernelName:Qt,backendName:"webgl",kernelFunc:TW},$W={kernelName:en,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=Xe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Az("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",s.shape,r.shape):new Ez("return (b >= 0.0) ? a : a * (b + 1.0);",s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)}},EW=Gz({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:uL}),RW={kernelName:nn,backendName:"webgl",kernelFunc:EW},AW=Uz({opSnippet:`\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = ${mm};\n float a1 = ${gm};\n float a2 = ${ym};\n float a3 = ${bm};\n float a4 = ${xm};\n float a5 = ${wm};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),_W={kernelName:tn,backendName:"webgl",kernelFunc:AW},FW=Uz({opSnippet:Vz+"\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:cL,dtype:"float32"}),DW={kernelName:sn,backendName:"webgl",kernelFunc:FW};function OW(e){const{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let l=r;return r<0&&(ie(-(i+1)<=r,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+r+1),o.splice(l,0,1),Jz({inputs:{x:a},backend:s,attrs:{shape:o}})}const MW={kernelName:rn,backendName:"webgl",kernelFunc:OW},LW="return exp(x) - 1.0;",zW=Uz({opSnippet:LW,packedOpSnippet:LW,cpuKernelImpl:hL}),PW={kernelName:an,backendName:"webgl",kernelFunc:zW};class BW{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${s}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${r};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${i}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${s});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${s}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${a};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function WW(e,t,n){const s=n.texData.get(e.dataId),r=ue(e.shape),a=e.shape[e.shape.length-1],i=Jz({inputs:{x:e},backend:n,attrs:{shape:[r/a,a]}}),o=i.shape,l=new BW("real",o,t),u=new BW("imag",o,t),c=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:o},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(l,c,"float32"),d=n.runWebGLProgram(u,c,"float32"),p=Dz({inputs:{real:h,imag:d},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d);const f=Jz({inputs:{x:p},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(p),f}const VW={kernelName:on,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return WW(s,!1,n)}};class UW{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}function GW(e){const{backend:t,attrs:n}=e,{shape:s,value:r}=n;let{dtype:a}=n;if(a=a||_e(r),"string"===a){const e=Ie(a,ue(s));return e.fill(r),t.makeTensorInfo(s,a,e)}{const e=new UW(s,r),n=[[r]];return t.runWebGLProgram(e,[],a,n)}}const HW={kernelName:ln,backendName:"webgl",kernelFunc:GW};class jW{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${t} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${t}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const qW={kernelName:un,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,r=new jW(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},KW="return floor(x);",XW=Uz({opSnippet:KW,packedOpSnippet:KW,cpuKernelImpl:dL}),YW={kernelName:cn,backendName:"webgl",kernelFunc:XW},ZW=Gz({opSnippet:"\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",packedOpSnippet:"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n",dtype:"int32"}),JW={kernelName:hn,backendName:"webgl",kernelFunc:ZW};class QW{constructor(e){this.variableNames=["A"];const t=nM(),[n,s]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class eV{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=nM(),[n,s]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${s}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const tV={kernelName:fr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:r}=t;const{numChannels:a}=s,i="undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],h=[u,l,a];if(o||i){const e=Xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=nV&&e===sV||(sV=e,nV=document.createElement("canvas").getContext("2d",{willReadFrequently:sV})),nV.canvas.width=l,nV.canvas.height=u,nV.drawImage(r,0,0,l,u),r=nV.canvas}const d=n.makeTensorInfo(c,"int32");n.texData.get(d.dataId).usage=ZD.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),r);const p=Xe().getBool("WEBGL_PACK")?new eV(h):new QW(h),f=n.runWebGLProgram(p,[d],"int32");return n.disposeData(d.dataId),f}};let nV,sV=Xe().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const rV={kernelName:yr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s,m=lc(c),g=Ju(r.shape,a.shape,l,h,u,d,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===p,k=()=>{const e=[r,a],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=Jz({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",qr(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Xe().getBool("WEBGL_EXP_CONV")){const e=p?Hz(p,!0):null,t=new MB(g,x,e,w,v),s=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],r=k();y=n.runWebGLProgram(t,r,"float32",s)}else if(Xe().getBool("WEBGL_CONV_IM2COL"))y=BB({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:p,preluActivationWeights:o,leakyreluAlpha:f});else{const e=p?Hz(p,!1):null,t=new DB(g,x,e,w,v),s=k();y=n.runWebGLProgram(t,s,"float32")}else y=PB({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:p,preluActivationWeights:o,leakyreluAlpha:f});const I=Jz({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}};const aV={kernelName:br,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=s,f=[];let m=c;null==m&&(m=[1,1]),ie(ic(l,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`));const g=Ju(r.shape,a.shape,l,m,u,h,!0),y=Xe().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=d?Hz(d,y):null,x=[r,a],w=null!=i,v=null!=o,k="leakyrelu"===d;if(w&&x.push(i),v&&x.push(o),k){const e=n.makeTensorInfo([],"float32",qr(p,"float32"));x.push(e),f.push(e)}let I;I=y?new mW(g,w,b,v,k):new fW(g,w,b,v,k);const N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],S=n.runWebGLProgram(I,x,"float32",N);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),S}};class iV{constructor(e,t,n,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=n;const r=xM(n.length);let a="\n int index;";for(let e=0;e<this.sliceDim;e++)a+=`\n index = round(getIndices(coords[0], ${e}));\n out_of_bounds = out_of_bounds || index < 0;\n out_of_bounds = out_of_bounds || index >= ${this.paramsShape[e]};\n flattenIndex += index * ${this.strides[e]};`;this.userCode=`\n void main() {\n ${r} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${a}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `}}const oV={kernelName:fn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,i=a[a.length-1],o=ue(s.shape),[l,u,c,h]=Jl(s,r),d=Jz({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),p=Jz({inputs:{x:s},backend:n,attrs:{shape:[ue(s.shape)/c,c]}});if(n.shouldExecuteOnCPU([s,r])||"string"===s.dtype){const e=n.readSync(r.dataId),t=n.bufferSync(s),a=pL(e,t,s.dtype,u,i,c,h,s.shape,o);return n.makeTensorInfo(l,s.dtype,a.values)}const f=new iV(i,h,[u,c],s.shape),m=n.runWebGLProgram(f,[p,d],p.dtype),g=Jz({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),g}};class lV{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=xM(this.rank),s=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let t=0;t<e.length;t++)2===t?s.push("index"):s.push(`${n[t]}`);return s.join()}(e);this.userCode=`\n void main() {\n ${n} resRC = getOutputCoords();\n int index = int(getIndices(resRC.x, resRC.z));\n float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${s}));\n }\n `}}function uV(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s,l=we(i,r.shape)[0];if(Xe().get("DEBUG")){const e=n.readSync(a.dataId),t=r.shape[l];for(let n=0;n<e.length;++n){const s=e[n];ie(s<=t-1&&s>=0,(()=>`GatherV2: the index value ${s} is not in [0, ${t-1}]`))}}const u=eg(r,a,l,o),c=ue(a.shape),h=[],d=Jz({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),p=Jz({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,c/u.batchSize]}});h.push(d),h.push(p);const f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,a])||"string"===r.dtype){const e=n.bufferSync(p),t=n.bufferSync(d),s=fL(t,e,f);return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(u.outputShape,s.dtype,s.values)}const m=new lV(d.shape,f),g=n.runWebGLProgram(m,[d,p],d.dtype);h.push(g);const y=Jz({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}const cV={kernelName:pn,backendName:"webgl",kernelFunc:uV},hV=Gz({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:mL,dtype:"bool"}),dV={kernelName:mn,backendName:"webgl",kernelFunc:hV},pV=Gz({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:gL}),fV={kernelName:gn,backendName:"webgl",kernelFunc:pV};const mV={kernelName:bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return WW(s,!0,n)}},gV=Uz({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),yV={kernelName:wn,backendName:"webgl",kernelFunc:gV},bV=Uz({opSnippet:"return float(isinf(x));",dtype:"bool"}),xV={kernelName:vn,backendName:"webgl",kernelFunc:bV},wV=Uz({opSnippet:"return float(isnan(x));",dtype:"bool"}),vV={kernelName:kn,backendName:"webgl",kernelFunc:wV},kV=Gz({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:yL,dtype:"bool"}),IV={kernelName:Nn,backendName:"webgl",kernelFunc:kV},NV=Gz({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:bL,dtype:"bool"}),SV={kernelName:Sn,backendName:"webgl",kernelFunc:NV};const TV={kernelName:Tn,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=xL(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},CV=Uz({opSnippet:Vz+"\n return x < 0.0 ? 0./0. : log(x);\n",packedOpSnippet:"\n vec4 result = log(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\n return result;\n",cpuKernelImpl:wL}),$V={kernelName:Cn,backendName:"webgl",kernelFunc:CV},EV=Uz({opSnippet:Vz+"\n return log(1.0 + x);\n"}),RV={kernelName:$n,backendName:"webgl",kernelFunc:EV},AV=Gz({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),_V={kernelName:En,backendName:"webgl",kernelFunc:AV},FV=Uz({opSnippet:"return float(!(x >= 1.0));"}),DV={kernelName:Rn,backendName:"webgl",kernelFunc:FV},OV=Gz({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n",dtype:"bool"}),MV={kernelName:An,backendName:"webgl",kernelFunc:OV};class LV{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${a}; j <= ${a}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${i}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${o};\n setOutput(val);\n }\n `}}class zV{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${a};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${a}; j <= ${a}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${o};\n setOutput(result);\n }\n `}}const PV={kernelName:On,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s,u=Xe().getBool("WEBGL_PACK_NORMALIZATION")?new zV(r.shape,a,i,o,l):new LV(r.shape,a,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)}};class BV{constructor(e,t,n,s,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=r,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${t})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${t} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${s}) * norm + float(${n});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${s})\n * float(${r})\n * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${r});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `}}const WV={kernelName:Mn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s,h=new BV(r.shape,o,l,u,c);return n.runWebGLProgram(h,[r,a,i],r.dtype)}};function VV(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=r.shape.length,l=we(a,r.shape);let u=l;const c=lh(u,o),h=null!=c,d=n.shouldExecuteOnCPU([r]);let p=r;if(h){if(d){const e=n.texData.get(p.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const s=XL(e,r.shape,r.dtype,c,t);p=n.makeTensorInfo(t,r.dtype);n.texData.get(p.dataId).values=s}else p=aP(r,c,n);u=ch(u.length,o)}oh("max",u,o);const[f,m]=ah(p.shape,u);let g,y=f;if(i&&(y=ih(f,l)),d){const e=n.texData.get(p.dataId).values,t=vL(e,ue(m),y,r.dtype);g=n.makeTensorInfo(y,r.dtype);n.texData.get(g.dataId).values=t}else g=function(e,t,n,s){const r=ue(t),a=Jz({inputs:{x:e},attrs:{shape:[ue(e.shape)/r,r]},backend:s}),i=nP(a,e.dtype,"max",s),o=Jz({inputs:{x:i},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}(p,m,y,n);return h&&n.disposeIntermediateTensorInfo(p),g}const UV={kernelName:zn,backendName:"webgl",kernelFunc:VV},GV=Gz({opSnippet:$z+"\n return max(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(max(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Rz+"\n return result;\n",cpuKernelImpl:kL}),HV={kernelName:Pn,backendName:"webgl",kernelFunc:GV};const jV={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;eM(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;ie(ic(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Yu(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&de(u.inShape,u.outShape))return _z({inputs:{x:r},backend:n});const c=new GP(u,"max",!1);return n.runWebGLProgram(c,[r],r.dtype)}};const qV={kernelName:Vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=s,c=Zu(r.shape,a,i,[1,1,1],o,u,l),h=new HP(c,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}};class KV{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,r=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=a-1-e.padInfo.left,l=r*a-1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${r};\n wR += ${s}) {\n float dyR = float(dyRCorner + wR) / ${t}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${a}; wC++) {\n float dyC = float(dyCCorner + wC) / ${n}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${a} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class XV{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=l-1-e.padInfo.top,d=u-1-e.padInfo.left,p=o*l*u-1;this.userCode=`\n const ivec3 pads = ivec3(${c}, ${h}, ${d});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${o};\n wD += ${r}) {\n float dyD = float(dyDCorner + wD) / ${t}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${l};\n wR += ${a}) {\n float dyR = float(dyRCorner + wR) / ${n}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC += ${i}) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${p} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${l} * ${u} +\n wR * ${u} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const YV={kernelName:Un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Zu(i.shape,o,l,[1,1,1],u,c),d=new HP(h,"max",!0),p=n.runWebGLProgram(d,[i],i.dtype),f=new XV(h),m=n.runWebGLProgram(f,[r,p],i.dtype);return n.disposeIntermediateTensorInfo(p),m}};const ZV={kernelName:Wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;eM([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=Yu(o.shape,l,u,1,c,h),p=new GP(d,"max",!0),f=n.runWebGLProgram(p,[o],o.dtype),m=new KV(d),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}};const JV={kernelName:Gn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;ie(4===s.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`));const u=[1,1];ie(ic(a,u),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`));const c=Yu(s.shape,r,a,u,i),[h,d]=function(e,t,n,s){let r=new GP(n,"max",!1);const a=s.runWebGLProgram(r,[e],"float32");return r=new GP(n,"max",!0,!0,t),[a,s.runWebGLProgram(r,[e],"float32")]}(s,o,c,l);return[h,d]}};const QV={kernelName:Hn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:r,axis:a}=t,i=n,o=s.shape.length,l=we(a,s.shape);let u=l;const c=lh(u,o),h=null!=c,d=i.shouldExecuteOnCPU([s]),p=[];let f=s;if(h){if(d){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=s.shape[c[e]];const n=XL(e,s.shape,s.dtype,c,t);f=i.makeTensorInfo(t,s.dtype);i.texData.get(f.dataId).values=n}else f=aP(s,c,i);p.push(f),u=ch(u.length,o)}oh("sum",u,o);const[m,g]=ah(f.shape,u);let y=m;r&&(y=ih(m,l));const b=function(e,t,n,s){const r=ue(t),a=Jz({inputs:{x:e},attrs:{shape:[ue(e.shape)/r,r]},backend:s}),i=nP(a,"float32","mean",s),o=Jz({inputs:{x:i},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}(f,g,y,i);for(const e of p)i.disposeIntermediateTensorInfo(e);return b}};const eU={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=we(a,r.shape);let u=l;const c=lh(u,o);let h=r;null!=c&&(h=lP({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ch(u.length,r.shape.length)),oh("min",u,o);const[d,p]=ah(h.shape,u),f=Jz({inputs:{x:h},backend:n,attrs:{shape:[-1,ue(p)]}}),m=nP(f,f.dtype,"min",n);let g;if(i){g=Jz({inputs:{x:m},backend:n,attrs:{shape:ih(d,l)}})}else g=Jz({inputs:{x:m},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},tU=Gz({opSnippet:$z+"\n return min(a, b);\n",packedOpSnippet:"\n vec4 result = vec4(min(a, b));\n bvec4 isNaNA = isnan(a);\n bvec4 isNaNB = isnan(b);\n bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n "+Rz+"\n return result;\n",cpuKernelImpl:IL}),nU={kernelName:qn,backendName:"webgl",kernelFunc:tU};class sU{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=xM(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),l="reflect"===n?0:1;this.userCode=1!==s?`\n ${r} start = ${r}(${a});\n ${r} end = ${r}(${i});\n\n void main() {\n ${r} outC = getOutputCoords();\n for (int i = 0; i < ${s}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${l};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};\n }\n }\n ${r} coords = outC - start;\n setOutput(getX(${o}));\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${l};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${l};\n }\n setOutput(getX(outC - start));\n }\n `}}class rU{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=xM(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=JL("rc",s),l=JL("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h="reflect"===n?0:1;let d="";if(1===s){const e=`\n ${r} source = rc;\n if (source < start) {\n source = start * 2 - source - ${h};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${h};\n }\n source -= start;\n `;d=`\n ${r} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n `}else{const e=`\n ${r} source = rc;\n ${r} lt = ${r}(lessThan(source, start));\n ${r} gte = ${r}(greaterThanEqual(source, end));\n ${r} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${h}) +\n gte * ((end - 1) * 2 - source + ${h});\n source -= start;\n `;d=`\n ${r} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {\n ${e}\n result[2] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[3] = getChannel(getX(${l.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${r} start = ${r}(${a});\n const ${r} end = ${r}(${i});\n\n void main() {\n ${r} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${d}\n setOutput(result);\n }\n `}}const aU={kernelName:Kn,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:r,mode:a}=n,i=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rU(s.shape,r,a):new sU(s.shape,r,a);return t.runWebGLProgram(i,[s],s.dtype)}},iU=Gz({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n bvec4 isNaN = equal(b, vec4(0.0));\n "+Rz+"\n return result;\n"}),oU={kernelName:Xn,backendName:"webgl",kernelFunc:iU};class lU{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${t-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${t-1}));\n }\n `}}const uU=Gz({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),cU={kernelName:Zt,backendName:"webgl",kernelFunc:uU},hU="return a - b;",dU=Gz({opSnippet:hU,packedOpSnippet:hU,supportsComplex:!0,cpuKernelImpl:jL}),pU={kernelName:tr,backendName:"webgl",kernelFunc:dU};function fU(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=we([a],r.shape),o=VV({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=ih(o.shape,i),u=Jz({inputs:{x:o},backend:n,attrs:{shape:l}}),c=dU({inputs:{a:r,b:u},backend:n}),h=FW({inputs:{x:c},backend:n}),d=iP({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),p=Jz({inputs:{x:d},backend:n,attrs:{shape:l}}),f=uU({inputs:{a:h,b:p},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),f}const mU={kernelName:Vs,backendName:"webgl",kernelFunc:fU};const gU={kernelName:Yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s,l=o?r:fU({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new lU(u,c,a),d=[[i]],p=n.runWebGLProgram(h,[l],"int32",d);return o||n.disposeIntermediateTensorInfo(l),p}},yU=iz+"\n return -x;\n";const bU={kernelName:Jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){const e=n.texData.get(s.dataId),[t,r]=SL(e.values,s.shape,s.dtype);return n.makeTensorInfo(r,s.dtype,t)}let r;return r=Xe().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new xz(s.shape,"\n vec4 result = -x;\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"):new az(s.shape,yU),n.runWebGLProgram(r,[s],s.dtype)}},xU=sf;const wU={kernelName:es,backendName:"webgl",kernelFunc:function(e){xr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=xU(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},vU=rf;const kU={kernelName:ts,backendName:"webgl",kernelFunc:function(e){xr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),{selectedIndices:d,validOutputs:p}=vU(c,h,i,o,l,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([p]))]}},IU=af;const NU={kernelName:ns,backendName:"webgl",kernelFunc:function(e){xr("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),d=i,p=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=IU(c,h,d,p,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class SU{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${s}), float(${n}),\n float(index == coords.y)));\n }\n `}}const TU={kernelName:rs,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s,u=ue(r.shape),c=new SU(u,i,o,l),h=Jz({inputs:{x:r},backend:n,attrs:{shape:[u]}}),d=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const p=Jz({inputs:{x:d},backend:n,attrs:{shape:[...r.shape,i]}});return n.disposeIntermediateTensorInfo(d),p}};function CU(e){const{inputs:t,backend:n}=e,{x:s}=t;if("complex64"===s.dtype){const e=pB({inputs:{input:s},backend:n}),t=CU({inputs:{x:e},backend:n}),r=EB({inputs:{input:s},backend:n}),a=CU({inputs:{x:r},backend:n}),i=Dz({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return GW({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:n})}const $U={kernelName:dr,backendName:"webgl",kernelFunc:CU};const EU={kernelName:ss,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,{x:r}=n;if("string"===r.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===r.dtype){const t=pB({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=EB({inputs:{input:r},backend:s}),i=CU({inputs:{x:a},backend:s}),o=Dz({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return GW({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:s})}};const RU={kernelName:as,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return OW({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{oe(a,e.shape,"All tensors passed to stack must have matching shapes"),ie(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=_B({inputs:t.map((e=>{const t=OW({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}};class AU{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=xM(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);this.userCode=1!==s?`\n ${r} start = ${r}(${a});\n ${r} end = ${r}(${i});\n\n void main() {\n ${r} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${r} coords = outC - start;\n setOutput(getX(${o}));\n }\n }\n `:`\n int start = ${a};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class _U{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=xM(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=JL("rc",s),l=JL("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${o[s-1]} += 1;\n if(${u}) {\n `,1===s?"":`}\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {`,1===s?"":` ${o[s-1]} += 1;\n if(${u}) {`],d=1===s?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let p="";for(let e=0,t=1===s?2:4;e<t;e++)p+=`\n ${h[e]}\n if (${d}) {\n result[${e}] = float(value);\n } else {\n ${r} source = rc - start;\n result[${e}] = getChannel(getX(${l.join()}), ${c});\n }\n `;p+=1===s?"} ":"}}",this.userCode=`\n const ${r} start = ${r}(${a});\n const ${r} end = ${r}(${i});\n\n void main() {\n ${r} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const FU=e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;if(0===ue(r.shape)){const e=a.map(((e,t)=>e[0]+r.shape[t]+e[1]));return GW({backend:n,attrs:{shape:e,value:i,dtype:r.dtype}})}const o=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _U(r.shape,a,i):new AU(r.shape,a,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},DU={kernelName:is,backendName:"webgl",kernelFunc:FU},OU=Gz({opSnippet:"\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n bvec4 isNaN1 = lessThan(a, vec4(0.0));\n bvec4 isNaN2 = lessThan(floor(b), b);\n bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n "+Rz+"\n return result;\n"}),MU={kernelName:ls,backendName:"webgl",kernelFunc:OU};const LU={kernelName:cs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=[],u=we(a,r.shape);let c=u;const h=lh(c,o);let d,p=r;if(null!=h&&(p=lP({inputs:{x:r},backend:n,attrs:{perm:h}}),c=ch(c.length,o),l.push(p)),oh("prod",c,o),n.shouldExecuteOnCPU([p])){const e=n.texData.get(p.dataId).values,{outVals:t,outShape:s,outDtype:r}=CL(p.shape,p.dtype,e,c);d=n.makeTensorInfo(s,r,t)}else{const[e,t]=ah(p.shape,c),s=ue(t),a=Jz({inputs:{x:p},backend:n,attrs:{shape:[-1,s]}}),i=nP(a,Ta(r.dtype),"prod",n);d=Jz({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(a),l.push(i)}if(i){l.push(d);const e=ih(d.shape,u);d=Jz({inputs:{x:d},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}};const zU={kernelName:hs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.readSync(e.dataId))),u=r.map((e=>e.shape)),c=n.readSync(a.dataId),h=n.readSync(i.dataId),[d,p,f]=$L(l,u,c,a.shape,a.dtype,h,i.shape,o),m=d.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,p);return m.concat([g])}};const PU={kernelName:ds,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:s,limits:r,deltas:a}=t,i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=EL(i,s.shape,s.dtype,o,r.shape,l,a.shape);return[n.makeTensorInfo([u.length],"int32",u),n.makeTensorInfo([c.length],s.dtype,c)]}};const BU={kernelName:ps,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),h=n.readSync(i.dataId),d=o.map((e=>n.readSync(e.dataId))),p=o.map((e=>e.shape)),[f,m]=RL(u,r.shape,c,a.shape,a.dtype,h,i.shape,d,p,l);return n.makeTensorInfo(f,a.dtype,m)}},WU=e=>{const{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:i}=n,o=AL(s,r,a,i);return t.makeTensorInfo([o.length],i,o)},VU={kernelName:fs,backendName:"webgl",kernelFunc:WU},UU=Uz({opSnippet:"return 1.0 / x;"}),GU={kernelName:gs,backendName:"webgl",kernelFunc:UU},HU=Uz({opSnippet:iz+"\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),jU={kernelName:ys,backendName:"webgl",kernelFunc:HU},qU=Uz({opSnippet:iz+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),KU={kernelName:Is,backendName:"webgl",kernelFunc:qU};class XU{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class YU{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${u[0]/c[0]},\n ${u[1]/c[1]},\n ${u[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${l-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const ZU={kernelName:vs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=Xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new YU(r.shape,l,u,a,i):new XU(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],"float32")}};class JU{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,d=1/c,p=2*Math.ceil(h)+2,f=2*Math.ceil(d)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${d});\n\n const int winHeight = int(${p});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const QU={kernelName:ks,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new JU(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class eG{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let d;d=r?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${d};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}class tG{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let d;d=r?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${u[0]/c[0]},\n ${u[1]/c[1]},\n ${u[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${d};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${l-1};\n bool hasNextRow = coords.z < ${n-1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `}}const nG={kernelName:xs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=Xe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new tG(r.shape,l,u,a,i):new eG(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],r.dtype)}};class sG{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,d=1/c,p=2*Math.ceil(h)+2,f=2*Math.ceil(d)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${d});\n\n const int winHeight = int(${p});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float sourceFracRow =\n float(${o[0]}) *\n (float(dyR) / float(${l[0]}));\n\n float sourceFracCol =\n float(${o[1]}) *\n (float(dyC) / float(${l[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${s}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${r}) - 1),\n ${n} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const rG={kernelName:ws,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new sG(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class aG{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const s=e.map(((n,s)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(s))).join(","),r=xM(n);this.userCode=`\n void main() {\n ${r} coords = getOutputCoords();\n setOutput(getX(${s}));\n }\n `}}class iG{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=JL("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,i=xM(n);function o(n){const s=e.map(((s,r)=>function(n,s){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${s[n]} - 1`:`${s[n]}`}(r,n)));return`getChannel(getX(${s.join(",")}), vec2(${s.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${r}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${i} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return o(e)}(s.slice())};\n if(${r}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(s.slice())};\n }\n if(${a}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n if(${r}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n }\n }\n setOutput(result);\n }\n `}}const oG={kernelName:Ns,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,i=r.shape.length,o=we(a,r.shape);if(0===i)return _z({inputs:{x:r},backend:n});const l=Xe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iG(r.shape,o):new aG(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}};class lG{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],s=e[2];this.outputShape=e;let r="";r="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n vec3 fill = vec3(${t.join(",")});\n float outputValue = fill[coords[3]];`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${r}\n if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const uG={kernelName:mr,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=new lG(s.shape,a),[u,c]=om(i,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[s],s.dtype,h)}},cG=Uz({opSnippet:"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n"}),hG={kernelName:Ss,backendName:"webgl",kernelFunc:cG},dG=Uz({opSnippet:"return inversesqrt(x);",cpuKernelImpl:_L}),pG={kernelName:Ts,backendName:"webgl",kernelFunc:dG};class fG{constructor(e,t,n,s,r,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const l=xM(r.length),u=xM(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let d="";1===s?d="i":2===s&&(d="i, coords[1]");const p=`getUpdates(${d})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`\n ${l} strides = ${l}(${r});\n\n void main() {\n ${u} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${e}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${t}; j++) {\n int index = round(${h});\n flattenedIndex += index * ${g};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${p};\n found = true;\n }\n }\n setOutput(mix(${m}, sum, float(found)));\n }\n `}}class mG{constructor(e,t,n,s,r,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const l=xM(r.length),u=xM(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let d="";1===s?d="i":2===s&&(d="i, coords[1]");const p=`getUpdates(${d})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`\n ${l} strides = ${l}(${r});\n\n void main() {\n ${u} coords = getOutputCoords();\n vec4 sum = vec4(0.);\n vec4 found = vec4(0.);\n for (int i = 0; i < ${e}; i+=2) {\n ivec2 flattenedIndex = ivec2(0);\n for (int j = 0; j < ${t}; j+=2) {\n ivec4 index = round(${h});\n flattenedIndex += index.xz * ${g};\n if (j + 1 < ${t}) {\n flattenedIndex += index.yw * ${y};\n }\n }\n if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\n flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\n vec4 updVals = ${p};\n if (flattenedIndex[0] == coords[0]) {\n sum.xy += updVals.xy;\n found.xy = vec2(1.);\n } else if (flattenedIndex[0] == coords[0] + 1) {\n sum.zw += updVals.xy;\n found.zw = vec2(1.);\n }\n if (flattenedIndex[1] == coords[0]) {\n sum.xy += updVals.zw;\n found.xy = vec2(1.);\n } else if (flattenedIndex[1] == coords[0] + 1) {\n sum.zw += updVals.zw;\n found.zw = vec2(1.);\n }\n }\n }\n setOutput(mix(${m}, sum, found));\n }\n `}}const gG={kernelName:Cs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=tu(0,r,i),d=[h/u,u];if(0===h)return n.makeTensorInfo(i,r.dtype);const p=Jz({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),f=Jz({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=Xe().getBool("WEBGL_PACK")?new mG(l,o,p.shape.length,f.shape.length,c,d):new fG(l,o,p.shape.length,f.shape.length,c,d);const y=n.runWebGLProgram(g,[f,p,m],f.dtype),b=Jz({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class yG{constructor(e,t,n,s){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const r=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=2===Xe().getNumber("WEBGL_VERSION")?"while (left < right) {":r,i="left"===s?"<":"<=";this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${a}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${i} value) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return right;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int valueIndex = coords[1];\n\n float value = getValues(batch, valueIndex);\n\n setOutput(float(findBound(batch, value)));\n }\n `}}const bG={kernelName:Es,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=new yG(r.shape[0],r.shape[1],a.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,a],"int32",l)}};class xG{constructor(e,t,n){let s,r;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)r="resRC",s="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let s=0;s<t.length;s++)i.push(`${n[s]}`),s<e&&a.push(`${n[s]}`);s=a.join(),r=i.join()}const a=xM(n);this.userCode=`\n void main() {\n ${a} resRC = getOutputCoords();\n float cVal = getC(${s});\n if (cVal >= 1.0) {\n setOutput(getA(${r}));\n } else {\n setOutput(getB(${r}));\n }\n }\n `}}const wG={kernelName:Rs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,i=new xG(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[s,r,a],Sa(r.dtype,a.dtype))}},vG=Uz({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${pm};\n float scale = ${fm};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),kG={kernelName:As,backendName:"webgl",kernelFunc:vG},IG=Uz({opSnippet:Vz+"\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:DL}),NG={kernelName:Ms,backendName:"webgl",kernelFunc:IG},SG=Uz({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),TG={kernelName:Os,backendName:"webgl",kernelFunc:SG},CG=Uz({opSnippet:Vz+"\n return sin(x);\n",packedOpSnippet:`\n vec4 result = sin(x);\n bvec4 isNaN = isnan(x);\n ${Rz}\n return result;\n`}),$G={kernelName:Fs,backendName:"webgl",kernelFunc:CG},EG=Uz({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),RG={kernelName:Ds,backendName:"webgl",kernelFunc:EG},AG=Uz({opSnippet:"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n"}),_G={kernelName:Ls,backendName:"webgl",kernelFunc:AG},FG={kernelName:Bs,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;ie(r.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=[[0,0]];l.push(...i);for(let e=1+a.length;e<r.shape.length;++e)l.push([0,0]);const u=[],c=FU({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),h=lm(c.shape,a,o,!1),d=um(h.length,a.length,!1),p=cm(c.shape,a,o,!1),f=Jz({inputs:{x:c},backend:n,attrs:{shape:h}}),m=lP({inputs:{x:f},backend:n,attrs:{perm:d}}),g=Jz({inputs:{x:m},backend:n,attrs:{shape:p}});return u.push(c),u.push(f),u.push(m),u.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}};const DG={kernelName:Us,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${a.shape}`);if(2!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n ${r.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${i.shape}`);const o=n.readSync(s.dataId),l=n.readSync(r.dataId),u=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,d,p,f,m]=LL(o,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(d,s.dtype,h),n.makeTensorInfo([d[0]],r.dtype,p),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}};const OG={kernelName:Gs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.readSync(r.dataId)),o=n.readSync(s.dataId),l=Array.from(n.readSync(a.dataId)),[u,c,h]=zL(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const MG={kernelName:Hs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=PL(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const LG={kernelName:js,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${a.shape}`);const i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=PL(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const zG={kernelName:qs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:d}=tu(0,r,o),p=!1;if("string"===a.dtype){const e=n.bufferSync(r),t=n.bufferSync(a),s=Jr(n.readSync(i.dataId)[0]),f=FL(e,t,o,d,c,u,l,h,s,p);return n.makeTensorInfo(o,f.dtype,f.values)}const f=new fG(u,l,r.shape.length,a.shape.length,h,[d,1],p),m=n.runWebGLProgram(f,[a,r,i],a.dtype),g=Jz({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),g}};const PG={kernelName:Ws,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=we(i,r.shape)[0],l=Pm(r,a,o),u=r.shape.length,c=new Array(u).fill(0),h=r.shape.slice();return l.map((e=>{const t=[...h];t[o]=e;const s=aB({inputs:{x:r},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,s}))}},BG="return sqrt(x);",WG=Uz({opSnippet:BG,packedOpSnippet:BG,cpuKernelImpl:BL}),VG={kernelName:zs,backendName:"webgl",kernelFunc:WG},UG=Uz({opSnippet:"return x * x;"}),GG={kernelName:Xs,backendName:"webgl",kernelFunc:UG},HG="return (a - b) * (a - b);",jG=Gz({opSnippet:HG,packedOpSnippet:HG}),qG={kernelName:Ks,backendName:"webgl",kernelFunc:jG};const KG={kernelName:Ys,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;if("string"!==r.dtype)throw new Error("Input must be of datatype string");const a=tg(n.readSync(r.dataId)),i=WL(a,"string",s);return n.makeTensorInfo(r.shape,"string",i)}};const XG={kernelName:pr,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:s}=e,r=iz+`\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,a=new az(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}};class YG{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,r=xM(n.length),a=xM(n.length);let i="";if(1===s)i="coords * strides + begin";else{let e=0;i=n.map(((t,s)=>(e++,1===n.length?`coords * strides[${s}] + begin[${s}]`:`coords[${e-1}] * strides[${s}] + begin[${s}]`))).join(",")}this.userCode=`\n ${r} begin = ${r}(${e});\n ${r} strides = ${r}(${t});\n\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}const ZG={kernelName:Zs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=s,{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=xu(r.shape,a,i,o,l,u,c,h,d);let v;if(m)v=Jz({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){ie(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=iu(b,x,w),t=aB({inputs:{x:r},backend:n,attrs:{begin:b,size:e}});v=Jz({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([r])){const e=n.readSync(r.dataId),t=Co(r.shape,r.dtype,e),s=VL(p,t,w,b);v=n.makeTensorInfo(f,r.dtype,s.values)}else{const e=new YG(b,w,p);v=n.runWebGLProgram(e,[r],r.dtype)}}const k=Jz({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}};const JG={kernelName:Js,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,d=n.readSync(c.dataId),p=n.readSync(h.dataId),[f,m]=UL(d,p,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const QG={kernelName:Qs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(a.dataId),l=n.readSync(i.dataId)[0],[u,c,h]=GL(o,l,r),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}};const eH={kernelName:er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=HL(i,r);return n.makeTensorInfo(a.shape,"int32",o)}},tH=Uz({opSnippet:"return tan(x);"}),nH={kernelName:nr,backendName:"webgl",kernelFunc:tH},sH=Uz({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),rH={kernelName:sr,backendName:"webgl",kernelFunc:sH};const aH={kernelName:$s,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{tensor:r,indices:a,updates:i}=t,{}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=tu(0,a,r.shape),d=[h/u,u];if(0===h)return n.makeTensorInfo(r.shape,a.dtype);const p=Jz({inputs:{x:a},backend:n,attrs:{shape:[l,o]}}),f=Jz({inputs:{x:i},backend:n,attrs:{shape:[l,u]}}),m=Jz({inputs:{x:r},backend:n,attrs:{shape:d}}),g=new fG(l,o,p.shape.length,f.shape.length,c,d,!1,!0),y=n.runWebGLProgram(g,[f,p,m],m.dtype),b=Jz({inputs:{x:y},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class iH{constructor(e,t){this.variableNames=["A"];const 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;const s=xM(this.rank),r=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let t=0;t<e.length;t++)s.push(`imod(${n[t]}, ${e[t]})`);return s.join()}(e);this.userCode=`\n void main() {\n ${s} resRC = getOutputCoords();\n setOutput(getA(${r}));\n }\n `}}function oH(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;if("string"===r.dtype||r.shape.length>5){const e=n.readSync(r.dataId),t="string"===r.dtype?e.map((e=>Jr(e))):e,s=Co(r.shape,r.dtype,t),i=qL(s,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new iH(r.shape,a);return n.runWebGLProgram(i,[r],r.dtype)}const lH={kernelName:rr,backendName:"webgl",kernelFunc:oH};class uH{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="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n "}}class cH{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="\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\n }\n "}}function hH(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function dH(e){let t=1;for(;t<e;)t*=2;return t}const pH={kernelName:ar,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s,o=Xe().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Xe().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,c=u[u.length-1];if(n.shouldExecuteOnCPU([r])||c<o||a>l){const e=n.readSync(r.dataId),[t,s]=KL(e,u,r.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(s.shape,s.dtype,s.values)]}if(0===a)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(1===c)return[r,GW({attrs:{shape:u,dtype:"int32",value:0},backend:n})];const h=n.texData.get(r.dataId),d=null!==h&&h.isPacked,p=d?n.unpackTensor(r):r,f=ue(u)/c,m=Jz({inputs:{x:p},attrs:{shape:[f,c]},backend:n});d&&hH(n,p);const g=dH(a),y=dH(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,s)=>{const r=x(),a=new uH(s),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(a,r,"int32",i),hH(n,o)};for(let e=1;e<g;e*=2){const t=2*e;for(let n=e;n>=1;n/=2)w(t,n,[f,y])}for(let e=y;e>g;e/=2){const t=x(),s=new cH([f,e/2]),r=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(s,t,"int32",r),hH(n,a);const i=g/2,o=2*i;for(let e=i;e>=1;e/=2)w(o,e,b.shape)}let v=b;b=aB({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,a]}}),hH(n,v);let k=uV({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});hH(n,m);const I=u.slice(0,-1);I.push(a),v=b,b=Jz({inputs:{x:b},attrs:{shape:I},backend:n}),hH(n,v);const N=k;return k=Jz({inputs:{x:k},attrs:{shape:I},backend:n}),hH(n,N),[k,b]}};class fH{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(s){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${o} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${r});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${r});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${t}));\n float mapY = mapCoord(inY, float(${e}));\n\n if (${i} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const mH={kernelName:ir,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=s,[c,h,d,p]=r.shape,[f,m]=null!=u?u:[h,d],g=new fH(h,d,i,o,l,[c,f,m,p]);return n.runWebGLProgram(g,[r,a],"float32")}};const gH={kernelName:lr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;eM(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(a.dataId),{outputValues:o,outputShape:l,indices:u}=YL(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const yH={kernelName:ur,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{value:r}=t;let{axis:a}=s;a<0&&(a+=r.shape.length);const i=r,o=i.shape.length,l=r.shape[a],u=new Array(o-1);let c=0;for(let e=0;e<o;e++)e!==a&&(u[c++]=i.shape[e]);const h=[],d=new Array(o).fill(0),p=i.shape.slice();p[a]=1;const f=new Array(l);for(let e=0;e<f.length;e++){d[a]=e;const t=aB({inputs:{x:i},backend:n,attrs:{begin:d,size:p}}),s=Jz({inputs:{x:t},backend:n,attrs:{shape:u}});f[e]=s,h.push(t)}return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class bH{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,r=e.inSize,a=e.numSegments,i=a*Math.ceil(r/n);this.outputShape=[s,i];const o=4*Math.floor(n/4),l=n%4,u="\n sumValue += dot(values, segFilter);\n ";let c="";r%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${r}) {\n return initializationValue;\n }\n `);let h="";r%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${r}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${c}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${h}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${a})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${a})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${2===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${3===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}const xH={kernelName:cr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s,o=r.shape.length,l=[];let u=0;const c=lh([u],o);let h=r;null!=c&&(h=lP({inputs:{x:r},backend:n,attrs:{perm:c}}),l.push(h),u=ch(1,o)[0]);const d=Qm(h.shape,u,i),p=ue([h.shape[u]]),f=Jz({inputs:{x:h},backend:n,attrs:{shape:[-1,p]}});l.push(f);const m=Ta(r.dtype),g=(e,t,s,r,a)=>{const i=e.shape[0],o=e.shape[1],u=Jm(o,a),c=new bH({windowSize:u,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,s],r);if(l.push(h),h.shape[1]===a)return h;const d=WU({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),p=oH({inputs:{x:d},backend:n,attrs:{reps:[o/u]}});l.push(d),l.push(p);return g(h,t,p,r,a)},y=Jz({inputs:{x:g(f,"unsortedSegmentSum",a,m,i)},backend:n,attrs:{shape:d}});let b=y;if(null!=c){l.push(y);const e=uh(c);b=lP({inputs:{x:b},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},wH=[dP,fP,gP,bP,vP,NP,SP,TP,_P,FP,OP,LP,PP,WP,UP,jP,qP,YP,ZP,JP,tB,oB,lB,uB,cB,gB,xB,kB,Oz,SB,FB,WB,jB,KB,XB,YB,ZB,QB,tW,sW,uW,cW,hW,pW,gW,xW,wW,kW,NW,SW,CW,$W,RW,_W,DW,MW,PW,VW,HW,qW,YW,JW,tV,rV,aV,oV,cV,dV,fV,Fz,mV,RB,yV,xV,vV,zz,IV,SV,TV,$V,RV,_V,DV,MV,PV,WV,UV,HV,jV,qV,YV,ZV,JV,QV,eU,nU,aU,oU,gU,Zz,bU,wU,kU,NU,dB,TU,EU,RU,DU,MU,Wz,LU,zU,PU,BU,VU,fB,cU,GU,jU,KU,Qz,ZU,QU,nG,rG,oG,uG,hG,pG,gG,bG,wG,kG,NG,TG,$G,RG,iB,mU,_G,FG,DG,OG,MG,LG,zG,PG,VG,GG,qG,KG,XG,ZG,JG,QG,eH,pU,oP,nH,rH,aH,lH,pH,mH,uP,gH,yH,xH,$U];for(const e of wH)Tr(e);const vH={"tfjs-core":Ou,"tfjs-backend-cpu":BR,"tfjs-backend-webgl":Sz,"tfjs-data":c$,"tfjs-layers":jw,"tfjs-converter":eC,tfjs:"4.20.0"}},570:e=>{e.exports=n;var t=null;try{t=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(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function s(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=s;var r={},a={};function i(e,t){var n,s,i;return t?(i=0<=(e>>>=0)&&e<256)&&(s=a[e])?s:(n=l(e,(0|e)<0?-1:0,!0),i&&(a[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(s=r[e])?s:(n=l(e,e<0?-1:0,!1),i&&(r[e]=n),n)}function o(e,t){if(isNaN(e))return t?y:g;if(t){if(e<0)return y;if(e>=p)return k}else{if(e<=-f)return I;if(e+1>=f)return v}return e<0?o(-e,t).neg():l(e%d|0,e/d|0,t)}function l(e,t,s){return new n(e,t,s)}n.fromInt=i,n.fromNumber=o,n.fromBits=l;var u=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return g;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return c(e.substring(1),t,n).neg();for(var r=o(u(n,8)),a=g,i=0;i<e.length;i+=8){var l=Math.min(8,e.length-i),h=parseInt(e.substring(i,i+l),n);if(l<8){var d=o(u(n,l));a=a.mul(d).add(o(h))}else a=(a=a.mul(r)).add(o(h))}return a.unsigned=t,a}function h(e,t){return"number"==typeof e?o(e,t):"string"==typeof e?c(e,t):l(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=h;var d=4294967296,p=d*d,f=p/2,m=i(1<<24),g=i(0);n.ZERO=g;var y=i(0,!0);n.UZERO=y;var b=i(1);n.ONE=b;var x=i(1,!0);n.UONE=x;var w=i(-1);n.NEG_ONE=w;var v=l(-1,2147483647,!1);n.MAX_VALUE=v;var k=l(-1,-1,!0);n.MAX_UNSIGNED_VALUE=k;var I=l(0,-2147483648,!1);n.MIN_VALUE=I;var N=n.prototype;N.toInt=function(){return this.unsigned?this.low>>>0:this.low},N.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},N.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(I)){var t=o(e),n=this.div(t),s=n.mul(t).sub(this);return n.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var r=o(u(e,6),this.unsigned),a=this,i="";;){var l=a.div(r),c=(a.sub(l.mul(r)).toInt()>>>0).toString(e);if((a=l).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.getNumBitsAbs=function(){if(this.isNegative())return this.eq(I)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},N.isZero=function(){return 0===this.high&&0===this.low},N.eqz=N.isZero,N.isNegative=function(){return!this.unsigned&&this.high<0},N.isPositive=function(){return this.unsigned||this.high>=0},N.isOdd=function(){return!(1&~this.low)},N.isEven=function(){return!(1&this.low)},N.equals=function(e){return s(e)||(e=h(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},N.eq=N.equals,N.notEquals=function(e){return!this.eq(e)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(e){return this.comp(e)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(e){return this.comp(e)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(e){return this.comp(e)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(e){return this.comp(e)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(e){if(s(e)||(e=h(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},N.comp=N.compare,N.negate=function(){return!this.unsigned&&this.eq(I)?I:this.not().add(b)},N.neg=N.negate,N.add=function(e){s(e)||(e=h(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,i=e.high>>>16,o=65535&e.high,u=e.low>>>16,c=0,d=0,p=0,f=0;return p+=(f+=a+(65535&e.low))>>>16,d+=(p+=r+u)>>>16,c+=(d+=n+o)>>>16,c+=t+i,l((p&=65535)<<16|(f&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},N.subtract=function(e){return s(e)||(e=h(e)),this.add(e.neg())},N.sub=N.subtract,N.multiply=function(e){if(this.isZero())return g;if(s(e)||(e=h(e)),t)return l(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(I))return e.isOdd()?I:g;if(e.eq(I))return this.isOdd()?I:g;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return o(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,r=65535&this.high,a=this.low>>>16,i=65535&this.low,u=e.high>>>16,c=65535&e.high,d=e.low>>>16,p=65535&e.low,f=0,y=0,b=0,x=0;return b+=(x+=i*p)>>>16,y+=(b+=a*p)>>>16,b&=65535,y+=(b+=i*d)>>>16,f+=(y+=r*p)>>>16,y&=65535,f+=(y+=a*d)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*p+r*d+a*c+i*u,l((b&=65535)<<16|(x&=65535),(f&=65535)<<16|(y&=65535),this.unsigned)},N.mul=N.multiply,N.divide=function(e){if(s(e)||(e=h(e)),e.isZero())throw Error("division by zero");var n,r,a;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?l((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return y;if(e.gt(this.shru(1)))return x;a=y}else{if(this.eq(I))return e.eq(b)||e.eq(w)?I:e.eq(I)?b:(n=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?b:w:(r=this.sub(e.mul(n)),a=n.add(r.div(e)));if(e.eq(I))return this.unsigned?y:g;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();a=g}for(r=this;r.gte(e);){n=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),c=i<=48?1:u(2,i-48),d=o(n),p=d.mul(e);p.isNegative()||p.gt(r);)p=(d=o(n-=c,this.unsigned)).mul(e);d.isZero()&&(d=b),a=a.add(d),r=r.sub(p)}return a},N.div=N.divide,N.modulo=function(e){return s(e)||(e=h(e)),t?l((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return l(~this.low,~this.high,this.unsigned)},N.and=function(e){return s(e)||(e=h(e)),l(this.low&e.low,this.high&e.high,this.unsigned)},N.or=function(e){return s(e)||(e=h(e)),l(this.low|e.low,this.high|e.high,this.unsigned)},N.xor=function(e){return s(e)||(e=h(e)),l(this.low^e.low,this.high^e.high,this.unsigned)},N.shiftLeft=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?l(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):l(0,this.low<<e-32,this.unsigned)},N.shl=N.shiftLeft,N.shiftRight=function(e){return s(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?l(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):l(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(e){if(s(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?l(this.low>>>e|t<<32-e,t>>>e,this.unsigned):l(32===e?t:t>>>e-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.toSigned=function(){return this.unsigned?l(this.low,this.high,!1):this},N.toUnsigned=function(){return this.unsigned?this:l(this.low,this.high,!0)},N.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},N.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},N.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,s){return s?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},391:(e,t,n)=>{var s=n(180),r=n(181),a=n(31),i=n(67),o=n(833),l=n(717),u=n(801);u.alea=s,u.xor128=r,u.xorwow=a,u.xorshift7=i,u.xor4096=o,u.tychei=l,e.exports=u},180:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this,n=function(){var e=4022871197,t=function(t){t=String(t);for(var n=0;n<t.length;n++){var s=.02519603282416938*(e+=t.charCodeAt(n));s-=e=s>>>0,e=(s*=e)>>>0,e+=4294967296*(s-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function l(e,t){var n=new i(e),s=t&&t.state,r=n.next;return r.int32=function(){return 4294967296*n.next()|0},r.double=function(){return r()+11102230246251565e-32*(2097152*r()|0)},r.quick=r,s&&("object"==typeof s&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.alea=l}(0,e=n.nmd(e),n.amdD)},717:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,s=t.d,r=t.a;return e=e<<25^e>>>7^n,n=n-s|0,s=s<<24^s>>>8^r,r=r-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-s|0,t.d=s<<16^n>>>16^r,t.a=r-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var s=0;s<n.length+20;s++)t.b^=0|n.charCodeAt(s),t.next()}function o(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function l(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.tychei=l}(0,e=n.nmd(e),n.amdD)},181:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var s=0;s<n.length+64;s++)t.x^=0|n.charCodeAt(s),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function l(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.xor128=l}(0,e=n.nmd(e),n.amdD)},833:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this;t.next=function(){var e,n,s=t.w,r=t.X,a=t.i;return t.w=s=s+1640531527|0,n=r[a+34&127],e=r[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=r[a]=n^e,t.i=a,n+(s^s>>>16)|0},function(e,t){var n,s,r,a,i,o=[],l=128;for(t===(0|t)?(s=t,t=null):(t+="\0",s=0,l=Math.max(l,t.length)),r=0,a=-32;a<l;++a)t&&(s^=t.charCodeAt((a+32)%t.length)),0===a&&(i=s),s^=s<<10,s^=s>>>15,s^=s<<4,s^=s>>>13,a>=0&&(i=i+1640531527|0,r=0==(n=o[127&a]^=s+i)?r+1:0);for(r>=128&&(o[127&(t&&t.length||0)]=-1),r=127,a=512;a>0;--a)s=o[r+34&127],n=o[r=r+1&127],s^=s<<13,n^=n<<17,s^=s>>>15,n^=n>>>12,o[r]=s^n;e.w=i,e.X=o,e.i=r}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.X&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.xor4096=l}(0,e=n.nmd(e),n.amdD)},67:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this;t.next=function(){var e,n,s=t.x,r=t.i;return e=s[r],n=(e^=e>>>7)^e<<24,n^=(e=s[r+1&7])^e>>>10,n^=(e=s[r+3&7])^e>>>3,n^=(e=s[r+4&7])^e<<7,e=s[r+7&7],n^=(e^=e<<13)^e<<9,s[r]=n,t.i=r+1&7,n},function(e,t){var n,s=[];if(t===(0|t))s[0]=t;else for(t=""+t,n=0;n<t.length;++n)s[7&n]=s[7&n]<<15^t.charCodeAt(n)+s[n+1&7]<<13;for(;s.length<8;)s.push(0);for(n=0;n<8&&0===s[n];++n);for(8==n?s[7]=-1:s[n],e.x=s,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.x&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.xorshift7=l}(0,e=n.nmd(e),n.amdD)},31:function(e,t,n){var s;!function(e,r,a){function i(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var s=0;s<n.length+64;s++)t.x^=0|n.charCodeAt(s),s==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function l(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&o(s,n),r.state=function(){return o(n,{})}),r}r&&r.exports?r.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,r))||(r.exports=s):this.xorwow=l}(0,e=n.nmd(e),n.amdD)},801:function(e,t,n){var s;!function(r,a,i){var o,l=256,u=i.pow(l,6),c=i.pow(2,52),h=2*c,d=l-1;function p(e,t,n){var s=[],d=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(l):(e=new Uint8Array(l),(r.crypto||r.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=r.navigator,n=t&&t.plugins;return[+new Date,r,n,r.screen,b(a)]}}():e,3),s),p=new f(s),x=function(){for(var e=p.g(6),t=u,n=0;e<c;)e=(e+n)*l,t*=l,n=p.g(1);for(;e>=h;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|p.g(4)},x.quick=function(){return p.g(4)/4294967296},x.double=x,y(b(p.S),a),(t.pass||n||function(e,t,n,s){return s&&(s.S&&m(s,p),e.state=function(){return m(p,{})}),n?(i.random=e,t):e})(x,d,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,s=this,r=0,a=s.i=s.j=0,i=s.S=[];for(n||(e=[n++]);r<l;)i[r]=r++;for(r=0;r<l;r++)i[r]=i[a=d&a+e[r%n]+(t=i[r])],i[a]=t;(s.g=function(e){for(var t,n=0,r=s.i,a=s.j,i=s.S;e--;)t=i[r=d&r+1],n=n*l+i[d&(i[r]=i[a=d&a+t])+(i[a]=t)];return s.i=r,s.j=a,n})(l)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function g(e,t){var n,s=[],r=typeof e;if(t&&"object"==r)for(n in e)try{s.push(g(e[n],t-1))}catch(e){}return s.length?s:"string"==r?e:e+"\0"}function y(e,t){for(var n,s=e+"",r=0;r<s.length;)t[d&r]=d&(n^=19*t[d&r])+s.charCodeAt(r++);return b(t)}function b(e){return String.fromCharCode.apply(0,e)}if(y(i.random(),a),e.exports){e.exports=p;try{o=n(234)}catch(e){}}else void 0===(s=function(){return p}.call(t,n,t,e))||(e.exports=s)}("undefined"!=typeof self?self:this,[],Math)},681:function(e,t,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,r)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&s(t,e,n);return r(t,e),t},i=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))((function(r,a){function i(e){try{l(s.next(e))}catch(e){a(e)}}function o(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}l((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const o=a(n(951)),l=n(951),u=n(389),c=n(772),h=n(763);t.default=class{constructor({epochs:e=50,batchSize:t=16,limitSize:n=2,learningRate:s=.001,validateRate:r=.15}={}){this.imageExamples=[],this.classNumber=[],this.MOBILE_NET_INPUT_WIDTH=224,this.MOBILE_NET_INPUT_HEIGHT=224,this.MOBILE_NET_INPUT_CHANNEL=3,this.IMAGE_NORMALIZATION_FACTOR=255,this.onProgress=()=>{},this.onLoss=()=>{},this.onEvents=()=>{},this.onTrainBegin=()=>{},this.onTrainEnd=()=>{},this.onEpochEnd=()=>{},this.model=null,this.epochs=e,this.batchSize=t,this.learningRate=s,this.validateRate=r,this.isRunning=!1,this.isReady=!1,this.isTrainedDone=!1,this.limitSize=n,this.mobilenetModule=null,this.classNumber=[]}load({jsonURL:e,labels:t}){return i(this,void 0,void 0,(function*(){if(t.length<=0)return Promise.reject(new Error("Labels length is 0"));try{this.model=yield o.loadLayersModel(e);for(var n=0;n<t.length;n++)this.registerClassNumber(t[n]);this.isReady=!0,this.model.summary()}catch(e){throw console.error("Model load failed",e),e}}))}registerClassNumber(e){const t=this.classNumber.indexOf(e);return-1!==t?t:(this.classNumber.push(e),this.classNumber.length-1)}_convertToTfDataset(){for(let e=0;e<this.imageExamples.length;e++)this.imageExamples[e]=(0,h.fisherYates)(this.imageExamples[e]);const e=[],t=[];for(let n=0;n<this.imageExamples.length;n++){const s=this.imageExamples[n].length,r=Math.ceil(this.validateRate*s),a=s-r,i=(0,h.flatOneHot)(n,this.classNumber.length),o=this.imageExamples[n].slice(0,a).map((e=>({data:e,label:i})));e.push(...o);const l=this.imageExamples[n].slice(a,a+r).map((e=>({data:e,label:i})));t.push(...l)}const n=(0,h.fisherYates)(e),s=(0,h.fisherYates)(t),r=o.data.array(n.map((e=>e.data))),a=o.data.array(s.map((e=>e.data))),i=o.data.array(n.map((e=>e.label))),l=o.data.array(s.map((e=>e.label)));return{trainDataset:o.data.zip({xs:r,ys:i}),validationDataset:o.data.zip({xs:a,ys:l})}}addData(e,t){return i(this,void 0,void 0,(function*(){try{if(null===this.mobilenetModule)throw new Error("mobilenetModule is null");{const n=(0,u.isTensor)(t)?t:yield(0,u.capture)(t,!1),s=o.tidy((()=>this.mobilenetModule.predict(n))),r=yield s.data(),a=this.registerClassNumber(e);this.imageExamples[a]||(this.imageExamples[a]=[]),this.imageExamples[a].push(r),this.classNumber.length>=this.limitSize&&(this.isReady=!0),s.dispose(),(0,u.isTensor)(t)||n.dispose()}return Promise.resolve()}catch(e){throw console.error("Model training failed",e),e}}))}init(){return i(this,void 0,void 0,(function*(){try{this.mobilenetModule=yield(0,u.loadModel)()}catch(e){throw console.log("init Error",e),e}}))}train(){return i(this,void 0,void 0,(function*(){if(this.isRunning)return Promise.reject(new Error("Training is already in progress."));const e={onTrainBegin:e=>{this.isTrainedDone=!1,this.onTrainBegin(e)},onTrainEnd:e=>{this.isTrainedDone=!0,this.onTrainEnd(e),this.isRunning=!1},onBatchBegin:(e,t)=>{},onBatchEnd:(e,t)=>{},onEpochBegin:(e,t)=>{},onEpochEnd:(e,t)=>{this.onEpochEnd(e,t),this.onLoss(t.loss),this.onProgress(e+1),this.onEvents({epoch:e,logs:t})}};try{if(this.isRunning=!0,this.classNumber.length<this.limitSize)return Promise.reject(new Error("Please train Data need over 2 data length"));const t=this._convertToTfDataset(),n=t.trainDataset.batch(this.batchSize),s=t.validationDataset.batch(this.batchSize),r=o.train.adam(this.learningRate),a=yield this._createModel(r),i=o.sequential();i.add(this.mobilenetModule),i.add(a),this.model=i;const l=yield a.fitDataset(n,{epochs:this.epochs,validationData:s,callbacks:e});return r.dispose(),l}catch(e){throw this.isRunning=!1,console.error("Model training failed",e),e}}))}infer(e){return i(this,void 0,void 0,(function*(){if(null===this.model)return Promise.reject(new Error("Model is Null"));try{const t=new Map,n=(0,c.cropTo)(e,224,!1),s=yield(0,u.capture)(n,!1),r=o.tidy((()=>this.model.predict(s))),a=yield r.data(),i=1e-6;for(let e=0;e<a.length;e++){let n=Math.max(0,Math.min(1,a[e]));n=n<i?0:n;const s=this.classNumber[e],r=t.get(s);void 0!==r?t.set(s,r+n):t.set(s,n)}return console.log("classProbabilities",t),(0,l.dispose)(r),t}catch(e){throw e}}))}saveModel(e,t){var n;return i(this,void 0,void 0,(function*(){try{if(console.log("saveModel try",this.isTrainedDone),!this.isTrainedDone)return Promise.reject(new Error("Train is not done status"));yield null===(n=this.model)||void 0===n?void 0:n.save(e,t)}catch(e){console.log("saveModel Error",e)}}))}running(){return this.isRunning}ready(){return this.isReady}_createModel(e){return i(this,void 0,void 0,(function*(){try{let t;t=o.initializers.varianceScaling({});const n=o.sequential({layers:[o.layers.dense({inputShape:this.mobilenetModule.outputs[0].shape.slice(1),units:128,activation:"relu",kernelInitializer:t,useBias:!0}),o.layers.dense({kernelInitializer:t,useBias:!1,activation:"softmax",units:this.classNumber.length})]});return n.compile({loss:"categoricalCrossentropy",optimizer:e,metrics:["accuracy"]}),n}catch(e){throw console.error("Failed to load model",e),e}}))}}},772:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cropTo=void 0;t.cropTo=function(e,t,n=!1,s=(()=>document.createElement("canvas"))()){let r,a;if(e instanceof ImageData)r=e.width,a=e.height;else if(e instanceof HTMLImageElement||e instanceof HTMLCanvasElement)r=e.width,a=e.height;else{if(!(e instanceof HTMLVideoElement))throw new Error("Unsupported Drawable type");r=e.videoWidth,a=e.videoHeight}const i=t/Math.min(r,a),o=Math.ceil(r*i),l=Math.ceil(a*i),u=o-t,c=l-t;s.width=s.height=t;const h=s.getContext("2d");return e instanceof ImageData?h.putImageData(e,-1*~~(u/2),-1*~~(c/2)):h.drawImage(e,-1*~~(u/2),-1*~~(c/2),o,l),n&&(h.scale(-1,1),h.drawImage(s,-1*t,0)),s}},763:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fisherYates=t.flatOneHot=void 0,t.flatOneHot=function(e,t){const n=new Array(t).fill(0);return n[e]=1,n},t.fisherYates=function(e){const t=e.length,n=e.slice();for(let e=t-1;e>0;e-=1){let t;t=Math.floor(Math.random()*(e+1)),[n[e],n[t]]=[n[t],n[e]]}return n}},389:function(e,t,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,r)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&s(t,e,n);return r(t,e),t},i=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))((function(r,a){function i(e){try{l(s.next(e))}catch(e){a(e)}}function o(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}l((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.cropTensor=t.capture=t.imageToTensor=t.mobileNetURL=t.loadModel=t.isTensor=void 0;const o=a(n(951));function l(e){return 1==e?"https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_1.0_224/model.json":"https://storage.googleapis.com/teachable-machine-models/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224_no_top/model.json"}function u(e,t,n){const s=Math.min(e.shape[0],e.shape[1]),r=e.shape[0]/2-s/2,a=e.shape[1]/2-s/2;if(t&&!n){let t=e.slice([r,a,0],[s,s,3]);t=t.reshape([s*s,1,3]);const n=[.2989,.587,.114];return t=o.mul(t,n),t=t.reshape([s,s,3]),t=o.sum(t,-1),t=o.expandDims(t,-1),t}return e.slice([r,a,0],[s,s,3])}t.isTensor=function(e){return"object"==typeof e.dataId&&"object"==typeof e.shape},t.loadModel=function(){return i(this,void 0,void 0,(function*(){const e=l(2),t=yield o.loadLayersModel(e);{const e=t.getLayer("out_relu"),n=o.model({inputs:t.inputs,outputs:e.output}),s=o.sequential();return s.add(n),s.add(o.layers.globalAveragePooling2d({})),s}}))},t.mobileNetURL=l,t.imageToTensor=function(e){let t;return t=e instanceof o.Tensor?e:o.browser.fromPixels(e),t},t.capture=function(e,t){return i(this,void 0,void 0,(function*(){return o.tidy((()=>u(o.browser.fromPixels(e),t).expandDims(0).toFloat().div(o.scalar(127)).sub(o.scalar(1))))}))},t.cropTensor=u},156:function(e,t,n){"use strict";var s=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))((function(r,a){function i(e){try{l(s.next(e))}catch(e){a(e)}}function o(e){try{l(s.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}l((s=s.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=r(n(681));n(951);class i{constructor(e){this.container=e}update(e,t){this.container.innerText=`Status: ${e} ${t}`}}!function(){s(this,void 0,void 0,(function*(){const e=new a.default({epochs:50,batchSize:16,validateRate:.15});yield e.init(),e.onProgress=e=>{const t=document.getElementById("progress-bar");if(null!==t){new i(t).update(e,"에포크")}},e.onEvents=e=>{const t=document.getElementById("loss-bar");if(null!==t){console.log("loss value",e,typeof e.logs.val_loss);const n=new i(t);n.update(e.logs.acc_0,"acc"),n.update(e.logs.loss,"loss"),n.update(e.logs.val_loss,"val_loss")}};const t=document.createElement("div");t.id="root";const n=()=>e.ready()?!e.running()||(window.alert("이미 진행 중입니다."),!1):(window.alert("준비된 데이터가 없습니다."),!1);function r(n){return s(this,void 0,void 0,(function*(){const s=document.createElement("canvas"),r=document.createElement("video");if(navigator.mediaDevices.getUserMedia){const e=yield navigator.mediaDevices.getUserMedia({video:!0});r.srcObject=e}r.addEventListener("loadedmetadata",(()=>{r.play()})),r.addEventListener("play",(()=>{s.width=150,s.height=150;const t=s.getContext("2d");t&&(t.drawImage(r,0,0,s.width,s.height),console.log("getImageData",s.width,s.height),e.addData(n,t.getImageData(0,0,s.width,s.height)))})),t.appendChild(s)}))}const o=document.createElement("button");o.textContent="라벨1 이미지",o.addEventListener("click",(()=>r("라벨1 이미지"))),t.appendChild(o);const l=document.createElement("button");l.textContent="라벨2 이미지",l.addEventListener("click",(()=>r("라벨2 이미지"))),t.appendChild(l);const u=document.createElement("button");u.textContent="모델 Train",u.addEventListener("click",(function(){return s(this,void 0,void 0,(function*(){n()&&(yield e.train())}))})),t.appendChild(u),document.body.appendChild(t);const c=document.createElement("button");c.textContent="예측하기",c.addEventListener("click",(()=>function(){return s(this,void 0,void 0,(function*(){if(!n())return;const s=document.createElement("canvas"),r=document.createElement("video");if(navigator.mediaDevices.getUserMedia){const e=yield navigator.mediaDevices.getUserMedia({video:!0});r.srcObject=e}r.addEventListener("loadedmetadata",(()=>{r.play()})),r.addEventListener("play",(()=>{s.width=224,s.height=224;const t=s.getContext("2d");t&&(t.drawImage(r,0,0,s.width,s.height),e.infer(t.getImageData(0,0,s.width,s.height)))})),t.appendChild(s)}))}())),t.appendChild(c)}))}()},817:()=>{},590:()=>{},530:()=>{},108:()=>{},551:()=>{},234:()=>{}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var a=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);n(156)})();
|