diff --git a/common/utils.js b/common/utils.js index 713db4c4..79d96e82 100644 --- a/common/utils.js +++ b/common/utils.js @@ -165,7 +165,7 @@ export async function setPolyfillBackend(device) { // Use 'webgl' by default for better performance. // Note: 'wasm' backend may run failed on some samples since // some ops aren't supported on 'wasm' backend at present - const backend = device === 'cpu' ? 'wasm' : 'webgl'; + const backend = device === 'cpu' ? 'wasm' : 'webgpu'; const tf = navigator.ml.createContext().tf; if (tf) { if (!(await tf.setBackend(backend))) { diff --git a/dist/webnn-polyfill.js b/dist/webnn-polyfill.js new file mode 100644 index 00000000..0cc86791 --- /dev/null +++ b/dist/webnn-polyfill.js @@ -0,0 +1,15471 @@ +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=102)}([function(e,t,n){"use strict";n.r(t),n.d(t,"AdadeltaOptimizer",(function(){return pn})),n.d(t,"AdagradOptimizer",(function(){return fn})),n.d(t,"AdamOptimizer",(function(){return gn})),n.d(t,"AdamaxOptimizer",(function(){return kn})),n.d(t,"MomentumOptimizer",(function(){return wn})),n.d(t,"Optimizer",(function(){return dn})),n.d(t,"OptimizerConstructors",(function(){return Sn})),n.d(t,"RMSPropOptimizer",(function(){return In})),n.d(t,"SGDOptimizer",(function(){return yn})),n.d(t,"Tensor",(function(){return te.a})),n.d(t,"TensorBuffer",(function(){return te.b})),n.d(t,"Variable",(function(){return te.c})),n.d(t,"Rank",(function(){return _n.a})),n.d(t,"sumOutType",(function(){return _n.b})),n.d(t,"upcastType",(function(){return _n.c})),n.d(t,"abs",(function(){return xn})),n.d(t,"acos",(function(){return Cn})),n.d(t,"acosh",(function(){return On})),n.d(t,"add",(function(){return Xt})),n.d(t,"addN",(function(){return Tn})),n.d(t,"all",(function(){return $n})),n.d(t,"any",(function(){return An})),n.d(t,"argMax",(function(){return Nn})),n.d(t,"argMin",(function(){return En})),n.d(t,"asin",(function(){return Rn})),n.d(t,"asinh",(function(){return Fn})),n.d(t,"atan",(function(){return Mn})),n.d(t,"atan2",(function(){return Dn})),n.d(t,"atanh",(function(){return Pn})),n.d(t,"avgPool",(function(){return Jn})),n.d(t,"avgPool3d",(function(){return er})),n.d(t,"basicLSTMCell",(function(){return ir})),n.d(t,"batchToSpaceND",(function(){return sr})),n.d(t,"batchNorm",(function(){return or})),n.d(t,"batchNorm2d",(function(){return ur})),n.d(t,"batchNorm3d",(function(){return cr})),n.d(t,"batchNorm4d",(function(){return lr})),n.d(t,"bincount",(function(){return dr})),n.d(t,"broadcastArgs",(function(){return pr})),n.d(t,"broadcastTo",(function(){return hr})),n.d(t,"buffer",(function(){return ne})),n.d(t,"cast",(function(){return se})),n.d(t,"ceil",(function(){return fr})),n.d(t,"clipByValue",(function(){return mr})),n.d(t,"clone",(function(){return oe})),n.d(t,"complex",(function(){return br.a})),n.d(t,"concat",(function(){return tr})),n.d(t,"concat1d",(function(){return gr})),n.d(t,"concat2d",(function(){return xr})),n.d(t,"concat3d",(function(){return vr})),n.d(t,"concat4d",(function(){return kr})),n.d(t,"conv1d",(function(){return wr})),n.d(t,"conv2d",(function(){return yr})),n.d(t,"conv2dTranspose",(function(){return Sr})),n.d(t,"conv3d",(function(){return _r})),n.d(t,"conv3dTranspose",(function(){return Or})),n.d(t,"cos",(function(){return Tr})),n.d(t,"cosh",(function(){return $r})),n.d(t,"cumprod",(function(){return Ar})),n.d(t,"cumsum",(function(){return Nr})),n.d(t,"denseBincount",(function(){return Er})),n.d(t,"depthToSpace",(function(){return Rr})),n.d(t,"depthwiseConv2d",(function(){return Fr})),n.d(t,"diag",(function(){return Mr})),n.d(t,"dilation2d",(function(){return Dr})),n.d(t,"div",(function(){return Zt})),n.d(t,"divNoNan",(function(){return jr})),n.d(t,"dot",(function(){return Lr})),n.d(t,"einsum",(function(){return zr})),n.d(t,"elu",(function(){return Wr})),n.d(t,"equal",(function(){return Pr})),n.d(t,"erf",(function(){return Gr})),n.d(t,"exp",(function(){return Ur})),n.d(t,"expandDims",(function(){return Vr})),n.d(t,"expm1",(function(){return Hr})),n.d(t,"eye",(function(){return Kr})),n.d(t,"fill",(function(){return hn})),n.d(t,"floor",(function(){return Xr})),n.d(t,"floorDiv",(function(){return Yt})),n.d(t,"gather",(function(){return Yr})),n.d(t,"greater",(function(){return Zr})),n.d(t,"greaterEqual",(function(){return Qr})),n.d(t,"imag",(function(){return Jr})),n.d(t,"isFinite",(function(){return ea})),n.d(t,"isInf",(function(){return ta})),n.d(t,"isNaN",(function(){return na})),n.d(t,"leakyRelu",(function(){return ra})),n.d(t,"less",(function(){return aa})),n.d(t,"lessEqual",(function(){return ia})),n.d(t,"linspace",(function(){return sa})),n.d(t,"localResponseNormalization",(function(){return oa})),n.d(t,"log",(function(){return ua})),n.d(t,"log1p",(function(){return ca})),n.d(t,"logSigmoid",(function(){return pa})),n.d(t,"logSoftmax",(function(){return ma})),n.d(t,"logSumExp",(function(){return Sa})),n.d(t,"logicalAnd",(function(){return _a})),n.d(t,"logicalNot",(function(){return Ca})),n.d(t,"logicalOr",(function(){return Oa})),n.d(t,"logicalXor",(function(){return Ta})),n.d(t,"lowerBound",(function(){return Na})),n.d(t,"matMul",(function(){return $e})),n.d(t,"max",(function(){return ha})),n.d(t,"maxPool",(function(){return Ea})),n.d(t,"maxPool3d",(function(){return Ra})),n.d(t,"maxPoolWithArgmax",(function(){return Fa})),n.d(t,"maximum",(function(){return vn})),n.d(t,"mean",(function(){return Ma})),n.d(t,"meshgrid",(function(){return Ba})),n.d(t,"min",(function(){return ja})),n.d(t,"minimum",(function(){return La})),n.d(t,"mirrorPad",(function(){return za})),n.d(t,"mod",(function(){return Wa})),n.d(t,"moments",(function(){return Ga})),n.d(t,"mul",(function(){return Qt})),n.d(t,"multiRNNCell",(function(){return Ua})),n.d(t,"multinomial",(function(){return Va})),n.d(t,"neg",(function(){return la})),n.d(t,"notEqual",(function(){return Ha})),n.d(t,"oneHot",(function(){return Ae})),n.d(t,"ones",(function(){return Pa})),n.d(t,"onesLike",(function(){return qa})),n.d(t,"outerProduct",(function(){return Ka})),n.d(t,"pad",(function(){return Xa})),n.d(t,"pad1d",(function(){return Ya})),n.d(t,"pad2d",(function(){return Za})),n.d(t,"pad3d",(function(){return Qa})),n.d(t,"pad4d",(function(){return Ja})),n.d(t,"pool",(function(){return ti})),n.d(t,"pow",(function(){return mn})),n.d(t,"prelu",(function(){return ni})),n.d(t,"print",(function(){return ue})),n.d(t,"prod",(function(){return ri})),n.d(t,"rand",(function(){return ai})),n.d(t,"randomGamma",(function(){return ci})),n.d(t,"randomNormal",(function(){return li})),n.d(t,"randomUniform",(function(){return di})),n.d(t,"range",(function(){return pi})),n.d(t,"real",(function(){return hi})),n.d(t,"reciprocal",(function(){return fi})),n.d(t,"relu",(function(){return mi})),n.d(t,"relu6",(function(){return bi})),n.d(t,"reshape",(function(){return Qn})),n.d(t,"reverse",(function(){return gi})),n.d(t,"reverse1d",(function(){return xi})),n.d(t,"reverse2d",(function(){return vi})),n.d(t,"reverse3d",(function(){return ki})),n.d(t,"reverse4d",(function(){return yi})),n.d(t,"round",(function(){return wi})),n.d(t,"rsqrt",(function(){return Ii})),n.d(t,"scalar",(function(){return ln})),n.d(t,"selu",(function(){return Si})),n.d(t,"separableConv2d",(function(){return _i})),n.d(t,"setdiff1dAsync",(function(){return Ci})),n.d(t,"sigmoid",(function(){return nr})),n.d(t,"sign",(function(){return Oi})),n.d(t,"sin",(function(){return Ti})),n.d(t,"sinh",(function(){return $i})),n.d(t,"slice",(function(){return rr})),n.d(t,"slice1d",(function(){return Ai})),n.d(t,"slice2d",(function(){return Ni})),n.d(t,"slice3d",(function(){return Ei})),n.d(t,"slice4d",(function(){return Ri})),n.d(t,"softmax",(function(){return Fi})),n.d(t,"softplus",(function(){return da})),n.d(t,"spaceToBatchND",(function(){return ei})),n.d(t,"fft",(function(){return Mi})),n.d(t,"ifft",(function(){return Di})),n.d(t,"irfft",(function(){return Pi})),n.d(t,"rfft",(function(){return ji})),n.d(t,"split",(function(){return Bi})),n.d(t,"sqrt",(function(){return Jt})),n.d(t,"square",(function(){return en})),n.d(t,"squaredDifference",(function(){return Li})),n.d(t,"squeeze",(function(){return zi})),n.d(t,"stack",(function(){return Wi})),n.d(t,"step",(function(){return Gi})),n.d(t,"stridedSlice",(function(){return Ui})),n.d(t,"sub",(function(){return bn})),n.d(t,"sum",(function(){return fa})),n.d(t,"tan",(function(){return Vi})),n.d(t,"tanh",(function(){return ar})),n.d(t,"tensor",(function(){return Hi.a})),n.d(t,"tensor1d",(function(){return qi})),n.d(t,"tensor2d",(function(){return Ki})),n.d(t,"tensor3d",(function(){return Be})),n.d(t,"tensor4d",(function(){return Xi})),n.d(t,"tensor5d",(function(){return Yi})),n.d(t,"tensor6d",(function(){return Zi})),n.d(t,"tile",(function(){return qr})),n.d(t,"topk",(function(){return Qi})),n.d(t,"truncatedNormal",(function(){return Ji})),n.d(t,"unique",(function(){return es})),n.d(t,"unsortedSegmentSum",(function(){return ts})),n.d(t,"unstack",(function(){return ns})),n.d(t,"upperBound",(function(){return rs})),n.d(t,"variable",(function(){return as})),n.d(t,"where",(function(){return Br})),n.d(t,"whereAsync",(function(){return ss})),n.d(t,"zeros",(function(){return Da})),n.d(t,"zerosLike",(function(){return tn})),n.d(t,"booleanMaskAsync",(function(){return os})),n.d(t,"transpose",(function(){return Ne})),n.d(t,"norm",(function(){return cs})),n.d(t,"movingAverage",(function(){return ls})),n.d(t,"scatterND",(function(){return ds})),n.d(t,"searchSorted",(function(){return Aa})),n.d(t,"sparseToDense",(function(){return ps})),n.d(t,"gatherND",(function(){return hs})),n.d(t,"dropout",(function(){return fs})),n.d(t,"enclosingPowerOfTwo",(function(){return ms})),n.d(t,"cosineWindow",(function(){return bs})),n.d(t,"inTopKAsync",(function(){return gs})),n.d(t,"op",(function(){return ie.b})),n.d(t,"OP_SCOPE_SUFFIX",(function(){return ie.a})),n.d(t,"image",(function(){return Co})),n.d(t,"linalg",(function(){return Oo})),n.d(t,"losses",(function(){return To})),n.d(t,"spectral",(function(){return So})),n.d(t,"fused",(function(){return p})),n.d(t,"signal",(function(){return _o})),n.d(t,"sparse",(function(){return $o})),n.d(t,"string",(function(){return Ao})),n.d(t,"Reduction",(function(){return so})),n.d(t,"train",(function(){return No})),n.d(t,"enableProdMode",(function(){return Tt})),n.d(t,"enableDebugMode",(function(){return $t})),n.d(t,"disableDeprecationWarnings",(function(){return At})),n.d(t,"deprecationWarn",(function(){return Nt})),n.d(t,"disposeVariables",(function(){return Et})),n.d(t,"engine",(function(){return Rt})),n.d(t,"memory",(function(){return Ft})),n.d(t,"profile",(function(){return Mt})),n.d(t,"tidy",(function(){return Dt})),n.d(t,"dispose",(function(){return Pt})),n.d(t,"keep",(function(){return Bt})),n.d(t,"time",(function(){return jt})),n.d(t,"setBackend",(function(){return Lt})),n.d(t,"ready",(function(){return zt})),n.d(t,"getBackend",(function(){return Wt})),n.d(t,"removeBackend",(function(){return Gt})),n.d(t,"findBackend",(function(){return Ut})),n.d(t,"findBackendFactory",(function(){return Vt})),n.d(t,"registerBackend",(function(){return Ht})),n.d(t,"backend",(function(){return qt})),n.d(t,"setPlatform",(function(){return Kt})),n.d(t,"getKernel",(function(){return De.c})),n.d(t,"getGradient",(function(){return De.b})),n.d(t,"getKernelsForBackend",(function(){return De.d})),n.d(t,"registerKernel",(function(){return De.f})),n.d(t,"registerGradient",(function(){return De.e})),n.d(t,"unregisterKernel",(function(){return De.h})),n.d(t,"unregisterGradient",(function(){return De.g})),n.d(t,"copyRegisteredKernels",(function(){return De.a})),n.d(t,"customGrad",(function(){return un})),n.d(t,"grad",(function(){return nn})),n.d(t,"grads",(function(){return rn})),n.d(t,"valueAndGrad",(function(){return an})),n.d(t,"valueAndGrads",(function(){return sn})),n.d(t,"variableGrads",(function(){return on})),n.d(t,"Environment",(function(){return g.b})),n.d(t,"env",(function(){return g.c})),n.d(t,"ENV",(function(){return g.a})),n.d(t,"version_core",(function(){return Ot})),n.d(t,"nextFrame",(function(){return Eo.a})),n.d(t,"browser",(function(){return s})),n.d(t,"io",(function(){return r})),n.d(t,"math",(function(){return a})),n.d(t,"serialization",(function(){return l})),n.d(t,"test_util",(function(){return d})),n.d(t,"util",(function(){return mt})),n.d(t,"backend_util",(function(){return f})),n.d(t,"broadcast_util",(function(){return i})),n.d(t,"tensor_util",(function(){return Te})),n.d(t,"slice_util",(function(){return c})),n.d(t,"gather_util",(function(){return o})),n.d(t,"scatter_util",(function(){return u})),n.d(t,"device_util",(function(){return Eu})),n.d(t,"kernel_impls",(function(){return m})),n.d(t,"KernelBackend",(function(){return Ru.b})),n.d(t,"DataStorage",(function(){return Ru.a})),n.d(t,"Abs",(function(){return re.a})),n.d(t,"Acos",(function(){return re.b})),n.d(t,"Acosh",(function(){return re.c})),n.d(t,"Add",(function(){return re.d})),n.d(t,"AddN",(function(){return re.e})),n.d(t,"All",(function(){return re.f})),n.d(t,"Any",(function(){return re.g})),n.d(t,"ArgMax",(function(){return re.h})),n.d(t,"ArgMin",(function(){return re.i})),n.d(t,"Asin",(function(){return re.j})),n.d(t,"Asinh",(function(){return re.k})),n.d(t,"Atan",(function(){return re.l})),n.d(t,"Atanh",(function(){return re.n})),n.d(t,"Atan2",(function(){return re.m})),n.d(t,"AvgPool",(function(){return re.o})),n.d(t,"AvgPoolGrad",(function(){return re.r})),n.d(t,"AvgPool3D",(function(){return re.p})),n.d(t,"AvgPool3DGrad",(function(){return re.q})),n.d(t,"BatchMatMul",(function(){return re.s})),n.d(t,"BatchToSpaceND",(function(){return re.t})),n.d(t,"Bincount",(function(){return re.u})),n.d(t,"BroadcastTo",(function(){return re.w})),n.d(t,"BroadcastArgs",(function(){return re.v})),n.d(t,"Cast",(function(){return re.x})),n.d(t,"Ceil",(function(){return re.y})),n.d(t,"ClipByValue",(function(){return re.z})),n.d(t,"Complex",(function(){return re.A})),n.d(t,"ComplexAbs",(function(){return re.B})),n.d(t,"Concat",(function(){return re.C})),n.d(t,"Conv2D",(function(){return re.D})),n.d(t,"Conv2DBackpropFilter",(function(){return re.E})),n.d(t,"Conv2DBackpropInput",(function(){return re.F})),n.d(t,"Conv3D",(function(){return re.G})),n.d(t,"Conv3DBackpropFilterV2",(function(){return re.H})),n.d(t,"Conv3DBackpropInputV2",(function(){return re.I})),n.d(t,"Cos",(function(){return re.J})),n.d(t,"Cosh",(function(){return re.K})),n.d(t,"Cumprod",(function(){return re.M})),n.d(t,"Cumsum",(function(){return re.N})),n.d(t,"CropAndResize",(function(){return re.L})),n.d(t,"DenseBincount",(function(){return re.O})),n.d(t,"DepthToSpace",(function(){return re.P})),n.d(t,"DepthwiseConv2dNative",(function(){return re.Q})),n.d(t,"DepthwiseConv2dNativeBackpropFilter",(function(){return re.R})),n.d(t,"DepthwiseConv2dNativeBackpropInput",(function(){return re.S})),n.d(t,"Diag",(function(){return re.T})),n.d(t,"Dilation2D",(function(){return re.U})),n.d(t,"Dilation2DBackpropInput",(function(){return re.W})),n.d(t,"Dilation2DBackpropFilter",(function(){return re.V})),n.d(t,"RealDiv",(function(){return re.oc})),n.d(t,"Einsum",(function(){return re.X})),n.d(t,"Elu",(function(){return re.Y})),n.d(t,"EluGrad",(function(){return re.Z})),n.d(t,"Erf",(function(){return re.bb})),n.d(t,"Equal",(function(){return re.ab})),n.d(t,"Exp",(function(){return re.cb})),n.d(t,"ExpandDims",(function(){return re.db})),n.d(t,"Expm1",(function(){return re.eb})),n.d(t,"FFT",(function(){return re.fb})),n.d(t,"Fill",(function(){return re.gb})),n.d(t,"FlipLeftRight",(function(){return re.hb})),n.d(t,"Floor",(function(){return re.ib})),n.d(t,"FloorDiv",(function(){return re.jb})),n.d(t,"FusedBatchNorm",(function(){return re.lb})),n.d(t,"GatherV2",(function(){return re.pb})),n.d(t,"GatherNd",(function(){return re.ob})),n.d(t,"Greater",(function(){return re.qb})),n.d(t,"GreaterEqual",(function(){return re.rb})),n.d(t,"Identity",(function(){return re.tb})),n.d(t,"IFFT",(function(){return re.sb})),n.d(t,"Imag",(function(){return re.ub})),n.d(t,"IsFinite",(function(){return re.vb})),n.d(t,"IsInf",(function(){return re.wb})),n.d(t,"IsNan",(function(){return re.xb})),n.d(t,"LeakyRelu",(function(){return re.Ab})),n.d(t,"Less",(function(){return re.Bb})),n.d(t,"LessEqual",(function(){return re.Cb})),n.d(t,"LinSpace",(function(){return re.Db})),n.d(t,"Log",(function(){return re.Eb})),n.d(t,"Log1p",(function(){return re.Fb})),n.d(t,"LogicalAnd",(function(){return re.Hb})),n.d(t,"LogicalNot",(function(){return re.Ib})),n.d(t,"LogicalOr",(function(){return re.Jb})),n.d(t,"LogSoftmax",(function(){return re.Gb})),n.d(t,"LowerBound",(function(){return re.Kb})),n.d(t,"LRN",(function(){return re.yb})),n.d(t,"LRNGrad",(function(){return re.zb})),n.d(t,"Max",(function(){return re.Lb})),n.d(t,"Maximum",(function(){return re.Rb})),n.d(t,"MaxPool",(function(){return re.Mb})),n.d(t,"MaxPoolGrad",(function(){return re.Pb})),n.d(t,"MaxPool3D",(function(){return re.Nb})),n.d(t,"MaxPool3DGrad",(function(){return re.Ob})),n.d(t,"MaxPoolWithArgmax",(function(){return re.Qb})),n.d(t,"Mean",(function(){return re.Sb})),n.d(t,"Min",(function(){return re.Tb})),n.d(t,"Minimum",(function(){return re.Ub})),n.d(t,"MirrorPad",(function(){return re.Vb})),n.d(t,"Mod",(function(){return re.Wb})),n.d(t,"Multinomial",(function(){return re.Xb})),n.d(t,"Multiply",(function(){return re.Yb})),n.d(t,"Neg",(function(){return re.Zb})),n.d(t,"NotEqual",(function(){return re.dc})),n.d(t,"NonMaxSuppressionV3",(function(){return re.ac})),n.d(t,"NonMaxSuppressionV4",(function(){return re.bc})),n.d(t,"NonMaxSuppressionV5",(function(){return re.cc})),n.d(t,"OnesLike",(function(){return re.fc})),n.d(t,"OneHot",(function(){return re.ec})),n.d(t,"Pack",(function(){return re.gc})),n.d(t,"PadV2",(function(){return re.hc})),n.d(t,"Pool",(function(){return re.ic})),n.d(t,"Pow",(function(){return re.jc})),n.d(t,"Prelu",(function(){return re.kc})),n.d(t,"Prod",(function(){return re.lc})),n.d(t,"Range",(function(){return re.mc})),n.d(t,"Real",(function(){return re.nc})),n.d(t,"Reciprocal",(function(){return re.pc})),n.d(t,"Relu",(function(){return re.qc})),n.d(t,"Reshape",(function(){return re.sc})),n.d(t,"ResizeNearestNeighbor",(function(){return re.vc})),n.d(t,"ResizeNearestNeighborGrad",(function(){return re.wc})),n.d(t,"ResizeBilinear",(function(){return re.tc})),n.d(t,"ResizeBilinearGrad",(function(){return re.uc})),n.d(t,"Relu6",(function(){return re.rc})),n.d(t,"Reverse",(function(){return re.xc})),n.d(t,"Round",(function(){return re.zc})),n.d(t,"Rsqrt",(function(){return re.Ac})),n.d(t,"ScatterNd",(function(){return re.Bc})),n.d(t,"SearchSorted",(function(){return re.Cc})),n.d(t,"Select",(function(){return re.Dc})),n.d(t,"Selu",(function(){return re.Ec})),n.d(t,"Slice",(function(){return re.Jc})),n.d(t,"Sin",(function(){return re.Hc})),n.d(t,"Sinh",(function(){return re.Ic})),n.d(t,"Sign",(function(){return re.Gc})),n.d(t,"Sigmoid",(function(){return re.Fc})),n.d(t,"Softplus",(function(){return re.Lc})),n.d(t,"Sqrt",(function(){return re.Tc})),n.d(t,"Sum",(function(){return re.cd})),n.d(t,"SpaceToBatchND",(function(){return re.Mc})),n.d(t,"SplitV",(function(){return re.Sc})),n.d(t,"Softmax",(function(){return re.Kc})),n.d(t,"SparseFillEmptyRows",(function(){return re.Nc})),n.d(t,"SparseReshape",(function(){return re.Oc})),n.d(t,"SparseSegmentMean",(function(){return re.Pc})),n.d(t,"SparseSegmentSum",(function(){return re.Qc})),n.d(t,"SparseToDense",(function(){return re.Rc})),n.d(t,"SquaredDifference",(function(){return re.Vc})),n.d(t,"Square",(function(){return re.Uc})),n.d(t,"StridedSlice",(function(){return re.Xc})),n.d(t,"StringNGrams",(function(){return re.Yc})),n.d(t,"StringSplit",(function(){return re.Zc})),n.d(t,"StringToHashBucketFast",(function(){return re.ad})),n.d(t,"Sub",(function(){return re.bd})),n.d(t,"Tan",(function(){return re.dd})),n.d(t,"Tanh",(function(){return re.ed})),n.d(t,"Tile",(function(){return re.fd})),n.d(t,"TopK",(function(){return re.gd})),n.d(t,"Transform",(function(){return re.hd})),n.d(t,"Transpose",(function(){return re.id})),n.d(t,"Unique",(function(){return re.jd})),n.d(t,"Unpack",(function(){return re.kd})),n.d(t,"UnsortedSegmentSum",(function(){return re.ld})),n.d(t,"UpperBound",(function(){return re.md})),n.d(t,"ZerosLike",(function(){return re.nd})),n.d(t,"Step",(function(){return re.Wc})),n.d(t,"FromPixels",(function(){return re.kb})),n.d(t,"RotateWithOffset",(function(){return re.yc})),n.d(t,"_FusedMatMul",(function(){return re.od})),n.d(t,"FusedConv2D",(function(){return re.mb})),n.d(t,"FusedDepthwiseConv2D",(function(){return re.nb}));var r={};n.r(r),n.d(r,"copyModel",(function(){return Q})),n.d(r,"listModels",(function(){return Y})),n.d(r,"moveModel",(function(){return J})),n.d(r,"removeModel",(function(){return Z})),n.d(r,"browserFiles",(function(){return he})),n.d(r,"browserHTTPRequest",(function(){return Ie})),n.d(r,"concatenateArrayBuffers",(function(){return x.d})),n.d(r,"decodeWeights",(function(){return x.e})),n.d(r,"encodeWeights",(function(){return x.f})),n.d(r,"fromMemory",(function(){return Ce})),n.d(r,"getLoadHandlers",(function(){return I})),n.d(r,"getModelArtifactsForJSON",(function(){return x.g})),n.d(r,"getModelArtifactsInfoForJSON",(function(){return x.h})),n.d(r,"getSaveHandlers",(function(){return w})),n.d(r,"http",(function(){return we})),n.d(r,"isHTTPScheme",(function(){return ke})),n.d(r,"loadWeights",(function(){return ge})),n.d(r,"registerLoadRouter",(function(){return y})),n.d(r,"registerSaveRouter",(function(){return k})),n.d(r,"weightsLoaderFactory",(function(){return xe})),n.d(r,"withSaveHandler",(function(){return Oe}));var a={};n.r(a),n.d(a,"confusionMatrix",(function(){return Ee}));var i={};n.r(i),n.d(i,"getBroadcastDims",(function(){return Re})),n.d(i,"getReductionAxes",(function(){return Fe})),n.d(i,"assertAndGetBroadcastShape",(function(){return Me}));var s={};n.r(s),n.d(s,"fromPixelsAsync",(function(){return We})),n.d(s,"toPixels",(function(){return Ge})),n.d(s,"fromPixels",(function(){return Ue}));var o={};n.r(o),n.d(o,"prepareAndValidate",(function(){return Ve}));var u={};n.r(u),n.d(u,"validateUpdateShape",(function(){return He})),n.d(u,"validateInput",(function(){return qe})),n.d(u,"calculateShapes",(function(){return Ke}));var c={};n.r(c),n.d(c,"assertParamsValid",(function(){return Xe})),n.d(c,"maskToAxes",(function(){return Ye})),n.d(c,"computeOutShape",(function(){return Ze})),n.d(c,"stridesWithElidedDims",(function(){return Qe})),n.d(c,"getNormalizedAxes",(function(){return tt})),n.d(c,"startIndicesWithElidedDims",(function(){return nt})),n.d(c,"stopIndicesWithElidedDims",(function(){return rt})),n.d(c,"stridesForAxis",(function(){return at})),n.d(c,"startForAxis",(function(){return it})),n.d(c,"stopForAxis",(function(){return st})),n.d(c,"isSliceContinous",(function(){return ot})),n.d(c,"computeFlatOffset",(function(){return ut})),n.d(c,"parseSliceParams",(function(){return ct})),n.d(c,"sliceInfo",(function(){return lt}));var l={};n.r(l),n.d(l,"Serializable",(function(){return pt})),n.d(l,"SerializationMap",(function(){return ht})),n.d(l,"registerClass",(function(){return ft}));var d={};n.r(d),n.d(d,"TEST_EPSILON_FLOAT16",(function(){return bt})),n.d(d,"expectArraysClose",(function(){return gt})),n.d(d,"testEpsilon",(function(){return xt})),n.d(d,"expectPromiseToFail",(function(){return kt})),n.d(d,"expectArraysEqual",(function(){return yt})),n.d(d,"expectNumbersClose",(function(){return wt})),n.d(d,"expectValuesInRange",(function(){return St})),n.d(d,"expectArrayBuffersEqual",(function(){return _t})),n.d(d,"encodeStrings",(function(){return Ct}));var p={};n.r(p),n.d(p,"conv2d",(function(){return Is})),n.d(p,"depthwiseConv2d",(function(){return Cs})),n.d(p,"matMul",(function(){return Os}));var h={};n.r(h),n.d(h,"segOpComputeOptimalWindowSize",(function(){return Ou})),n.d(h,"computeOutShape",(function(){return Tu})),n.d(h,"collectGatherOpShapeInfo",(function(){return $u}));var f={};n.r(f),n.d(f,"axesAreInnerMostDims",(function(){return ba})),n.d(f,"combineLocations",(function(){return ga})),n.d(f,"computeOutAndReduceShapes",(function(){return xa})),n.d(f,"expandShapeToKeepDim",(function(){return va})),n.d(f,"assertAxesAreInnerMostDims",(function(){return ka})),n.d(f,"getAxesPermutation",(function(){return ya})),n.d(f,"getUndoAxesPermutation",(function(){return wa})),n.d(f,"getInnerMostAxes",(function(){return Ia})),n.d(f,"getBroadcastDims",(function(){return Re})),n.d(f,"getReductionAxes",(function(){return Fe})),n.d(f,"assertAndGetBroadcastShape",(function(){return Me})),n.d(f,"assertParamsConsistent",(function(){return Ro})),n.d(f,"computeOutShape",(function(){return Fo})),n.d(f,"computeDilation2DInfo",(function(){return Bn})),n.d(f,"computePool2DInfo",(function(){return jn})),n.d(f,"computePool3DInfo",(function(){return Ln})),n.d(f,"computeConv2DInfo",(function(){return zn})),n.d(f,"computeConv3DInfo",(function(){return Wn})),n.d(f,"computeDefaultPad",(function(){return Gn})),n.d(f,"tupleValuesAreOne",(function(){return Kn})),n.d(f,"eitherStridesOrDilationsAreOne",(function(){return Xn})),n.d(f,"convertConv2DDataFormat",(function(){return Yn})),n.d(f,"checkPadOnDimRoundingMode",(function(){return Zn})),n.d(f,"getFusedDyActivation",(function(){return vs})),n.d(f,"getFusedBiasGradient",(function(){return ks})),n.d(f,"applyActivation",(function(){return ys})),n.d(f,"shouldFuse",(function(){return ws})),n.d(f,"PARALLELIZE_THRESHOLD",(function(){return Mo})),n.d(f,"computeOptimalWindowSize",(function(){return Do})),n.d(f,"slice_util",(function(){return c})),n.d(f,"upcastType",(function(){return _n.c})),n.d(f,"getImageCenter",(function(){return Po})),n.d(f,"getReshaped",(function(){return Bo})),n.d(f,"getPermuted",(function(){return jo})),n.d(f,"getReshapedPermuted",(function(){return Lo})),n.d(f,"getSliceBeginCoords",(function(){return zo})),n.d(f,"getSliceSize",(function(){return Wo})),n.d(f,"prepareAndValidate",(function(){return Ve})),n.d(f,"validateUpdateShape",(function(){return He})),n.d(f,"validateInput",(function(){return qe})),n.d(f,"calculateShapes",(function(){return Ke})),n.d(f,"SELU_SCALEALPHA",(function(){return Go})),n.d(f,"SELU_SCALE",(function(){return Uo})),n.d(f,"ERF_P",(function(){return Vo})),n.d(f,"ERF_A1",(function(){return Ho})),n.d(f,"ERF_A2",(function(){return qo})),n.d(f,"ERF_A3",(function(){return Ko})),n.d(f,"ERF_A4",(function(){return Xo})),n.d(f,"ERF_A5",(function(){return Yo})),n.d(f,"warn",(function(){return Zo.b})),n.d(f,"log",(function(){return Zo.a})),n.d(f,"mergeRealAndImagArrays",(function(){return Qo})),n.d(f,"splitRealAndImagArrays",(function(){return Jo})),n.d(f,"complexWithEvenIndex",(function(){return eu})),n.d(f,"complexWithOddIndex",(function(){return tu})),n.d(f,"getComplexWithIndex",(function(){return nu})),n.d(f,"assignToTypedArray",(function(){return ru})),n.d(f,"exponents",(function(){return au})),n.d(f,"exponent",(function(){return iu})),n.d(f,"decodeEinsumEquation",(function(){return uu})),n.d(f,"getEinsumPermutation",(function(){return cu})),n.d(f,"checkEinsumDimSizes",(function(){return lu})),n.d(f,"getEinsumComputePath",(function(){return du})),n.d(f,"isIdentityPermutation",(function(){return pu})),n.d(f,"prepareSplitSize",(function(){return fu})),n.d(f,"getSparseFillEmptyRowsIndicesDenseShapeMismatch",(function(){return mu})),n.d(f,"getSparseFillEmptyRowsNegativeIndexErrorMessage",(function(){return bu})),n.d(f,"getSparseFillEmptyRowsOutOfRangeIndexErrorMessage",(function(){return gu})),n.d(f,"getSparseReshapeMultipleNegativeOneOutputDimErrorMessage",(function(){return xu})),n.d(f,"getSparseReshapeNegativeOutputDimErrorMessage",(function(){return vu})),n.d(f,"getSparseReshapeEmptyTensorZeroOutputDimErrorMessage",(function(){return ku})),n.d(f,"getSparseReshapeInputOutputMultipleErrorMessage",(function(){return yu})),n.d(f,"getSparseReshapeInputOutputMismatchErrorMessage",(function(){return wu})),n.d(f,"getSparseSegmentReductionNegativeSegmentIdsErrorMessage",(function(){return Iu})),n.d(f,"getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage",(function(){return Su})),n.d(f,"getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage",(function(){return _u})),n.d(f,"getSparseSegmentReductionIndicesOutOfRangeErrorMessage",(function(){return Cu})),n.d(f,"segment_util",(function(){return h})),n.d(f,"fromUint8ToStringArray",(function(){return Au})),n.d(f,"fromStringArrayToUint8",(function(){return Nu}));var m={};n.r(m),n.d(m,"nonMaxSuppressionV3Impl",(function(){return Ls})),n.d(m,"nonMaxSuppressionV4Impl",(function(){return zs})),n.d(m,"nonMaxSuppressionV5Impl",(function(){return Ws})),n.d(m,"whereImpl",(function(){return is}));var b=n(3),g=(n(49),n(9)),x=n(17); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class v{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==v.instance&&(v.instance=new v),v.instance}static registerSaveRouter(e){v.getInstance().saveRouters.push(e)}static registerLoadRouter(e){v.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return v.getHandlers(e,"save")}static getLoadHandlers(e,t){return v.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?v.getInstance().loadRouters:v.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&r.push(a)})),r}}const k=e=>v.registerSaveRouter(e),y=e=>v.registerLoadRouter(e),w=e=>v.getSaveHandlers(e),I=(e,t)=>v.getLoadHandlers(e,t) +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */,S="tensorflowjs",_="models_store",C="model_info_store";function O(){if(!Object(g.c)().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 T(e){const t=e.result;t.createObjectStore(_,{keyPath:"modelPath"}),t.createObjectStore(C,{keyPath:"modelPath"})}class ${constructor(e){if(this.indexedDB=O(),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 r=this.indexedDB.open(S,1);r.onupgradeneeded=()=>T(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(_,"readonly"),r=t.objectStore(_).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{const r=Object(x.h)(t),i=a.transaction(C,"readwrite");let s=i.objectStore(C);const o=s.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;o.onsuccess=()=>{u=a.transaction(_,"readwrite");const o=u.objectStore(_).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});o.onsuccess=()=>e({modelArtifactsInfo:r}),o.onerror=e=>{s=i.objectStore(C);const t=s.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(o.error)),t.onerror=e=>(a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),i.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)}))}}$.URL_SCHEME="indexeddb://";const A=e=>{return Object(g.c)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($.URL_SCHEME)?(t=e.slice($.URL_SCHEME.length),new $(t)):null;var t};v.registerSaveRouter(A),v.registerLoadRouter(A);class N{constructor(){this.indexedDB=O()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(S,1);n.onupgradeneeded=()=>T(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(C,"readonly"),i=a.objectStore(C).getAll();i.onsuccess=()=>{const t={};for(const e of i.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},i.onerror=e=>(r.close(),t(i.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith($.URL_SCHEME)?t.slice($.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(S,1);r.onupgradeneeded=()=>T(r),r.onsuccess=()=>{const a=r.result,i=a.transaction(C,"readwrite"),s=i.objectStore(C),o=s.get(e);let u;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=s.delete(e),i=()=>{u=a.transaction(_,"readwrite");const r=u.objectStore(_).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=i,r.onerror=e=>(i(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),i.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)}))}}var E=n(15); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const R="/",F="tensorflowjs_models",M="info",D="model_topology",P="weight_specs",B="weight_data",j="model_metadata";function L(e){return{info:[F,e,M].join(R),topology:[F,e,D].join(R),weightSpecs:[F,e,P].join(R),weightData:[F,e,B].join(R),modelMetadata:[F,e,j].join(R)}}function z(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function W(e){const t=e.split(R);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(R)}class G{constructor(e){if(!Object(g.c)().getBool("IS_BROWSER")||"undefined"==typeof window||"undefined"==typeof 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=L(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),r=Object(x.h)(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,Object(x.a)(e.weightData));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,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw z(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){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 r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);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.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const i=this.LS.getItem(this.keys.weightData);if(null==i)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=Object(x.b)(i),t}}G.URL_SCHEME="localstorage://";const U=e=>{return Object(g.c)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(G.URL_SCHEME)?(t=e.slice(G.URL_SCHEME.length),new G(t)):null;var t};v.registerSaveRouter(U),v.registerLoadRouter(U);class V{constructor(){Object(E.b)(Object(g.c)().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),Object(E.b)("undefined"==typeof window||"undefined"!=typeof window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=F+R,n=R+M;for(let r=0;r"scheme must not be undefined or null.")),e.endsWith(H)&&(e=e.slice(0,e.indexOf(H))),Object(E.b)(e.length>0,(()=>"scheme must not be an empty string."));const n=q.getInstance();Object(E.b)(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function K(e){if(-1===e.indexOf(H))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${q.getSchemes().join(",")}`);return{scheme:e.split(H)[0],path:e.split(H)[1]}}async function X(e,t,n=!1){Object(E.b)(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=v.getLoadHandlers(e);Object(E.b)(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),Object(E.b)(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const a=r[0],i=v.getSaveHandlers(t);Object(E.b)(i.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),Object(E.b)(i.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const s=i[0],o=K(e).scheme,u=K(e).path,c=o===K(e).scheme,l=await a.load();n&&c&&await q.getManager(o).removeModel(u);const d=await s.save(l);return n&&!c&&await q.getManager(o).removeModel(u),d.modelArtifactsInfo}async function Y(){const e=q.getSchemes(),t={};for(const n of e){const e=await q.getManager(n).listModels();for(const r in e){t[n+H+r]=e[r]}}return t}async function Z(e){const t=K(e);return q.getManager(t.scheme).removeModel(t.path)}async function Q(e,t){return X(e,t,!1)}async function J(e,t){return X(e,t,!0)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ee{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)}}if(Object(g.c)().get("IS_BROWSER")){Object(g.c)().setPlatform("browser",new ee);try{q.registerManager(G.URL_SCHEME,new V)}catch(e){}try{q.registerManager($.URL_SCHEME,new N)}catch(e){}}n(108);var te=n(14); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function ne(e,t="float32",n){return t=t||"float32",E.c(e),new te.b(e,t,n)}var re=n(4),ae=n(1),ie=n(2);const se=Object(ie.b)({cast_: +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Object(ae.a)(e,"x","cast");if(!E.B(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 r={x:n},a={dtype:t};return b.a.runKernel(re.x,r,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oe=Object(ie.b)({clone_:function(e){const t={x:Object(ae.a)(e,"x","clone","string_or_numeric")};return b.a.runKernel(re.tb,t)}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ue(e,t=!1){console.log(e.toString(t))} +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */Object(b.b)();const ce={buffer:ne,cast:se,clone:oe,print:ue};Object(te.e)(ce);function le(e){return new Promise((e=>setTimeout(e))).then(e)}class de{constructor(e){if(!Object(g.c)().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(de.URL_SCHEME)&&(e=e.slice(de.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=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r=Object(x.i)(e,n),a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),i=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(i.download=this.modelJsonFileName,i.href=a,await le((()=>i.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await le((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Object(x.h)(e)}}}}de.URL_SCHEME="downloads://";class pe{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 r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const i=Object(x.g)(r,(e=>this.loadWeights(e)));e(i)},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 r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(a).then((e=>[t,Object(x.d)(e)]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Object(x.c)(e.name))),r={};for(const a of e)a.paths.forEach((e=>{const a=Object(x.c)(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function he(e){return new pe(e)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function fe(e,t,n,r){!function(e){Object(E.b)(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){Object(E.b)(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),Object(E.b)(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),Object(E.b)(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let a=0;return Promise.all(e.map((i=>(i.then((i=>{const s=n+ ++a/e.length*(r-n);return t(s),i})),i))))}v.registerSaveRouter((e=>Object(g.c)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(de.URL_SCHEME)?function(e="model"){return new de(e)}(e.slice(de.URL_SCHEME.length)):null));var me=n(51); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */async function be(e,t){null==t&&(t={});const n=null==t.fetchFunc?Object(g.c)().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(r):await fe(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await fe(a,t.onProgress,.5,1)}async function ge(e,t="",n,r){return xe((e=>be(e,{requestInit:r})))(e,t,n)}function xe(e){return async(t,n="",r)=>{const a=t.map((()=>!1)),i={},s=null!=r?r.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,c=me.a[u]*E.O(e.shape),l=()=>{a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:n,sizeBytes:c})};null!=r?r.forEach(((t,n)=>{t===e.name&&(l(),s[n]=!0)})):l(),o.push(e.name),n+=c}))})),!s.every((e=>e))){const e=r.filter(((e,t)=>!s[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const u=a.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),c=[];u.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;c.push(t)}))}));const l=await e(c),d={};let p=0;return u.forEach((e=>{const n=t[e].paths.length;let r=0;for(let e=0;e{const t=a.slice(e.groupOffset,e.groupOffset+e.sizeBytes),n=Object(x.e)(t,[e.manifestEntry]);for(const e in n)d[e]=n[e]})),p+=n})),d}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ve{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(Object(E.b)("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=Object(g.c)().platform.fetch,Object(E.b)(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&Object(E.b)(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||{}}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=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=Object(x.i)(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:Object(x.h)(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.status}.`)}async load(){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,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Object(x.g)(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),a=n>t?e.substring(n):"";return[r+"/",a]}(t),a=this.weightPathPrefix||n,i=[];for(const t of e)i.push(...t.weights);const s=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):s.push(a+e+r);this.weightUrlConverter&&s.push(...await Promise.all(o));const u=await be(s,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Object(x.d)(u)]}}function ke(e){return null!=e.match(ve.URL_SCHEME_REGEX)}ve.URL_SCHEME_REGEX=/^https?:\/\//;const ye=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>ke(e))):ke(e),n)return we(e,t)}return null};function we(e,t){return new ve(e,t)}function Ie(e,t){return we(e,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */v.registerSaveRouter(ye),v.registerLoadRouter(ye);class Se{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class _e{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function Ce(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new Se(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 Se({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 Se({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function Oe(e){return new _e(e)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Te=n(10); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $e=Object(ie.b)({matMul_:function(e,t,n=!1,r=!1){let a=Object(ae.a)(e,"a","matMul"),i=Object(ae.a)(t,"b","matMul");[a,i]=Object(Te.makeTypesMatch)(a,i);const s={a:a,b:i},o={transposeA:n,transposeB:r};return b.a.runKernel(re.s,s,o)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ae=Object(ie.b)({oneHot_:function(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:Object(ae.a)(e,"indices","oneHot","int32")},i={depth:t,onValue:n,offValue:r};return b.a.runKernel(re.ec,a,i)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ne=Object(ie.b)({transpose_:function(e,t){const n=Object(ae.a)(e,"x","transpose");if(null==t&&(t=n.shape.map(((e,t)=>t)).reverse()),E.b(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`)),t.forEach((e=>{E.b(e>=0&&e"All entries in 'perm' must be between 0 and "+(n.rank-1)+` but got ${t}`))})),n.rank<=1)return n.clone();const r={x:n},a={perm:t};return b.a.runKernel(re.id,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ee=Object(ie.b)({confusionMatrix_:function(e,t,n){const r=Object(ae.a)(e,"labels","confusionMatrix"),a=Object(ae.a)(t,"predictions","confusionMatrix");E.b(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),E.b(1===r.rank,(()=>`Expected the rank of labels to be 1, but got ${r.rank}`)),E.b(1===a.rank,(()=>`Expected the rank of predictions to be 1, but got ${a.rank}`)),E.b(r.shape[0]===a.shape[0],(()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${a.shape[0]}. Labels and predictions should have the same number of elements.`)),E.b(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const i=Ae(se(r,"int32"),n),s=Ae(se(a,"int32"),n),o=Ne(i),u=$e(o,s);return se(u,"int32")}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Re(e,t){const n=e.length,r=[];for(let a=0;a1&&1===s&&r.unshift(i)}return r}function Fe(e,t){const n=[];for(let r=0;r1)&&n.unshift(i)}return n}function Me(e,t){const n=[],r=Math.max(e.length,t.length);for(let a=0;a4)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,r=!1,a=!1,i=!1,s=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)i=!0;else if(null!=e.getContext)s=!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(a){const t=2;if(a&&e.readyState element.")}if(null!=Object(De.c)(re.kb,b.a.backendName)){const n={pixels:e},r={numChannels:t};return b.a.runKernel(re.kb,n,r)}const[u,c]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let l,d;if(s)l=e.getContext("2d").getImageData(0,0,u,c).data;else if(r||n)l=e.data;else if(i||a||o){if(null==je)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.");je=new OffscreenCanvas(1,1).getContext("2d")}else je=document.createElement("canvas").getContext("2d");je.canvas.width=u,je.canvas.height=c,je.drawImage(e,0,0,u,c),l=je.getImageData(0,0,u,c).data}if(4===t)d=new Int32Array(l);else{const e=u*c;d=new Int32Array(e*t);for(let n=0;n4||2===i)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${i}`);if("float32"!==n.dtype&&"int32"!==n.dtype)throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const s=await n.data(),o="float32"===n.dtype?255:1,u=new Uint8ClampedArray(a*r*4);for(let e=0;e1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${a}.`)}else if("int32"===n.dtype&&(a<0||a>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${a}.`);1===i?(t[0]=a*o,t[1]=a*o,t[2]=a*o):t[r]=a*o}const r=4*e;u[r+0]=Math.round(t[0]),u[r+1]=Math.round(t[1]),u[r+2]=Math.round(t[2]),u[r+3]=Math.round(t[3])}if(null!=t){t.width=a,t.height=r;const e=t.getContext("2d"),n=new ImageData(u,a,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),u}const Ue=Object(ie.b)({fromPixels_:Le});function Ve(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===Object(E.O)(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,i=a[a.length-1];let s=1;for(let e=0;ee/c)),1].slice(0,i);return[u,s,c,l]}function He(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,i=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank1?t.shape[r-1]:1,i=n.length;let s=1;for(let e=a;e`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),E.b(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let a=0;a`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}function Ye(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function Ze(e,t,n){const r=[];for(let a=0;a0){const u=t[0],c=n+1;l=nt(s,u,c,r,e),d=rt(o,u,c,a,e),p=Qe(i,u,c,e)}else for(let t=0;t-1)i[a]=0;else{const s=Je(t,n,a);let o=r[s];e&1<-1)i[a]=Number.MAX_SAFE_INTEGER;else{const s=Je(t,n,a);let o=r[s];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[a];return s<0&&(s+=u),s=E.i(0,s,u-1),s}function st(e,t,n,r,a,i){let s=t[a];const o=n[a]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[a];return s<0&&(s+=u),s=o>0?E.i(0,s,u):E.i(-1,s,u-1),s}function ot(e,t,n){let r=n.length;for(let e=0;e1){r=e;break}for(let a=r+1;a0||n[a]!==e[a])return!1;return!0}function ut(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r{E.b(-1!==e,(()=>"slice() does not support negative begin indexing."))})),i=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.lengtht>=0?t:(E.b(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,i]}function lt(e,t,n,r,a,i,s,o,u){let c;if(null==r?(c=new Array(t.length),c.fill(1)):c=r,null!=s&&0!=(s&s-1))throw new Error("Multiple ellipses in slice is not allowed.");let l=!1;const d={dims:c.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:c.slice(),beginMask:a,endMask:i,ellipsisMask:s,newAxisMask:o,shrinkAxisMask:u};for(let e=0;e0?0:-1,p.strides[t]>0?r:r-1];if(n&&p.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[t];const s=!!(p.beginMask&1<=r)throw Error(`slice index ${p.begin[t]} of dimension ${t} out of bounds.`)}else p.begin[t]=dt(p.begin[t],0,p.strides[t],r,a,i),p.end[t]=dt(p.end[t],1,p.strides[t],r,a,i);const e=1===p.strides[t]&&0===p.begin[t]&&p.end[t]===r;h=h&&e,f=f&&(0===t&&1===p.strides[t]||e)}else h=h&&1===p.strides[t]&&s,f=f&&(0===t&&1===p.strides[t]||s);let o,u=!1;if(p.beginValid&&p.endValid?(o=p.end[t]-p.begin[t],u=!0):n?(o=1,u=!0):s&&r>=0&&(o=p.strides[t]<0?-r:r,u=!0),u){let e;e=0===o||o<0!=p.strides[t]<0?0:Math.trunc(o/p.strides[t])+(o%p.strides[t]!=0?1:0),b.push(e)}else b.push(-1)}for(let e=0;e=0?g.push(b[t]):-2===t&&g.push(1)}return{finalShapeSparse:g.filter(((e,t)=>-2!==p.finalShapeGatherIndices[t])),finalShape:g,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function dt(e,t,n,r,a,i){if(a[t])return n>0?i[t]:i[t+1&1];{const t=e<0?r+e:e;return ti[1]?i[1]:t}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pt{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class ht{constructor(){this.classNameMap={}}static getMap(){return null==ht.instance&&(ht.instance=new ht),ht.instance}static register(e){ht.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function ft(e){Object(E.b)(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),Object(E.b)("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),Object(E.b)(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),ht.register(e)}var mt=n(6); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bt=.1;function gt(e,t,n){return null==n&&(n=xt()),vt(e,t,((e,t)=>It(e,t,n)))}function xt(){return 32===b.a.backend.floatPrecision()?.001:bt}function vt(e,t,n){let r=!0;if((Object(E.A)(e)||Object(E.A)(t))&&(r=!1),Object(E.A)(e)&&Object(E.A)(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${r}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=Object(ae.c)(e),r=Object(ae.c)(t);if(!Object(E.a)(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const a=Object(E.A)(e)?e:Object(E.m)(e),i=Object(E.A)(t)?t:Object(E.m)(t);if(a.length!==i.length)throw new Error(`Arrays have different lengths actual: ${a.length} vs expected: ${i.length}.\nActual: ${a}.\nExpected: ${i}.`);for(let e=0;et.fail()),(()=>t()))}function yt(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return Object(E.z)(e)||Object(E.z)(e[0])||Object(E.z)(t)||Object(E.z)(t[0])?vt(e,n,((e,t)=>e==t)):vt(e,t,((e,t)=>It(e,t,0)))}function wt(e,t,n){if(null==n&&(n=xt()),!It(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function It(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function St(e,t,n){for(let r=0;rn)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function _t(e,t){const n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let e=0;ee.dispose()))}function Bt(e){return b.a.keep(e)}function jt(e){return b.a.time(e)}function Lt(e){return b.a.setBackend(e)}function zt(){return b.a.ready()}function Wt(){return b.a.backendName}function Gt(e){b.a.removeBackend(e)}function Ut(e){return b.a.findBackend(e)}function Vt(e){return b.a.findBackendFactory(e)}function Ht(e,t,n=1){return b.a.registerBackend(e,t,n)}function qt(){return b.a.backend}function Kt(e,t){Object(g.c)().setPlatform(e,t)} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */Object(te.d)(Nt);const Xt=Object(ie.b)({add_:function(e,t){let n=Object(ae.a)(e,"a","add"),r=Object(ae.a)(t,"b","add");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.d,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yt=Object(ie.b)({floorDiv_:function(e,t){let n=Object(ae.a)(e,"a","floorDiv"),r=Object(ae.a)(t,"b","floorDiv");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.jb,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zt=Object(ie.b)({div_:function(e,t){let n=Object(ae.a)(e,"a","div"),r=Object(ae.a)(t,"b","div");if([n,r]=Object(Te.makeTypesMatch)(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Yt(n,r);const a={a:n,b:r};return b.a.runKernel(re.oc,a,{})}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qt=Object(ie.b)({mul_:function(e,t){let n=Object(ae.a)(e,"a","mul"),r=Object(ae.a)(t,"b","mul");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.Yb,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jt=Object(ie.b)({sqrt_:function(e){const t={x:Object(ae.a)(e,"x","sqrt","float32")};return b.a.runKernel(re.Tc,t)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const en=Object(ie.b)({square_:function(e){const t=Object(ae.a)(e,"x","square");return b.a.runKernel("Square",{x:t},{})}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tn=Object(ie.b)({zerosLike_:function(e){const t={x:Object(ae.a)(e,"x","zerosLike")};return b.a.runKernel(re.nd,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nn(e){return E.b(E.u(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const r=Object(ae.a)(t,"x","tf.grad","string_or_numeric"),a=null!=n?Object(ae.a)(n,"dy","tf.grad"):null;return b.a.tidy((()=>{const{value:t,grads:n}=b.a.gradients((()=>e(r)),[r],a);return null!=a&&E.e(t.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),cn(n),n[0]}))}}function rn(e){return E.b(E.u(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{E.b(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const r=Object(ae.b)(t,"args","tf.grads","string_or_numeric"),a=null!=n?Object(ae.a)(n,"dy","tf.grads"):null;return b.a.tidy((()=>{const{value:t,grads:n}=b.a.gradients((()=>e(...r)),r,a);return null!=a&&E.e(t.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),cn(n),n}))}}function an(e){return E.b(E.u(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{E.b(t instanceof te.a,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),E.b(null==n||n instanceof te.a,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:r,value:a}=b.a.gradients((()=>e(t)),[t],n);return cn(r),{grad:r[0],value:a}}}function sn(e){return E.b(E.u(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{E.b(Array.isArray(t)&&t.every((e=>e instanceof te.a)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),E.b(null==n||n instanceof te.a,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const r=b.a.gradients((()=>e(...t)),t,n);return null!=n&&E.e(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),cn(r.grads),r}}function on(e,t){E.b(E.u(e),(()=>"The f passed in variableGrads(f) must be a function")),E.b(null==t||Array.isArray(t)&&t.every((e=>e instanceof te.c)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in b.a.registeredVariables)t.push(b.a.registeredVariables[e])}const r=n?t.filter((e=>!e.trainable)):null,a=t.length;t=t.filter((e=>e.trainable)),E.b(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:i,grads:s}=b.a.gradients(e,t,null,!0);E.b(s.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().")),E.b(0===i.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=s[t]&&(o[e.name]=s[t])})),null!=r&&r.forEach((e=>o[e.name]=null)),{value:i,grads:o}}function un(e){return b.a.customGrad(e)}function cn(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.")} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ln(e,t){if((Object(E.A)(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&&Object(E.A)(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Object(Pe.a)(e,[],[],t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class dn extends pt{minimize(e,t=!1,n){const{value:r,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return Pt(a),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return on(e,t)}dispose(){null!=this.iterations_&&Pt(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:ln(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(dn,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class pn extends dn{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=b.a.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=b.a.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Dt((()=>tn(r).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Dt((()=>tn(r).variable(false)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedGrads[n].variable,s=this.accumulatedUpdates[n].variable;Dt((()=>{const e=Xt(Qt(i,this.rho),Qt(en(a),1-this.rho)),t=Qt(Zt(Jt(Xt(s,this.epsilon)),Jt(Xt(i,this.epsilon))),a),n=Xt(Qt(s,this.rho),Qt(en(t),1-this.rho));i.assign(e),s.assign(n);const o=Xt(Qt(t,-this.learningRate),r);r.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Pt(this.accumulatedGrads.map((e=>e.variable))),Pt(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;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function hn(e,t,n){const r={shape:e,value:t,dtype:n};return b.a.runKernel(re.gb,{},r)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */pn.className="Adadelta",ft(pn);class fn extends dn{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 r=b.a.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Dt((()=>hn(r.shape,this.initialAccumulatorValue).variable(e)))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedGrads[n].variable;Dt((()=>{const e=Xt(i,en(a));i.assign(e);const t=Xt(Qt(Zt(a,Jt(Xt(e,b.a.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Pt(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)}}fn.className="Adagrad",ft(fn);const mn=Object(ie.b)({pow_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){let n=Object(ae.a)(e,"base","pow"),r=Object(ae.a)(t,"exp","pow");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.jc,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bn=Object(ie.b)({sub_:function(e,t){let n=Object(ae.a)(e,"a","sub"),r=Object(ae.a)(t,"b","sub");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.bd,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class gn extends dn{constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Dt((()=>{this.accBeta1=ln(t).variable(),this.accBeta2=ln(n).variable()})),null==r&&(this.epsilon=b.a.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Dt((()=>{const n=bn(1,this.accBeta1),r=bn(1,this.accBeta2);t.forEach(((t,a)=>{const i=b.a.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Dt((()=>tn(i).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Dt((()=>tn(i).variable(false)))});const s=Array.isArray(e)?e[a].tensor:e[t];if(null==s)return;const o=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,c=Xt(Qt(o,this.beta1),Qt(s,1-this.beta1)),l=Xt(Qt(u,this.beta2),Qt(en(s),1-this.beta2)),d=Zt(c,n),p=Zt(l,r);o.assign(c),u.assign(l);const h=Xt(Qt(Zt(d,Xt(Jt(p),this.epsilon)),-this.learningRate),i);i.assign(h)})),this.accBeta1.assign(Qt(this.accBeta1,this.beta1)),this.accBeta2.assign(Qt(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Pt(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Pt(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),Dt((()=>{this.accBeta1.assign(mn(this.beta1,this.iterations_+1)),this.accBeta2.assign(mn(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}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)}}gn.className="Adam",ft(gn);const xn=Object(ie.b)({abs_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const t=Object(ae.a)(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return b.a.runKernel(re.B,e)}{const e={x:t};return b.a.runKernel(re.a,e)}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vn=Object(ie.b)({maximum_:function(e,t){let n=Object(ae.a)(e,"a","maximum"),r=Object(ae.a)(t,"b","maximum");[n,r]=Object(Te.makeTypesMatch)(n,r),"bool"===n.dtype&&(n=se(n,"int32"),r=se(r,"int32")),Me(n.shape,r.shape);const a={a:n,b:r};return b.a.runKernel(re.Rb,a)}}); +/** +* @license +* Copyright 2018 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*/class kn extends dn{constructor(e,t,n,r=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Dt((()=>{this.iteration=ln(0).variable(),this.accBeta1=ln(t).variable()})),null==r&&(this.epsilon=b.a.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Dt((()=>{const n=bn(1,this.accBeta1),r=Zt(-this.learningRate,Xt(Qt(this.iteration,this.decay),1));t.forEach(((t,a)=>{const i=b.a.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:tn(i).variable(false)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:tn(i).variable(false)});const s=Array.isArray(e)?e[a].tensor:e[t];if(null==s)return;const o=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,c=Xt(Qt(o,this.beta1),Qt(s,1-this.beta1)),l=Qt(u,this.beta2),d=xn(s),p=vn(l,d);o.assign(c),u.assign(p);const h=Xt(Qt(Zt(r,n),Zt(c,Xt(p,this.epsilon))),i);i.assign(h)})),this.iteration.assign(Xt(this.iteration,1)),this.accBeta1.assign(Qt(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Pt(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Pt(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)}}kn.className="Adamax",ft(kn); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class yn extends dn{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 r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=b.a.registeredVariables[t];Dt((()=>{const e=Xt(Qt(this.c,r),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Bt(ln(-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)}}yn.className="SGD",ft(yn); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class wn extends yn{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=ln(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=b.a.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Dt((()=>tn(r).variable(e)))}}const a=this.accumulations[n].variable,i=Array.isArray(e)?e[n].tensor:e[t];null!=i&&Dt((()=>{let e;const t=Xt(Qt(this.m,a),i);e=this.useNesterov?Xt(Qt(this.c,Xt(i,Qt(t,this.m))),r):Xt(Qt(this.c,t),r),a.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Pt(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)}}wn.className="Momentum",ft(wn); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class In extends dn{constructor(e,t=.9,n=0,r=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==r&&(this.epsilon=b.a.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 r=b.a.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Dt((()=>tn(r).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Dt((()=>tn(r).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Dt((()=>tn(r).variable(a)))});const i=Array.isArray(e)?e[n].tensor:e[t];if(null==i)return;const s=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Dt((()=>{const e=Xt(Qt(s,this.decay),Qt(en(i),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=Xt(Qt(t,this.decay),Qt(i,1-this.decay)),u=Zt(Qt(i,this.learningRate),Jt(bn(e,Xt(en(a),this.epsilon)))),c=Xt(Qt(o,this.momentum),u);s.assign(e),t.assign(a),o.assign(c);const l=bn(r,c);r.assign(l)}else{const e=Xt(Qt(s,this.decay),Qt(en(i),1-this.decay)),t=Xt(Qt(o,this.momentum),Zt(Qt(i,this.learningRate),Jt(Xt(e,this.epsilon))));s.assign(e),o.assign(t);const n=bn(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Pt(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Pt(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Pt(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)}}In.className="RMSProp",ft(In); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Sn{static sgd(e){return new yn(e)}static momentum(e,t,n=!1){return new wn(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,a=!1){return new In(e,t,n,r,a)}static adam(e=.001,t=.9,n=.999,r=null){return new gn(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new pn(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,a=0){return new kn(e,t,n,r,a)}static adagrad(e,t=.1){return new fn(e,t)}}var _n=n(32); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cn=Object(ie.b)({acos_:function(e){const t={x:Object(ae.a)(e,"x","acos")};return b.a.runKernel(re.b,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const On=Object(ie.b)({acosh_:function(e){const t={x:Object(ae.a)(e,"x","acosh")};return b.a.runKernel(re.c,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tn=Object(ie.b)({addN_:function(e){E.b(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),E.b(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>Object(ae.a)(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(!E.a(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return b.a.runKernel(re.e,r)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $n=Object(ie.b)({all_:function(e,t=null,n=!1){const r={x:Object(ae.a)(e,"x","all","bool")},a={axis:t,keepDims:n};return b.a.runKernel(re.f,r,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const An=Object(ie.b)({any_:function(e,t=null,n=!1){const r={x:Object(ae.a)(e,"x","any","bool")},a={axis:t,keepDims:n};return b.a.runKernel(re.g,r,a)}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nn=Object(ie.b)({argMax_:function(e,t=0){const n={x:Object(ae.a)(e,"x","argMax")},r={axis:t};return b.a.runKernel(re.h,n,r)}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const En=Object(ie.b)({argMin_:function(e,t=0){const n={x:Object(ae.a)(e,"x","argMin")},r={axis:t};return b.a.runKernel(re.i,n,r)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Rn=Object(ie.b)({asin_:function(e){const t={x:Object(ae.a)(e,"x","asin")};return b.a.runKernel(re.j,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fn=Object(ie.b)({asinh_:function(e){const t={x:Object(ae.a)(e,"x","asinh")};return b.a.runKernel(re.k,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mn=Object(ie.b)({atan_:function(e){const t={x:Object(ae.a)(e,"x","atan")};return b.a.runKernel(re.l,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Dn=Object(ie.b)({atan2_:function(e,t){let n=Object(ae.a)(e,"a","atan2"),r=Object(ae.a)(t,"b","atan2");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.m,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pn=Object(ie.b)({atanh_:function(e){const t={x:Object(ae.a)(e,"x","atanh")};return b.a.runKernel(re.n,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bn(e,t,n,r,a="NHWC",i){return zn(e,[...t,e[3]],n,i,r,null,null,Yn(a))}function jn(e,t,n,r,a,i,s="channelsLast"){const[o,u]=Un(t);let c;if("channelsLast"===s)c=[o,u,e[3],e[3]];else{if("channelsFirst"!==s)throw new Error(`Unknown dataFormat ${s}`);c=[o,u,e[1],e[1]]}return zn(e,c,n,r,a,i,!1,s)}function Ln(e,t,n,r,a,i,s="NDHWC"){const[o,u,c]=Vn(t);let l,d;if("NDHWC"===s)d="channelsLast",l=[o,u,c,e[4],e[4]];else{if("NCDHW"!==s)throw new Error(`Unknown dataFormat ${s}`);d="channelsFirst",l=[o,u,c,e[1],e[1]]}return Wn(e,l,n,r,a,!1,d,i)}function zn(e,t,n,r,a,i,s=!1,o="channelsLast"){let[u,c,l,d]=[-1,-1,-1,-1];if("channelsLast"===o)[u,c,l,d]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,d,c,l]=e}const[p,h,,f]=t,[m,b]=Un(n),[g,x]=Un(r),v=Hn(p,g),k=Hn(h,x),{padInfo:y,outHeight:w,outWidth:I}=function(e,t,n,r,a,i,s,o,u){let c,l,d;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=Gn(e,t,n));const i=e[0],s=e[1],o=qn((i-t+2*r)/n+1,a),u=qn((s-t+2*r)/n+1,a);return[o,u]}([t,n],i,r,e,o);l=a[0],d=a[1]}else if("same"===e){l=Math.ceil(t/r),d=Math.ceil(n/a);const e=Math.max(0,(l-1)*r+i-t),o=Math.max(0,(d-1)*a+s-n),u=Math.floor(e/2),p=e-u,h=Math.floor(o/2);c={top:u,bottom:p,left:h,right:o-h,type:"SAME"}}else if("valid"===e)c={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-i+1)/r),d=Math.ceil((n-s+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===u?e[1][0]:e[2][0],h="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:0===p&&0===h&&0===f&&0===m?"VALID":"EXPLICIT"},l=qn((t-i+p+h)/r+1,o),d=qn((n-s+f+m)/a+1,o)}}return{padInfo:c,outHeight:l,outWidth:d}}(a,c,l,m,b,v,k,i,o),S=s?f*d:f;let _;return"channelsFirst"===o?_=[u,S,w,I]:"channelsLast"===o&&(_=[u,w,I,S]),{batchSize:u,dataFormat:o,inHeight:c,inWidth:l,inChannels:d,outHeight:w,outWidth:I,outChannels:S,padInfo:y,strideHeight:m,strideWidth:b,filterHeight:p,filterWidth:h,effectiveFilterHeight:v,effectiveFilterWidth:k,dilationHeight:g,dilationWidth:x,inShape:e,outShape:_,filterShape:t}}function Wn(e,t,n,r,a,i=!1,s="channelsLast",o){let[u,c,l,d,p]=[-1,-1,-1,-1,-1];if("channelsLast"===s)[u,c,l,d,p]=e;else{if("channelsFirst"!==s)throw new Error(`Unknown dataFormat ${s}`);[u,p,c,l,d]=e}const[h,f,m,,b]=t,[g,x,v]=Vn(n),[k,y,w]=Vn(r),I=Hn(h,k),S=Hn(f,y),_=Hn(m,w),{padInfo:C,outDepth:O,outHeight:T,outWidth:$}=function(e,t,n,r,a,i,s,o,u,c,l){let d,p,h,f;if("number"==typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const i=function(e,t,n,r,a,i){null==a&&(a=Gn(e,t,r));const s=e[0],o=e[1],u=e[2],c=qn((s-t+2*a)/r+1,i),l=qn((o-t+2*a)/r+1,i),d=qn((u-t+2*a)/r+1,i);return[c,l,d,n]}([t,n,r,1],o,1,a,e,l);p=i[0],h=i[1],f=i[2]}else if("same"===e){p=Math.ceil(t/a),h=Math.ceil(n/i),f=Math.ceil(r/s);const e=(p-1)*a+o-t,l=(h-1)*i+u-n,m=(f-1)*s+c-r,b=Math.floor(e/2),g=e-b,x=Math.floor(l/2),v=l-x,k=Math.floor(m/2);d={top:x,bottom:v,left:k,right:m-k,front:b,back:g,type:"SAME"}}else{if("valid"!==e)throw Error(`Unknown padding parameter: ${e}`);d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/a),h=Math.ceil((n-u+1)/i),f=Math.ceil((r-c+1)/s)}return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}(a,c,l,d,g,x,v,I,S,_,o),A=i?b*p:b;let N;return"channelsFirst"===s?N=[u,A,O,T,$]:"channelsLast"===s&&(N=[u,O,T,$,A]),{batchSize:u,dataFormat:s,inDepth:c,inHeight:l,inWidth:d,inChannels:p,outDepth:O,outHeight:T,outWidth:$,outChannels:A,padInfo:C,strideDepth:g,strideHeight:x,strideWidth:v,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:S,effectiveFilterWidth:_,dilationDepth:k,dilationHeight:y,dilationWidth:w,inShape:e,outShape:N,filterShape:t}}function Gn(e,t,n,r=1){const a=Hn(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function Un(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Vn(e){return"number"==typeof e?[e,e,e]:e}function Hn(e,t){return t<=1?e:e+(e-1)*(t-1)}function qn(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 Kn(e){const[t,n,r]=Un(e);return 1===t&&1===n&&1===r}function Xn(e,t){return Kn(e)||Kn(t)}function Yn(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Zn(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)E.b(E.v(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=>{E.b(E.v(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qn=Object(ie.b)({reshape_:function(e,t){const n={x:Object(ae.a)(e,"x","reshape","string_or_numeric")},r={shape:t};return b.a.runKernel(re.sc,n,r)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jn=Object(ie.b)({avgPool_:function(e,t,n,r,a){const i=Object(ae.a)(e,"x","avgPool","float32");E.b(Xn(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let s=i,o=!1;3===i.rank&&(o=!0,s=Qn(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E.b(4===s.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${s.rank}.`)),Zn("avgPool",r,a);const u={x:s},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let l=b.a.runKernel(re.o,u,c);return l=se(l,i.dtype),o?Qn(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const er=Object(ie.b)({avgPool3d_:function(e,t,n,r,a,i="NDHWC"){const s=Object(ae.a)(e,"x","avgPool3d","float32");let o=s,u=!1;4===s.rank&&(u=!0,o=Qn(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),E.b(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),E.b("NDHWC"===i,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`)),Zn("avgPool3d",r,a);const c={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:i};let d=b.a.runKernel(re.p,c,l);return d=se(d,o.dtype),u?Qn(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tr=Object(ie.b)({concat_:function(e,t=0){Object(E.b)(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Object(ae.b)(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 oe(n[0]);const r=n,a={axis:t};return b.a.runKernel(re.C,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nr=Object(ie.b)({sigmoid_:function(e){const t={x:Object(ae.a)(e,"x","sigmoid","float32")};return b.a.runKernel(re.Fc,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const rr=Object(ie.b)({slice_:function(e,t,n){const r=Object(ae.a)(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},i={begin:t,size:n};return b.a.runKernel(re.Jc,a,i)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ar=Object(ie.b)({tanh_:function(e){const t={x:Object(ae.a)(e,"x","tanh","float32")};return b.a.runKernel(re.ed,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ir=Object(ie.b)({basicLSTMCell_:function(e,t,n,r,a,i){const s=Object(ae.a)(e,"forgetBias","basicLSTMCell"),o=Object(ae.a)(t,"lstmKernel","basicLSTMCell"),u=Object(ae.a)(n,"lstmBias","basicLSTMCell"),c=Object(ae.a)(r,"data","basicLSTMCell"),l=Object(ae.a)(a,"c","basicLSTMCell"),d=Object(ae.a)(i,"h","basicLSTMCell"),p=tr([c,d],1),h=$e(p,o),f=Xt(h,u),m=f.shape[0],b=f.shape[1]/4,g=[m,b],x=rr(f,[0,0],g),v=rr(f,[0,b],g),k=rr(f,[0,2*b],g),y=rr(f,[0,3*b],g),w=Xt(Qt(nr(x),ar(v)),Qt(l,nr(Xt(s,k))));return[w,Qt(ar(w),nr(y))]}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const sr=Object(ie.b)({batchToSpaceND_:function(e,t,n){const r=Object(ae.a)(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));E.b(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),E.b(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),E.b(r.shape[0]%a==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const i={x:r},s={blockShape:t,crops:n};return b.a.runKernel(re.t,i,s)}});const or=Object(ie.b)({batchNorm_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,r,a,i){null==i&&(i=.001);const s=Object(ae.a)(e,"x","batchNorm"),o=Object(ae.a)(t,"mean","batchNorm"),u=Object(ae.a)(n,"variance","batchNorm");let c,l;null!=a&&(c=Object(ae.a)(a,"scale","batchNorm")),null!=r&&(l=Object(ae.a)(r,"offset","batchNorm")),E.b(o.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),E.b(null==l||o.rank===l.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),E.b(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const d=function(e){let t;return t=0===e.rank||1===e.rank?Qn(e,[1,1,1,e.size]):2===e.rank?Qn(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Qn(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(s),p={x:d,scale:c,offset:l,mean:o,variance:u},h={varianceEpsilon:i},f=b.a.runKernel(re.lb,p,h);return Qn(f,s.shape)}});const ur=Object(ie.b)({batchNorm2d_:function(e,t,n,r,a,i){const s=Object(ae.a)(e,"x","batchNorm"),o=Object(ae.a)(t,"mean","batchNorm"),u=Object(ae.a)(n,"variance","batchNorm");let c,l;return null!=a&&(c=Object(ae.a)(a,"scale","batchNorm")),null!=r&&(l=Object(ae.a)(r,"offset","batchNorm")),E.b(2===s.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${s.rank}.`)),E.b(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),E.b(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&E.b(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`)),null!=l&&E.b(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`)),or(s,o,u,l,c,i)}});const cr=Object(ie.b)({batchNorm3d_:function(e,t,n,r,a,i){const s=Object(ae.a)(e,"x","batchNorm"),o=Object(ae.a)(t,"mean","batchNorm"),u=Object(ae.a)(n,"variance","batchNorm");let c,l;return null!=a&&(c=Object(ae.a)(a,"scale","batchNorm")),null!=r&&(l=Object(ae.a)(r,"offset","batchNorm")),E.b(3===s.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${s.rank}.`)),E.b(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),E.b(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&E.b(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`)),null!=l&&E.b(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`)),or(s,o,u,l,c,i)}});const lr=Object(ie.b)({batchNorm4d_:function(e,t,n,r,a,i){const s=Object(ae.a)(e,"x","batchNorm"),o=Object(ae.a)(t,"mean","batchNorm"),u=Object(ae.a)(n,"variance","batchNorm");let c,l;return null!=a&&(c=Object(ae.a)(a,"scale","batchNorm")),null!=r&&(l=Object(ae.a)(r,"offset","batchNorm")),E.b(4===s.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${s.rank}.`)),E.b(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),E.b(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&E.b(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`)),null!=l&&E.b(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${l.rank}.`)),or(s,o,u,l,c,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const dr=Object(ie.b)({bincount_:function(e,t,n){const r=Object(ae.a)(e,"x","bincount"),a=Object(ae.a)(t,"weights","bincount");E.b("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),E.b(n>=0,(()=>`size must be non-negative, but got ${n}.`)),E.b(a.size===r.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`));const i={x:r,weights:a},s={size:n};return b.a.runKernel(re.u,i,s)}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pr=Object(ie.b)({broadcastArgs_:function(e,t){const n=Object(ae.a)(e,"s0","broadcastArgs","int32"),r=Object(ae.a)(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!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return b.a.runKernel(re.v,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hr=Object(ie.b)({broadcastTo_:function(e,t){let n=Object(ae.a)(e,"broadcastTo","x");const r=n.shape;if(t.some((e=>!(e>0)||e%1!=0)))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;e--)if(a[e]===t[e])i[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===i.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return oe(n);const s={x:n},o={reps:i};return b.a.runKernel(re.fd,s,o)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fr=Object(ie.b)({ceil_:function(e){const t={x:Object(ae.a)(e,"x","ceil","float32")};return b.a.runKernel(re.y,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mr=Object(ie.b)({clipByValue_:function(e,t,n){const r=Object(ae.a)(e,"x","clipByValue");E.b(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`));const a={x:r},i={clipValueMin:t,clipValueMax:n};return b.a.runKernel(re.z,a,i)}});var br=n(23);const gr=Object(ie.b)({concat1d_:function(e){return tr(e,0)}});const xr=Object(ie.b)({concat2d_:function(e,t){return tr(e,t)}});const vr=Object(ie.b)({concat3d_:function(e,t){return tr(e,t)}});const kr=Object(ie.b)({concat4d_:function(e,t){return tr(e,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yr=Object(ie.b)({conv2d_:function(e,t,n,r,a="NHWC",i=[1,1],s){const o=Object(ae.a)(e,"x","conv2d","float32"),u=Object(ae.a)(t,"filter","conv2d","float32");let c=o,l=!1;3===o.rank&&(l=!0,c=Qn(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E.b(4===c.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`)),E.b(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),Zn("conv2d",r,s);const d="NHWC"===a?c.shape[3]:c.shape[1];E.b(d===u.shape[2],(()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${u.shape[2]}.`)),E.b(Xn(n,i),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`));const p={x:c,filter:u},h={strides:n,pad:r,dataFormat:a,dilations:i,dimRoundingMode:s},f=b.a.runKernel(re.D,p,h);return l?Qn(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const wr=Object(ie.b)({conv1d_:function(e,t,n,r,a="NWC",i=1,s){const o=Object(ae.a)(e,"x","conv1d"),u=Object(ae.a)(t,"filter","conv1d");let c=o,l=!1;2===o.rank&&(l=!0,c=Qn(o,[1,o.shape[0],o.shape[1]])),E.b(3===c.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`)),E.b(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),Zn("conv1d",r,s),E.b(c.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),E.b(Xn(n,i),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${i}'`)),E.b("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const d=Qn(u,[1,u.shape[0],u.shape[1],u.shape[2]]),p=Qn(c,[c.shape[0],1,c.shape[1],c.shape[2]]),h=yr(p,d,[1,n],r,"NHWC",[1,i],s);return Qn(h,l?[h.shape[2],h.shape[3]]:[h.shape[0],h.shape[2],h.shape[3]])}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ir=Object(ie.b)({conv2DBackpropInput_:function(e,t,n,r,a,i="NHWC",s){E.b(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,u=t,c=!1;3===t.rank&&(c=!0,u=Qn(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),E.b(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),E.b(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),E.b(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const l="NHWC"===i?o[3]:o[1],d="NHWC"===i?u.shape[3]:u.shape[1];E.b(l===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[2]}.`)),E.b(d===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`)),Zn("conv2dDerInput",a,s);const p={dy:u,filter:n},h={strides:r,pad:a,dataFormat:i,dimRoundingMode:s,inputShape:o},f=b.a.runKernel(re.F,p,h);return c?Qn(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});const Sr=Object(ie.b)({conv2dTranspose_:function(e,t,n,r,a,i){const s=Object(ae.a)(e,"x","conv2dTranspose"),o=Object(ae.a)(t,"filter","conv2dTranspose");return Ir(n,s,o,r,a,"NHWC",i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _r=Object(ie.b)({conv3d_:function(e,t,n,r,a="NDHWC",i=[1,1,1]){const s=Object(ae.a)(e,"x","conv3d"),o=Object(ae.a)(t,"filter","conv3d");let u=s,c=!1;4===s.rank&&(c=!0,u=Qn(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),E.b(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),E.b(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),E.b(u.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),E.b(Xn(n,i),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`)),E.b("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`));const l={x:u,filter:o},d={strides:n,pad:r,dataFormat:a,dilations:i},p=b.a.runKernel(re.G,l,d);return c?Qn(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cr=Object(ie.b)({conv3DBackpropInput_:function(e,t,n,r,a){E.b(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let i=e,s=t,o=!1;4===t.rank&&(o=!0,s=Qn(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),i=[1,e[0],e[1],e[2],e[3]]);const u=i[4],c=s.shape[4];E.b(5===i.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${i.length}.`)),E.b(5===s.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${s.rank}`)),E.b(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),E.b(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),E.b(c===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`));const l={dy:s,filter:n},d={pad:a,strides:r,inputShape:i},p=b.a.runKernel(re.I,l,d);return o?Qn(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Or=Object(ie.b)({conv3dTranspose_:function(e,t,n,r,a){const i=Object(ae.a)(e,"x","conv3dTranspose"),s=Object(ae.a)(t,"filter","conv3dTranspose");return Cr(n,i,s,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tr=Object(ie.b)({cos_:function(e){const t={x:Object(ae.a)(e,"x","cos","float32")};return b.a.runKernel(re.J,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $r=Object(ie.b)({cosh_:function(e){const t={x:Object(ae.a)(e,"x","cosh","float32")};return b.a.runKernel(re.K,t)}}); +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the 'License'); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an 'AS IS' BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ar=Object(ie.b)({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:Object(ae.a)(e,"x","cumprod")},i={axis:t,exclusive:n,reverse:r};return b.a.runKernel(re.M,a,i)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nr=Object(ie.b)({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:Object(ae.a)(e,"x","cumsum")},i={axis:t,exclusive:n,reverse:r};return b.a.runKernel(re.N,a,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Er=Object(ie.b)({denseBincount_:function(e,t,n,r=!1){const a=Object(ae.a)(e,"x","denseBincount"),i=Object(ae.a)(t,"weights","denseBincount");E.b("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),E.b(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),E.b(n>=0,(()=>`size must be non-negative, but got ${n}.`)),E.b(i.size===a.size||0===i.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${i.shape}.`));const s={x:a,weights:i},o={size:n,binaryOutput:r};return b.a.runKernel(re.O,s,o)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Rr=Object(ie.b)({depthToSpace_:function(e,t,n="NHWC"){const r=Object(ae.a)(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],s="NHWC"===n?r.shape[3]:r.shape[1];E.b(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),E.b(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),E.b(i*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${i} and ${t} for depthToSpace with input shape\n ${r.shape}`)),E.b(s%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${s} for depthToSpace with input shape ${r.shape}`));const o={x:r},u={blockSize:t,dataFormat:n};return b.a.runKernel(re.P,o,u)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fr=Object(ie.b)({depthwiseConv2d_:function(e,t,n,r,a="NHWC",i=[1,1],s){const o=Object(ae.a)(e,"x","depthwiseConv2d","float32"),u=Object(ae.a)(t,"filter","depthwiseConv2d","float32");let c=o,l=!1;3===o.rank&&(l=!0,c=Qn(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E.b(4===c.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`)),E.b(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`)),E.b(c.shape[3]===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`)),Zn("depthwiseConv2d",r,s);const d={x:c,filter:u},p={strides:n,pad:r,dataFormat:a,dilations:i,dimRoundingMode:s},h=b.a.runKernel(re.Q,d,p);return l?Qn(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mr=Object(ie.b)({diag_:function(e){const t={x:Object(ae.a)(e,"x","diag")};return b.a.runKernel(re.T,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Dr=Object(ie.b)({dilation2d_:function(e,t,n,r,a=[1,1],i="NHWC"){const s=Object(ae.a)(e,"x","dilation2d"),o=Object(ae.a)(t,"filter","dilation2d");E.b(3===s.rank||4===s.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${s.rank}.`)),E.b(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),E.b("NHWC"===i,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${i}`));let u=s,c=!1;3===s.rank&&(u=Qn(s,[1,s.shape[0],s.shape[1],s.shape[2]]),c=!0);const l={x:u,filter:o},d={strides:n,pad:r,dilations:a},p=b.a.runKernel(re.U,l,d);return c?Qn(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pr=Object(ie.b)({equal_:function(e,t){let n=Object(ae.a)(e,"a","equal","string_or_numeric"),r=Object(ae.a)(t,"b","equal","string_or_numeric");[n,r]=Object(Te.makeTypesMatch)(n,r),Me(n.shape,r.shape);const a={a:n,b:r};return b.a.runKernel(re.ab,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Br=Object(ie.b)({where_:function(e,t,n){const r=Object(ae.a)(t,"a","where"),a=Object(ae.a)(n,"b","where"),i=Object(ae.a)(e,"condition","where","bool"),s=Me(Me(i.shape,r.shape),a.shape),o={condition:hr(i,s),t:hr(r,s),e:hr(a,s)};return b.a.runKernel(re.Dc,o)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const jr=Object(ie.b)({divNoNan_:function(e,t){let n=Object(ae.a)(e,"a","div"),r=Object(ae.a)(t,"b","div");[n,r]=Object(Te.makeTypesMatch)(n,r);const a=Zt(n,r),i=tn(a),s=Pr(r,i);return Br(s,i,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lr=Object(ie.b)({dot_:function(e,t){const n=Object(ae.a)(e,"t1","dot"),r=Object(ae.a)(t,"t2","dot");E.b(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];if(E.b(a===i,(()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${i}.`)),1===n.rank&&1===r.rank){const e=Qn(n,[1,-1]),t=Qn(r,[-1,1]),a=$e(e,t);return Qn(a,[])}if(1===n.rank&&2===r.rank){const e=Qn(n,[1,-1]),t=Qn(r,[r.shape[0],r.shape[1]]),a=$e(e,t);return Qn(a,[a.size])}if(2===n.rank&&1===r.rank){const e=Qn(r,[-1,1]),t=$e(n,e);return Qn(t,[t.size])}{const e=Qn(r,[r.shape[0],r.shape[1]]);return $e(n,e)}}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zr=Object(ie.b)({einsum_:function(e,...t){const n=t.map(((e,t)=>Object(ae.a)(e,`tensors${t}`,"einsum"))),r={equation:e};return b.a.runKernel(re.X,n,r)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wr=Object(ie.b)({elu_:function(e){const t={x:Object(ae.a)(e,"x","elu","float32")};return b.a.runKernel(re.Y,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Gr=Object(ie.b)({erf_:function(e){let t=Object(ae.a)(e,"x","erf");E.b("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=se(t,"float32"));const n={x:t};return b.a.runKernel(re.bb,n)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ur=Object(ie.b)({exp_:function(e){const t={x:Object(ae.a)(e,"x","exp")};return b.a.runKernel(re.cb,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vr=Object(ie.b)({expandDims_:function(e,t=0){const n=Object(ae.a)(e,"x","expandDims","string_or_numeric");E.b(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},a={dim:t};return b.a.runKernel(re.db,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hr=Object(ie.b)({expm1_:function(e){const t={x:Object(ae.a)(e,"x","expm1")};return b.a.runKernel(re.eb,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qr=Object(ie.b)({tile_:function(e,t){const n=Object(ae.a)(e,"x","tile","string_or_numeric");E.b(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},a={reps:t};return b.a.runKernel(re.fd,r,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kr=Object(ie.b)({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=ne([e,t],r),i=e<=t?e:t;for(let e=0;e`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${i.rank}.`)),E.b(E.v(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let s=i,o=!1;3===i.rank&&(o=!0,s=Qn(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const u={x:s},c={depthRadius:t,bias:n,alpha:r,beta:a},l=b.a.runKernel(re.yb,u,c);return o?Qn(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ua=Object(ie.b)({log_:function(e){const t={x:Object(ae.a)(e,"x","log","float32")};return b.a.runKernel(re.Eb,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ca=Object(ie.b)({log1p_:function(e){const t={x:Object(ae.a)(e,"x","log1p")};return b.a.runKernel(re.Fb,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const la=Object(ie.b)({neg_:function(e){const t={x:Object(ae.a)(e,"x","neg")};return b.a.runKernel(re.Zb,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const da=Object(ie.b)({softplus_:function(e){const t={x:Object(ae.a)(e,"x","softplus")};return b.a.runKernel(re.Lc,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pa=Object(ie.b)({logSigmoid_:function(e){const t=Object(ae.a)(e,"x","logSigmoid"),n=un((e=>({value:la(da(la(e))),gradFunc:t=>Qt(t,nr(la(e)))})));return n(t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ha=Object(ie.b)({max_:function(e,t=null,n=!1){const r={x:Object(ae.a)(e,"x","max")},a={reductionIndices:t,keepDims:n};return b.a.runKernel(re.Lb,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fa=Object(ie.b)({sum_:function(e,t=null,n=!1){let r=Object(ae.a)(e,"x","sum");"bool"===r.dtype&&(r=se(r,"int32"));const a={x:r},i={axis:t,keepDims:n};return b.a.runKernel(re.cd,a,i)}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ma=Object(ie.b)({logSoftmax_:function(e,t=-1){const n=Object(ae.a)(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 r=un(((e,n)=>{const r=ha(e,t,!0),a=bn(e,r),i=bn(se(a,"float32"),ua(fa(Ur(a),t,!0)));n([i]);return{value:i,gradFunc:(e,n)=>{const[r]=n,a=Ur(r);return bn(e,Qt(fa(e,t,!0),a))}}}));return r(n)}}); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ba(e,t){for(let n=0;ne[t]))]}function va(e,t){return ga(e,t.map((e=>1)),t)}function ka(e,t,n){E.b(ba(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function ya(e,t){if(ba(e,t))return null;const n=[];for(let r=0;rn.push(e))),n}function wa(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Ia(e,t){const n=[];for(let r=t-e;r=$a)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=$a)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const c={sortedSequence:o,values:u},l={side:n};return b.a.runKernel(re.Cc,c,l)}}); +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Na(e,t){return Aa(e,t,"left")} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ea=Object(ie.b)({maxPool_:function(e,t,n,r,a){const i=Object(ae.a)(e,"x","maxPool");let s=i,o=!1;3===i.rank&&(o=!0,s=Qn(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E.b(4===s.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.rank}.`)),E.b(Xn(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Zn("maxPool",r,a);const u={x:s},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a},l=b.a.runKernel(re.Mb,u,c);return o?Qn(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ra=Object(ie.b)({maxPool3d_:function(e,t=[1,1,1],n,r,a,i="NDHWC"){const s=Object(ae.a)(e,"x","maxPool3d");let o=s,u=!1;4===s.rank&&(u=!0,o=Qn(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),E.b(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),E.b("NDHWC"===i,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`)),Zn("maxPool3d",r,a);const c={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:i},d=b.a.runKernel(re.Nb,c,l);return u?Qn(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fa=Object(ie.b)({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const i={x:Object(ae.a)(e,"x","maxPoolWithArgmax")},s={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},o=b.a.runKernel(re.Qb,i,s);return{result:o[0],indexes:o[1]}}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ma=Object(ie.b)({mean_:function(e,t=null,n=!1){const r={x:Object(ae.a)(e,"x","mean")},a={axis:t,keepDims:n};return b.a.runKernel(re.Sb,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Da(e,t="float32"){if("complex64"===t){const t=Da(e,"float32"),n=Da(e,"float32");return Object(br.a)(t,n)}const n=Object(E.F)(Object(E.O)(e),t);return b.a.makeTensor(n,e,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Pa(e,t="float32"){if("complex64"===t){const t=Pa(e,"float32"),n=Da(e,"float32");return Object(br.a)(t,n)}const n=Object(E.D)(Object(E.O)(e),t);return b.a.makeTensor(n,e,t)} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ba(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 r=Object(ae.a)(e,"x","meshgrid",e instanceof te.a?e.dtype:"float32");if(void 0===t)return[r];let a=Object(ae.a)(t,"y","meshgrid",t instanceof te.a?t.dtype:"float32");const i=Object(E.O)(r.shape),s=Object(E.O)(a.shape);return"xy"===n?(r=Qn(r,[1,-1]),a=Qn(a,[-1,1]),[$e(Pa([s,1],r.dtype),r),$e(a,Pa([1,i],a.dtype))]):(r=Qn(r,[-1,1]),a=Qn(a,[1,-1]),[$e(r,Pa([1,s],r.dtype)),$e(Pa([i,1],a.dtype),a)])} +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ja=Object(ie.b)({min_:function(e,t=null,n=!1){const r={x:Object(ae.a)(e,"x","min")},a={axis:t,keepDims:n};return b.a.runKernel(re.Tb,r,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const La=Object(ie.b)({minimum_:function(e,t){let n=Object(ae.a)(e,"a","minimum"),r=Object(ae.a)(t,"b","minimum");[n,r]=Object(Te.makeTypesMatch)(n,r),"bool"===n.dtype&&(n=se(n,"int32"),r=se(r,"int32")),Me(n.shape,r.shape);const a={a:n,b:r};return b.a.runKernel(re.Ub,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const za=Object(ie.b)({mirrorPad_:function(e,t,n){E.b("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=Object(ae.a)(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");E.b(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const a="reflect"===n?1:0;for(let e=0;e"Invalid number of paddings. Must be length of 2 each.")),E.b(t[e][0]>=0&&t[e][0]<=r.shape[e]-a&&t[e][1]>=0&&t[e][1]<=r.shape[e]-a,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-a} or less than 0 for input of shape ${r.shape}`));const i={paddings:t,mode:n},s={x:r};return b.a.runKernel(re.Vb,s,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wa=Object(ie.b)({mod_:function(e,t){let n=Object(ae.a)(e,"a","mod"),r=Object(ae.a)(t,"b","mod");[n,r]=Object(Te.makeTypesMatch)(n,r);const a={a:n,b:r};return b.a.runKernel(re.Wb,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ga=Object(ie.b)({moments_:function(e,t=null,n=!1){e=Object(ae.a)(e,"x","moments");const r=Object(E.I)(t,e.shape),a=Ma(e,r,n);let i=a.shape;n||(i=va(a.shape,r));const s=en(bn(se(e,"float32"),Qn(a,i)));return{mean:a,variance:Ma(s,r,n)}}});const Ua=Object(ie.b)({multiRNNCell_:function(e,t,n,r){const a=Object(ae.a)(t,"data","multiRNNCell"),i=Object(ae.b)(n,"c","multiRNNCell"),s=Object(ae.b)(r,"h","multiRNNCell");let o=a;const u=[];for(let t=0;t2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${s}`);n=n||Math.random();const o={logits:1===s?Qn(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},c=b.a.runKernel(re.Xb,o,u);return 1===s?Qn(c,[c.size]):c}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ha=Object(ie.b)({notEqual_:function(e,t){let n=Object(ae.a)(e,"a","notEqual","string_or_numeric"),r=Object(ae.a)(t,"b","notEqual","string_or_numeric");[n,r]=Object(Te.makeTypesMatch)(n,r),Me(n.shape,r.shape);const a={a:n,b:r};return b.a.runKernel(re.dc,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qa=Object(ie.b)({onesLike_:function(e){const t={x:Object(ae.a)(e,"x","onesLike")};return b.a.runKernel(re.fc,t)}});const Ka=Object(ie.b)({outerProduct_:function(e,t){const n=Object(ae.a)(e,"v1","outerProduct"),r=Object(ae.a)(t,"v2","outerProduct");E.b(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const a=Qn(n,[-1,1]),i=Qn(r,[1,-1]);return $e(a,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xa=Object(ie.b)({pad_:function(e,t,n=0){const r=Object(ae.a)(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},i={x:r};return b.a.runKernel(re.hc,i,a)}});const Ya=Object(ie.b)({pad1d_:function(e,t,n=0){return Object(E.b)(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Xa(e,[t],n)}});const Za=Object(ie.b)({pad2d_:function(e,t,n=0){return Object(E.b)(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Xa(e,t,n)}});const Qa=Object(ie.b)({pad3d_:function(e,t,n=0){return Object(E.b)(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.")),Xa(e,t,n)}});const Ja=Object(ie.b)({pad4d_:function(e,t,n=0){return Object(E.b)(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.")),Xa(e,t,n)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ei=Object(ie.b)({spaceToBatchND_:function(e,t,n){const r=Object(ae.a)(e,"x","spaceToBatchND");E.b(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),E.b(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),E.b(r.shape.reduce(((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:r},i={blockShape:t,paddings:n};return b.a.runKernel(re.Mc,a,i)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ti=Object(ie.b)({pool_:function(e,t,n,r,a,i,s){null==a&&(a=[1,1]),null==i&&(i=1),0===r&&(r="valid");const o=Object(ae.a)(e,"x","maxPool");let u=o,c=!1;3===o.rank&&(c=!0,u=Qn(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E.b(Xn(i,a),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${a}'`));const l=jn(u.shape,t,i,a,r),d=[l.dilationHeight,l.dilationWidth];let p;p="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),a=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],a[t]]))}([l.filterHeight,l.filterWidth],d):[[0,0],[0,0]];const h=1===d[0]&&1===d[1],[f,m]=function(e,t,n){const r=n.map((e=>e[0])),a=n.map((e=>e[1])),i=e.concat(r,a),s=t.map(((e,t)=>(e-i[t]%e)%e)),o=a.map(((e,t)=>e+s[t])),u=t.map(((e,t)=>[r[t],o[t]])),c=t.map(((e,t)=>[0,s[t]]));return[u,c]}([l.inHeight,l.inWidth],d,p),b=h?r:"valid",g=h?u:ei(u,d,f),x=("avg"===n?()=>Jn(g,t,i,b,s):()=>Ea(g,t,i,b,s))(),v=h?x:sr(x,d,m);return c?Qn(v,[v.shape[1],v.shape[2],v.shape[3]]):v}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ni=Object(ie.b)({prelu_:function(e,t){const n={x:Object(ae.a)(e,"x","prelu"),alpha:Object(ae.a)(t,"alpha","prelu")};return b.a.runKernel(re.kc,n)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ri=Object(ie.b)({prod_:function(e,t=null,n=!1){let r=Object(ae.a)(e,"x","prod");"bool"===r.dtype&&(r=se(r,"int32"));const a={x:r},i={axis:t,keepDims:n};return b.a.runKernel(re.lc,a,i)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ai=Object(ie.b)({rand_:function(e,t,n){const r=Object(E.O)(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let e=0;e=1||0===i);const s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*r*s,t=this.mean+this.stdDev*a*s,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 oi{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ii.alea(a.toString()),this.randn=new si(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,r,a,i;for(;;){do{r=this.randn.nextValue(),i=1+this.c*r}while(i<=0);if(i*=i*i,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),a=this.randu(),anull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ii.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const ci=Object(ie.b)({randomGamma_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n=1,r="float32",a){if(null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const i=new oi(t,n,r,a),s=ne(e,r);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),gi(t,0)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vi=Object(ie.b)({reverse2d_:function(e,t){const n=Object(ae.a)(e,"x","reverse");return E.b(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),gi(n,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ki=Object(ie.b)({reverse3d_:function(e,t){const n=Object(ae.a)(e,"x","reverse");return E.b(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),gi(n,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yi=Object(ie.b)({reverse4d_:function(e,t){const n=Object(ae.a)(e,"x","reverse");return E.b(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),gi(n,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wi=Object(ie.b)({round_:function(e){const t={x:Object(ae.a)(e,"x","round")};return b.a.runKernel(re.zc,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ii=Object(ie.b)({rsqrt_:function(e){const t={x:Object(ae.a)(e,"x","rsqrt","float32")};return b.a.runKernel(re.Ac,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Si=Object(ie.b)({selu_:function(e){const t={x:Object(ae.a)(e,"x","selu")};return b.a.runKernel(re.Ec,t)}});const _i=Object(ie.b)({separableConv2d_:function(e,t,n,r,a,i=[1,1],s="NHWC"){const o=Object(ae.a)(e,"x","separableConv2d"),u=Object(ae.a)(t,"depthwiseFilter","separableConv2d"),c=Object(ae.a)(n,"pointwiseFilter","separableConv2d");let l=o,d=!1;if(3===o.rank&&(d=!0,l=Qn(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===s)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");E.b(4===l.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${l.rank}.`)),E.b(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),E.b(4===c.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),E.b(1===c.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`)),E.b(1===c.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`));const p=u.shape[2],h=u.shape[3];E.b(c.shape[2]===p*h,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`));const f=Fr(l,u,r,a,s,i),m=yr(f,c,1,"valid",s);return d?Qn(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}); +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ci=async function(e,t){const n=Object(ae.a)(e,"x","setdiff1d"),r=Object(ae.a)(t,"y","setdiff1d");E.b(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),E.b(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),E.b(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const a=await n.data(),i=await r.data(),s=new Set(i);let o=0;for(let e=0;e`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),rr(r,[t],[n])}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ni=Object(ie.b)({slice2d_:function(e,t,n){const r=Object(ae.a)(e,"x","slice2d");return E.b(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),rr(r,t,n)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ei=Object(ie.b)({slice3d_:function(e,t,n){const r=Object(ae.a)(e,"x","slice3d");return E.b(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),rr(r,t,n)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ri=Object(ie.b)({slice4d_:function(e,t,n){const r=Object(ae.a)(e,"x","slice4d");return E.b(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),rr(r,t,n)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fi=Object(ie.b)({softmax_:function(e,t=-1){const n=Object(ae.a)(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 r={logits:n},a={dim:t};return b.a.runKernel(re.Kc,r,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mi=Object(ie.b)({fft_:function(e){Object(E.b)("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return b.a.runKernel(re.fb,t)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Di=Object(ie.b)({ifft_:function(e){Object(E.b)("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return b.a.runKernel(re.sb,t)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pi=Object(ie.b)({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=Qn(e,[n,t]);r=Di(a)}else{const a=[n,2*(t-1)],i=Qn(hi(e),[n,t]),s=Qn(Jr(e),[n,t]),o=gi(rr(i,[0,1],[n,t-2]),1),u=Qt(gi(rr(s,[0,1],[n,t-2]),1),ln(-1)),c=tr([i,o],1),l=tr([s,u],1),d=Qn(Object(br.a)(c,l),[a[0],a[1]]);r=Di(d)}if(r=hi(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Qn(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Bi=Object(ie.b)({split_:function(e,t,n=0){const r={x:Object(ae.a)(e,"x","split")},a={numOrSizeSplits:t,axis:n};return b.a.runKernel(re.Sc,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ji=Object(ie.b)({rfft_:function(e,t){Object(E.b)("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t0)),i=e.shape.map((e=>e));i[e.shape.length-1]=t,a=rr(e,r,i),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,a=tr([e,Da(r)],e.shape.length-1),n=t}else a=e;const i=tn(a),s=Qn(Object(br.a)(a,i),[r,n]),o=Mi(s),u=Math.floor(n/2)+1,c=hi(o),l=Jr(o),d=Bi(c,[u,n-u],c.shape.length-1),p=Bi(l,[u,n-u],l.shape.length-1),h=a.shape.slice();return h[a.shape.length-1]=u,Qn(Object(br.a)(d[0],p[0]),h)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Li=Object(ie.b)({squaredDifference_:function(e,t){let n=Object(ae.a)(e,"a","squaredDifference"),r=Object(ae.a)(t,"b","squaredDifference");[n,r]=Object(Te.makeTypesMatch)(n,r),Me(n.shape,r.shape);const a={a:n,b:r};return b.a.runKernel(re.Vc,a,{})}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zi=Object(ie.b)({squeeze_:function(e,t){const n=Object(ae.a)(e,"x","squeeze");return Qn(n,Object(E.Q)(n.shape,t).newShape)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wi=Object(ie.b)({stack_:function(e,t=0){const n=Object(ae.b)(e,"tensors","stack","string_or_numeric");E.b(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&E.b(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,a={axis:t};return b.a.runKernel(re.gc,r,a)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Gi=Object(ie.b)({step_:function(e,t=0){const n={x:Object(ae.a)(e,"x","step")},r={alpha:t};return b.a.runKernel(re.Wc,n,r)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ui=Object(ie.b)({stridedSlice_:function(e,t,n,r,a=0,i=0,s=0,o=0,u=0){const c={x:Object(ae.a)(e,"x","stridedSlice","string_or_numeric")},l={begin:t,end:n,strides:r,beginMask:a,endMask:i,ellipsisMask:s,newAxisMask:o,shrinkAxisMask:u};return b.a.runKernel(re.Xc,c,l)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vi=Object(ie.b)({tan_:function(e){const t={x:Object(ae.a)(e,"x","tan","float32")};return b.a.runKernel(re.dd,t)}});var Hi=n(31); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function qi(e,t){Object(E.d)(e);const n=Object(ae.c)(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Object(Pe.a)(e,null,n,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ki(e,t,n){if(Object(E.d)(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Object(ae.c)(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Object(Pe.a)(e,t,r,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Xi(e,t,n){if(Object(E.d)(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Object(ae.c)(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Object(Pe.a)(e,t,r,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Yi(e,t,n){if(Object(E.d)(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Object(ae.c)(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Object(Pe.a)(e,t,r,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Zi(e,t,n){if(Object(E.d)(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Object(ae.c)(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,Object(Pe.a)(e,t,r,n)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qi=Object(ie.b)({topk_:function(e,t=1,n=!0){const r=Object(ae.a)(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const a=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const i={x:r},s={k:t,sorted:n},[o,u]=b.a.runKernel(re.gd,i,s);return{values:o,indices:u}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ji=Object(ie.b)({truncatedNormal_:function(e,t=0,n=1,r,a){if(null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const i=new si(t,n,r,!0,a),s=ne(e,r);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const r={x:n},a={axis:t},[i,s]=b.a.runKernel(re.jd,r,a);return{values:i,indices:s}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ts=Object(ie.b)({unsortedSegmentSum_:function(e,t,n){const r=Object(ae.a)(e,"x","unsortedSegmentSum"),a=Object(ae.a)(t,"segmentIds","unsortedSegmentSum","int32");Object(E.b)(Object(E.v)(n),(()=>"numSegments must be of dtype int"));const i={x:r,segmentIds:a},s={numSegments:n};return b.a.runKernel(re.ld,i,s)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ns=Object(ie.b)({unstack_:function(e,t=0){const n=Object(ae.a)(e,"x","unstack","string_or_numeric");E.b(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},a={axis:t};return b.a.runKernel(re.kd,r,a)}}); +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function rs(e,t){return Aa(e,t,"right")} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function as(e,t=!0,n,r){return b.a.makeVariable(e,t,n,r)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function is(e,t){const n=[];for(let e=0;e0,(()=>"mask cannot be scalar")),E.e(o.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let e=i;e"Shape mismatch in v and x"));const u=ln(1),c=bn(u,o);let l=Qt(bn(s,i),c);if(a){E.b(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=Object(ae.a)(r,"step","movingAverage");l=Zt(l,bn(u,mn(o,e)))}return Xt(i,l)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ds=Object(ie.b)({scatterND_:function(e,t,n){const r=Object(ae.a)(e,"indices","scatterND","int32"),a=Object(ae.a)(t,"updates","scatterND");qe(a,r,n);const i={indices:r,updates:a},s={shape:n};return b.a.runKernel(re.Bc,i,s)}});const ps=Object(ie.b)({sparseToDense_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,r=0){const a=Object(ae.a)(e,"sparseIndices","sparseToDense","int32"),i=Object(ae.a)(t,"sparseValues","sparseToDense"),s=Object(ae.a)(r,"defaultValue","sparseToDense",i.dtype);!function(e,t,n,r){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 a=e.rank>0?e.shape[0]:1,i=e.rank>1?e.shape[1]:1;if(n.length!==i)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${i}.`);const s=t.size;if(0!==t.rank&&(1!==t.rank||s!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,i,n,s);const o={sparseIndices:a,sparseValues:i,defaultValue:s},u={outputShape:n};return b.a.runKernel(re.Rc,o,u)}}); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hs=Object(ie.b)({gatherND_:function(e,t){const n=Object(ae.a)(t,"indices","gatherND","int32"),r={params:Object(ae.a)(e,"x","gatherND","string_or_numeric"),indices:n};return b.a.runKernel(re.ob,r)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fs=Object(ie.b)({dropout_: +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t,n,r){const a=Object(ae.a)(e,"x","dropout");if(E.b("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),E.b(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof te.a?a.clone():a;const i=function(e,t){if(null==t)return e.shape.slice();if(E.a(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),Object(E.b)(r.rank-1===a.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`)),Object(E.e)(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=r.shape[r.shape.length-1];Object(E.b)(n>0&&n<=i,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${i}), but got ${n}`));const s=await r.data(),o=await a.data(),[u,c]=[s.length/i,i],l=Object(E.o)("bool",u);for(let e=0;et.value-e.value)),l[e]=0;for(let t=0;t`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),E.b(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),E.b(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const c="NHWC"===i?o.shape[3]:o.shape[1],l="NHWC"===i?u.shape[3]:u.shape[1];E.b(c===n[2],(()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`)),E.b(l===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${l}) must match output depth for filter (${n[3]}).`)),Zn("conv2dDerFilter",a,s);const d={x:o,dy:u},p={strides:r,pad:a,dataFormat:i,dimRoundingMode:s,filterShape:n};return b.a.runKernel(re.E,d,p)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function vs(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Qt(e,Gi(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ks(e,t){let n=t;const r=Fe(e.shape,t.shape);return r.length>0&&(n=fa(n,r)),Qn(n,e.shape)}function ys(e,t,n,r){if("linear"===t)return e;if("relu"===t)return mi(e);if("elu"===t)return Wr(e);if("relu6"===t)return bi(e);if("prelu"===t)return ni(e,n);if("leakyrelu"===t)return ra(e,r);if("sigmoid"===t)return nr(e);throw new Error(`Unknown fused activation ${t}.`)}const ws=(e,t)=>!(e>0)||"linear"===t; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Is=Object(ie.b)({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:i=[1,1],dimRoundingMode:s,bias:o,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:l}){if(u=u||"linear",!1===ws(b.a.state.gradientDepth,u)){let d=yr(e,t,n,r,a,i,s);return null!=o&&(d=Xt(d,o)),ys(d,u,c,l)}const d=Object(ae.a)(e,"x","conv2d","float32"),p=Object(ae.a)(t,"filter","conv2d","float32");let h=d,f=!1;3===d.rank&&(f=!0,h=Qn(d,[1,d.shape[0],d.shape[1],d.shape[2]])),E.b(4===h.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`)),E.b(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Zn("fused conv2d",r,s),E.b(h.shape[3]===p.shape[2],(()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`)),E.b(Xn(n,i),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`)),E.b("NHWC"===a,(()=>`Error in conv2d: got dataFormat of ${a} but only NHWC is currently supported.`));const m=zn(h.shape,p.shape,n,i,r,s);let g,x;null!=o&&(g=Object(ae.a)(o,"bias","fused conv2d"),[g]=Object(Te.makeTypesMatch)(g,d),Me(m.outShape,g.shape)),null!=c&&(x=Object(ae.a)(c,"prelu weights","fused conv2d"));const v=(e,t)=>{const[a,s,o,c]=t,l=vs(e,o,u);E.b(Kn(i),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`));const d=[Ir(s.shape,l,a,n,r),xs(s,l,a.shape,n,r)];if(null!=c){const e=ks(c,l);d.push(e)}return d},k={x:h,filter:p,bias:g,preluActivationWeights:x},y={strides:n,pad:r,dataFormat:a,dilations:i,dimRoundingMode:s,activation:u,leakyreluAlpha:l};if(null==o){const e=un(((e,t,n)=>{let r=b.a.runKernel(re.mb,k,y);return n([t,e,r]),f&&(r=Qn(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:v}}));return e(h,p)}{const e=un(((e,t,n,r)=>{let a=b.a.runKernel(re.mb,k,y);return r([t,e,a,n]),f&&(a=Qn(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:v}}));return e(h,p,g)}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ss=Object(ie.b)({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,i=[1,1],s){let o=e;3===e.rank&&(o=Qn(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Qn(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const c={x:o,dy:u},l={strides:r,pad:a,dimRoundingMode:s,dilations:i,filterShape:n};return b.a.runKernel(re.R,c,l)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _s=Object(ie.b)({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,i=[1,1],s){let o=t,u=!1;3===t.rank&&(u=!0,o=Qn(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const c={dy:o,filter:n},l={strides:r,pad:a,dimRoundingMode:s,dilations:i,inputShape:e},d=b.a.runKernel(re.S,c,l);return u?Qn(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cs=Object(ie.b)({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:i=[1,1],dimRoundingMode:s,bias:o,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:l}){if(!1===ws(b.a.state.gradientDepth,u)){let d=Fr(e,t,n,r,a,i,s);return null!=o&&(d=Xt(d,o)),ys(d,u,c,l)}const d=Object(ae.a)(e,"x","depthwiseConv2d","float32"),p=Object(ae.a)(t,"filter","depthwiseConv2d","float32");let h=d,f=!1;3===d.rank&&(f=!0,h=Qn(d,[1,d.shape[0],d.shape[1],d.shape[2]])),E.b(4===h.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`)),E.b(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),E.b(h.shape[3]===p.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`)),null==i&&(i=[1,1]),E.b(Xn(n,i),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`)),Zn("fused depthwiseConv2d",r,s);const m=zn(h.shape,p.shape,n,i,r,s,!0);let g,x;null!=o&&(g=Object(ae.a)(o,"bias","fused conv2d"),[g]=Object(Te.makeTypesMatch)(g,d),Me(m.outShape,g.shape)),null!=c&&(x=Object(ae.a)(c,"prelu weights","fused depthwiseConv2d"));const v=(e,t)=>{E.b(Kn(i),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`));const[a,o,c,l]=t,d=vs(e,c,u),p=_s(o.shape,d,a,n,r,i,s),h=Ss(o,d,a.shape,n,r,i,s);if(null!=l){return[p,h,ks(g,d)]}return[p,h]},k={x:h,filter:p,bias:g,preluActivationWeights:x},y={strides:n,pad:r,dataFormat:a,dilations:i,dimRoundingMode:s,activation:u,leakyreluAlpha:l};if(null==o){const e=un(((e,t,n)=>{let r=b.a.runKernel(re.nb,k,y);return n([t,e,r]),f&&(r=Qn(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:v}}));return e(h,p)}{const e=un(((e,t,n,r)=>{let a=b.a.runKernel(re.nb,k,y);return r([t,e,a,n]),f&&(a=Qn(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:v}}));return e(h,p,g)}}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Os=Object(ie.b)({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:i="linear",preluActivationWeights:s,leakyreluAlpha:o}){if(!1===ws(b.a.state.gradientDepth,i)){let u=$e(e,t,n,r);return null!=a&&(u=Xt(u,a)),ys(u,i,s,o)}let u=Object(ae.a)(e,"a","fused matMul"),c=Object(ae.a)(t,"b","fused matMul");[u,c]=Object(Te.makeTypesMatch)(u,c);const l=n?u.shape[u.rank-2]:u.shape[u.rank-1],d=r?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?u.shape[u.rank-1]:u.shape[u.rank-2],h=r?c.shape[c.rank-2]:c.shape[c.rank-1],f=u.shape.slice(0,-2),m=c.shape.slice(0,-2),g=E.O(f),x=E.O(m);E.b(l===d,(()=>`Error in fused matMul: inner shapes (${l}) and (${d}) of Tensors with shapes ${u.shape} and ${c.shape} and transposeA=${n} and transposeB=${r} must match.`));const v=Me(u.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,h]),k=Qn(u,n?[g,l,p]:[g,p,l]),y=Qn(c,r?[x,h,d]:[x,d,h]);let w,I;null!=a&&(w=Object(ae.a)(a,"bias","fused matMul"),[w]=Object(Te.makeTypesMatch)(w,u),Me(v,w.shape)),null!=s&&(I=Object(ae.a)(s,"prelu weights","fused matMul"));const S=(e,t)=>{const[s,o,u,c]=t,l=vs(Qn(e,u.shape),u,i);let d,p;if(n||r?!n&&r?(d=$e(l,o,!1,!1),p=$e(l,s,!0,!1)):n&&!r?(d=$e(o,l,!1,!0),p=$e(s,l,!1,!1)):(d=$e(o,l,!0,!0),p=$e(l,s,!0,!0)):(d=$e(l,o,!1,!0),p=$e(s,l,!0,!1)),null!=a){return[d,p,ks(c,l)]}return[d,p]},_={a:k,b:y,bias:w,preluActivationWeights:I},C={transposeA:n,transposeB:r,activation:i,leakyreluAlpha:o};if(null==a){const e=un(((e,t,n)=>{const r=b.a.runKernel(re.od,_,C);return n([e,t,r]),{value:Qn(r,v),gradFunc:S}}));return e(k,y)}{const e=un(((e,t,n,r)=>{const a=b.a.runKernel(re.od,_,C);return r([e,t,a,n]),{value:Qn(a,v),gradFunc:S}}));return e(k,y,w)}}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ts=Object(ie.b)({hammingWindow_:function(e){return bs(e,.54,.46)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $s=Object(ie.b)({hannWindow_:function(e){return bs(e,.5,.5)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const As=Object(ie.b)({frame_:function(e,t,n,r=!1,a=0){let i=0;const s=[];for(;i+t<=e.size;)s.push(rr(e,i,t)),i+=n;if(r)for(;i`Error in cropAndResize: image must be rank 4,but got rank ${s.rank}.`)),E.b(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`)),E.b(1===u.rank&&u.shape[0]===c,(()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`)),E.b(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),E.b(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),E.b("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const l={image:s,boxes:o,boxInd:u},d={method:a,extrapolationValue:i,cropSize:r};return b.a.runKernel(re.L,l,d)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Rs=Object(ie.b)({flipLeftRight_:function(e){const t=Object(ae.a)(e,"image","flipLeftRight","float32");E.b(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return b.a.runKernel(re.hb,n,{})}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fs=Object(ie.b)({grayscaleToRGB_:function(e){const t=Object(ae.a)(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];E.b(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),E.b(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,qr(t,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ms=Object(ie.b)({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Object(ae.a)(e,"image","rotateWithOffset","float32");E.b(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const i={image:a},s={radians:t,fillValue:n,center:r};return b.a.runKernel(re.yc,i,s)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ds(e,t,n,r,a,i){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==i&&(i=0);const s=e.shape[0];return n=Math.min(n,s),E.b(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),E.b(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),E.b(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),E.b(1===t.rank,(()=>"scores must be a 1D tensor")),E.b(t.shape[0]===s,(()=>`scores has incompatible shape with boxes. Expected ${s}, but was ${t.shape[0]}`)),E.b(0<=i&&i<=1,(()=>`softNmsSigma must be in [0, 1], but was '${i}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:i}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ps=Object(ie.b)({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const i=Object(ae.a)(e,"boxes","nonMaxSuppression","float32"),s=Object(ae.a)(t,"scores","nonMaxSuppression","float32"),o=Ds(i,s,n,r,a),u={maxOutputSize:n=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:a=o.scoreThreshold};return b.a.runKernel(re.ac,{boxes:i,scores:s},u)}}); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bs(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,i=0,s=!1;for(;r>>1);const o=n(t,e[i]);o>0?r=i+1:(a=i,s=!o)}return s?r:-r-1} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(e,t,n||js)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function js(e,t){return e>t?1:ea&&c.push({score:t[e],boxIndex:e,suppressBeginIndex:0});c.sort(Hs);const l=i>0?-.5/i:0,d=[],p=[];for(;d.length0;){const t=c.pop(),{score:n,boxIndex:i,suppressBeginIndex:s}=t;if(n=s;--n){const s=Us(e,i,d[n]);if(s>=r){o=!0;break}if(t.score=t.score*Vs(r,l,s),t.score<=a)break}t.suppressBeginIndex=d.length,o||(t.score===n?(d.push(i),p.push(t.score)):t.score>a&&Bs(c,t,Hs))}const h=d.length,f=n-h;o&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:d};return s&&(m.selectedScores=p),u&&(m.validOutputs=h),m}function Us(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),s=Math.min(r[1],r[3]),o=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(a[0],a[2]),l=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(o-i)*(u-s),f=(d-c)*(p-l);if(h<=0||f<=0)return 0;const m=Math.max(i,c),b=Math.max(s,l),g=Math.min(o,d),x=Math.min(u,p),v=Math.max(g-m,0)*Math.max(x-b,0);return v/(h+f-v)}function Vs(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Hs(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qs=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const i=Object(ae.a)(e,"boxes","nonMaxSuppressionAsync"),s=Object(ae.a)(t,"scores","nonMaxSuppressionAsync"),o=Ds(i,s,n,r,a);n=o.maxOutputSize,r=o.iouThreshold,a=o.scoreThreshold;const u=await Promise.all([i.data(),s.data()]),c=u[0],l=u[1],{selectedIndices:d}=Ls(c,l,n,r,a);return i!==e&&i.dispose(),s!==t&&s.dispose(),qi(d,"int32")}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ks=Object(ie.b)({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,i=0){const s=Object(ae.a)(e,"boxes","nonMaxSuppression"),o=Object(ae.a)(t,"scores","nonMaxSuppression"),u=Ds(s,o,n,r,a,i),c={boxes:s,scores:o},l={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:i=u.softNmsSigma},d=b.a.runKernel(re.cc,c,l);return{selectedIndices:d[0],selectedScores:d[1]}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xs=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,i=0){const s=Object(ae.a)(e,"boxes","nonMaxSuppressionAsync"),o=Object(ae.a)(t,"scores","nonMaxSuppressionAsync"),u=Ds(s,o,n,r,a,i);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,i=u.softNmsSigma;const c=await Promise.all([s.data(),o.data()]),l=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=Ws(l,d,n,r,a,i);return s!==e&&s.dispose(),o!==t&&o.dispose(),{selectedIndices:qi(p,"int32"),selectedScores:qi(h)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ys=Object(ie.b)({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,i=!1){const s=Object(ae.a)(e,"boxes","nonMaxSuppression"),o=Object(ae.a)(t,"scores","nonMaxSuppression"),u=Ds(s,o,n,r,a,null),c={boxes:s,scores:o},l={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:i},d=b.a.runKernel(re.bc,c,l);return{selectedIndices:d[0],validOutputs:d[1]}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zs=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,i=!1){const s=Object(ae.a)(e,"boxes","nonMaxSuppressionAsync"),o=Object(ae.a)(t,"scores","nonMaxSuppressionAsync"),u=Ds(s,o,n,r,a,null),c=u.maxOutputSize,l=u.iouThreshold,d=u.scoreThreshold,[p,h]=await Promise.all([s.data(),o.data()]),{selectedIndices:f,validOutputs:m}=zs(p,h,c,l,d,i);return s!==e&&s.dispose(),o!==t&&o.dispose(),{selectedIndices:qi(f,"int32"),validOutputs:ln(m,"int32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qs=Object(ie.b)({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Object(ae.a)(e,"images","resizeBilinear");E.b(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),E.b(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),E.b(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let i=a,s=!1;3===a.rank&&(s=!0,i=Qn(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const[]=t,o={images:i},u={alignCorners:n,halfPixelCenters:r,size:t},c=b.a.runKernel(re.tc,o,u);return s?Qn(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Js=Object(ie.b)({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Object(ae.a)(e,"images","resizeNearestNeighbor");E.b(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),E.b(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),E.b("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),E.b(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let i=a,s=!1;3===a.rank&&(s=!0,i=Qn(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const[]=t,o={images:i},u={alignCorners:n,halfPixelCenters:r,size:t},c=b.a.runKernel(re.vc,o,u);return s?Qn(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const eo=Object(ie.b)({threshold_:function(e,t="binary",n=!1,r=.5){const a=Object(ae.a)(e,"image","threshold"),i=a.shape[0]*a.shape[1];let s,o,u,c,l=Qt(qi([r]),255);if(E.b(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),E.b(3===a.shape[2]||1===a.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`)),E.b("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),E.b("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[s,o,u]=Bi(a,[1,1,1],-1);const e=Qt(s,.2989),t=Qt(o,.587),n=Qt(u,.114);c=Xt(Xt(e,t),n)}else c=e;if("otsu"===t){l=function(e,t){let n,r,a,i,s,o,u=qi([-1]),c=qi([0]),l=qi([0]);for(let d=0;d`Error in transform: image must be rank 4,but got rank ${s.rank}.`)),E.b(2===o.rank&&(o.shape[0]===s.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),E.b(null==i||2===i.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${i}.`));const u={image:s,transforms:o},c={interpolation:n,fillMode:r,fillValue:a,outputShape:i};return b.a.runKernel(re.hd,u,c)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const no=Object(ie.b)({bandPart_:function(e,t,n){Object(E.b)(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),Object(E.b)(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const r=Object(ae.a)(e,"a","bandPart");Object(E.b)(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const a=r.shape,[i,s]=r.shape.slice(-2);if(!(t<=i))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${i}).`);if(!(n<=s))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${s}).`);t<0&&(t=i),n<0&&(n=s);const o=Qn(pi(0,i,1,"int32"),[-1,1]),u=pi(0,s,1,"int32"),c=bn(o,u),l=_a(ia(c,ln(+t,"int32")),Qr(c,ln(-n,"int32"))),d=Da([i,s],r.dtype);return Qn(Wi(ns(Qn(r,[-1,i,s])).map((e=>Br(l,e,d)))),a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ro=Object(ie.b)({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,Object(E.b)(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`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Bi(e,e.shape[0],0).map((e=>zi(e,[0])));Object(E.b)(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t{let e=r[t];if(t>0)for(let r=0;r{Object(E.b)(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let a=Kr(n),i=oe(e);const s=Ki([[1]],[1,1]);let o=oe(s);const u=n>=r?r:n;for(let e=0;e{const t=rr(i,[e,e],[n-e,1]),u=cs(t),c=rr(i,[e,e],[1,1]),l=Br(Zr(c,0),Ki([[-1]]),Ki([[1]])),d=bn(c,Qt(l,u)),p=Zt(t,d);o=1===p.shape[0]?oe(s):tr([s,rr(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const h=la(Zt($e(l,d),u)),f=rr(i,[e,0],[n-e,r]),m=Qt(h,o),b=Ne(o);if(0===e)i=bn(f,$e(m,$e(b,f)));else{const t=bn(f,$e(m,$e(b,f)));i=tr([rr(i,[0,0],[e,r]),t],0)}const g=Ne(m),x=rr(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=bn(x,$e($e(x,o),g));else{const t=bn(x,$e($e(x,o),g));a=tr([rr(a,[0,0],[n,e]),t],1)}return[o,i,a]})),Pt([t,u,c])}return!t&&n>r&&(a=rr(a,[0,0],[n,r]),i=rr(i,[0,0],[r,r])),[a,i]}))}const io=Object(ie.b)({qr_:function(e,t=!1){if(Object(E.b)(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return ao(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=ns(Qn(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],i=[];r.forEach((e=>{const[n,r]=ao(e,t);a.push(n),i.push(r)}));return[Qn(Wi(a,0),e.shape),Qn(Wi(i,0),e.shape)]}}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var so;!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"}(so||(so={}));const oo=Object(ie.b)({computeWeightedLoss_:function(e,t,n=so.SUM_BY_NONZERO_WEIGHTS){const r=Object(ae.a)(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=Object(ae.a)(t,"weights","computeWeightedLoss"));const i=null==a?r:Qt(r,a);if(n===so.NONE)return i;if(n===so.SUM)return fa(i);if(n===so.MEAN){if(null==a)return Ma(i);{const e=r.size/a.size,t=Zt(fa(i),fa(a));return e>1?Zt(t,ln(e)):t}}if(n===so.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Zt(fa(i),ln(r.size));{const e=Qt(a,Pa(r.shape)),t=se(fa(Ha(e,ln(0))),"float32");return Zt(fa(i),t)}}throw Error(`Unknown reduction: ${n}`)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uo=Object(ie.b)({absoluteDifference_:function(e,t,n,r=so.SUM_BY_NONZERO_WEIGHTS){const a=Object(ae.a)(e,"labels","absoluteDifference"),i=Object(ae.a)(t,"predictions","absoluteDifference");let s=null;null!=n&&(s=Object(ae.a)(n,"weights","absoluteDifference")),Object(E.e)(a.shape,i.shape,"Error in absoluteDifference: ");const o=xn(bn(a,i));return oo(o,s,r)}});const co=Object(ie.b)({cosineDistance_:function(e,t,n,r,a=so.SUM_BY_NONZERO_WEIGHTS){const i=Object(ae.a)(e,"labels","cosineDistance"),s=Object(ae.a)(t,"predictions","cosineDistance");let o=null;null!=r&&(o=Object(ae.a)(r,"weights","cosineDistance")),Object(E.e)(i.shape,s.shape,"Error in cosineDistance: ");const u=ln(1),c=bn(u,fa(Qt(i,s),n,!0));return oo(c,o,a)}});const lo=Object(ie.b)({hingeLoss_:function(e,t,n,r=so.SUM_BY_NONZERO_WEIGHTS){let a=Object(ae.a)(e,"labels","hingeLoss");const i=Object(ae.a)(t,"predictions","hingeLoss");let s=null;null!=n&&(s=Object(ae.a)(n,"weights","hingeLoss")),Object(E.e)(a.shape,i.shape,"Error in hingeLoss: ");const o=ln(1);a=bn(Qt(ln(2),a),o);const u=mi(bn(o,Qt(a,i)));return oo(u,s,r)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const po=Object(ie.b)({huberLoss_:function(e,t,n,r=1,a=so.SUM_BY_NONZERO_WEIGHTS){const i=Object(ae.a)(e,"labels","huberLoss"),s=Object(ae.a)(t,"predictions","huberLoss");let o=null;null!=n&&(o=Object(ae.a)(n,"weights","huberLoss")),Object(E.e)(i.shape,s.shape,"Error in huberLoss: ");const u=ln(r),c=xn(bn(s,i)),l=La(c,u),d=bn(c,l),p=Xt(Qt(ln(.5),en(l)),Qt(u,d));return oo(p,o,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ho=Object(ie.b)({logLoss_:function(e,t,n,r=1e-7,a=so.SUM_BY_NONZERO_WEIGHTS){const i=Object(ae.a)(e,"labels","logLoss"),s=Object(ae.a)(t,"predictions","logLoss");let o=null;null!=n&&(o=Object(ae.a)(n,"weights","logLoss")),Object(E.e)(i.shape,s.shape,"Error in logLoss: ");const u=ln(1),c=ln(r),l=la(Qt(i,ua(Xt(s,c)))),d=Qt(bn(u,i),ua(Xt(bn(u,s),c))),p=bn(l,d);return oo(p,o,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fo=Object(ie.b)({meanSquaredError_:function(e,t,n,r=so.SUM_BY_NONZERO_WEIGHTS){const a=Object(ae.a)(e,"labels","meanSquaredError"),i=Object(ae.a)(t,"predictions","meanSquaredError");let s=null;null!=n&&(s=Object(ae.a)(n,"weights","meanSquaredError")),Object(E.e)(a.shape,i.shape,"Error in meanSquaredError: ");const o=Li(a,i);return oo(o,s,r)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mo=Object(ie.b)({sigmoidCrossEntropy_:function(e,t,n,r=0,a=so.SUM_BY_NONZERO_WEIGHTS){let i=Object(ae.a)(e,"multiClassLabels","sigmoidCrossEntropy");const s=Object(ae.a)(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=Object(ae.a)(n,"weights","sigmoidCrossEntropy")),Object(E.e)(i.shape,s.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=ln(r),t=ln(1),n=ln(.5);i=Xt(Qt(i,bn(t,e)),Qt(n,e))}const u=function(e,t){const n=Object(ae.a)(e,"labels","sigmoidCrossEntropyWithLogits"),r=Object(ae.a)(t,"logits","sigmoidCrossEntropyWithLogits");Object(E.e)(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=mi(r),i=Qt(r,n),s=ca(Ur(la(xn(r))));return Xt(bn(a,i),s)}(i,s);return oo(u,o,a)}}); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bo=Object(ie.b)({softmaxCrossEntropy_:function(e,t,n,r=0,a=so.SUM_BY_NONZERO_WEIGHTS){let i=Object(ae.a)(e,"onehotLabels","softmaxCrossEntropy");const s=Object(ae.a)(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=Object(ae.a)(n,"weights","softmaxCrossEntropy")),Object(E.e)(i.shape,s.shape,"Error in softmaxCrossEntropy: "),r>0){const e=ln(r),t=ln(1),n=ln(i.shape[1]);i=Xt(Qt(i,bn(t,e)),Zt(e,n))}const u=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 r=un(((e,t,r)=>{const a=Sa(t,[n],!0),i=bn(se(t,"float32"),a);r([e,i]);const s=la(Qt(i,e));return{value:fa(s,[n]),gradFunc:(e,t)=>{const[r,a]=t,i=va(e.shape,[n]);return[Qt(Qn(e,i),bn(se(r,"float32"),Ur(a))),Qt(Qn(e,i),bn(Ur(a),se(r,"float32")))]}}}));return r(e,t)}(i,s);return oo(u,o,a)}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const go=Object(ie.b)({sparseFillEmptyRows_:function(e,t,n,r){const a=Object(ae.a)(e,"indices","sparseFillEmptyRows","int32"),i=Object(ae.a)(t,"values","sparseFillEmptyRows"),s=Object(ae.a)(n,"denseShape","sparseFillEmptyRows","int32"),o=Object(ae.a)(r,"defaultValue","sparseFillEmptyRows",i.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==i.rank)throw new Error(`Values should be Tensor1D but received shape ${i.shape}`);if(1!==s.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${s.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const u={indices:a,values:i,denseShape:s,defaultValue:o},c=b.a.runKernel(re.Nc,u);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xo=Object(ie.b)({sparseReshape_:function(e,t,n){const r=Object(ae.a)(e,"inputIndices","sparseReshape","int32"),a=Object(ae.a)(t,"inputShape","sparseReshape","int32"),i=Object(ae.a)(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`New shape should be Tensor1D but received shape ${i.shape}`);const s={inputIndices:r,inputShape:a,newShape:i},o=b.a.runKernel(re.Oc,s);return{outputIndices:o[0],outputShape:o[1]}}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vo=Object(ie.b)({sparseSegmentMean_:function(e,t,n){const r=Object(ae.a)(e,"data","sparseSegmentMean"),a=Object(ae.a)(t,"indices","sparseSegmentMean","int32"),i=Object(ae.a)(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==i.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${i.shape}`);const s={data:r,indices:a,segmentIds:i};return b.a.runKernel(re.Pc,s)}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ko=Object(ie.b)({sparseSegmentSum_:function(e,t,n){const r=Object(ae.a)(e,"data","sparseSegmentSum"),a=Object(ae.a)(t,"indices","sparseSegmentSum","int32"),i=Object(ae.a)(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==i.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${i.shape}`);const s={data:r,indices:a,segmentIds:i};return b.a.runKernel(re.Qc,s)}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yo=Object(ie.b)({stringNGrams_:function(e,t,n,r,a,i,s,o){const u=Object(ae.a)(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const c=Object(ae.a)(t,"dataSplits","stringNGrams");if("int32"!==c.dtype)throw new Error("Data splits must be of datatype int32");const l={separator:n,nGramWidths:r,leftPad:a,rightPad:i,padWidth:s,preserveShortSequences:o},d={data:u,dataSplits:c},p=b.a.runKernel(re.Yc,d,l);return{nGrams:p[0],nGramsSplits:p[1]}}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wo=Object(ie.b)({stringSplit_:function(e,t,n=!0){const r=Object(ae.a)(e,"input","stringSplit","string"),a=Object(ae.a)(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const i={skipEmpty:n},s={input:r,delimiter:a},o=b.a.runKernel(re.Zc,s,i);return{indices:o[0],values:o[1],shape:o[2]}}}); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Io=Object(ie.b)({stringToHashBucketFast_:function(e,t){const n=Object(ae.a)(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return b.a.runKernel(re.ad,a,r)}}),So={fft:Mi,ifft:Di,rfft:ji,irfft:Pi},_o={hammingWindow:Ts,hannWindow:$s,frame:As,stft:Ns},Co={flipLeftRight:Rs,grayscaleToRGB:Fs,resizeNearestNeighbor:Js,resizeBilinear:Qs,rotateWithOffset:Ms,cropAndResize:Es,nonMaxSuppression:Ps,nonMaxSuppressionAsync:qs,nonMaxSuppressionWithScore:Ks,nonMaxSuppressionWithScoreAsync:Xs,nonMaxSuppressionPadded:Ys,nonMaxSuppressionPaddedAsync:Zs,threshold:eo,transform:to},Oo={bandPart:no,gramSchmidt:ro,qr:io},To={absoluteDifference:uo,computeWeightedLoss:oo,cosineDistance:co,hingeLoss:lo,huberLoss:po,logLoss:ho,meanSquaredError:fo,sigmoidCrossEntropy:mo,softmaxCrossEntropy:bo},$o={sparseFillEmptyRows:go,sparseReshape:xo,sparseSegmentMean:vo,sparseSegmentSum:ko},Ao={stringNGrams:yo,stringSplit:wo,stringToHashBucketFast:Io},No={sgd:Sn.sgd,momentum:Sn.momentum,adadelta:Sn.adadelta,adagrad:Sn.adagrad,rmsprop:Sn.rmsprop,adamax:Sn.adamax,adam:Sn.adam}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Eo=n(93); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ro(e,t){const n=e[0].length;e.forEach(((e,t)=>{E.b(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),E.b(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,a)=>{for(let i=0;i`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`))}))}function Fo(e,t){const n=e[0].slice();for(let r=1;r=2*t+1||r%2==1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function Lo(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let n=1;n/g;function uu(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(ou,"").length)/su.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 ("->").');const[r,a]=e.split(su);Object(E.b)(-1===r.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const i=r.split(","),s=i.length;if(t!==s)throw new Error(`Expected ${s} input tensors, received ${t}`);if(s>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let e=0;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-1!==e)),{permutationIndices:n,expandDims:r}}function lu(e,t,n){const r=new Array(e);for(let e=0;e`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(a)}, but got dimension ${a[n]}`))}}function du(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let e=0;ee===t))}function hu(e,t){const n=[];for(let r=0;r"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{const a=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);Object(E.b)(a<=1,(()=>"There should be only one negative value in split array."));const i=t.indexOf(-1);if(-1!==i){const r=t.reduce(((e,t)=>t>0?e+t:e));t[i]=e.shape[n]-r}Object(E.b)(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function mu(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function bu(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function gu(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xu(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function vu(e,t){return`size ${e} must be non-negative, not ${t}`}function ku(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function yu(e,t){return`Input to reshape is a SparseTensor with ${Object(E.O)(e)}\n dense values, but the requested shape requires a multiple of ${Object(E.O)(t)}. inputShape=${e} outputShape= ${t}`}function wu(e,t){return`Input to reshape is a tensor with ${Object(E.O)(e)} dense values, but the requested shape has ${Object(E.O)(t)}. inputShape=${e} outputShape=${t}`} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Iu(){return"segment ids must be >= 0"}function Su(){return"segment ids are not increasing"}function _u(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Cu(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ou(e,t){let n,r=!1;for(e<=Mo?(n=e,r=!0):n=Object(E.G)(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=Object(E.G)(e,n+1);return n}function Tu(e,t,n){const r=[],a=e.length;for(let i=0;ia))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>i)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${i}).`);if(nObject(mt.decodeString)(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Nu(e){return e.map((e=>Object(mt.encodeString)(e)))}var Eu=n(53),Ru=n(50); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return p}));var r=n(3),a=n(9),i=n(14),s=n(15),o=n(6); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function u(e,t){let n=e;if(Object(s.A)(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Object(s.A)(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Object(a.c)().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&c(e,r,[]),r}function c(e,t,n){if(n=n||[],!Array.isArray(e)&&!Object(s.A)(e))return void Object(s.b)(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));Object(s.b)(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),Object(s.b)(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t=0&&(c=a),l(a,c,t,n),null==e||!Object(s.A)(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const d=u(e,c);Object(s.A)(e)||Array.isArray(e)||(e=[e]);const p="string"!==c?Object(o.toTypedArray)(e,c):Object(s.m)(e,[],!0);return r.a.makeTensor(p,d,c)}function p(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>d(e,`${t}[${a}]`,n,r)))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return s}));var r=n(3),a=n(15); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const i="__op";function s(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+=i;const o=(...e)=>{r.a.startScope(n);try{const t=s(...e);return Object(a.x)(t)&&console.error("Cannot return a Promise inside of tidy."),r.a.endScope(t),t}catch(e){throw r.a.endScope(null),e}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return v})),n.d(t,"a",(function(){return k}));var r=n(50),a=n(9),i=n(35),s=n(4),o=n(30),u=n(29),c=n(6),l=n(15); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class d{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new h)}profileKernel(e,t,n){let r;const i=()=>{r=n()};let s;const o=c.now();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(i);else{i();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:c.now()-o})}if(Object(a.c)().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{p(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:i}=e;n.forEach((e=>{Promise.all([e.data(),r,i]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function p(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?r:""} `}}console.log(`%c${o}\t%c${s}\t%c${u}D ${d}\t%c${c}\t%c${p}\t%c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var f=n(14),m=n(10); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function b(e){return null!=e.kernelName}class g{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 x{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new g}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){Object(o.d)(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 r.b||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r)),(()=>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 x.nextTensorId++}nextVariableId(){return x.nextVariableId++}clone(e){const t=k.runKernel(s.tb,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return k.runKernel(s.x,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=Object(o.c)(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 r=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],s=r-t-a-i;if(s>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${s} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,i=this.state.numTensors;let s,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const c=b(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(b(e)){const{kernelName:t,inputs:a,attrs:i}=e;null==this.backendName&&this.backend;const c=Object(o.c)(t,this.backendName);l.b(null!=c,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),s=()=>{const e=this.backend.numDataIds();u=c.kernelFunc({inputs:a,attrs:i,backend:this.backend});const s=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,s);const o=s.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,a,o);n=this.saveTensorsForBackwardMode(e)}return o}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};s=()=>{const e=this.backend.numDataIds();u=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,e,n),n}}const{inputs:d,attrs:p}=e,h=b(e)?null:e.backwardsFunc;let f;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(f=this.profiler.profileKernel(c,d,(()=>s())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs):t=s()})),r&&this.addTapeNode(c,d,t,h,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(d).map((e=>null!=d[e]?d[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=Object(o.b)(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let i;r.saveAllInputs?(l.b(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),i=Object.keys(t).map((e=>t[e]))):i=e.map((e=>t[e]));const s=n.filter(((e,t)=>a[t]));return i.concat(s)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&l.z(e[0])&&(a=e.map((e=>c.encodeString(e))));const i=r.write(a,t,n),s=new f.a(t,n,i,this.nextTensorId());if(this.trackTensor(s,r),"string"===n){const e=this.state.tensorInfo.get(i),t=Object(l.f)(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return s}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,i=new f.a(r,a,n,this.nextTensorId());return this.trackTensor(i,t),i}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new f.c(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*l.g(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 f.c||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*l.g(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,r,a,i){const s={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},u=Object(o.b)(e);null!=u&&(r=u.gradFunc),null!=r&&(s.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=l.F(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],a,i))),this.state.activeTape.push(s)}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=Object(m.getTensorsInContainer)(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(l.b(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 a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));l.b(a instanceof f.a,(()=>"The result y returned by f() must be a tensor."));const i=function(e,t,n){const r={},a={};for(let e=0;er[e.id]=!0)),o=!0,a[i.id]=!0;break}if(o)break}}const i={};i[n.id]=!0;const s={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e0)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[a.id]=null==n?function(e){const t=Object(l.D)(Object(l.O)(e),"float32");return k.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const i=t[a],s=[];if(i.outputs.forEach((t=>{const n=e[t.id];null!=n?s.push(n):s.push(null)})),null==i.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${i.kernelName}.`);const o=i.gradient(s);for(const t in i.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const s=i.inputs[t];if(!l.a(a.shape,s.shape))throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${s.shape}'`);if(null==e[s.id])e[s.id]=a;else{const t=e[s.id];e[s.id]=r(t,a),t.dispose()}}}}(e,i,(e=>this.tidy(e)),y);const r=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:a,grads:r}}))}customGrad(e){return l.b(l.u(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;l.b(t.every((e=>e instanceof f.a)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};t.forEach(((e,t)=>{r[t]=e}));return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),l.b(n.value instanceof f.a,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),l.b(l.u(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),i=Array.isArray(a)?a:[a];l.b(i.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),l.b(i.every((e=>e instanceof f.a)),(()=>"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 s={};return i.forEach(((e,t)=>{s[t]=()=>e})),s},inputs:r})}}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=Object(c.now)(),n=await this.backend.time(e);return n.wallMs=Object(c.now)()-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 g;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 v(){const e=Object(i.b)();if(null==e._tfengine){const t=new a.b(e);e._tfengine=new x(t)}return Object(a.d)(e._tfengine.ENV),Object(f.f)((()=>e._tfengine)),e._tfengine}x.nextTensorId=0,x.nextVariableId=0;const k=v();function y(e,t){const n={a:e,b:t};return k.runKernel(s.d,n)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"d",(function(){return s})),n.d(t,"e",(function(){return o})),n.d(t,"f",(function(){return u})),n.d(t,"g",(function(){return c})),n.d(t,"h",(function(){return l})),n.d(t,"i",(function(){return d})),n.d(t,"j",(function(){return p})),n.d(t,"k",(function(){return h})),n.d(t,"l",(function(){return f})),n.d(t,"n",(function(){return m})),n.d(t,"m",(function(){return b})),n.d(t,"o",(function(){return g})),n.d(t,"r",(function(){return x})),n.d(t,"p",(function(){return v})),n.d(t,"q",(function(){return k})),n.d(t,"s",(function(){return y})),n.d(t,"t",(function(){return w})),n.d(t,"u",(function(){return I})),n.d(t,"w",(function(){return S})),n.d(t,"v",(function(){return _})),n.d(t,"x",(function(){return C})),n.d(t,"y",(function(){return O})),n.d(t,"z",(function(){return T})),n.d(t,"A",(function(){return $})),n.d(t,"B",(function(){return A})),n.d(t,"C",(function(){return N})),n.d(t,"D",(function(){return E})),n.d(t,"E",(function(){return R})),n.d(t,"F",(function(){return F})),n.d(t,"G",(function(){return M})),n.d(t,"H",(function(){return D})),n.d(t,"I",(function(){return P})),n.d(t,"J",(function(){return B})),n.d(t,"K",(function(){return j})),n.d(t,"M",(function(){return L})),n.d(t,"N",(function(){return z})),n.d(t,"L",(function(){return W})),n.d(t,"O",(function(){return G})),n.d(t,"P",(function(){return U})),n.d(t,"Q",(function(){return V})),n.d(t,"R",(function(){return H})),n.d(t,"S",(function(){return q})),n.d(t,"T",(function(){return K})),n.d(t,"U",(function(){return X})),n.d(t,"W",(function(){return Y})),n.d(t,"V",(function(){return Z})),n.d(t,"oc",(function(){return Q})),n.d(t,"X",(function(){return J})),n.d(t,"Y",(function(){return ee})),n.d(t,"Z",(function(){return te})),n.d(t,"bb",(function(){return ne})),n.d(t,"ab",(function(){return re})),n.d(t,"cb",(function(){return ae})),n.d(t,"db",(function(){return ie})),n.d(t,"eb",(function(){return se})),n.d(t,"fb",(function(){return oe})),n.d(t,"gb",(function(){return ue})),n.d(t,"hb",(function(){return ce})),n.d(t,"ib",(function(){return le})),n.d(t,"jb",(function(){return de})),n.d(t,"lb",(function(){return pe})),n.d(t,"pb",(function(){return he})),n.d(t,"ob",(function(){return fe})),n.d(t,"qb",(function(){return me})),n.d(t,"rb",(function(){return be})),n.d(t,"tb",(function(){return ge})),n.d(t,"sb",(function(){return xe})),n.d(t,"ub",(function(){return ve})),n.d(t,"vb",(function(){return ke})),n.d(t,"wb",(function(){return ye})),n.d(t,"xb",(function(){return we})),n.d(t,"Ab",(function(){return Ie})),n.d(t,"Bb",(function(){return Se})),n.d(t,"Cb",(function(){return _e})),n.d(t,"Db",(function(){return Ce})),n.d(t,"Eb",(function(){return Oe})),n.d(t,"Fb",(function(){return Te})),n.d(t,"Hb",(function(){return $e})),n.d(t,"Ib",(function(){return Ae})),n.d(t,"Jb",(function(){return Ne})),n.d(t,"Gb",(function(){return Ee})),n.d(t,"Kb",(function(){return Re})),n.d(t,"yb",(function(){return Fe})),n.d(t,"zb",(function(){return Me})),n.d(t,"Lb",(function(){return De})),n.d(t,"Rb",(function(){return Pe})),n.d(t,"Mb",(function(){return Be})),n.d(t,"Pb",(function(){return je})),n.d(t,"Nb",(function(){return Le})),n.d(t,"Ob",(function(){return ze})),n.d(t,"Qb",(function(){return We})),n.d(t,"Sb",(function(){return Ge})),n.d(t,"Tb",(function(){return Ue})),n.d(t,"Ub",(function(){return Ve})),n.d(t,"Vb",(function(){return He})),n.d(t,"Wb",(function(){return qe})),n.d(t,"Xb",(function(){return Ke})),n.d(t,"Yb",(function(){return Xe})),n.d(t,"Zb",(function(){return Ye})),n.d(t,"dc",(function(){return Ze})),n.d(t,"ac",(function(){return Qe})),n.d(t,"bc",(function(){return Je})),n.d(t,"cc",(function(){return et})),n.d(t,"fc",(function(){return tt})),n.d(t,"ec",(function(){return nt})),n.d(t,"gc",(function(){return rt})),n.d(t,"hc",(function(){return at})),n.d(t,"ic",(function(){return it})),n.d(t,"jc",(function(){return st})),n.d(t,"kc",(function(){return ot})),n.d(t,"lc",(function(){return ut})),n.d(t,"mc",(function(){return ct})),n.d(t,"nc",(function(){return lt})),n.d(t,"pc",(function(){return dt})),n.d(t,"qc",(function(){return pt})),n.d(t,"sc",(function(){return ht})),n.d(t,"vc",(function(){return ft})),n.d(t,"wc",(function(){return mt})),n.d(t,"tc",(function(){return bt})),n.d(t,"uc",(function(){return gt})),n.d(t,"rc",(function(){return xt})),n.d(t,"xc",(function(){return vt})),n.d(t,"zc",(function(){return kt})),n.d(t,"Ac",(function(){return yt})),n.d(t,"Bc",(function(){return wt})),n.d(t,"Cc",(function(){return It})),n.d(t,"Dc",(function(){return St})),n.d(t,"Ec",(function(){return _t})),n.d(t,"Jc",(function(){return Ct})),n.d(t,"Hc",(function(){return Ot})),n.d(t,"Ic",(function(){return Tt})),n.d(t,"Gc",(function(){return $t})),n.d(t,"Fc",(function(){return At})),n.d(t,"Lc",(function(){return Nt})),n.d(t,"Tc",(function(){return Et})),n.d(t,"cd",(function(){return Rt})),n.d(t,"Mc",(function(){return Ft})),n.d(t,"Sc",(function(){return Mt})),n.d(t,"Kc",(function(){return Dt})),n.d(t,"Nc",(function(){return Pt})),n.d(t,"Oc",(function(){return Bt})),n.d(t,"Pc",(function(){return jt})),n.d(t,"Qc",(function(){return Lt})),n.d(t,"Rc",(function(){return zt})),n.d(t,"Vc",(function(){return Wt})),n.d(t,"Uc",(function(){return Gt})),n.d(t,"Xc",(function(){return Ut})),n.d(t,"Yc",(function(){return Vt})),n.d(t,"Zc",(function(){return Ht})),n.d(t,"ad",(function(){return qt})),n.d(t,"bd",(function(){return Kt})),n.d(t,"dd",(function(){return Xt})),n.d(t,"ed",(function(){return Yt})),n.d(t,"fd",(function(){return Zt})),n.d(t,"gd",(function(){return Qt})),n.d(t,"hd",(function(){return Jt})),n.d(t,"id",(function(){return en})),n.d(t,"jd",(function(){return tn})),n.d(t,"kd",(function(){return nn})),n.d(t,"ld",(function(){return rn})),n.d(t,"md",(function(){return an})),n.d(t,"nd",(function(){return sn})),n.d(t,"Wc",(function(){return on})),n.d(t,"kb",(function(){return un})),n.d(t,"yc",(function(){return cn})),n.d(t,"od",(function(){return ln})),n.d(t,"mb",(function(){return dn})),n.d(t,"nb",(function(){return pn}));const r="Abs",a="Acos",i="Acosh",s="Add",o="AddN",u="All",c="Any",l="ArgMax",d="ArgMin",p="Asin",h="Asinh",f="Atan",m="Atanh",b="Atan2",g="AvgPool",x="AvgPoolGrad",v="AvgPool3D",k="AvgPool3DGrad",y="BatchMatMul",w="BatchToSpaceND",I="Bincount",S="BroadcastTo",_="BroadcastArgs",C="Cast",O="Ceil",T="ClipByValue",$="Complex",A="ComplexAbs",N="Concat",E="Conv2D",R="Conv2DBackpropFilter",F="Conv2DBackpropInput",M="Conv3D",D="Conv3DBackpropFilterV2",P="Conv3DBackpropInputV2",B="Cos",j="Cosh",L="Cumprod",z="Cumsum",W="CropAndResize",G="DenseBincount",U="DepthToSpace",V="DepthwiseConv2dNative",H="DepthwiseConv2dNativeBackpropFilter",q="DepthwiseConv2dNativeBackpropInput",K="Diag",X="Dilation2D",Y="Dilation2DBackpropInput",Z="Dilation2DBackpropFilter",Q="RealDiv",J="Einsum",ee="Elu",te="EluGrad",ne="Erf",re="Equal",ae="Exp",ie="ExpandDims",se="Expm1",oe="FFT",ue="Fill",ce="FlipLeftRight",le="Floor",de="FloorDiv",pe="FusedBatchNorm",he="GatherV2",fe="GatherNd",me="Greater",be="GreaterEqual",ge="Identity",xe="IFFT",ve="Imag",ke="IsFinite",ye="IsInf",we="IsNan",Ie="LeakyRelu",Se="Less",_e="LessEqual",Ce="LinSpace",Oe="Log",Te="Log1p",$e="LogicalAnd",Ae="LogicalNot",Ne="LogicalOr",Ee="LogSoftmax",Re="LowerBound",Fe="LRN",Me="LRNGrad",De="Max",Pe="Maximum",Be="MaxPool",je="MaxPoolGrad",Le="MaxPool3D",ze="MaxPool3DGrad",We="MaxPoolWithArgmax",Ge="Mean",Ue="Min",Ve="Minimum",He="MirrorPad",qe="Mod",Ke="Multinomial",Xe="Multiply",Ye="Neg",Ze="NotEqual",Qe="NonMaxSuppressionV3",Je="NonMaxSuppressionV4",et="NonMaxSuppressionV5",tt="OnesLike",nt="OneHot",rt="Pack",at="PadV2",it="Pool",st="Pow",ot="Prelu",ut="Prod",ct="Range",lt="Real",dt="Reciprocal",pt="Relu",ht="Reshape",ft="ResizeNearestNeighbor",mt="ResizeNearestNeighborGrad",bt="ResizeBilinear",gt="ResizeBilinearGrad",xt="Relu6",vt="Reverse",kt="Round",yt="Rsqrt",wt="ScatterNd",It="SearchSorted",St="Select",_t="Selu",Ct="Slice",Ot="Sin",Tt="Sinh",$t="Sign",At="Sigmoid",Nt="Softplus",Et="Sqrt",Rt="Sum",Ft="SpaceToBatchND",Mt="SplitV",Dt="Softmax",Pt="SparseFillEmptyRows",Bt="SparseReshape",jt="SparseSegmentMean",Lt="SparseSegmentSum",zt="SparseToDense",Wt="SquaredDifference",Gt="Square",Ut="StridedSlice",Vt="StringNGrams",Ht="StringSplit",qt="StringToHashBucketFast",Kt="Sub",Xt="Tan",Yt="Tanh",Zt="Tile",Qt="TopK",Jt="Transform",en="Transpose",tn="Unique",nn="Unpack",rn="UnsortedSegmentSum",an="UpperBound",sn="ZerosLike",on="Step",un="FromPixels",cn="RotateWithOffset",ln="_FusedMatMul",dn="FusedConv2D",pn="FusedDepthwiseConv2D"},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"i",(function(){return o})),n.d(t,"k",(function(){return u})),n.d(t,"l",(function(){return c})),n.d(t,"m",(function(){return l})),n.d(t,"n",(function(){return d})),n.d(t,"h",(function(){return p})),n.d(t,"d",(function(){return h})),n.d(t,"s",(function(){return f})),n.d(t,"j",(function(){return m})),n.d(t,"u",(function(){return b})),n.d(t,"v",(function(){return g})),n.d(t,"e",(function(){return x})),n.d(t,"p",(function(){return v})),n.d(t,"r",(function(){return k})),n.d(t,"t",(function(){return y})),n.d(t,"q",(function(){return w})),n.d(t,"o",(function(){return I})),n.d(t,"b",(function(){return S})),n.d(t,"g",(function(){return _})),n.d(t,"c",(function(){return C})),n.d(t,"f",(function(){return O}));var r=n(0),a=n(36),i=n(11);function s(e,t){if(!e)throw new Error(t)}function o(e){return"boolean"==typeof e}function u(e){return"number"==typeof e&&Number.isInteger(e)}function c(e){return e instanceof Array&&e.every((e=>u(e)))}function l(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int8Array||e instanceof Uint8Array}function d(e){return 0===e[0]&&1===e[1]||(1===e[0]&&2===e[1]||2===e[0]&&3===e[1])}function p(e){if("float32"===e)return Float32Array;if("int32"===e)return Int32Array;if("uint32"===e)return Uint32Array;if("float16"===e)return Uint16Array;if("int8"===e)return Int8Array;if("uint8"===e)return Uint8Array;throw new Error("Type is not supported.")}function h(e){let t;return"float32"===e.dtype?t=i.d.float32:"int32"===e.dtype&&(t=i.d.int32),{type:t,dimensions:e.shape}}function f(e){s(e.type in i.d,"The operand type is invalid."),e.dimensions&&s(c(e.dimensions),"The dimensions is invalid.")}function m(e){return!e.every((e=>e>0))}function b(e,t,n){s(l(e),"The value is not a typed array."),s(e instanceof p(t),"The type of value is invalid."),s(e.length===v(n),`the value length ${e.length} is invalid, size of [${n}] ${v(n)} is expected.`)}function g(e,t){t===i.d.int32?s(Number.isInteger(e),"the value is not an int32."):t===i.d.uint32?s(Number.isInteger(e)&&e>=0,"the value is not an uint32."):t===i.d.int8?s(Number.isInteger(e)&&e>=-128&&e<=127,"the value is not an int8."):t===i.d.uint8&&s(Number.isInteger(e)&&e>=0&&e<=255,"the value is not an uint8.")}function x(e,t){const n=function(e){if("float32"===e)return"float32";if("int32"===e)return"int32";throw new Error("The operand type is not supported by TF.js.")}(e.type);if(void 0!==e.dimensions){s(l(t),"Only ArrayBufferView value is supported.");const a=t;b(a,e.type,e.dimensions);const i=function(e){let t;if(e instanceof Float32Array)t=new Float32Array(e.length);else if(e instanceof Int32Array)t=new Int32Array(e.length);else if(e instanceof Uint32Array)t=new Uint32Array(e.length);else if(e instanceof Uint16Array)t=new Uint16Array(e.length);else if(e instanceof Int8Array)t=new Int8Array(e.length);else{if(!(e instanceof Uint8Array))throw new Error("Type is not supported.");t=new Uint8Array(e.length)}return t.set(e),t}(a);return r.tensor(i,e.dimensions,n)}return"number"==typeof t?(g(t,e.type),r.scalar(t,n)):(b(t,e.type,e.dimensions),r.scalar(t[0],n))}function v(e){return void 0===e||c(e)&&0===e.length?1:e.reduce(((e,t)=>t>0?e*t:e),1)}function k(e,t=""){s(e instanceof i.c,`The parameter ${t} is not an operand.`)}function y(e,t=""){s(void 0===e||e instanceof i.c,`The parameter ${t} is not an optional operand.`)}function w(e,t){if("undefined"!=typeof e&&e.length>0)for(let n=0;n=t||e[n]<-t)return!1;return!0}function I(e){return e.reduce(((e,t)=>e*t))}function S(e,t){s(e.length===t.length,`The actual length ${e.length} is not equal to expected length ${t.length}.`);for(let n=0;nn?u-n:0;switch(e){case a.a["same-upper"]:s=Math.floor(c/2),o=Math.floor((c+1)/2);break;case a.a["same-lower"]:s=Math.floor((c+1)/2),o=Math.floor(c/2)}return[s,o]}function O(e,t){const n=[],r=e.length,a=t.length,i=Math.max(r,a);for(let s=0;s=8){const n=l.add(2*t),r=h(e,0).add(l),a=h(e,t-8);return b(m(a,37).mul(n).add(r),m(r,25).add(a).mul(n),n)}if(t>=4){const n=l.add(2*t);return b(f(e,0).shl(3).add(t),f(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return d(l.mul(n).xor(u.mul(r))).mul(l)}return l}(e,t):function(e,t=e.length){const n=l.add(2*t),r=h(e,0).mul(c),a=h(e,8),i=h(e,t-8).mul(n),s=h(e,t-16).mul(l);return b(m(r.add(a),43).add(m(i,30)).add(s),r.add(m(a.add(l),18)).add(i),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=l.add(2*t),r=h(e,0).mul(l),a=h(e,8),i=h(e,t-8).mul(n),s=h(e,t-16).mul(l),o=m(r.add(a),43).add(m(i,30)).add(s),u=b(o,r.add(m(a.add(l),18)).add(i),n),c=h(e,16).mul(n),d=h(e,24),p=o.add(h(e,t-32)).mul(n),f=u.add(h(e,t-24)).mul(n);return b(m(c.add(d),43).add(m(p,30)).add(f),c.add(m(d.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(c).add(113),i=d(a.mul(l).add(113)).mul(l),o=[s.UZERO,s.UZERO],p=[s.UZERO,s.UZERO];r=r.mul(l).add(h(e,0));let x=0;const v=64*(t-1>>6),k=v+(t-1&63)-63;do{r=m(r.add(a).add(o[0]).add(h(e,x+8)),37).mul(c),a=m(a.add(o[1]).add(h(e,x+48)),42).mul(c),r=r.xor(p[1]),a=a.add(o[0]).add(h(e,x+40)),i=m(i.add(p[0]),33).mul(c),o=g(e,x,o[1].mul(c),r.add(p[0])),p=g(e,x+32,i.add(p[1]),a.add(h(e,x+16))),[i,r]=[r,i],x+=64}while(x!==v);const y=c.add(i.and(255).shl(1));return x=k,p[0]=p[0].add(t-1&63),o[0]=o[0].add(p[0]),p[0]=p[0].add(o[0]),r=m(r.add(a).add(o[0]).add(h(e,x+8)),37).mul(y),a=m(a.add(o[1]).add(h(e,x+48)),42).mul(y),r=r.xor(p[1].mul(9)),a=a.add(o[0].mul(9).add(h(e,x+40))),i=m(i.add(p[0]),33).mul(y),o=g(e,x,o[1].mul(y),r.add(p[0])),p=g(e,x+32,i.add(p[1]),a.add(h(e,x+16))),[i,r]=[r,i],b(b(o[0],p[0],y).add(d(a).mul(u)).add(i),b(o[1],p[1],y).add(r),y)} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function v(e,t){return"string"===t?I(e):k([e],t)}function k(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=a.m(e)),Object(r.c)().getBool("DEBUG")&&a.h(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{null!=e&&r.util.assert("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"b",(function(){return s}));var r=n(0),a=n(7); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function i(e,t,n){return({inputs:i,attrs:s,backend:o})=>{const{x:u}=i;if(Object(a.a)(u,e),"string"===u.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const c=o,l=c.data.get(u.dataId).values,d=r.util.sizeFromShape(u.shape),p=n||u.dtype,h=r.util.getArrayFromDType(p,d);for(let e=0;e{const{x:o}=r;if(Object(a.a)(o,e),"string"===o.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const u=s,c=u.data.get(o.dataId).values,l=n||o.dtype,d=t(c,l,i);return u.makeTensorInfo(o.shape,l,d)}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return o})),n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return c}));var r=n(15); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a="tfjsflags";class i{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=s,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(o().getBool("IS_TEST")||o().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];o().getBool("IS_TEST")||o().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(Object(r.x)(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(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("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(a in e){e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function s(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 o(){return u}let u=null;function c(e){u=e}},function(e,t,n){"use strict";n.r(t),n.d(t,"makeTypesMatch",(function(){return s})),n.d(t,"assertTypesMatch",(function(){return o})),n.d(t,"isTensorInList",(function(){return u})),n.d(t,"getTensorsInContainer",(function(){return c}));var r=n(14),a=n(32),i=n(15); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function s(e,t){if(e.dtype===t.dtype)return[e,t];const n=Object(a.c)(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function o(e,t){Object(i.b)(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function u(e,t){return t.some((t=>t.id===e.id))}function c(e){const t=[];return l(e,t,new Set),t}function l(e,t,n){if(null==e)return;if(e instanceof r.a)return void t.push(e);if(a=e,!Array.isArray(a)&&"object"!=typeof a)return;var a;const i=e;for(const e in i){const r=i[e];n.has(r)||(n.add(r),l(r,t,n))}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return r})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return o})),n.d(t,"e",(function(){return u}));var r,a=n(5);!function(e){e.float32="float32",e.float16="float16",e.int32="int32",e.uint32="uint32",e.int8="int8",e.uint8="uint8"}(r||(r={}));class i{constructor(e){this.builder_=e}get builder(){return this.builder_}}class s extends i{constructor(e,t,n){super(n),a.a("string"==typeof e,"The name parameter is invalid"),this.name=e,a.s(t),this.desc=t}}class o extends i{constructor(e,t,n){super(n),this.desc=e,this.value=t}static createScalar(e,t=r.float32,n){return a.a(t in r,"The operand type is invalid."),a.v(e,t),new o({type:t},e,n)}static createTensor(e,t,n){a.a(a.m(t),"Only ArrayBufferView value type is supported.");const r=t;return a.s(e),a.u(r,e.type,e.dimensions),new o(e,r.slice(),n)}}class u extends i{constructor(e){super(e.builder),this.operation=e}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e){return(t,n,a,i,s)=>{const o=r.backend_util.assertAndGetBroadcastShape(t,n),u=o.length,c=r.util.computeStrides(o),l=r.util.sizeFromShape(o),d=r.util.getTypedArrayFromDType(s,l),p=t.length,h=n.length,f=r.util.computeStrides(t),m=r.util.computeStrides(n),b=r.backend_util.getBroadcastDims(t,o),g=r.backend_util.getBroadcastDims(n,o);if(b.length+g.length===0)for(let t=0;ts[e]=0));const o=r.util.locToIndex(s,p,f),l=n.slice(-h);g.forEach((e=>l[e]=0));const x=r.util.locToIndex(l,h,m);d[t]=e(a[o],i[x])}return[d,o]}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return u}));var r=n(0),a=n(7),i=n(28),s=n(18); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function o(e,t,n,o){return null==n?({inputs:n,backend:i})=>{const{a:s,b:u}=n,c=i;Object(a.a)([s,u],e);const l=c.data.get(s.dataId).values,d=c.data.get(u.dataId).values,p="string"===s.dtype?r.backend_util.fromUint8ToStringArray(l):l,h="string"===s.dtype?r.backend_util.fromUint8ToStringArray(d):d,f=o||s.dtype,[m,b]=t(s.shape,u.shape,p,h,f);return c.makeTensorInfo(b,f,m)}:({inputs:e,backend:r})=>{const{a:a,b:u}=e,c=r;if("complex64"===a.dtype||"complex64"===u.dtype){const e=Object(i.a)({inputs:{x:a},backend:c,attrs:{dtype:"complex64"}}),t=c.data.get(e.dataId),r=t.complexTensorInfos.real,o=t.complexTensorInfos.imag,l=c.data.get(r.dataId).values,d=c.data.get(o.dataId).values,p=Object(i.a)({inputs:{x:u},backend:c,attrs:{dtype:"complex64"}}),h=c.data.get(p.dataId),f=h.complexTensorInfos.real,m=h.complexTensorInfos.imag,b=c.data.get(f.dataId).values,g=c.data.get(m.dataId).values,[x,v,k]=n(a.shape,u.shape,l,d,b,g),y=c.makeTensorInfo(k,"float32",x),w=c.makeTensorInfo(k,"float32",v),I=Object(s.a)({inputs:{real:y,imag:w},backend:c});return c.disposeIntermediateTensorInfo(e),c.disposeIntermediateTensorInfo(p),c.disposeIntermediateTensorInfo(y),c.disposeIntermediateTensorInfo(w),I}{const e=c.data.get(a.dataId).values,n=c.data.get(u.dataId).values,r=o||a.dtype,[i,s]=t(a.shape,u.shape,e,n,r);return c.makeTensorInfo(s,r,i)}}}function u(e){return(t,n,a,i,s,o)=>{const u=r.backend_util.assertAndGetBroadcastShape(t,n),c=r.util.sizeFromShape(u),l=u.length,d=r.util.computeStrides(u),p=r.util.getTypedArrayFromDType("float32",c),h=r.util.getTypedArrayFromDType("float32",c),f=r.backend_util.getBroadcastDims(t,u),m=r.backend_util.getBroadcastDims(n,u),b=r.backend_util.mergeRealAndImagArrays(a,i),g=r.backend_util.mergeRealAndImagArrays(s,o),x=t.length,v=r.util.computeStrides(t),k=n.length,y=r.util.computeStrides(n);if(f.length+m.length===0)for(let t=0;ta[e]=0));const i=r.util.locToIndex(a,x,v),s=n.slice(-k);m.forEach((e=>s[e]=0));const o=r.util.locToIndex(s,k,y),u=e(b[2*i],b[2*i+1],g[2*o],g[2*o+1]);p[t]=u.real,h[t]=u.imag}return[p,h,u]}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"f",(function(){return m})),n.d(t,"e",(function(){return b})),n.d(t,"d",(function(){return g})),n.d(t,"a",(function(){return x})),n.d(t,"c",(function(){return v}));var r=n(35),a=n(15);function i(e,t,n,r){const i=Object(a.j)(t),o=function(e,t,n,r){const i=Object(a.O)(t),o=r[r.length-1],u=new Array(o).fill(0),l=t.length,d="complex64"===n?c(e):e;if(l>1)for(let e=0;e" "+e)).join("\n")),p.join("\n")}function s(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:Object(a.z)(e)?`'${e}'`:"bool"===n?o(e):parseFloat(e.toFixed(7)).toString(),Object(a.L)(r,t)}function o(e){return 0===e?"false":"true"}function u(e,t,n,r,a,i=!0){const l="complex64"===n?2:1,d=t[0],p=t.length;if(0===p){if("complex64"===n){return[s(c(e)[0],0,n)]}return"bool"===n?[o(e[0])]:[e[0].toString()]}if(1===p){if(d>20){const t=3*l;let r=Array.from(e.slice(0,t)),i=Array.from(e.slice((d-3)*l,d*l));return"complex64"===n&&(r=c(r),i=c(i)),["["+r.map(((e,t)=>s(e,a[t],n))).join(", ")+", ..., "+i.map(((e,t)=>s(e,a[d-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?c(e):Array.from(e)).map(((e,t)=>s(e,a[t],n))).join(", ")+"]"]}const h=t.slice(1),f=r.slice(1),m=r[0]*l,b=[];if(d>20){for(let t=0;t<3;t++){const r=t*m,i=r+m;b.push(...u(e.slice(r,i),h,n,f,a,!1))}b.push("...");for(let t=d-3;t`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||a.n(t,this.size),this.strides=Object(a.j)(e)}set(e,...t){0===t.length&&(t=[0]),a.b(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;tl.decodeString(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(),p().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=p().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>l.decodeString(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 p().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(p().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return h.print(this,e)}clone(){return this.throwIfDisposed(),h.clone(this)}toString(e=!1){return i(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),h.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),p().makeVariable(this,e,t,n)}}Object.defineProperty(x,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Object(r.a)("Tensor",(()=>x));class v extends x{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!a.a(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);p().disposeTensor(this),this.dataId=e.dataId,p().incRef(this,null)}dispose(){p().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(v,Symbol.hasInstance,{value:e=>e instanceof x&&null!=e.assign&&e.assign instanceof Function})},function(e,t,n){"use strict"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function r(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,o(e,t,n)}function a(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,o(e,n,r),o(t,n,r)}function i(e,t,n){return Math.max(e,Math.min(t,n))}function s(e){return e%2==0?e:e+1}function o(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function u(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`))}function h(e){d(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function f(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||E(e)&&!n)for(let r=0;r0),n){return new Promise(((r,a)=>{let i=0;const s=()=>{if(e())return void r();i++;const o=t(i);null!=n&&i>=n?a():setTimeout(s,o)};s()}))}function S(e,t){let n=1,r=-1;for(let t=0;t=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){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 a=e.slice();return a[r]=t/n,a}function _(e,t){const n=t.length;return d((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),d(e.every((e=>x(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function C(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,i=null==t||a?null:_(t,e).sort();let s=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),r.push(t)),i[s]<=t&&s++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function O(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)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function T(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 $(e,t){for(let n=0;nt+=e.length)),t}function M(e){return"string"==typeof e||e instanceof String}function D(e){return"boolean"==typeof e}function P(e){return"number"==typeof e}function B(e){return Array.isArray(e)?B(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":P(e)?"float32":M(e)?"string":D(e)?"bool":"float32"}function j(e){return!!(e&&e.constructor&&e.call&&e.apply)}function L(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function W(e,t,n,r=!1){const a=new Array;if(1===t.length){const i=t[0]*(r?2:1);for(let t=0;te*t))*(r?2:1);for(let t=0;te*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return W(0,e,t,n)}function U(e,t){const n=V(e,t);for(let e=0;ee*t),1);if(null==t||"float32"===t)return G(e,new Float32Array(n));if("int32"===t)return G(e,new Int32Array(n));if("bool"===t)return G(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function q(e){e.forEach((t=>{d(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function K(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;te.name)):Object.keys(e);for(let i=0;i{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,r=new Uint8Array(n);let a=0;for(let e=0;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 r=new Uint8Array(t);let a=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),r.buffer}const l="undefined"!=typeof e&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function d(t){return l?e.byteLength(t):new Blob([t]).size}function p(t){if(l)return e.from(t).toString("base64");const n=new Uint8Array(t);let r="";for(let e=0,t=n.length;e{t+=e.byteLength}));const n=new Uint8Array(t);let r=0;return e.forEach((e=>{n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function m(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function b(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.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}async function g(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),null!=e.weightsManifest){const[r,a]=await t(e.weightsManifest);n.weightSpecs=r,n.weightData=a}return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),n}function x(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:d(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:d(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function v(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(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 r=>{const a=new ArrayBuffer(4*r.length),i=new Uint32Array(a);for(let a=0;a>10]+(1023&s)]+t[s>>10];i[a]=o}return new Float32Array(a)}}}).call(this,n(104).Buffer)},function(e,t,n){"use strict"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function r(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,i=n.data.get(r.dataId).values,s=n.data.get(a.dataId).values,o=n.makeTensorInfo(r.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",i),imag:n.makeTensorInfo(a.shape,"float32",s)},o}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return a}));const a={kernelName:n(0).Complex,backendName:"cpu",kernelFunc:r}},function(e,t,n){"use strict"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function r(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return a}));const a={kernelName:n(0).Identity,backendName:"cpu",kernelFunc:r}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(3),a=n(15),i=n(6); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function s(e,t,n,s){if(null==s&&(s=Object(a.r)(e)),"complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Object(a.A)(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){Object(a.c)(t);const e=Object(a.O)(t),r=Object(a.O)(n);Object(a.b)(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Object(a.A)(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?Object(i.toTypedArray)(e,s):Object(a.m)(e,[],!0),r.a.makeTensor(e,t,s)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e){return(t,n,a)=>{const i=r.util.getTypedArrayFromDType(n,t.length);for(let n=0;ne+t[n]));d.set(l.get(...r),...n)}return"string"===i?r.backend_util.fromStringArrayToUint8(d.values):d.values}function s(e){const{inputs:t,backend:n,attrs:s}=e,{x:o}=t,{begin:u,size:c}=s;Object(a.a)(o,"slice");const[l,d]=r.slice_util.parseSliceParams(o,u,c);r.slice_util.assertParamsValid(o,l,d);const p=i(n.data.get(o.dataId).values,l,d,o.shape,o.dtype);return n.makeTensorInfo(d,o.dtype,p)}const o={kernelName:r.Slice,backendName:"cpu",kernelFunc:s}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(3),a=n(4),i=n(1),s=n(15),o=n(2);const u=Object(o.b)({complex_: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e,t){const n=Object(i.a)(e,"real","complex"),o=Object(i.a)(t,"imag","complex");s.e(n.shape,o.shape,`real and imag shapes, ${n.shape} and ${o.shape}, must match in call to tf.complex().`);const u={real:n,imag:o};return r.a.runKernel(a.A,u)}})},function(e,t,n){"use strict"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function r(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.real,i=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,i)}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return a}));const a={kernelName:n(0).Real,backendName:"cpu",kernelFunc:r}},function(e,t){e.exports=function(){throw new Error("define cannot be used indirect")}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return c}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>e+t)),o=Object(i.b)(((e,t,n,r)=>({real:e+n,imag:t+r}))),u=Object(i.a)(r.Add,s,o),c={kernelName:r.Add,backendName:"cpu",kernelFunc:u}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return c}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>e*t)),o=Object(i.b)(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),u=Object(i.a)(r.Multiply,s,o),c={kernelName:r.Multiply,backendName:"cpu",kernelFunc:u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return l}));var r=n(0),a=n(12),i=n(86),s=n(18),o=n(19),u=n(24); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function c(e){const{inputs:t,backend:n,attrs:l}=e,{x:d}=t,{dtype:p}=l;if("complex64"===p){if("complex64"===d.dtype)return Object(o.a)({inputs:{x:d},backend:n});const e=Object(i.a)(n,d.shape,d.dtype),t=c({inputs:{x:d},backend:n,attrs:{dtype:"float32"}}),r=Object(s.a)({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===d.dtype){const e=Object(u.a)({inputs:{input:d},backend:n}),t=c({inputs:{x:e},backend:n,attrs:{dtype:p}});return n.disposeIntermediateTensorInfo(e),t}if(!r.util.hasEncodingLoss(d.dtype,p)){const e=Object(o.a)({inputs:{x:d},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:p}}if("int32"===p){const e=n.data.get(d.dataId).values,t=Int32Array.from(e);return n.makeTensorInfo(d.shape,"int32",t)}if("bool"===p){const e=n.data.get(d.dataId).values,t=r.util.toTypedArray([0],d.dtype),[i,s]=Object(a.a)(((e,t)=>e!==t?1:0))(d.shape,[],e,t,"bool");return n.makeTensorInfo(s,"bool",i)}throw new Error(`Error in Cast: failed to cast ${d.dtype} to ${p}`)}const l={kernelName:r.Cast,backendName:"cpu",kernelFunc:c}},function(e,t,n){"use strict";n.d(t,"b",(function(){return a})),n.d(t,"a",(function(){return i}));var r=n(9); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(...e){Object(r.c)().getBool("IS_TEST")||Object(r.c)().getBool("PROD")||console.warn(...e)}function i(...e){Object(r.c)().getBool("IS_TEST")||Object(r.c)().getBool("PROD")||console.log(...e)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"b",(function(){return c})),n.d(t,"d",(function(){return l})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return p})),n.d(t,"h",(function(){return h})),n.d(t,"g",(function(){return f})),n.d(t,"a",(function(){return m}));var r=n(9),a=n(35),i=n(29); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)("kernelRegistry",(()=>new Map)),o=Object(a.a)("gradRegistry",(()=>new Map));function u(e,t){const n=b(e,t);return s.get(n)}function c(e){return o.get(e)}function l(e){const t=s.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[i,s]=a,[o]=i.split("_");o===e&&n.push(s)}return n}function d(e){const{kernelName:t,backendName:n}=e,r=b(t,n);s.has(r)&&i.b(`The kernel '${t}' for backend '${n}' is already registered`),s.set(r,e)}function p(e){const{kernelName:t}=e;o.has(t)&&Object(r.c)().getBool("DEBUG")&&i.b(`Overriding the gradient for '${t}'`),o.set(t,e)}function h(e,t){const n=b(e,t);if(!s.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);s.delete(n)}function f(e){if(!o.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);o.delete(e)}function m(e,t){l(e).forEach((e=>{d(Object.assign({},e,{backendName:t}))}))}function b(e,t){return`${t}_${e}`}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(1),a=n(20); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function i(e,t,n){const i=Object(r.c)(e,n);return Object(a.a)(e,t,i,n)}},function(e,t,n){"use strict"; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var r,a,i,s,o;n.d(t,"a",(function(){return r})),n.d(t,"c",(function(){return c})),n.d(t,"b",(function(){return l})),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(r||(r={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(a||(a={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(i||(i={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(s||(s={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(o||(o={}));const u={float32:s,int32:a,bool:i,complex64:o};function c(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return u[e][t]}function l(e){return c(e,"int32")}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return i}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a,i){const s=r.util.sizeFromShape(a),o=r.util.makeZerosTypedArray(i,n);for(let n=0;n=i||(o[r]+=s>0?t[n]:1)}return o}function i(e,t,n,a=!1){const i=e.shape[0],s=e.shape[1],o=Object(r.buffer)([i,n],t.dtype);for(let r=0;r=n||(a?o.set(1,r,s):t.size>0?o.set(o.get(r,s)+t.get(r,i),r,s):o.set(o.get(r,s)+1,r,s))}return o}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return c}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>e-t)),o=Object(i.b)(((e,t,n,r)=>({real:e-n,imag:t-r}))),u=Object(i.a)(r.Sub,s,o),c={kernelName:r.Sub,backendName:"cpu",kernelFunc:u}},function(e,t,n){"use strict";(function(e,r){ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let a;function i(){if(null==a){let t;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof e)t=e;else if("undefined"!=typeof r)t=r;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}a=t}return a}function s(e,t){const n=function(){const e=i();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return s}))}).call(this,n(37),n(38))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"b",(function(){return l})),n.d(t,"a",(function(){return d})),n.d(t,"c",(function(){return p})),n.d(t,"i",(function(){return h})),n.d(t,"h",(function(){return f})),n.d(t,"g",(function(){return m})),n.d(t,"j",(function(){return b})),n.d(t,"f",(function(){return g})),n.d(t,"d",(function(){return ve}));var r=n(47),a=n(87),i=n(11),s=n(0);class o{constructor(e){this.outputs_=[],this.builder_=e}get builder(){return this.builder_}get outputs(){return this.outputs_}compute(e){const t=new Map;for(const n of this.inputs())t.set(n,e.getTensor(n));const n=s.tidy((()=>this.computeImpl(t)));for(let t=0;t=-t.rank,"The axis parameter is invalid.");const n=this.axis_>=0?this.axis_:t.rank+this.axis_,r=e.get(this.mean_);x.a(1===r.rank,"The mean operand is not 1-D.");const a=e.get(this.variance_);let i,o;x.a(1===a.rank,"The mean operand is not 1-D."),this.scale_&&(i=e.get(this.scale_),x.a(1===i.rank,"The scale operand is not 1-D.")),this.bias_&&(o=e.get(this.bias_),x.a(1===o.rank,"The bias operand is not 1-D."));const u=Array.from(Array(t.rank).keys());u[n]=t.rank-1,u[t.rank-1]=n;const c=s.transpose(s.batchNorm(s.transpose(t,u),r,a,o,i,this.epsilon_),u);return this.needCheckOutputShape_&&(x.b(c.shape,t.shape),this.needCheckOutputShape_=!1),c}}class k extends u{constructor(e,t){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.a_=e,x.r(t),this.b_=t}inputs(){return[this.a_,this.b_]}run(e){const t=e.get(this.a_),n=e.get(this.b_),r=this.runOp(t,n);if(this.needCheckOutputShape_){let e;if(this instanceof T){const r=t.rank,a=n.rank;1===r&&1===a?e=[]:2===r&&1===a?e=[t.shape[0],1]:1===r&&2===a?e=[1,n.shape[1]]:r>=2&&a>=2&&(e=x.f(t.shape.slice(0,-2),n.shape.slice(0,-2)),e.push(t.shape[r-2]),e.push(n.shape[a-1]))}else e=x.f(t.shape,n.shape);x.b(r.shape,e),this.needCheckOutputShape_=!1}return r}}class y extends k{runOp(e,t){return s.add(e,t)}}class w extends k{runOp(e,t){return s.sub(e,t)}}class I extends k{runOp(e,t){return s.mul(e,t)}}class S extends k{runOp(e,t){return s.div(e,t)}}class _ extends k{runOp(e,t){return s.maximum(e,t)}}class C extends k{runOp(e,t){return s.minimum(e,t)}}class O extends k{runOp(e,t){return s.pow(e,t)}}class T extends k{runOp(e,t){if(1===e.rank)return 1===t.rank?s.dot(e,t):s.matMul(s.reshape(e,[1,-1]),t);if(1===t.rank)return s.matMul(e,s.reshape(t,[-1,1]));{const n=e.rank>t.rank?e.rank:t.rank;let r=s.matMul(e,t);return r.rank!==n&&(r=s.reshape(r,[1].concat(r.shape))),r}}}class $ extends u{constructor(e){void 0!==e?(super(e.builder),x.r(e),this.x_=e):(super(void 0),this.x_=void 0),this.needCheckOutputShape_=!0}inputs(){return[this.x_]}run(e){const t=e.get(this.x_),n=this.runOp(t);return this.needCheckOutputShape_&&(x.b(n.shape,t.shape),this.needCheckOutputShape_=!1),n}}class A extends ${runOp(e){return s.abs(e)}}class N extends ${runOp(e){return s.ceil(e)}}class E extends ${runOp(e){return s.cos(e)}}class R extends ${runOp(e){return s.exp(e)}}class F extends ${runOp(e){return s.floor(e)}}class M extends ${runOp(e){return s.log(e)}}class D extends ${runOp(e){return s.neg(e)}}class P extends ${runOp(e){return s.sin(e)}}class B extends ${runOp(e){return s.tan(e)}}class j extends ${apply(e){return this.builder_=e.builder,x.r(e),this.x_=e,this.createOutput(),this.output}}class L extends j{runOp(e){return s.sigmoid(e)}}class z extends j{runOp(e){return s.tanh(e)}}class W extends j{runOp(e){return s.relu(e)}}class G extends j{runOp(e){return s.div(s.mul(e,s.maximum(0,s.minimum(6,s.add(e,3)))),6)}}class U extends j{constructor(e,t={}){if(void 0!==e?(super(e),x.r(e),this.x_=e):(super(void 0),this.x_=void 0),void 0!==t.minValue){const e=t.minValue;x.a("number"==typeof e,"The minValue parameter is invalid"),this.minValue_=e}if(void 0!==t.maxValue){const e=t.maxValue;x.a("number"==typeof e,"The maxValue parameter is invalid"),this.maxValue_=e}}get minValue(){return void 0!==this.minValue_?this.minValue_:-1/0}get maxValue(){return void 0!==this.maxValue_?this.maxValue_:1/0}runOp(e){return void 0!==this.minValue_&&void 0!==this.maxValue_?s.clipByValue(e,this.minValue_,this.maxValue_):void 0!==this.minValue_&&void 0===this.maxValue_?s.maximum(e,this.minValue_):void 0===this.minValue_&&void 0!==this.maxValue_?s.minimum(e,this.maxValue_):s.clone(e)}}class V extends u{constructor(e,t){super(e[0].builder),this.needCheckOutputShape_=!0,x.a(e.every((e=>e instanceof i.c)),"The parameter is not an operand."),this.inputs_=e,x.a(x.k(t),"The axis parameter is invalid."),this.axis_=t}inputs(){return this.inputs_}run(e){const t=[];for(const n of this.inputs())t.push(e.get(n));const n=s.concat(t,this.axis_);if(this.needCheckOutputShape_){const e=t[0].shape.slice();for(let n=1;n1===e)),"The tf.conv2dTranspose does not support dilations parameter."),x.a(x.k(r),"The gourps parameter is invalid."),this.groups_=r,x.a(1===this.groups_,"The tf.conv2dTranspose does not support groups parameter."),x.a(a in c,"The input layout parameter is invalid."),this.inputLayout_=a,x.a(i in p,"The filter layout parameter is invalid."),this.filterLayout_=i,x.a(s in d,"The autoPad parameter is invalid."),this.autoPad_=s,x.a(void 0===u||x.l(u)&&2===u.length,"The outputSizes parameter is invalid."),this.outputSizes_=u,void 0===u?(x.a(x.l(o)&&2===o.length,"The outputPadding parameter is invalid."),this.outputPadding_=o):this.outputPadding_=[0,0],this.bias_=l,this.bias_&&x.r(this.bias_),h instanceof W?(this.fusedActivation_="relu",this.activation_=void 0):this.isRelu6(h)?(this.fusedActivation_="relu6",this.activation_=void 0):h instanceof H?(this.fusedActivation_="leakyrelu",this.leakyreluAlpha_=h.alpha,this.activation_=void 0):h instanceof L?(this.fusedActivation_="sigmoid",this.activation_=void 0):(this.fusedActivation_=void 0,this.activation_=h)}isRelu6(e){if(e instanceof U){const t=e;if(Math.abs(t.minValue-0)<1e-5&&Math.abs(t.maxValue-6)<1e-5)return!0}return!1}getFusedOutputs(){return this.activation_?[this.activation_.apply(this.output)]:[this.output]}inputs(){const e=[this.input_,this.filter_];return this.bias_&&e.push(this.bias_),e}run(e){let t,n,r=e.get(this.input_);if(this.bias_&&(n=e.get(this.bias_)),this.inputLayout_===c.nchw&&(r=s.transpose(r,[0,2,3,1])),void 0===this.filterTensor_){if(t=e.get(this.filter_),this.filterLayout_===p.iohw?t=s.transpose(t,[2,3,1,0]):this.filterLayout_===p.ohwi&&(t=s.transpose(t,[1,2,0,3])),1!==this.groups_)throw new Error("Unsupported the groups parameter by tfjs.convTranspose2d");this.filter_ instanceof i.a&&(this.filterTensor_=t,s.keep(this.filterTensor_))}else t=this.filterTensor_;const a=x.g(r,t,this.padding_,this.strides_,this.dilations_,this.autoPad_,this.outputPadding_);let o;const u=[r.shape[0],0,0,t.shape[2]];if(void 0!==this.outputSizes_)u[1]=this.outputSizes_[0],u[2]=this.outputSizes_[1];else for(let e=0;e<2;++e)u[e+1]=(r.shape[e+1]-1)*this.strides_[e]+t.shape[e]+(t.shape[e]-1)*(this.dilations_[e]-1)-a[e+1][0]-a[e+1][1]+this.outputPadding_[e];if(o=s.conv2dTranspose(r,t,u,this.strides_,a),n&&(o=s.add(o,n)),"relu"===this.fusedActivation_?o=s.relu(o):"relu6"===this.fusedActivation_?o=s.clipByValue(o,0,6):"leakyrelu"===this.fusedActivation_?o=s.leakyRelu(o,this.leakyreluAlpha_):"sigmoid"===this.fusedActivation_?o=s.sigmoid(o):void 0!==this.fusedActivation_&&x.a(!1,`The ${this.fusedActivation_} is un supported.`),this.inputLayout_===c.nchw){o=s.transpose(o,[0,3,1,2]);const e=u[3];u[3]=u[2],u[2]=u[1],u[1]=e}return this.needCheckOutputShape_&&(x.b(o.shape,u),this.needCheckOutputShape_=!1),o}dispose(){this.filterTensor_&&s.dispose(this.filterTensor_)}}class X extends o{constructor(e,t,n,r,a,s={}){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.r(t),this.weight_=t,x.r(n),this.recurrentWeight_=n,x.a(x.k(r)&&r>0,"The steps parameter is invalid."),this.steps_=r,x.a(x.k(a)&&a>0,"The hiddenSize parameter is invalid."),this.hiddenSize_=a,this.initOptions(s.bias,s.recurrentBias,s.initialHiddenState,s.resetAfter,s.returnSequence,s.direction,s.layout,s.activations),this.outputs.push(new i.e(this)),this.returnSequence_&&this.outputs_.push(new i.e(this))}initOptions(e,t,n,r=!0,a=!1,i=f.forward,s=h.zrn,o=[this.builder.sigmoid(),this.builder.tanh()]){x.t(e),this.bias_=e,x.t(t),this.recurrentBias_=t,x.t(n),this.initialHiddenState_=n,x.a(x.i(r),"The resetAfter parameter is not a boolean."),this.resetAfter_=r,x.a(x.i(a),"The resetAfter parameter is not a boolean."),this.returnSequence_=a,x.a(i in f,"The direction parameter is invalid."),this.direction_=i,x.a(s in h,"The layout parameter is invalid."),this.layout_=s,x.a(o instanceof Array&&2===o.length&&o.every((e=>e instanceof j)),"The activations parameter is invalid."),this.activations_=o}inputs(){const e=[this.input_,this.weight_,this.recurrentWeight_];return this.bias_&&e.push(this.bias_),this.recurrentBias_&&e.push(this.recurrentBias_),this.initialHiddenState_&&e.push(this.initialHiddenState_),e}computeImpl(e){const t=e.get(this.input_),n=e.get(this.weight_),r=e.get(this.recurrentWeight_),a=this.bias_?e.get(this.bias_):void 0,i=this.recurrentWeight_?e.get(this.recurrentBias_):void 0,o=this.initialHiddenState_?e.get(this.initialHiddenState_):void 0,u=this.steps_,c=this.hiddenSize_,l=this.resetAfter_,d=this.returnSequence_,p=this.layout_,h=this.activations_,m=this.direction_,b=m===f.both?2:1;let g,v=o;void 0===v&&(v=s.zeros([b,1,c]));const k=[],y=[],w=[],I=[];for(let e=0;e0,"The hiddenSize parameter is invalid."),this.hiddenSize_=a,this.initOptions(i.bias,i.recurrentBias,i.resetAfter,i.layout,i.activations)}initOptions(e,t,n=!0,r=h.zrn,a=[this.builder.sigmoid(),this.builder.tanh()]){x.t(e),this.bias_=e,x.t(t),this.recurrentBias_=t,x.a(x.i(n),"The resetAfter parameter is not a boolean."),this.resetAfter_=n,x.a(r in h,"The layout parameter is invalid."),this.layout_=r,x.a(a instanceof Array&&2===a.length&&a.every((e=>e instanceof j)),"The activations parameter is invalid."),this.activations_=a}inputs(){const e=[this.input_,this.weight_,this.recurrentWeight_,this.hiddenState_];return this.bias_&&e.push(this.bias_),this.recurrentBias_&&e.push(this.recurrentBias_),e}static compute(e,t,n,r,a,i,o,u,c=!0,l=h.zrn){const d=s.scalar(1),p=s.scalar(0),f=l===h.zrn?{z:0,r:a,n:2*a}:{r:0,z:a,n:2*a},m=i[0],b=i[1],g=m.runOp(s.add(s.add(o?s.slice(o,[f.z],[a]):p,u?s.slice(u,[f.z],[a]):p),s.add(s.matMul(e,s.transpose(s.slice(t,[f.z,0],[a,-1]))),s.matMul(r,s.transpose(s.slice(n,[f.z,0],[a,-1])))))),x=m.runOp(s.add(s.add(o?s.slice(o,[f.r],[a]):p,u?s.slice(u,[f.r],[a]):p),s.add(s.matMul(e,s.transpose(s.slice(t,[f.r,0],[a,-1]))),s.matMul(r,s.transpose(s.slice(n,[f.r,0],[a,-1]))))));let v;return v=c?b.runOp(s.add(o?s.slice(o,[f.n],[a]):p,s.add(s.matMul(e,s.transpose(s.slice(t,[f.n,0],[a,-1]))),s.mul(x,s.add(u?s.slice(u,[f.n],[a]):p,s.matMul(r,s.transpose(s.slice(n,[f.n,0],[a,-1])))))))):b.runOp(s.add(s.add(o?s.slice(o,[f.n],[a]):p,u?s.slice(u,[f.n],[a]):p),s.add(s.matMul(e,s.transpose(s.slice(t,[f.n,0],[a,-1]))),s.matMul(s.mul(x,r),s.transpose(s.slice(n,[f.n,0],[a,-1])))))),s.add(s.mul(g,r),s.mul(v,s.sub(d,g)))}run(e){const t=e.get(this.input_),n=Y.compute(t,e.get(this.weight_),e.get(this.recurrentWeight_),e.get(this.hiddenState_),this.hiddenSize_,this.activations_,this.bias_?e.get(this.bias_):void 0,this.recurrentBias_?e.get(this.recurrentBias_):void 0,this.resetAfter_,this.layout_);if(this.needCheckOutputShape_){const e=[t.shape[0],this.hiddenSize_];x.b(n.shape,e),this.needCheckOutputShape_=!1}return n}}class Z extends u{constructor(e,t={}){if(super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.t(t.scale),this.scale_=t.scale,x.t(t.bias),this.bias_=t.bias,void 0!==t.epsilon){const e=t.epsilon;x.a("number"==typeof e,"The epsilon parameter is invalid"),this.epsilon_=e}else this.epsilon_=1e-5;void 0!==t.layout?(x.a(t.layout in c,"The layout parameter is invalid."),this.layout_=t.layout):this.layout_=c.nchw}inputs(){const e=[this.input_];return this.scale_&&e.push(this.scale_),this.bias_&&e.push(this.bias_),e}run(e){const t=e.get(this.input_);x.a(4===t.rank,"The input operand is not 4-D.");let n,r,a=[2,3],i=[1,-1,1,1],o=t.shape[1];this.layout_===c.nhwc&&(a=[1,2],i=[1,1,1,-1],o=t.shape[3]),this.scale_&&(n=e.get(this.scale_),x.a(1===n.rank,"The scale operand is not 1-D."),x.a(n.shape[0]===o,"The length of scale is not equal to the size of the feature dimension of the input.")),this.bias_&&(r=e.get(this.bias_),x.a(1===r.rank,"The bias operand is not 1-D."),x.a(r.shape[0]===o,"The length of bias is not equal to the size of the feature dimension of the input."));const u=s.mean(t,a,!0),l=s.mean(s.pow(s.sub(t,u),2),a,!0),d=s.div(s.sub(t,u),s.sqrt(s.add(l,this.epsilon_))),p=n?s.mul(s.reshape(n,i),d):d,h=r?s.add(s.reshape(r,i),p):p;return this.needCheckOutputShape_&&(x.b(h.shape,t.shape),this.needCheckOutputShape_=!1),h}}class Q extends u{constructor(e,t,n={}){super(e.builder),this.mode_=m.constant,this.value_=0,this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.r(t),this.padding_=t,void 0!==n.mode&&(x.a(n.mode in m,"The mode parameter is invalid."),this.mode_=n.mode),void 0!==n.value&&(this.value_=n.value)}inputs(){return[this.input_,this.padding_]}run(e){const t=e.get(this.input_),n=e.get(this.padding_);x.a(2===n.rank&&"int32"===n.dtype&&n.shape[0]===t.rank,"The padding operand is invalid.");const r=n.arraySync(),a=t.shape.map(((e,t)=>e+r[t][0]+r[t][1]));let i;if(this.mode_===m.constant)i=s.pad(t,r,this.value_);else if(this.mode_===m.edge){const e=new Array(r.length);let n=t;for(;;){for(let t=0;t0?(e[t][n]=1,r[t][n]-=1):e[t][n]=0}if(e.every((e=>0===e[0]&&0===e[1])))break;n=s.mirrorPad(n,e,"symmetric")}i=n}else{let e;this.mode_===m.reflection?e="reflect":this.mode_===m.symmetric&&(e="symmetric"),i=s.mirrorPad(t,r,e)}return this.needCheckOutputShape_&&(x.b(i.shape,a),this.needCheckOutputShape_=!1),i}}class J extends u{constructor(e,t={}){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,this.initOptions(t.windowDimensions,t.padding,t.strides,t.dilations,t.layout,t.autoPad,t.roundingType,t.outputSizes)}initOptions(e=[-1,-1],t=[0,0,0,0],n=[1,1],r=[1,1],a=c.nchw,i=d.explicit,s=b.floor,o){x.a(x.l(e)&&2===e.length,"The padding parameter is invalid."),this.windowDimensions_=e,x.a(x.l(t)&&4===t.length,"The padding parameter is invalid."),this.padding_=t,x.a(x.l(n)&&2===n.length,"The strides parameter is invalid."),this.strides_=n,x.a(x.l(r)&&2===r.length,"The dilations parameter is invalid."),this.dilations_=r,x.a(a in c,"The layout parameter is invalid."),this.layout_=a,x.a(i in d,"The autoPad parameter is invalid."),this.autoPad_=i,x.a(s in b,"The roundingType parameter is invalid."),this.roundingType_=s,o&&x.a(x.l(o)&&2===o.length,"The outputSizes parameter is invalid."),this.outputSizes_=o}inputs(){return[this.input_]}calculateOutputSizes(e,t){const n=e[1],r=e[2],a=this.windowDimensions_[0],i=this.windowDimensions_[1];let s,o=this.padding_[0],u=this.padding_[1],c=this.padding_[2],l=this.padding_[3];if(this.autoPad_!==d.explicit&&([o,u]=x.c(this.autoPad_,this.dilations_[0],n,a,this.strides_[0],o,u),[c,l]=x.c(this.autoPad_,this.dilations_[1],r,i,this.strides_[1],c,l)),void 0===t)s=Math.trunc;else switch(t){case"ceil":s=Math.ceil;break;case"floor":s=Math.floor;break;case"round":s=Math.round}const p=a+(a-1)*(this.dilations_[0]-1),h=i+(i-1)*(this.dilations_[1]-1);return[1+s((n-p+o+u)/this.strides_[0]),1+s((r-h+c+l)/this.strides_[1])]}run(e){let t=e.get(this.input_);this.layout_===c.nchw&&(t=s.transpose(t,[0,2,3,1]));const n=this.windowDimensions_;let r;if(-1===n[0]&&-1===n[1]&&(n[0]=t.shape[1],n[1]=t.shape[2]),void 0!==this.outputSizes_){let e=!1;for(const n of[void 0,"ceil","floor","round"]){const[a,i]=this.calculateOutputSizes(t.shape,n);if(this.outputSizes_[0]===a&&this.outputSizes_[1]===i){r=n,e=!0;break}}x.a(e,`The outputSizes [${this.outputSizes_}] is invalid.`)}else r=this.roundingType_===b.floor?"floor":"ceil";const a=this.getPoolingType();let i,o;if(this.autoPad_===d.explicit)this.padding_.every((e=>0===e))?(i="valid",r=void 0):i=[[0,0],[this.padding_[0],this.padding_[1]],[this.padding_[2],this.padding_[3]],[0,0]];else if(this.autoPad_===d["same-upper"])i="same",r=void 0;else{i=[[0,0],[0,0],[0,0],[0,0]];const e=[0,0];for(let n=0;n<2;++n)e[n]=Math.ceil(t.shape[1+n]/this.strides_[n]);const r=[0,0];for(let a=0;a<2;++a)r[a]=this.strides_[a]*(e[a]-1)+((n[a]-1)*this.dilations_[a]+1)-t.shape[1+a];for(let e=0;e<2;++e)i[e+1][0]=r[e]-Math.floor(r[e]/2),i[e+1][1]=Math.floor(r[e]/2)}if("l2"===a?(t=s.pow(t,2),o=s.sqrt(s.pool(t,this.windowDimensions_,"avg",i,this.dilations_,this.strides_,r))):o=s.pool(t,this.windowDimensions_,a,i,this.dilations_,this.strides_,r),this.layout_===c.nchw&&(o=s.transpose(o,[0,3,1,2])),this.needCheckOutputShape_){let e,n,a;void 0!==this.outputSizes_?(e=this.outputSizes_[0],n=this.outputSizes_[1]):(r=this.roundingType_===b.floor?"floor":"ceil",[e,n]=this.calculateOutputSizes(t.shape,r)),a=this.layout_===c.nchw?[t.shape[0],t.shape[3],e,n]:[t.shape[0],e,n,t.shape[3]],x.b(o.shape,a),this.needCheckOutputShape_=!1}return o}}class ee extends J{getPoolingType(){return"avg"}}class te extends J{getPoolingType(){return"max"}}class ne extends J{getPoolingType(){return"l2"}}class re extends u{constructor(e,t={}){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,void 0!==t.axes?(x.a(x.l(t.axes),"The axes parameter is invalid."),this.axes_=t.axes):this.axes_=void 0,void 0!==t.keepDimensions?(x.a(x.i(t.keepDimensions),"The keepDimensions parameter is not a boolean."),this.keepDimensions_=t.keepDimensions):this.keepDimensions_=!1}inputs(){return[this.input_]}run(e){var t;const n=e.get(this.input_);x.a(x.q(this.axes_,n.rank),`The axes must be in range [-${n.rank}, ${n.rank})`);const r=this.runOp(n,this.axes_,this.keepDimensions_);if(this.needCheckOutputShape_){const e=null!==(t=this.axes_)&&void 0!==t?t:[...Array(n.rank).keys()];let a=n.shape.slice();for(let t=0;t!(1===t&&-1!==e.indexOf(n))))),x.b(r.shape,a),this.needCheckOutputShape_=!1}return r}}class ae extends re{runOp(e,t,n){return s.logSumExp(e,t,n)}}class ie extends re{runOp(e,t,n){return s.max(e,t,n)}}class se extends re{runOp(e,t,n){return s.mean(e,t,n)}}class oe extends re{runOp(e,t,n){return s.min(e,t,n)}}class ue extends re{runOp(e,t,n){return s.prod(e,t,n)}}class ce extends re{runOp(e,t,n){return s.sum(e,t,n)}}class le extends re{runOp(e,t,n){return s.sum(s.abs(e),t,n)}}class de extends re{runOp(e,t,n){return s.sqrt(s.sum(s.pow(e,2),t,n))}}class pe extends u{constructor(e,t={}){if(super(e.builder),this.mode_=g["nearest-neighbor"],this.scales_=[1,1],this.axes_=[2,3],this.needCheckOutputShape_=!0,x.r(e),this.input_=e,void 0!==t.scales){const e=t.scales;x.a(e instanceof Array&&e.every((e=>"number"==typeof e))&&2===e.length,"The scales parameter is invalid."),this.scales_=t.scales}void 0!==t.sizes&&(x.a(x.l(t.sizes)&&2===t.sizes.length,"The sizes parameter is invalid."),this.sizes_=t.sizes),void 0!==t.axes&&(x.a(x.l(t.axes)&&2===t.axes.length&&x.n(t.axes),"The axes parameter is invalid."),this.axes_=t.axes),x.a(void 0!==this.scales_||void 0!==this.sizes_,"The scales or sizes parameter is not provied."),void 0!==t.mode&&(x.a(t.mode in g,"The mode parameter is invalid."),this.mode_=t.mode)}inputs(){return[this.input_]}run(e){let t=e.get(this.input_);x.a(4===t.rank,"The input tensor is not 4-D.");const n=t.shape.slice(),r=[0,0];let a;return void 0!==this.sizes_?(r[0]=this.sizes_[0],r[1]=this.sizes_[1]):void 0!==this.scales_&&(r[0]=Math.floor(t.shape[this.axes_[0]]*this.scales_[0]),r[1]=Math.floor(t.shape[this.axes_[1]]*this.scales_[1])),0===this.axes_[0]?t=s.transpose(t,[2,0,1,3]):2===this.axes_[0]&&(t=s.transpose(t,[0,2,3,1])),this.mode_===g["nearest-neighbor"]?a=s.image.resizeNearestNeighbor(t,r,!1,!0):this.mode_===g.linear&&(a=s.image.resizeBilinear(t,r,!1,!0)),0===this.axes_[0]?a=s.transpose(a,[1,2,0,3]):2===this.axes_[0]&&(a=s.transpose(a,[0,3,1,2])),this.needCheckOutputShape_&&(this.axes_.map(((e,t)=>n[e]=r[t])),x.b(a.shape,n),this.needCheckOutputShape_=!1),a}}class he extends u{constructor(e,t){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.a(x.l(t)&&0!==t.length,"The newShape parameter is invalid."),this.newShape_=t}inputs(){return[this.input_]}run(e){const t=e.get(this.input_),n=s.reshape(t,this.newShape_);if(this.needCheckOutputShape_){const e=this.newShape_.slice();-1!==e.indexOf(-1)&&(e[e.indexOf(-1)]=x.o(t.shape)/x.o(e)*-1),x.b(n.shape,e),this.needCheckOutputShape_=!1}return n}}class fe extends u{constructor(e,t,n,r){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.a(x.l(t),"The starts parameter is invalid."),this.starts_=t,x.a(x.l(n)&&n.every((e=>e>0||-1===e)),"The sizes parameter is invalid."),this.sizes_=n,x.a(n.length==n.length,"The length of sizes is not equal to the length of sizes.))"),x.a(void 0===r||x.l(r),"The axes parameter is invalid."),void 0!==r&&x.a(n.length===r.length,"The length of axes is invalid.))"),this.axes_=r}inputs(){return[this.input_]}run(e){const t=e.get(this.input_),n=t.shape.length;if(void 0===this.axes_){this.axes_=[];for(let e=0;ee=-n)),"The value of axes is invalid."),x.a(this.starts_.length===this.axes_.length,"The length of starts is invalid."),x.a(this.sizes_.length===this.axes_.length,"The length of sizes is invalid.");const r=new Array(this.axes_.length).fill(0),a=new Array(this.axes_.length).fill(-1);for(let e=0;e=0?this.starts_[e]:this.starts_[e]+t.shape[i],a[i]=this.sizes_[e]}const i=s.slice(t,r,a);if(this.needCheckOutputShape_){const e=t.shape.slice();for(let r=0;r=0?this.axes_[r]:this.axes_[r]+n,i=t.shape[a],s=this.starts_[r],o=this.sizes_[r];e[a]=o>=0?o:s>=0?i-s:-s}x.b(i.shape,e)}return i}}class me extends u{constructor(e){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.x_=e}inputs(){return[this.x_]}run(e){const t=e.get(this.x_);if(2!==t.rank)throw new Error("The rank of x parameter should be 2.");const n=s.softmax(t);return this.needCheckOutputShape_&&(x.b(n.shape,t.shape),this.needCheckOutputShape_=!1),n}}class be extends o{constructor(e,t,n={}){var r;super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,x.a(x.k(t)||x.l(t),"The splits parameter is invalid."),this.splits_=t,x.a(void 0===n.axis||x.k(n.axis),"The options.axis is invalid."),this.axis_=null!==(r=n.axis)&&void 0!==r?r:0;const a=x.k(t)?t:t.length;for(let e=0;e=0?this.axis_:this.axis_+t.rank;let r=[];r="number"==typeof this.splits_?new Array(this.splits_).fill(t.shape[e]/this.splits_):this.splits_.slice();const a=[];for(const n of r){const r=t.shape.slice();r[e]=n,a.push(r)}for(let e=0;e!(1===t&&-1!==e.indexOf(n))));x.b(r.shape,a),this.needCheckOutputShape_=!1}return r}}class xe extends u{constructor(e,t){super(e.builder),this.needCheckOutputShape_=!0,x.r(e),this.input_=e,void 0!==t&&x.a(x.l(t)&&0!==t.length,"The permutation parameter is invalid."),this.permutation_=t}inputs(){return[this.input_]}run(e){var t;const n=e.get(this.input_),r=s.transpose(n,this.permutation_);if(this.needCheckOutputShape_){const e=null!==(t=this.permutation_)&&void 0!==t?t:new Array(n.rank).fill(0).map(((e,t,n)=>n.length-t-1)),a=new Array(n.rank).fill(0).map(((t,r)=>n.shape[e[r]]));x.b(r.shape,a),this.needCheckOutputShape_=!1}return r}}!function(e){e.nchw="nchw",e.nhwc="nhwc"}(c||(c={})),function(e){e.oihw="oihw",e.hwio="hwio",e.ohwi="ohwi",e.ihwo="ihwo"}(l||(l={})),function(e){e.explicit="explicit",e["same-upper"]="same-upper",e["same-lower"]="same-lower"}(d||(d={})),function(e){e.iohw="iohw",e.hwoi="hwoi",e.ohwi="ohwi"}(p||(p={})),function(e){e.zrn="zrn",e.rzn="rzn"}(h||(h={})),function(e){e.forward="forward",e.backward="backward",e.both="both"}(f||(f={})),function(e){e.constant="constant",e.edge="edge",e.reflection="reflection",e.symmetric="symmetric"}(m||(m={})),function(e){e.floor="floor",e.ceil="ceil"}(b||(b={})),function(e){e["nearest-neighbor"]="nearest-neighbor",e.linear="linear"}(g||(g={}));class ve{constructor(e){x.a(e instanceof r.a,"The context paramter is invalid."),this.context_=e}get context(){return this.context_}async build(e){return await a.a.buildAndCompile(e)}input(e,t){return new i.b(e,t,this)}constant(e,t){return"number"==typeof e?(void 0===t&&(t=i.d.float32),i.a.createScalar(e,t,this)):i.a.createTensor(e,t,this)}batchNormalization(e,t,n,r={}){return this.validateOperandBuilder([e,t,n,r.scale,r.bias]),new v(e,t,n,r).getFusedOutputs()[0]}clamp(e={},t={}){if(e instanceof i.c){const n=e;return this.validateOperandBuilder([n]),new U(n,t).output}return new U(void 0,e)}concat(e,t){return this.validateOperandBuilder(e),new V(e,t).output}conv2d(e,t,n={}){const r=[e,t];return n.bias&&r.push(n.bias),this.validateOperandBuilder(r),new q(e,t,n).getFusedOutputs()[0]}convTranspose2d(e,t,n={}){const r=[e,t];return n.bias&&r.push(n.bias),this.validateOperandBuilder(r),new K(e,t,n).getFusedOutputs()[0]}add(e,t){return this.validateOperandBuilder([e,t]),new y(e,t).output}sub(e,t){return this.validateOperandBuilder([e,t]),new w(e,t).output}mul(e,t){return this.validateOperandBuilder([e,t]),new I(e,t).output}div(e,t){return this.validateOperandBuilder([e,t]),new S(e,t).output}max(e,t){return this.validateOperandBuilder([e,t]),new _(e,t).output}min(e,t){return this.validateOperandBuilder([e,t]),new C(e,t).output}pow(e,t){return this.validateOperandBuilder([e,t]),new O(e,t).output}abs(e){return this.validateOperandBuilder([e]),new A(e).output}ceil(e){return this.validateOperandBuilder([e]),new N(e).output}cos(e){return this.validateOperandBuilder([e]),new E(e).output}exp(e){return this.validateOperandBuilder([e]),new R(e).output}floor(e){return this.validateOperandBuilder([e]),new F(e).output}log(e){return this.validateOperandBuilder([e]),new M(e).output}neg(e){return this.validateOperandBuilder([e]),new D(e).output}sin(e){return this.validateOperandBuilder([e]),new P(e).output}tan(e){return this.validateOperandBuilder([e]),new B(e).output}hardSwish(e){return void 0===e?new G(void 0):(this.validateOperandBuilder([e]),new G(e).output)}relu(e){return void 0===e?new W(void 0):(this.validateOperandBuilder([e]),new W(e).output)}sigmoid(e){return void 0===e?new L(void 0):(this.validateOperandBuilder([e]),new L(e).output)}tanh(e){return void 0===e?new z(void 0):(this.validateOperandBuilder([e]),new z(e).output)}gemm(e,t,n={}){return this.validateOperandBuilder([e,t,n.c]),class{static build(e,t,n,r={}){x.r(t),x.r(n),x.a(void 0===r.c||"number"==typeof r.c||r.c instanceof i.c,"The options.c is invalid."),x.a(void 0===r.aTranspose||x.i(r.aTranspose),"The options.aTranspose is invalid."),x.a(void 0===r.bTranspose||x.i(r.bTranspose),"The options.bTranspose is invalid."),x.a(void 0===r.alpha||"number"==typeof r.alpha,"The options.alpha is invalid."),x.a(void 0===r.beta||"number"==typeof r.beta,"The options.beta is invalid."),r.aTranspose&&(t=e.transpose(t)),r.bTranspose&&(n=e.transpose(n));const a=e.constant(void 0===r.alpha?1:r.alpha),s=e.constant(void 0===r.beta?1:r.beta),o=e.matmul(e.mul(a,t),n);return r.c?e.add(o,e.mul(s,r.c)):o}}.build(this,e,t,n)}gru(e,t,n,r,a,i={}){return this.validateOperandBuilder([e,t,n,i.bias,i.recurrentBias,i.initialHiddenState]),new X(e,t,n,r,a,i).outputs}gruCell(e,t,n,r,a,i={}){return this.validateOperandBuilder([e,t,n,r,i.bias,i.recurrentBias]),new Y(e,t,n,r,a,i).output}instanceNormalization(e,t={}){return this.validateOperandBuilder([e,t.bias,t.scale]),new Z(e,t).output}leakyRelu(e={},t={}){if(e instanceof i.c){const n=e;return this.validateOperandBuilder([n]),new H(n,t.alpha).output}return new H(void 0,e.alpha)}matmul(e,t){return this.validateOperandBuilder([e,t]),new T(e,t).output}pad(e,t,n={}){return this.validateOperandBuilder([e,t]),new Q(e,t,n).output}averagePool2d(e,t={}){return this.validateOperandBuilder([e]),new ee(e,t).output}l2Pool2d(e,t={}){return this.validateOperandBuilder([e]),new ne(e,t).output}maxPool2d(e,t={}){return this.validateOperandBuilder([e]),new te(e,t).output}reduceL1(e,t={}){return this.validateOperandBuilder([e]),new le(e,t).output}reduceL2(e,t={}){return this.validateOperandBuilder([e]),new de(e,t).output}reduceLogSumExp(e,t={}){return this.validateOperandBuilder([e]),new ae(e,t).output}reduceMax(e,t={}){return this.validateOperandBuilder([e]),new ie(e,t).output}reduceMean(e,t={}){return this.validateOperandBuilder([e]),new se(e,t).output}reduceMin(e,t={}){return this.validateOperandBuilder([e]),new oe(e,t).output}reduceProduct(e,t={}){return this.validateOperandBuilder([e]),new ue(e,t).output}reduceSum(e,t={}){return this.validateOperandBuilder([e]),new ce(e,t).output}resample2d(e,t={}){return this.validateOperandBuilder([e]),new pe(e,t).output}reshape(e,t){return this.validateOperandBuilder([e]),new he(e,t).output}slice(e,t,n,r={}){return this.validateOperandBuilder([e]),new fe(e,t,n,r.axes).output}softmax(e){return this.validateOperandBuilder([e]),new me(e).output}split(e,t,n={}){return this.validateOperandBuilder([e]),new be(e,t,n).outputs}squeeze(e,t={}){return this.validateOperandBuilder([e]),new ge(e,t.axes).output}transpose(e,t={}){return this.validateOperandBuilder([e]),new xe(e,t.permutation).output}validateOperandBuilder(e){x.a(e.every((e=>!e||e instanceof i.c&&e.builder===this)),"The operand is not built by this builder.")}}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){var n,r,a=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function o(e){if(n===setTimeout)return setTimeout(e,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(e){n=i}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(e){r=s}}();var u,c=[],l=!1,d=-1;function p(){l&&u&&(l=!1,u.length?c=u.concat(c):d=-1,c.length&&h())}function h(){if(!l){var e=o(p);l=!0;for(var t=c.length;t;){for(u=c,c=[];++d1)for(var n=1;ne===t?1:0)),o=Object(i.a)(r.Equal,s,null,"bool"),u={kernelName:r.Equal,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return u}));var r=n(0),a=n(21),i=n(8); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)((e=>Math.exp(e))),o=Object(i.b)(r.Exp,s,"float32"),u={kernelName:r.Exp,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a,i){const s=t.length,o=r.util.sizeFromShape(t),u=r.util.computeStrides(t),c=r.util.computeStrides(i),l=r.util.getTypedArrayFromDType(n,r.util.sizeFromShape(i));for(let t=0;t1/(1+Math.exp(-e)))),o=Object(i.a)(r.Sigmoid,(e=>1/(1+Math.exp(-e)))),u={kernelName:r.Sigmoid,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a,i,s=!1,o=0){const u=a.length,c=[t[0],e.length/t[0]],l=c[1],d=u>0?i[u-1]+1:0;if(d<0)throw new Error(r.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());const p=t.slice();p[0]=d;const h=p.reduce(((e,t)=>e*t),1),f=r.util.getArrayFromDType(n,h);if(0===u)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error(r.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,b=1,g=0,x=i[m];for(;;){let t=0;if(b=t)throw new Error(r.backend_util.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(x<0||x>=d)throw new Error(r.backend_util.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(x,d));x>g&&f.fill(o,g*l,x*l);for(let t=m;t=c[0])throw new Error(r.backend_util.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(t,a[t],c[0]));for(let t=0;tu)break}return g!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.")})),a.registerFlag("IS_BROWSER",(()=>t.isBrowser())),a.registerFlag("IS_NODE",(()=>"undefined"!=typeof e&&"undefined"!=typeof e.versions&&"undefined"!=typeof e.versions.node)),a.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),a.registerFlag("PROD",(()=>!1)),a.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>a.getBool("DEBUG"))),a.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),a.registerFlag("IS_TEST",(()=>!1)),a.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),a.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),a.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1))}).call(this,n(38))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return a}));class r{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 a{refCount(e){return i("refCount")}incRef(e){return i("incRef")}timerAvailable(){return!0}time(e){return i("time")}read(e){return i("read")}readSync(e){return i("readSync")}readToGPU(e,t){return i("readToGPU")}numDataIds(){return i("numDataIds")}disposeData(e,t){return i("disposeData")}write(e,t,n){return i("write")}move(e,t,n,r,a){return i("move")}memory(){return i("memory")}floatPrecision(){return i("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return i("dispose")}}function i(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(e,t,n){"use strict";n.d(t,"a",(function(){return r})); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const r={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8}},function(e,t){},function(e,t,n){"use strict";let r;function a(e){r=e}function i(e){if(void 0!==r)return r;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 s(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}n.r(t),n.d(t,"mockIsMobile",(function(){return a})),n.d(t,"isMobile",(function(){return i})),n.d(t,"isBrowser",(function(){return s}))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return s}));var r=n(0),a=n(7); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function i(e){const t=new Float32Array(e.length);for(let n=0;n{const{x:t}=e.inputs,n=e.backend;Object(a.a)(t,"abs");let s=new Float32Array(r.util.sizeFromShape(t.shape));return s=i(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,t.dtype)}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(21),i=n(8); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)((e=>Math.ceil(e))),o=Object(i.b)(r.Ceil,s),u={kernelName:r.Ceil,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a){const i=r.util.getArrayFromDType(n,r.util.sizeFromShape(t));if(a&&"string"!==n){let t=0;e.forEach((e=>{const n=r.util.sizeFromShape(e.shape);i.set(e.vals,t),t+=n}))}else{let a=0;e.forEach((e=>{const s="string"===n?r.backend_util.fromUint8ToStringArray(e.vals):e.vals;let o=0;for(let n=0;nMath.expm1(e))),o=Object(i.b)(r.Expm1,s),u={kernelName:r.Expm1,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(21),i=n(8); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)((e=>Math.floor(e))),o=Object(i.b)(r.Floor,s),u={kernelName:r.Floor,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a,i,s,o,u,c){const l=Object(r.buffer)([a,s],n);for(let n=0;n=c/s)throw new Error(`Invalid indices: ${r} does not index into ${u}`);for(let e=0;ee>t?1:0)),o=Object(i.a)(r.Greater,s,null,"bool"),u={kernelName:r.Greater,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>e>=t?1:0)),o=Object(i.a)(r.GreaterEqual,s,null,"bool"),u={kernelName:r.GreaterEqual,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>ee<=t?1:0)),o=Object(i.a)(r.LessEqual,s,null,"bool"),u={kernelName:r.LessEqual,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n){const a=(t-e)/(n-1),i=r.util.makeZerosTypedArray(n,"float32");i[0]=e;for(let e=1;eMath.log(e))),o=Object(i.b)(r.Log,s),u={kernelName:r.Log,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a){const i=r.util.getTypedArrayFromDType(a,r.util.sizeFromShape(n));for(let n=0;na)&&(a=t)}i[n]=a}return i}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>Math.max(e,t))),o=Object(i.a)(r.Maximum,s),u={kernelName:r.Maximum,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>Math.min(e,t))),o=Object(i.a)(r.Minimum,s),u={kernelName:r.Minimum,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return o}));var r=n(0),a=n(7),i=n(27); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function s(e,t,n){const a=r.util.createScalarValue(-1,n);return Object(i.c)([],t,a,e,n)}const o={kernelName:r.Neg,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;Object(a.a)(r,"neg");const i=n.data.get(r.dataId).values,[o,u]=s(i,r.shape,r.dtype);return n.makeTensorInfo(u,r.dtype,o)}}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>e!==t?1:0)),o=Object(i.a)(r.NotEqual,s,null,"bool"),u={kernelName:r.NotEqual,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return o}));var r=n(0),a=n(7),i=n(16); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function s(e,t,n,a){const[i,s]=r.backend_util.computeOutAndReduceShapes(e,a),o=Object(r.upcastType)(t,"int32"),u=r.util.makeZerosTypedArray(r.util.sizeFromShape(i),o),c=r.util.sizeFromShape(s);for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,k,x)}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a){if(e===t||e1)return r.util.makeZerosTypedArray(0,a);const i=Math.abs(Math.ceil((t-e)/n)),s=r.util.makeZerosTypedArray(i,a);t1/Math.sqrt(e))),o=Object(i.b)(r.Rsqrt,s),u={kernelName:r.Rsqrt,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a,i,s,o){const u=t[0],c=s[0],l=new Array(c),d=new Array(u),p=t[1];if(0===c){if(0!==u)throw new Error(r.backend_util.getSparseFillEmptyRowsIndicesDenseShapeMismatch(u));return[r.util.getArrayFromDType(n,0),[0,p],r.util.getArrayFromDType(i,0),l,d]}let h=!0,f=0;const m=new Array(c).fill(0);for(let t=0;t=c)throw new Error(r.backend_util.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(t,n,c));++m[n],h=h&&n>=f,f=n}let b=!0;for(let e=0;e0&&(m[e]+=m[e-1])}if(b&&h){const t=e,n=a;for(let e=0;e0){h[p-1]=1;for(let e=p-2;e>=0;--e)h[e]=h[e+1]*a[e+1]}const f=[];if(u>0){f[u-1]=1;for(let e=u-2;e>=0;--e)f[e]=f[e+1]*c[e+1]}const m=r.util.getArrayFromDType(n,o*u);for(let t=0;tMath.sqrt(e))),o=Object(i.a)(r.Sqrt,(e=>Math.sqrt(e))),u={kernelName:r.Sqrt,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"a",(function(){return u}));var r=n(0),a=n(12),i=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const s=Object(a.a)(((e,t)=>{const n=e-t;return n*n})),o=Object(i.a)(r.SquaredDifference,s),u={kernelName:r.SquaredDifference,backendName:"cpu",kernelFunc:o}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(0); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,a){const i=Object(r.buffer)(e,t.dtype);for(let e=0;e0?0:s-o);let p=0;p+=u*this.leftPad.length;for(let t=0;te.forEach((e=>h[f++]=e));for(let e=0;e0){m(e[d+l-1]);for(let e=0;e0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let r=1;r=e;if(a=a&&t[r]<=n,!a)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 i=a-1,s=r.util.getArrayFromDType("int32",a);if(0===n||0===a){const e=new Array(n);for(let e=0;e<=i;++e)s[e]=0;return[e,s]}s[0]=0;for(let e=1;e<=i;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach((e=>{r+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===r&&(r=1),s[e]=s[e-1]+r}const o=new Array(s[i]);for(let n=0;n{const s=t[n+1]-t[n],u=this.getNumNGrams(s,i);this.createNGrams(e,r,o,a,u,i),a+=u})),this.preserveShort&&a===s[n]){const i=t[n+1]-t[n];if(0===i)continue;const s=i+2*this.padWidth,u=1;this.createNGrams(e,r,o,a,u,s)}}return[o,s]}}function i(e,t,n,r,i,s,o,u){return new a(n,r,i,s,o,u).compute(e,t)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(0); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function a(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t{const n=t.value-e.value;return 0===n?e.index-t.index:n};function i(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){const r=s-n+1,a=t-n+1,o=Math.log(r),u=.5*Math.exp(2*o/3),c=.5*Math.sqrt(o*u*(r-u)/r)*Math.sign(a-r/2);i(e,t,Math.max(n,Math.floor(t-a*u/r+c)),Math.min(s,Math.floor(t+(r-a)*u/r+c)))}const o=e[t];let u=n,c=s;for(r.util.swap(e,n,t),a(e[s],o)>0&&r.util.swap(e,n,s);u0;)c-=1}0===a(e[n],o)?r.util.swap(e,n,c):(c+=1,r.util.swap(e,c,s)),c<=t&&(n=c+1),t<=c&&(s=c-1)}}function s(e,t,n,s,o){const u=t[t.length-1],[c,l]=[e.length/u,u],d=r.util.getTypedArrayFromDType(n,c*s),p=r.util.getTypedArrayFromDType("int32",c*s);for(let t=0;tu[t]={value:e,index:t})),s{for(let n=0;nnew s(this.constantTensors_,this.inputs_,e,this.operandRefs_).compute(n)));for(const e of Object.keys(a)){const n=a[e],s=i.d(n),o=await n.data(),u=t[e];i.u(u,s.type,s.dimensions),u.set(o),r.dispose(n)}}validateInputs(e){for(const t in e){i.a("string"==typeof t&&this.inputs_.has(t),"The name of the input is invalid.");const n=this.inputs_.get(t);let r,a;if(void 0!==e[t].dimensions){const s=e[t];r=s.resource,a=s.dimensions,i.a(void 0!==r,"The resource of input is undefined."),i.a(!0===i.l(a),"The type of the input dimensions is invalid."),i.a(a.length===n.desc.dimensions.length,"The rank of the input dimensions is invalid."),i.a(!i.j(a),"The value of input dimensions is negative.");for(let e=0;e0&&i.a(t===a[e],"The value of the input dimensions is invalid.")}}else r=e[t],i.a(!i.j(n.desc.dimensions),"The input dimensions is not specified."),a=n.desc.dimensions;i.a(i.m(r),"Only resource of ArrayBufferView type is supported."),i.u(r,n.desc.type,a)}}static async buildAndCompile(e){const t=new o(e);return t.build(),await t.compile(),t}build(){const e=new Set;for(const t of this.outputs_.values())this.buildOperation(t.operation,e)}buildOperation(e,t){if(!t.has(e)){t.add(e);for(const n of e.inputs()){if(this.operandRefs_.has(n)){let e=this.operandRefs_.get(n);e++,this.operandRefs_.set(n,e)}else this.operandRefs_.set(n,1);if(n instanceof a.b){if(this.inputs_.has(n.name)){if(this.inputs_.get(n.name)!==n)throw new Error("The name of this input is existed.");continue}this.inputs_.set(n.name,n)}else n instanceof a.a?this.constants_.has(n)||this.constants_.add(n):n instanceof a.e&&this.buildOperation(n.operation,t)}}}async compile(){await r.ready(),this.allocateConstants(),await this.computeOnce()}allocateConstants(){for(const e of this.constants_)this.constantTensors_.set(e,i.e(e.desc,e.value))}async computeOnce(){const e={};for(const t of this.inputs_.keys()){const n=this.inputs_.get(t),r=n.desc.dimensions.map((e=>e<0?1:e)),a=new(i.h(n.desc.type))(i.p(n.desc.dimensions));e[t]={resource:a,dimensions:r}}const t=r.tidy((()=>new s(this.constantTensors_,this.inputs_,e,this.operandRefs_).compute(this.outputs_)));for(const e of Object.keys(t)){const n=t[e];await n.data(),r.dispose(n)}}dispose(){for(const e of this.constantTensors_.values())r.dispose(e);const e=new Set;for(const t of this.outputs_.values())this.disposeOperation(t.operation,e)}disposeOperation(e,t){if(!t.has(e)){e.dispose(),t.add(e);for(const n of e.inputs())n instanceof a.e&&this.disposeOperation(n.operation,t)}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return Nn}));var r,a,i=n(0); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let s;!function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"}(r||(r={})),function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"}(a||(a={}));const o={kernelName:i._FusedMatMul,backendName:"wasm",setupFunc:function(e){s=e.wasm.cwrap(i._FusedMatMul,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:o,b:u,bias:c,preluActivationWeights:l}=t;if("float32"!==o.dtype||"float32"!==u.dtype)throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:d,transposeB:p,activation:h,leakyreluAlpha:f}=r,m=n.dataIdMap.get(o.dataId).id,b=n.dataIdMap.get(u.dataId).id;let g=0;if(null!=c){const e=n.dataIdMap.get(c.dataId);if(1!==e.shape.length)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${e.shape.length}.`);g=e.id}const x=null==l?0:n.dataIdMap.get(l.dataId).id,v=a[h];if(null==v)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);const k=d?o.shape[2]:o.shape[1],y=p?u.shape[1]:u.shape[2],w=i.broadcast_util.assertAndGetBroadcastShape(o.shape.slice(0,-2),u.shape.slice(0,-2)),I=n.makeOutput([...w,k,y],o.dtype),S=n.dataIdMap.get(I.dataId).id,_=new Uint8Array(new Int32Array(o.shape).buffer),C=new Uint8Array(new Int32Array(u.shape).buffer);return s(m,_,o.shape.length,b,C,u.shape.length,d,p,v,g,x,f||0,S),I}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function u(e,t){let n;return{kernelName:e,backendName:"wasm",setupFunc:function(t){n=t.wasm.cwrap(e,null,["number","number","number"])},kernelFunc:function(e){const{backend:a,inputs:{x:s}}=e,o=a.dataIdMap.get(s.dataId).id,u=a.makeOutput(s.shape,t||s.dtype),c=a.dataIdMap.get(u.dataId).id;return 0===i.util.sizeFromShape(u.shape)||n(o,r[s.dtype],c),u}}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const c=u(i.Abs); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function l(e,t,n){let a;return{kernelName:e,backendName:"wasm",setupFunc:function(t){a=t.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:s}=e,{a:o,b:u}=s,c=t.dataIdMap.get(o.dataId).id,l=t.dataIdMap.get(u.dataId).id,d=null!=n?n:o.dtype,p=i.backend_util.assertAndGetBroadcastShape(o.shape,u.shape),h=t.makeOutput(p,d);if(0===i.util.sizeFromShape(p))return h;const f=new Uint8Array(new Int32Array(o.shape).buffer),m=new Uint8Array(new Int32Array(u.shape).buffer),b=t.dataIdMap.get(h.dataId).id;return a(c,f,o.shape.length,l,m,u.shape.length,r[o.dtype],b),h}}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const d=l(i.Add); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let p;const h={kernelName:i.AddN,backendName:"wasm",setupFunc:function(e){p=e.wasm.cwrap(i.AddN,null,["array","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(0===i.util.sizeFromShape(a.shape))return a;const s=t.map((e=>n.dataIdMap.get(e.dataId).id)),o=new Uint8Array(new Int32Array(s).buffer),u=n.dataIdMap.get(a.dataId).id;return p(o,s.length,r[a.dtype],u),a}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype),a=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(a),r}const m={kernelName:i.Identity,backendName:"wasm",kernelFunc:f}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let b;function g(e){const{inputs:t,backend:n,attrs:a}=e,[i,s]=function(e,t){const n=[],r=[];for(let a=0;a=e&&(-1===t||r[t]>r[n])&&(t=n);r[t]=e}return[n,r]}(t.x.shape,a.perm);let o=!0;for(let e=0;e`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`)),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const $={kernelName:i.Reshape,backendName:"wasm",kernelFunc:T}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let A;const N={kernelName:i.BatchMatMul,backendName:"wasm",setupFunc:function(e){A=e.wasm.cwrap(i.BatchMatMul,null,["number","array","number","number","array","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s}=t,{transposeA:o,transposeB:u}=r;if("float32"!==a.dtype||"float32"!==s.dtype)throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const c=a.shape.length,l=s.shape.length,d=o?a.shape[c-2]:a.shape[c-1],p=u?s.shape[l-1]:s.shape[l-2],h=o?a.shape[c-1]:a.shape[c-2],f=u?s.shape[l-2]:s.shape[l-1],m=a.shape.slice(0,-2),b=s.shape.slice(0,-2),g=i.util.sizeFromShape(m),x=i.util.sizeFromShape(b),v=i.broadcast_util.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,f]);i.util.assert(d===p,(()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${u} must match.`));const k=u?[x,f,p]:[x,p,f],y=T({inputs:{x:a},backend:n,attrs:{shape:o?[g,d,h]:[g,h,d]}}),w=T({inputs:{x:s},backend:n,attrs:{shape:k}}),I=n.dataIdMap.get(y.dataId).id,S=n.dataIdMap.get(w.dataId).id,_=o?y.shape[2]:y.shape[1],C=u?w.shape[1]:w.shape[2],O=Math.max(g,x),$=n.makeOutput([O,_,C],y.dtype),N=n.dataIdMap.get($.dataId).id,E=new Uint8Array(new Int32Array(y.shape).buffer),R=new Uint8Array(new Int32Array(w.shape).buffer);return A(I,E,y.shape.length,S,R,w.shape.length,o,u,N),n.disposeData(y.dataId),n.disposeData(w.dataId),$.shape=v,$}};var E=n(22); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function R(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:a}=e,[s,o]=i.slice_util.parseSliceParams(t,n,r),u=i.slice_util.isSliceContinous(t.shape,s,o),c=a.readSync(t.dataId),l=a.makeOutput(o,t.dtype),d=i.util.computeStrides(t.shape),p=a.dataIdMap.get(l.dataId);if(u){const e=i.slice_util.computeFlatOffset(s,d);if("string"===t.dtype)p.stringBytes=c.slice(e,e+i.util.sizeFromShape(o));else{a.typedArrayFromHeap(l).set(c.subarray(e,e+i.util.sizeFromShape(o)))}return l}if("string"===t.dtype){const e=Object(E.c)(c,s,o,t.shape,t.dtype);return p.stringBytes=e,l}const h=a.typedArrayFromHeap(l),f=t.shape.length;if(2===f)!function(e,t,n,r,a){let i=0;const s=r[0],o=r[1],u=s+a[0];for(let r=s;re*t)),c=i.backend_util.getReshaped(a.shape,s,u),l=i.backend_util.getPermuted(c.length,s.length),d=i.backend_util.getReshapedPermuted(a.shape,s,u),p=i.backend_util.getSliceBeginCoords(o,s.length),h=i.backend_util.getSliceSize(d,o,s.length),f=T({inputs:{x:a},backend:n,attrs:{shape:c}}),m=g({inputs:{x:f},backend:n,attrs:{perm:l}}),b=R({inputs:{x:T({inputs:{x:m},backend:n,attrs:{shape:d}})},backend:n,attrs:{begin:p,size:h}});return n.disposeData(f.dataId),n.disposeData(m.dataId),n.disposeData(f.dataId),b}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function D(e){const{inputs:{x:t},attrs:{dtype:n},backend:r}=e,a=r.makeOutput(t.shape,n),i=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(a).set(i),a}const P={kernelName:i.Cast,backendName:"wasm",kernelFunc:D},B=u(i.Ceil); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let j;const L={kernelName:i.ClipByValue,backendName:"wasm",setupFunc:function(e){j=e.wasm.cwrap(i.ClipByValue,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:i,clipValueMax:s}=r,o=n.dataIdMap.get(a.dataId).id,u=n.makeOutput(a.shape,a.dtype),c=n.dataIdMap.get(u.dataId).id;return j(o,i,s,c),u}};var z=n(56); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function W(e){const{inputs:t,backend:n}=e,r=i.util.parseAxisParam(e.attrs.axis,t[0].shape)[0];let a=i.backend_util.computeOutShape(t.map((e=>e.shape)),r);const s=t.filter((e=>i.util.sizeFromShape(e.shape)>0));if(1===s.length)return f({inputs:{x:s[0]},backend:n});const o=n.makeOutput(a,t[0].dtype);if(0===i.util.sizeFromShape(a))return o;const u=s.map((e=>e.shape));if(i.backend_util.assertParamsConsistent(u,r),"string"===s[0].dtype){const e=s.map((e=>{const t=i.util.sizeFromShape(e.shape.slice(r));return T({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));a=i.backend_util.computeOutShape(e.map((e=>e.shape)),1);const c=1===e[0].shape[0],l=Object(z.a)(u,a,t[0].dtype,c),d=i.backend_util.computeOutShape(s.map((e=>e.shape)),r);o.shape=d;return n.dataIdMap.get(o.dataId).stringBytes=i.backend_util.fromStringArrayToUint8(l),e.forEach((e=>n.disposeData(e.dataId))),o}const c=i.util.sizeFromShape(s[0].shape.slice(0,r));let l=0;const d=s.map((e=>{const t=i.util.sizeFromShape(e.shape.slice(r));return l+=t,t})),p=s.map((e=>n.typedArrayFromHeap(e))),h=n.typedArrayFromHeap(o);for(let e=0;e`cumprod does not support ${s.dtype} tensors in the WASM backend`));const d=i.backend_util.getAxesPermutation([o],l);let p=s;null!==d&&(p=g({inputs:{x:s},attrs:{perm:d},backend:n}));const h=i.backend_util.getInnerMostAxes(1,l)[0];i.backend_util.assertAxesAreInnerMostDims("cumprod",[h],l);const f=n.makeOutput(p.shape,p.dtype),m=p.shape[h],b=n.dataIdMap.get(p.dataId).id,x=n.dataIdMap.get(f.dataId).id;J(b,u?1:0,c?1:0,m,x,r[s.dtype]);let v=f;if(null!==d){v=g({inputs:{x:f},attrs:{perm:i.backend_util.getUndoAxesPermutation(d)},backend:n}),n.disposeData(p.dataId),n.disposeData(f.dataId)}return v}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let te;const ne={kernelName:i.Cumsum,backendName:"wasm",setupFunc:function(e){te=e.wasm.cwrap(i.Cumsum,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:s}=t,{axis:o,exclusive:u,reverse:c}=a,l=s.shape.length;i.util.assert("float32"===s.dtype||"int32"===s.dtype,(()=>`cumsum does not support ${s.dtype} tensors in the WASM backend`));const d=i.backend_util.getAxesPermutation([o],l);let p=s;null!==d&&(p=g({inputs:{x:s},attrs:{perm:d},backend:n}));const h=i.backend_util.getInnerMostAxes(1,l)[0];i.backend_util.assertAxesAreInnerMostDims("cumsum",[h],l);const f=n.makeOutput(p.shape,p.dtype),m=p.shape[h],b=n.dataIdMap.get(p.dataId).id,x=n.dataIdMap.get(f.dataId).id;te(b,u?1:0,c?1:0,m,x,r[s.dtype]);let v=f;if(null!==d){v=g({inputs:{x:f},attrs:{perm:i.backend_util.getUndoAxesPermutation(d)},backend:n}),n.disposeData(p.dataId),n.disposeData(f.dataId)}return v}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let re;const ae={kernelName:i.DepthToSpace,backendName:"wasm",setupFunc:function(e){re=e.wasm.cwrap(i.DepthToSpace,null,["number","number","number","array","number","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{blockSize:s,dataFormat:o}=r,u=a.shape[0],c=("NHWC"===o?a.shape[1]:a.shape[2])*s,l=("NHWC"===o?a.shape[2]:a.shape[3])*s,d=("NHWC"===o?a.shape[3]:a.shape[1])/(s*s),p="NHWC"===o?[u,c,l,d]:[u,d,c,l],h=t.makeOutput(p,"float32"),f=t.dataIdMap.get(a.dataId).id,m=new Uint8Array(new Int32Array(i.util.computeStrides(a.shape)).buffer),b=new Uint8Array(new Int32Array(p).buffer),g=new Uint8Array(new Int32Array(i.util.computeStrides(p)).buffer),x=t.dataIdMap.get(h.dataId).id;return re(f,s,"NHWC"===o?1:0,m,a.shape.length-1,b,g,p.length,x),h}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ie;const se={kernelName:i.DepthwiseConv2dNative,backendName:"wasm",setupFunc:function(e){ie=e.wasm.cwrap(i.DepthwiseConv2dNative,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s}=t,o=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(s.dataId).id,{strides:c,dilations:l,pad:d,dimRoundingMode:p}=n,h=null==l?[1,1]:l,f=i.backend_util.computeConv2DInfo(a.shape,s.shape,c,h,d,p,!0),m=f.filterHeight,b=f.filterWidth,g=f.padInfo.top,x=f.padInfo.right,v=f.padInfo.bottom,k=f.padInfo.left,y=f.dilationHeight,w=f.dilationWidth,I=f.strideHeight,S=f.strideWidth,_=f.inChannels,C=f.outChannels,O="SAME"===f.padInfo.type?1:0;if("channelsLast"!==f.dataFormat)throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);const T=r.makeOutput(f.outShape,"float32"),$=r.dataIdMap.get(T.dataId).id;return ie(o,a.shape[0],a.shape[1],a.shape[2],u,m,b,g,x,v,k,O,y,w,I,S,_,C,$),T}},oe=u(i.Elu),ue=l(i.Equal,0,"bool"),ce=u(i.Exp,"float32"); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function le(e){const{inputs:t,attrs:n,backend:r}=e,{input:a}=t,{dim:s}=n,o=a.shape.length,u=a.shape.slice();let c=s;return s<0&&(i.util.assert(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),c=o+s+1),u.splice(c,0,1),T({inputs:{x:a},backend:r,attrs:{shape:u}})}const de={kernelName:i.ExpandDims,backendName:"wasm",kernelFunc:le}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function pe(e){const{attrs:{shape:t,value:n,dtype:r},backend:a}=e,i=a.makeOutput(t,r);return a.typedArrayFromHeap(i).fill(n),i}const he={kernelName:i.Fill,backendName:"wasm",kernelFunc:pe}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let fe;const me={kernelName:i.FlipLeftRight,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{image:r}=t,a=n.makeOutput(r.shape,r.dtype),i=n.dataIdMap.get(r.dataId).id,s=n.dataIdMap.get(a.dataId).id,[o,u,c,l]=r.shape;return fe(i,o,u,c,l,s),a},setupFunc:function(e){fe=e.wasm.cwrap(i.FlipLeftRight,null,["number","number","number","number","number","number"])}},be=u(i.Floor),ge=l(i.FloorDiv); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let xe;const ve={kernelName:i.FusedBatchNorm,backendName:"wasm",setupFunc:function(e){xe=e.wasm.cwrap(i.FusedBatchNorm,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:a}=r,{x:s,mean:o,variance:u,offset:c,scale:l}=n,d=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(o.dataId).id,h=t.dataIdMap.get(u.dataId).id,f=null!=c?t.dataIdMap.get(c.dataId).id:0,m=null!=l?t.dataIdMap.get(l.dataId).id:0,b=t.makeOutput(s.shape,s.dtype);if(0===i.util.sizeFromShape(s.shape))return b;const g=t.dataIdMap.get(b.dataId).id;return xe(d,p,h,f,m,a,g),b}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ke;const ye={kernelName:i.FusedConv2D,backendName:"wasm",setupFunc:function(e){ke=e.wasm.cwrap(i.FusedConv2D,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:s,filter:o,bias:u,preluActivationWeights:c}=t,{strides:l,pad:d,dilations:p,dataFormat:h,dimRoundingMode:f,activation:m,leakyreluAlpha:b}=n,g=i.backend_util.computeConv2DInfo(s.shape,o.shape,l,p,d,f),x=a[m];if(null==x)throw new Error(`${m} activation not yet supported for FusedConv2D in the wasm backend.`);const v=r.dataIdMap.get(s.dataId).id,k=r.dataIdMap.get(o.dataId).id,y=g.outChannels;let w=0;if(null!=u){const e=r.dataIdMap.get(u.dataId);if(1!==e.shape.length)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==y)throw new Error(`FusedConv2D bias shape (${e.shape}) does not match the number of output channels (${y})`);w=e.id}const I=g.filterHeight,S=g.filterWidth,_=g.padInfo.top,C=g.padInfo.right,O=g.padInfo.bottom,T=g.padInfo.left,$=g.dilationHeight,A=g.dilationWidth,N=g.strideHeight,E=g.strideWidth,R=g.inChannels,F="SAME"===g.padInfo.type?1:0,M=g.batchSize,D=g.inHeight,P=g.inWidth;if("NHWC"!==h)throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);const B=r.makeOutput(g.outShape,"float32"),j=r.dataIdMap.get(B.dataId).id,L=null==c?0:r.dataIdMap.get(c.dataId).id;return ke(v,M,D,P,k,I,S,w,_,C,O,T,F,$,A,N,E,R,y,x,L,b||0,j),B}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let we;const Ie={kernelName:i.FusedDepthwiseConv2D,backendName:"wasm",setupFunc:function(e){we=e.wasm.cwrap(i.FusedDepthwiseConv2D,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:s,filter:o,bias:u,preluActivationWeights:c}=t,{strides:l,pad:d,dilations:p,dataFormat:h,dimRoundingMode:f,activation:m,leakyreluAlpha:b}=n,g=i.backend_util.computeConv2DInfo(s.shape,o.shape,l,p,d,f,!0),x=a[m];if(null==x)throw new Error(`${m} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const v=r.dataIdMap.get(s.dataId).id,k=r.dataIdMap.get(o.dataId).id,y=g.outChannels;let w=0;if(null!=u){const e=r.dataIdMap.get(u.dataId);if(1!==e.shape.length)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==y)throw new Error(`FusedDepthwiseConv2D bias shape (${e.shape}) does not match the number of output channels (${y})`);w=e.id}const I=g.filterHeight,S=g.filterWidth,_=g.padInfo.top,C=g.padInfo.right,O=g.padInfo.bottom,T=g.padInfo.left,$=g.dilationHeight,A=g.dilationWidth,N=g.strideHeight,E=g.strideWidth,R=g.inChannels,F="SAME"===g.padInfo.type?1:0,M=g.batchSize,D=g.inHeight,P=g.inWidth;if("NHWC"!==h)throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);const B=r.makeOutput(g.outShape,"float32"),j=r.dataIdMap.get(B.dataId).id,L=null==c?0:r.dataIdMap.get(c.dataId).id;return we(v,M,D,P,k,I,S,w,_,C,O,T,F,$,A,N,E,R,y,x,L,b||0,j),B}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Se;const _e={kernelName:i.GatherNd,backendName:"wasm",setupFunc:function(e){Se=e.wasm.cwrap(i.GatherNd,null,["number","number","number","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{params:a,indices:s}=n,[o,u,c,l]=i.gather_util.prepareAndValidate(a,s),d=t.makeOutput(o,a.dtype);if(0===u)return d;const p=s.shape,h=p[p.length-1],f=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(s.dataId).id,b=new Uint8Array(new Int32Array(l).buffer),g=t.dataIdMap.get(d.dataId).id;return Se(f,r[a.dtype],m,u,h,c,b,g),d}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ce;const Oe={kernelName:i.GatherV2,backendName:"wasm",setupFunc:function(e){Ce=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{x:s,indices:o}=n,{axis:u,batchDims:c}=a,l=i.util.parseAxisParam(u,s.shape)[0],d=t.readSync(o.dataId),p=s.shape[l];for(let e=0;e=0,(()=>`GatherV2: the index value ${t} is not in [0, ${p-1}]`))}const h=i.backend_util.segment_util.collectGatherOpShapeInfo(s,o,l,c),f=T({inputs:{x:s},attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]},backend:t}),m=i.util.sizeFromShape(o.shape),b=T({inputs:{x:o},attrs:{shape:[h.batchSize,m/h.batchSize]},backend:t}),g=[h.batchSize,h.outerSize,m/h.batchSize,h.sliceSize],x=t.makeOutput(g,s.dtype);if(0===i.util.sizeFromShape(s.shape))return x;const v=f.shape.length-1,k=t.dataIdMap.get(f.dataId).id,y=t.dataIdMap.get(b.dataId).id,w=t.dataIdMap.get(x.dataId).id,I=new Uint8Array(new Int32Array(i.util.computeStrides(f.shape)).buffer),S=new Uint8Array(new Int32Array(i.util.computeStrides(g)).buffer);return Ce(k,r[s.dtype],I,v,y,h.batchSize,S,w),t.disposeData(f.dataId),t.disposeData(b.dataId),x.shape=h.outputShape,x}},Te=l(i.Greater,0,"bool"),$e=l(i.GreaterEqual,0,"bool"); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let Ae;const Ne={kernelName:i.LeakyRelu,backendName:"wasm",setupFunc:function(e){Ae=e.wasm.cwrap(i.LeakyRelu,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:{x:t},attrs:{alpha:n},backend:a}=e,s=a.dataIdMap.get(t.dataId).id,o=a.makeOutput(t.shape,"float32");if(0!==i.util.sizeFromShape(t.shape)){const e=a.dataIdMap.get(o.dataId).id;Ae(s,r[t.dtype],n,e)}return o}},Ee=l(i.Less,0,"bool"),Re=l(i.LessEqual,0,"bool"),Fe=u(i.Log),Me=l(i.LogicalAnd,0,"bool"); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let De;const Pe={kernelName:i.Max,backendName:"wasm",setupFunc:function(e){De=e.wasm.cwrap(i.Max,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{reductionIndices:s,keepDims:o}=a,{x:u}=n;let c=t.dataIdMap.get(u.dataId).id,l=u;const{transposed:d,axes:p,originalAxes:h,inputWasTransposed:f}=v(u,s,t);if(f){l=d,c=t.dataIdMap.get(d.dataId).id}const m=l.shape.length;i.backend_util.assertAxesAreInnerMostDims("max",p,m);const[b,g]=i.backend_util.computeOutAndReduceShapes(l.shape,p),x=i.util.sizeFromShape(g),k=t.makeOutput(b,u.dtype);if(0!==i.util.sizeFromShape(l.shape)){const e=t.dataIdMap.get(k.dataId).id;De(c,r[u.dtype],x,e)}if(f&&t.disposeData(d.dataId),o){const e=i.backend_util.expandShapeToKeepDim(k.shape,h);k.shape=e}return k}},Be=l(i.Maximum); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let je;const Le={kernelName:i.MaxPool,backendName:"wasm",setupFunc:function(e){je=e.wasm.cwrap(i.MaxPool,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,s=r.dataIdMap.get(a.dataId).id;i.util.assert("float32"===a.dtype,(()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`));const{filterSize:o,strides:u,pad:c,dimRoundingMode:l}=n,d=i.backend_util.computePool2DInfo(a.shape,o,u,1,c,l),p=d.filterHeight,h=d.filterWidth,f=d.padInfo.top,m=d.padInfo.right,b=d.padInfo.bottom,g=d.padInfo.left,x=d.dilationHeight,v=d.dilationWidth,k=d.strideHeight,y=d.strideWidth,w=d.inChannels,I=d.outChannels;if("channelsLast"!==d.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);const S=r.makeOutput(d.outShape,"float32"),_=r.dataIdMap.get(S.dataId).id;return je(s,a.shape[0],a.shape[1],a.shape[2],p,h,f,m,b,g,x,v,k,y,w,I,_),S}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ze;const We={kernelName:i.Mean,backendName:"wasm",setupFunc:function(e){ze=e.wasm.cwrap(i.Mean,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,u=t.dataIdMap.get(o.dataId).id;let c=u,l=o;const{transposed:d,axes:p,originalAxes:h,inputWasTransposed:f}=v(o,a,t);let m=p;if(f){const e=t.dataIdMap.get(d.dataId).id;e!==u&&(l=d,c=e,m=i.backend_util.getInnerMostAxes(m.length,l.shape.length))}i.backend_util.assertAxesAreInnerMostDims("mean",m,l.shape.length);const[b,g]=i.backend_util.computeOutAndReduceShapes(l.shape,m),x=i.util.sizeFromShape(g);let k=l;"float32"!==l.dtype&&(k=D({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),c=t.dataIdMap.get(k.dataId).id);const y=t.makeOutput(b,"float32");if(0!==i.util.sizeFromShape(l.shape)){const e=t.dataIdMap.get(y.dataId).id;ze(c,x,e)}if(f&&t.disposeData(d.dataId),s){const e=i.backend_util.expandShapeToKeepDim(y.shape,h);y.shape=e}return"float32"!==l.dtype&&t.disposeData(k.dataId),y}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Ge;const Ue={kernelName:i.Min,backendName:"wasm",setupFunc:function(e){Ge=e.wasm.cwrap(i.Min,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:s,keepDims:o}=a,{x:u}=n,c=t.dataIdMap.get(u.dataId).id;let l=c,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,s,t);if(m){const e=t.dataIdMap.get(p.dataId).id;e!==c&&(d=p,l=e)}const b=d.shape.length;i.backend_util.assertAxesAreInnerMostDims("min",h,b);const[g,x]=i.backend_util.computeOutAndReduceShapes(d.shape,h),k=i.util.sizeFromShape(x),y=t.makeOutput(g,d.dtype);if(0!==i.util.sizeFromShape(d.shape)){const e=t.dataIdMap.get(y.dataId).id;Ge(l,r[u.dtype],k,e)}if(m&&t.disposeData(p.dataId),o){const e=i.backend_util.expandShapeToKeepDim(y.shape,f);y.shape=e}return y}},Ve=l(i.Minimum); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var He;let qe;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(He||(He={}));const Ke={kernelName:i.MirrorPad,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:a,mode:i}}=e,s=a.map(((e,n)=>e[0]+t.shape[n]+e[1])),o=n.dataIdMap.get(t.dataId).id,u=n.makeOutput(s,t.dtype),c=n.dataIdMap.get(u.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),d=a.map((e=>e[0])),p=a.map((e=>e[1])),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return qe(o,l,t.shape.length,r[t.dtype],h,f,He[i],c),u},setupFunc:function(e){qe=e.wasm.cwrap(i.MirrorPad,null,["number","array","number","number","array","array","number","number"])}},Xe=l(i.Multiply),Ye=u(i.Neg); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ze(e,t){const n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],a=n[1],i=n[2],s=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:a,pSelectedScores:i,pValidOutputs:s}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Qe;const Je={kernelName:i.NonMaxSuppressionV3,backendName:"wasm",setupFunc:function(e){Qe=e.wasm.cwrap(i.NonMaxSuppressionV3,"number",["number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:i,scoreThreshold:s}=r,{boxes:o,scores:u}=n,c=t.dataIdMap.get(o.dataId).id,l=t.dataIdMap.get(u.dataId).id,d=Qe(c,l,i,a,s),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=Ze(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let et;const tt={kernelName:i.NonMaxSuppressionV4,backendName:"wasm",setupFunc:function(e){et=e.wasm.cwrap(i.NonMaxSuppressionV4,"number",["number","number","number","number","number","bool"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:i,scoreThreshold:s,padToMaxOutputSize:o}=r,{boxes:u,scores:c}=n,l=t.dataIdMap.get(u.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=et(l,d,i,a,s,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:b}=Ze(t,p);return t.wasm._free(m),[t.makeOutput([f],"int32",h),t.makeOutput([],"int32",b)]}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let nt;const rt={kernelName:i.NonMaxSuppressionV5,backendName:"wasm",setupFunc:function(e){nt=e.wasm.cwrap(i.NonMaxSuppressionV5,"number",["number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:i,scoreThreshold:s,softNmsSigma:o}=r,{boxes:u,scores:c}=n,l=t.dataIdMap.get(u.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=nt(l,d,i,a,s,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:b}=Ze(t,p);return t.wasm._free(b),[t.makeOutput([f],"int32",h),t.makeOutput([f],"float32",m)]}},at=l(i.NotEqual,0,"bool"); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let it;const st={kernelName:i.OneHot,backendName:"wasm",setupFunc:function(e){it=e.wasm.cwrap(i.OneHot,null,["number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{depth:i,onValue:s,offValue:o}=r,u=n.makeOutput([...a.shape,i],"int32"),c=n.dataIdMap.get(u.dataId).id,l=n.dataIdMap.get(a.dataId).id;return it(l,i,s,o,c),u}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ot={kernelName:i.OnesLike,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ut={kernelName:i.Pack,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return le({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{i.util.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),i.util.assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const u=[],c=W({inputs:t.map((e=>{const t=le({inputs:{input:e},backend:n,attrs:{dim:a}});return u.push(t),t})),backend:n,attrs:{axis:a}});return u.forEach((e=>n.disposeData(e.dataId))),c}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ct;const lt={kernelName:i.PadV2,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:a,constantValue:s}}=e,o=a.map(((e,n)=>e[0]+t.shape[n]+e[1]));if(0===i.util.sizeFromShape(t.shape))return pe({backend:n,attrs:{shape:o,value:s,dtype:t.dtype}});const u=n.dataIdMap.get(t.dataId).id,c=n.makeOutput(o,t.dtype),l=n.dataIdMap.get(c.dataId).id,d=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map((e=>e[0])),h=a.map((e=>e[1])),f=new Uint8Array(new Int32Array(p).buffer),m=new Uint8Array(new Int32Array(h).buffer);return ct(u,d,t.shape.length,r[t.dtype],f,m,s,l),c},setupFunc:function(e){ct=e.wasm.cwrap(i.PadV2,null,["number","array","number","number","array","array","number","number"])}},dt=l(i.Pow); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let pt;const ht={kernelName:i.Prelu,backendName:"wasm",setupFunc:function(e){pt=e.wasm.cwrap(i.Prelu,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,i=n.dataIdMap.get(r.dataId).id,s=n.dataIdMap.get(a.dataId).id;let o=i;const u=r;let c=u;"float32"!==u.dtype&&(c=D({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),o=n.dataIdMap.get(c.dataId).id);const l=n.makeOutput(r.shape,"float32"),d=n.dataIdMap.get(l.dataId).id;return pt(o,s,d),"float32"!==u.dtype&&n.disposeData(c.dataId),l}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let ft;const mt={kernelName:i.Prod,backendName:"wasm",setupFunc:function(e){ft=e.wasm.cwrap(i.Prod,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:s,keepDims:o}=a,{x:u}=n,c=t.dataIdMap.get(u.dataId).id;let l=c,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,s,t);let b=h;if(m){const e=t.dataIdMap.get(p.dataId).id;e!==c&&(d=p,l=e,b=i.backend_util.getInnerMostAxes(b.length,d.shape.length))}i.backend_util.assertAxesAreInnerMostDims("prod",b,d.shape.length);const[g,x]=i.backend_util.computeOutAndReduceShapes(d.shape,b),k=i.util.sizeFromShape(x),y=t.makeOutput(g,d.dtype);if(0!==i.util.sizeFromShape(d.shape)){const e=t.dataIdMap.get(y.dataId).id;ft(l,k,r[y.dtype],e)}if(m&&t.disposeData(p.dataId),o){const e=i.backend_util.expandShapeToKeepDim(y.shape,f);y.shape=e}return y}};var bt=n(73); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gt={kernelName:i.Range,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:i,dtype:s}=n,o=Object(bt.a)(r,a,i,s),u=t.makeOutput([o.length],s);return t.typedArrayFromHeap(u).set(o),u}},xt=l(i.RealDiv),vt=u(i.Relu),kt=u(i.Relu6); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let yt;const wt={kernelName:i.ResizeBilinear,backendName:"wasm",setupFunc:function(e){yt=e.wasm.cwrap(i.ResizeBilinear,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:s,halfPixelCenters:o,size:u}=r,[c,l]=u,[d,p,h,f]=a.shape,m=[d,c,l,f];let b,g=t.dataIdMap.get(a.dataId);"float32"!==g.dtype&&(b=D({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(b.dataId));const x=g.id,v=t.makeOutput(m,"float32");if(0===i.util.sizeFromShape(a.shape))return v;const k=t.dataIdMap.get(v.dataId).id;return yt(x,d,p,h,f,c,l,s?1:0,o?1:0,k),null!=b&&t.disposeData(b.dataId),v}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let It;const St={kernelName:i.Reverse,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=i.util.parseAxisParam(s,a.shape);if(0===a.shape.length)return f({inputs:{x:a},backend:n});const u=n.makeOutput(a.shape,a.dtype),c=n.dataIdMap.get(a.dataId).id,l=n.dataIdMap.get(u.dataId).id,d=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(a.shape).buffer);It(c,d,o.length,p,a.shape.length,l);const h=T({inputs:{x:u},attrs:{shape:a.shape},backend:n});return n.disposeData(u.dataId),h},setupFunc:function(e){It=e.wasm.cwrap(i.Reverse,null,["number","array","number","array","number","number"])}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let _t;const Ct={kernelName:i.RotateWithOffset,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{radians:s,fillValue:o,center:u}=r,c=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(a.dataId).id,d=n.dataIdMap.get(c.dataId).id,[p,h,f,m]=a.shape,[b,g]=i.backend_util.getImageCenter(u,h,f),x="number"==typeof o?[o,o,o,0===o?0:255]:[...o,255],v=new Uint8Array(new Int32Array(x).buffer);return _t(l,p,h,f,m,s,b,g,v,x.length,d),c},setupFunc:function(e){_t=e.wasm.cwrap(i.RotateWithOffset,null,["number","number","number","number","number","number","number","number","array","number","number"])}},Ot=u(i.Round),Tt=u(i.Rsqrt); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let $t;const At={kernelName:i.ScatterNd,backendName:"wasm",setupFunc:function(e){$t=e.wasm.cwrap(i.ScatterNd,null,["number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{indices:s,updates:o}=n,{shape:u}=a,c=t.makeOutput(u,o.dtype);if(0===i.util.sizeFromShape(u))return c;const{sliceRank:l,numUpdates:d,sliceSize:p,strides:h,outputSize:f}=i.scatter_util.calculateShapes(o,s,u),m=t.dataIdMap.get(s.dataId).id,b=t.dataIdMap.get(o.dataId).id,g=new Uint8Array(new Int32Array(h).buffer),x=t.dataIdMap.get(c.dataId).id;return $t(m,b,r[o.dtype],l,d,p,g,f,x),c}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Nt;const Et={kernelName:i.Select,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,o=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(a.dataId).id,c=n.dataIdMap.get(s.dataId).id,l=n.makeOutput(a.shape,a.dtype),d=n.dataIdMap.get(l.dataId).id,p=r.shape.length,h=a.shape.length,f=0===p||p>1||1===h?1:i.util.sizeFromShape(a.shape.slice(1));return Nt(o,u,c,f,d),l},setupFunc:function(e){Nt=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let Rt;const Ft={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){Rt=e.wasm.cwrap(i.Sigmoid,null,["number","number"])},kernelFunc:function(e){const{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(a.dataId).id;return 0===i.util.sizeFromShape(a.shape)||Rt(r,s),a}},Mt=u(i.Sin); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let Dt;const Pt={kernelName:i.Softmax,backendName:"wasm",setupFunc:function(e){Dt=e.wasm.cwrap(i.Softmax,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,a=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(s.dataId).id,u=n.shape[r],c=i.util.sizeFromShape(n.shape)/u;return 0===i.util.sizeFromShape(s.shape)||Dt(a,o,u,c),s}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Bt={kernelName:i.SpaceToBatchND,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r,u=i.util.sizeFromShape(s),c=[[0,0]];c.push(...o);for(let e=1+s.length;e0?l+1:0;if(d<0)throw new Error(i.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());const p=s.shape.slice();p[0]=d;const h=n.dataIdMap.get(s.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.dataIdMap.get(u.dataId).id,b=n.makeOutput(p,s.dtype),g=n.dataIdMap.get(b.dataId).id,x=n.makeOutput([4],"int32"),v=n.dataIdMap.get(x.dataId).id;Gt(h,r[s.dtype],s.shape[0],f,m,g,v,t,0);const k=n.readSync(x.dataId);let y;switch(k[0]){case 0:y=i.backend_util.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break;case 1:y=i.backend_util.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break;case 2:y=i.backend_util.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(k[1],k[2]);break;case 3:y=i.backend_util.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(k[1],k[2],k[3]);break;default:y=""}if(n.disposeData(x.dataId),y)throw n.disposeData(b.dataId),new Error(y);return b} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ht={kernelName:i.SparseSegmentMean,backendName:"wasm",setupFunc:Ut,kernelFunc:function(e){return Vt(e,!0)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qt={kernelName:i.SparseSegmentSum,backendName:"wasm",setupFunc:Ut,kernelFunc:function(e){return Vt(e,!1)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kt={kernelName:i.SplitV,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=n,u=i.util.parseAxisParam(o,a.shape)[0],c=i.backend_util.prepareSplitSize(a,s,u),l=new Array(a.shape.length).fill(0),d=a.shape.slice();return c.map((e=>{const t=[...d];t[u]=e;const n=R({inputs:{x:a},attrs:{begin:l,size:t},backend:r});return l[u]+=e,n}))}},Xt=u(i.Sqrt),Yt=u(i.Square),Zt=l(i.SquaredDifference); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let Qt;const Jt={kernelName:i.Step,backendName:"wasm",setupFunc:function(e){Qt=e.wasm.cwrap(i.Step,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{alpha:i}=a,{x:s}=n,o=t.dataIdMap.get(s.dataId).id,u=t.makeOutput(s.shape,s.dtype),c=t.dataIdMap.get(u.dataId).id;return Qt(o,i,r[s.dtype],c),u}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */let en;const tn={kernelName:i.StridedSlice,backendName:"wasm",setupFunc:function(e){en=e.wasm.cwrap(i.StridedSlice,null,["number","array","number","array","array","array","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{begin:s,end:o,strides:u,beginMask:c,endMask:l,ellipsisMask:d,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:f,finalShape:m,isIdentity:b,sliceDim0:g,isSimpleSlice:x,begin:v,end:k,strides:y}=i.slice_util.sliceInfo(a.shape,s,o,u,c,l,d,p,h);let w;if(b)w=T({inputs:{x:a},backend:t,attrs:{shape:m}});else if(g||x){i.util.assert(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=i.slice_util.computeOutShape(v,k,y),n=R({inputs:{x:a},backend:t,attrs:{begin:v,size:e}});w=T({inputs:{x:n},backend:t,attrs:{shape:m}}),t.disposeData(n.dataId)}else{const e=t.makeOutput(f,"float32"),n=t.dataIdMap.get(a.dataId).id,r=new Uint8Array(new Int32Array(i.util.computeStrides(a.shape)).buffer),s=new Uint8Array(new Int32Array(v).buffer),o=new Uint8Array(new Int32Array(k).buffer),u=new Uint8Array(new Int32Array(y).buffer),c=new Uint8Array(new Int32Array(f).buffer),l=new Uint8Array(new Int32Array(i.util.computeStrides(f)).buffer),d=t.dataIdMap.get(e.dataId).id;en(n,r,a.shape.length,s,o,u,c,l,f.length,d),w=T({inputs:{x:e},backend:t,attrs:{shape:m}}),t.disposeData(e.dataId)}return w}},nn=l(i.Sub); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let rn;const an={kernelName:i.Sum,backendName:"wasm",setupFunc:function(e){rn=e.wasm.cwrap(i.Sum,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:s,keepDims:o}=a,{x:u}=n,c=t.dataIdMap.get(u.dataId).id;let l=c,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,s,t);let b=h;if(m){const e=t.dataIdMap.get(p.dataId).id;e!==c&&(d=p,l=e,b=i.backend_util.getInnerMostAxes(b.length,d.shape.length))}i.backend_util.assertAxesAreInnerMostDims("sum",b,d.shape.length);const[g,x]=i.backend_util.computeOutAndReduceShapes(d.shape,b),k=i.util.sizeFromShape(x),y=t.makeOutput(g,d.dtype);if(0!==i.util.sizeFromShape(d.shape)){const e=t.dataIdMap.get(y.dataId).id;rn(l,k,r[y.dtype],e)}if(m&&t.disposeData(p.dataId),o){const e=i.backend_util.expandShapeToKeepDim(y.shape,f);y.shape=e}return y}},sn=u(i.Tan),on=u(i.Tanh); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let un;const cn={kernelName:i.Tile,backendName:"wasm",setupFunc:function(e){un=e.wasm.cwrap(i.Tile,null,["number","array","number","array","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,s=n.dataIdMap.get(i.dataId).id,{reps:o}=a,u=new Array(i.shape.length);for(let e=0;e{const{x:a}=e,{k:i,sorted:s}=n,o=t.dataIdMap.get(a.dataId).id,u=new Uint8Array(new Int32Array(a.shape).buffer),c=a.shape.slice();c[c.length-1]=i;const l=t.makeOutput(c,a.dtype),d=t.dataIdMap.get(l.dataId).id,p=t.makeOutput(c,"int32"),h=t.dataIdMap.get(p.dataId).id;return ln(o,u,a.shape.length,r[a.dtype],i,s,d,h),[l,p]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +let pn;const hn={kernelName:i.Transform,backendName:"wasm",setupFunc:function(e){pn=e.wasm.cwrap(i.Transform,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{image:a,transforms:s}=n,{interpolation:o,fillMode:u,fillValue:c,outputShape:l}=r,[d,p,h,f]=a.shape,[m,b]=null!=l?l:[p,h],g=[d,m,b,f],x=new Uint8Array(new Int32Array(i.util.computeStrides(a.shape)).buffer),v=t.makeOutput(g,a.dtype),k=t.dataIdMap.get(v.dataId).id,y=t.dataIdMap.get(a.dataId).id,w=t.dataIdMap.get(s.dataId).id,I="nearest"===o?1:2;let S;switch(u){case"constant":default:S=1;break;case"reflect":S=2;break;case"wrap":S=3;break;case"nearest":S=4}return pn(y,w,s.shape[0]>1,d,m,b,f,h,p,x,a.shape.length-1,I,S,c,k),v}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fn={kernelName:i.Unpack,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:i}=r;i<0&&(i+=a.shape.length);const s=a.shape[i],o=a.shape.length,u=new Array(o-1);let c=0;for(let e=0;e({dataId:e,dtype:t,shape:u})))}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mn={kernelName:i.ZerosLike,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}},bn=[o,c,d,h,y,I,_,O,N,M,P,B,L,G,V,q,K,X,Q,ee,ne,ae,se,oe,ue,ce,de,he,me,be,ge,ve,ye,Ie,_e,Oe,Te,$e,m,Ne,Ee,Re,Fe,Me,Pe,Be,Le,We,Ue,Ve,Ke,Xe,Ye,Je,tt,rt,at,st,ot,ut,lt,dt,ht,mt,gt,xt,vt,kt,$,wt,St,Ct,Ot,Tt,At,Et,Ft,Mt,F,Pt,Bt,Lt,Wt,Ht,qt,Kt,Xt,Yt,Zt,Jt,tn,nn,an,sn,on,cn,dn,hn,x,fn,mn]; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */for(const e of bn)Object(i.registerKernel)(e); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gn=Object(i.env)();gn.registerFlag("WASM_HAS_SIMD_SUPPORT",(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])))),gn.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(gn.get("IS_NODE"))return!1;try{return(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}}));var xn=n(91),vn=n.n(xn);var kn=n(98),yn=n.n(kn); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class wn extends i.KernelBackend{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(En),Rn=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new i.DataStorage(this,Object(i.engine)())}write(e,t,n){const r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){const t=i.util.now();e();return{kernelMs:i.util.now()-t}}move(e,t,n,r,a){const s=this.dataIdNextNumber++;if("string"===r){const i=t;return void this.dataIdMap.set(e,{id:s,stringBytes:i,shape:n,dtype:r,memoryOffset:null,refCount:a})}const o=i.util.sizeFromShape(n),u=o*i.util.bytesPerElement(r),c=this.wasm._malloc(u);this.dataIdMap.set(e,{id:s,memoryOffset:c,shape:n,dtype:r,refCount:a}),this.wasm.tfjs.registerTensor(s,o,c),null!=t&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),c)}async read(e){return this.readSync(e)}readSync(e,t,n){const{memoryOffset:r,dtype:a,shape:s,stringBytes:o}=this.dataIdMap.get(e);if("string"===a)return null!=t&&0!==t||!(null==n||n>=o.length)?o.slice(t,n):o;t=t||0,n=n||i.util.sizeFromShape(s);const u=i.util.bytesPerElement(a);return function(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}(this.wasm.HEAPU8.slice(r+t*u,r+n*u).buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){const n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){if(this.dataIdMap.has(e)){return this.dataIdMap.get(e).refCount}return 0}incRef(e){const t=this.dataIdMap.get(e);null!=t&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let r;if(null==n)r=this.write(null,e,t);else{const a=this.dataIdNextNumber++;r={id:a},this.dataIdMap.set(r,{id:a,memoryOffset:n,shape:e,dtype:t,refCount:1});const s=i.util.sizeFromShape(e);this.wasm.tfjs.registerTensor(a,s,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){const r=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(n),s=i.util.sizeFromShape(e);switch(t){case"float32":return new Float32Array(r,a,s);case"int32":return new Int32Array(r,a,s);case"bool":return new Uint8Array(r,a,s);default:throw new Error(`Unknown dtype ${t}`)}}}function In(e,t,n){if(null!=Cn)return Cn;let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),null!=Tn&&null!=Tn[r]?Tn[r]:n+r}async function Sn(){const[e,t]=await Promise.all([Object(i.env)().getAsync("WASM_HAS_SIMD_SUPPORT"),Object(i.env)().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const a={};var s;a.locateFile=(n,r)=>{if(n.endsWith(".worker.js")){const e='"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\n");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=((info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports});self.onmessage=(e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["__emscripten_thread_exit"](result)}}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else if(e.data.cmd==="processProxyingQueue"){if(Module["_pthread_self"]()){Module["_emscripten_proxy_execute_queue"](e.data.queue)}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}});'.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?In(e,t,null!=On?On:r):r+n},An&&(a.instantiateWasm=(s=In(e,t,null!=On?On:""),(e,t)=>(i.util.fetch(s,{credentials:"same-origin"}).then((n=>{n.ok||e.env.a(`failed to load wasm binary file at '${s}'`),n.arrayBuffer().then((n=>{WebAssembly.instantiate(n,e).then((e=>{t(e.instance,e.module)}))}))})),{})));let o,u=!1;a.onAbort=()=>{if(u)return;if($n)return;$n=!0;r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})},t&&e&&null==Cn?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+vn.a.toString()],{type:"text/javascript"}),o=vn()(a)):o=yn()(a),o.then((e=>{u=!0,$n=!1;e.tfjs={init:e.cwrap("init",null,[]),initWithThreadsCount:e.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:e.cwrap("get_threads_count","number",[]),registerTensor:e.cwrap("register_tensor",null,["number","number","number"]),disposeData:e.cwrap("dispose_data",null,["number"]),dispose:e.cwrap("dispose",null,[])},n({wasm:e})}))}))}const _n=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let Cn=null,On=null,Tn={},$n=!1,An=!1;function Nn(e,t=!1){if($n)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if("string"==typeof e)On=e;else{Tn=e;const t=_n.filter((e=>null==Tn[e]));if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}An=t}let En=-1,Rn=-1;Object(i.registerBackend)("wasm",(async()=>{const{wasm:e}=await Sn();return new wn(e)}),2)},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(47);class a{constructor(){}createContext(e={}){return new r.a(e)}}},function(e,t){e.exports=r;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function r(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function a(e){return!0===(e&&e.__isLong__)}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0}),r.isLong=a;var i={},s={};function o(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=s[e])?r:(n=c(e,(0|e)<0?-1:0,!0),a&&(s[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=i[e])?r:(n=c(e,e<0?-1:0,!1),a&&(i[e]=n),n)}function u(e,t){if(isNaN(e))return t?x:g;if(t){if(e<0)return x;if(e>=f)return I}else{if(e<=-m)return S;if(e+1>=m)return w}return e<0?u(-e,t).neg():c(e%h|0,e/h|0,t)}function c(e,t,n){return new r(e,t,n)}r.fromInt=o,r.fromNumber=u,r.fromBits=c;var l=Math.pow;function d(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||360)throw Error("interior hyphen");if(0===r)return d(e.substring(1),t,n).neg();for(var a=u(l(n,8)),i=g,s=0;s>>0:this.low},_.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},_.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((i=o).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},_.getHighBits=function(){return this.high},_.getHighBitsUnsigned=function(){return this.high>>>0},_.getLowBits=function(){return this.low},_.getLowBitsUnsigned=function(){return this.low>>>0},_.getNumBitsAbs=function(){if(this.isNegative())return this.eq(S)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},_.isOdd=function(){return 1==(1&this.low)},_.isEven=function(){return 0==(1&this.low)},_.equals=function(e){return a(e)||(e=p(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},_.eq=_.equals,_.notEquals=function(e){return!this.eq(e)},_.neq=_.notEquals,_.ne=_.notEquals,_.lessThan=function(e){return this.comp(e)<0},_.lt=_.lessThan,_.lessThanOrEqual=function(e){return this.comp(e)<=0},_.lte=_.lessThanOrEqual,_.le=_.lessThanOrEqual,_.greaterThan=function(e){return this.comp(e)>0},_.gt=_.greaterThan,_.greaterThanOrEqual=function(e){return this.comp(e)>=0},_.gte=_.greaterThanOrEqual,_.ge=_.greaterThanOrEqual,_.compare=function(e){if(a(e)||(e=p(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},_.comp=_.compare,_.negate=function(){return!this.unsigned&&this.eq(S)?S:this.not().add(v)},_.neg=_.negate,_.add=function(e){a(e)||(e=p(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,i=65535&this.low,s=e.high>>>16,o=65535&e.high,u=e.low>>>16,l=0,d=0,h=0,f=0;return h+=(f+=i+(65535&e.low))>>>16,d+=(h+=r+u)>>>16,l+=(d+=n+o)>>>16,l+=t+s,c((h&=65535)<<16|(f&=65535),(l&=65535)<<16|(d&=65535),this.unsigned)},_.subtract=function(e){return a(e)||(e=p(e)),this.add(e.neg())},_.sub=_.subtract,_.multiply=function(e){if(this.isZero())return g;if(a(e)||(e=p(e)),n)return c(n.mul(this.low,this.high,e.low,e.high),n.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(S))return e.isOdd()?S:g;if(e.eq(S))return this.isOdd()?S: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(b)&&e.lt(b))return u(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,r=65535&this.high,i=this.low>>>16,s=65535&this.low,o=e.high>>>16,l=65535&e.high,d=e.low>>>16,h=65535&e.low,f=0,m=0,x=0,v=0;return x+=(v+=s*h)>>>16,m+=(x+=i*h)>>>16,x&=65535,m+=(x+=s*d)>>>16,f+=(m+=r*h)>>>16,m&=65535,f+=(m+=i*d)>>>16,m&=65535,f+=(m+=s*l)>>>16,f+=t*h+r*d+i*l+s*o,c((x&=65535)<<16|(v&=65535),(f&=65535)<<16|(m&=65535),this.unsigned)},_.mul=_.multiply,_.divide=function(e){if(a(e)||(e=p(e)),e.isZero())throw Error("division by zero");var t,r,i;if(n)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?c((this.unsigned?n.div_u:n.div_s)(this.low,this.high,e.low,e.high),n.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?x:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return x;if(e.gt(this.shru(1)))return k;i=x}else{if(this.eq(S))return e.eq(v)||e.eq(y)?S:e.eq(S)?v:(t=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?v:y:(r=this.sub(e.mul(t)),i=t.add(r.div(e)));if(e.eq(S))return this.unsigned?x: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();i=g}for(r=this;r.gte(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),o=s<=48?1:l(2,s-48),d=u(t),h=d.mul(e);h.isNegative()||h.gt(r);)h=(d=u(t-=o,this.unsigned)).mul(e);d.isZero()&&(d=v),i=i.add(d),r=r.sub(h)}return i},_.div=_.divide,_.modulo=function(e){return a(e)||(e=p(e)),n?c((this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,e.low,e.high),n.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},_.mod=_.modulo,_.rem=_.modulo,_.not=function(){return c(~this.low,~this.high,this.unsigned)},_.and=function(e){return a(e)||(e=p(e)),c(this.low&e.low,this.high&e.high,this.unsigned)},_.or=function(e){return a(e)||(e=p(e)),c(this.low|e.low,this.high|e.high,this.unsigned)},_.xor=function(e){return a(e)||(e=p(e)),c(this.low^e.low,this.high^e.high,this.unsigned)},_.shiftLeft=function(e){return a(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?c(this.low<>>32-e,this.unsigned):c(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):c(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},_.shr=_.shiftRight,_.shiftRightUnsigned=function(e){if(a(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?c(this.low>>>e|t<<32-e,t>>>e,this.unsigned):c(32===e?t:t>>>e-32,0,this.unsigned)},_.shru=_.shiftRightUnsigned,_.shr_u=_.shiftRightUnsigned,_.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},_.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},_.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},_.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]},_.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]},r.fromBytes=function(e,t,n){return n?r.fromBytesLE(e,t):r.fromBytesBE(e,t)},r.fromBytesLE=function(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},r.fromBytesBE=function(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},function(e,t,n){(function(t,r,a,i){var s,o=(s=(s="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||t,function(e){function t(){return M.buffer!=G&&Q(M.buffer),U}function o(){return M.buffer!=G&&Q(M.buffer),V}function u(){return M.buffer!=G&&Q(M.buffer),H}function c(){return M.buffer!=G&&Q(M.buffer),q}var l,d,p,h="undefined"!=typeof(e=e||{})?e:{};h.ready=new Promise((function(e,t){l=e,d=t})),"undefined"!=typeof r&&r.listeners&&(p={uncaughtException:r.listeners("uncaughtException"),unhandledRejection:r.listeners("unhandledRejection")});var f,m,b,g,x,v,k=Object.assign({},h),y=[],w=(e,t)=>{throw t},I="object"==typeof window,S="function"==typeof importScripts,_="object"==typeof r&&"object"==typeof r.versions&&"string"==typeof r.versions.node,C=h.ENVIRONMENT_IS_PTHREAD||!1,O="";function T(e){return h.locateFile?h.locateFile(e,O):O+e}if(_){let e;O=S?n(52).dirname(O)+"/":a+"/",v=()=>{x||(g=n(94),x=n(52))},f=function(e,t){return v(),e=x.normalize(e),g.readFileSync(e,t?void 0:"utf8")},b=e=>{var t=f(e,!0);return t.buffer||(t=new Uint8Array(t)),t},m=(e,t,n)=>{v(),e=x.normalize(e),g.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},r.argv.length>1&&r.argv[1].replace(/\\/g,"/"),y=r.argv.slice(2),r.on("uncaughtException",(function(e){if(!(e instanceof dt))throw e})),r.on("unhandledRejection",(function(e){throw e})),w=(e,t)=>{if(ie())throw r.exitCode=e,t;var n;(n=t)instanceof dt||R("exiting due to exception: "+n),r.exit(e)},h.inspect=function(){return"[Emscripten Module object]"};try{e=n(121)}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}i.Worker=e.Worker}else(I||S)&&(S?O=self.location.href:"undefined"!=typeof document&&document.currentScript&&(O=document.currentScript.src),"undefined"!=typeof s&&s&&(O=s),O=0!==O.indexOf("blob:")?O.substr(0,O.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(f=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},S&&(b=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),m=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(i.performance=n(122).performance);var $=console.log.bind(console),A=console.warn.bind(console);_&&(v(),$=e=>g.writeSync(1,e+"\n"),A=e=>g.writeSync(2,e+"\n"));var N,E=h.print||$,R=h.printErr||A;function F(e){F.shown||(F.shown={}),F.shown[e]||(F.shown[e]=1,R(e))}Object.assign(h,k),k=null,h.arguments&&(y=h.arguments),h.thisProgram&&h.thisProgram,h.quit&&(w=h.quit),Atomics.load,Atomics.store,Atomics.compareExchange,h.wasmBinary&&(N=h.wasmBinary);var M,D,P=h.noExitRuntime||!0;"object"!=typeof WebAssembly&&de("no native wasm support detected");var B,j=!1;function L(e){return h["_"+e]}function z(e,n,r,a,i){var s={string:function(e){var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);Z(e,t=ct(n),n)}return t},array:function(e){var n=ct(e.length);return function(e,n){t().set(e,n)}(e,n),n}},o=L(e),u=[],c=0;if(a)for(var l=0;l(e.buffer instanceof SharedArrayBuffer&&(e=new Uint8Array(e)),t.decode.call(t,e))}var G,U,V,H,q,K="undefined"!=typeof TextDecoder?new W("utf8"):void 0;function X(e,t,n){for(var r=t+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.subarray&&K)return K.decode(e.subarray(t,a));for(var i="";t>10,56320|1023&c)}}else i+=String.fromCharCode((31&s)<<6|o)}else i+=String.fromCharCode(s)}return i}function Y(e,t){return e?X(o(),e,t):""}function Z(e,t,n){return function(e,t,n,r){if(!(r>0))return 0;for(var a=n,i=n+r-1,s=0;s=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=i)break;t[n++]=o}else if(o<=2047){if(n+1>=i)break;t[n++]=192|o>>6,t[n++]=128|63&o}else if(o<=65535){if(n+2>=i)break;t[n++]=224|o>>12,t[n++]=128|o>>6&63,t[n++]=128|63&o}else{if(n+3>=i)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63,t[n++]=128|o>>6&63,t[n++]=128|63&o}}return t[n]=0,n-a}(e,o(),t,n)}function Q(e){G=e,h.HEAP8=U=new Int8Array(e),h.HEAP16=new Int16Array(e),h.HEAP32=H=new Int32Array(e),h.HEAPU8=V=new Uint8Array(e),h.HEAPU16=new Uint16Array(e),h.HEAPU32=new Uint32Array(e),h.HEAPF32=new Float32Array(e),h.HEAPF64=q=new Float64Array(e)}"undefined"!=typeof TextDecoder&&new W("utf-16le"),C&&(G=h.buffer);var J,ee=h.INITIAL_MEMORY||16777216;if(C)M=h.wasmMemory,G=h.buffer;else if(h.wasmMemory)M=h.wasmMemory;else if(!((M=new WebAssembly.Memory({initial:ee/65536,maximum:32768,shared:!0})).buffer instanceof SharedArrayBuffer))throw R("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");M&&(G=M.buffer),ee=G.byteLength,Q(G);var te=[],ne=[],re=[],ae=[];function ie(){return P||!1}function se(){C||be(ne)}var oe,ue=0,ce=null,le=null;function de(e){C?postMessage({cmd:"onAbort",arg:e}):h.onAbort&&h.onAbort(e),R(e="Aborted("+e+")"),j=!0,B=1,e+=". Build with -s ASSERTIONS=1 for more info.";var t=new WebAssembly.RuntimeError(e);throw d(t),t}function pe(e){return e.startsWith("data:application/octet-stream;base64,")}function he(e){return e.startsWith("file://")}function fe(e){try{if(e==oe&&N)return new Uint8Array(N);if(b)return b(e);throw"both async and sync fetching of the wasm failed"}catch(e){de(e)}}h.preloadedImages={},h.preloadedAudios={},pe(oe="tfjs-backend-wasm-threaded-simd.wasm")||(oe=T(oe));var me={};function be(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var n=t.func;"number"==typeof n?void 0===t.arg?Se(n)():Se(n)(t.arg):n(void 0===t.arg?null:t.arg)}else t(h)}}function ge(e){var t=ot(),n=e();return ut(t),n}function xe(e){var t=ke.pthreads[e];if(t){u()[e>>2]=0;var n=t.worker;ke.returnWorkerToPool(n)}}function ve(e){!function(e,t){if(B=e,!t&&C)throw ye(e),"unwind";var n;ie()||C||ke.terminateAllThreads(),B=n=e,ie()||(ke.terminateAllThreads(),h.onExit&&h.onExit(n),j=!0),w(n,new dt(n))}(e)}var ke={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],init:function(){C?ke.initWorker():ke.initMainThread()},initMainThread:function(){for(var e=0;e<8;++e)ke.allocateUnusedWorker()},initWorker:function(){P=!1},pthreads:{},setExitStatus:function(e){B=e},terminateAllThreads:function(){for(var e in ke.pthreads){var t=ke.pthreads[e];t&&t.worker&&ke.returnWorkerToPool(t.worker)}for(var n=0;n>2]=0;try{e()}finally{u()[lt>>2]=1}},receiveObjectTransfer:function(e){},threadInit:function(){for(var e in ke.tlsInitFunctions)ke.tlsInitFunctions[e]()},loadWasmModuleToWorker:function(e,t){e.onmessage=n=>{var r,a=n.data,i=a.cmd;if(e.pthread&&(ke.currentProxiedOperationCallerThread=e.pthread.threadInfoStruct),a.targetThread&&a.targetThread!=Je()){var s=ke.pthreads[a.targetThread];return s?s.worker.postMessage(a,a.transferList):R('Internal error! Worker sent a message "'+i+'" to target pthread '+a.targetThread+", but that thread no longer exists!"),void(ke.currentProxiedOperationCallerThread=void 0)}"processQueuedMainThreadWork"===i?et():"spawnThread"===i?Ce(a):"cleanupThread"===i?xe(a.thread):"killThread"===i?function(e){u()[e>>2]=0;var t=ke.pthreads[e];delete ke.pthreads[e],t.worker.terminate(),it(e),ke.runningWorkers.splice(ke.runningWorkers.indexOf(t.worker),1),t.worker.pthread=void 0}(a.thread):"cancelThread"===i?(r=a.thread,ke.pthreads[r].worker.postMessage({cmd:"cancel"})):"loaded"===i?(e.loaded=!0,t&&t(e),e.runPthread&&(e.runPthread(),delete e.runPthread)):"print"===i?E("Thread "+a.threadId+": "+a.text):"printErr"===i?R("Thread "+a.threadId+": "+a.text):"alert"===i?alert("Thread "+a.threadId+": "+a.text):"setimmediate"===a.target?e.postMessage(a):"onAbort"===i?h.onAbort&&h.onAbort(a.arg):R("worker sent an unknown command "+i),ke.currentProxiedOperationCallerThread=void 0},e.onerror=e=>{throw R("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:h.mainScriptUrlOrBlob||s,wasmMemory:M,wasmModule:D})},allocateUnusedWorker:function(){var e=T("tfjs-backend-wasm-threaded-simd.worker.js");ke.unusedWorkers.push(new Worker(e))},getNewWorker:function(){return 0==ke.unusedWorkers.length&&(ke.allocateUnusedWorker(),ke.loadWasmModuleToWorker(ke.unusedWorkers[0])),ke.unusedWorkers.pop()}};function ye(e){if(C)return Te(1,0,e);try{ve(e)}catch(e){!function(e){if(e instanceof dt||"unwind"==e)return B;w(1,e)}(e)}}h.establishStackSpace=function(){var e=Je(),t=u()[e+44>>2],n=u()[e+48>>2];st(t,t-n),ut(t)};var we,Ie=[];function Se(e){var t=Ie[e];return t||(e>=Ie.length&&(Ie.length=e+1),Ie[e]=t=J.get(e)),t}function _e(e,t){var n,r;if(0===e)n=Date.now();else{if(1!==e&&4!==e)return r=28,u()[Qe()>>2]=r,-1;n=we()}return u()[t>>2]=n/1e3|0,u()[t+4>>2]=n%1e3*1e3*1e3|0,0}function Ce(e){var t=ke.getNewWorker();if(!t)return 6;ke.runningWorkers.push(t);var n=ke.pthreads[e.pthread_ptr]={worker:t,threadInfoStruct:e.pthread_ptr};t.pthread=n;var r={cmd:"run",start_routine:e.startRoutine,arg:e.arg,threadInfoStruct:e.pthread_ptr};return t.runPthread=()=>{r.time=performance.now(),t.postMessage(r,e.transferList)},t.loaded&&(t.runPthread(),delete t.runPthread),0}function Oe(){return 2147483648}function Te(e,t){var n=arguments.length-2,r=arguments;return ge((function(){for(var a=n,i=ct(8*a),s=i>>3,o=0;o{var e=r.hrtime();return 1e3*e[0]+e[1]/1e6}:C?()=>performance.now()-h.__performance_now_clock_drift:()=>performance.now();var $e=[];function Ae(e){try{return M.grow(e-G.byteLength+65535>>>16),Q(M.buffer),1}catch(e){}}var Ne={inEventHandler:0,removeAllEventListeners:function(){for(var e=Ne.eventHandlers.length-1;e>=0;--e)Ne._removeHandler(e);Ne.eventHandlers=[],Ne.deferredCalls=[]},registerRemoveEventListeners:function(){Ne.removeEventListenersRegistered||(re.push(Ne.removeAllEventListeners),Ne.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(e,t,n){function r(e,t){if(e.length!=t.length)return!1;for(var n in e)if(e[n]!=t[n])return!1;return!0}for(var a in Ne.deferredCalls){var i=Ne.deferredCalls[a];if(i.targetFunction==e&&r(i.argsList,n))return}Ne.deferredCalls.push({targetFunction:e,precedence:t,argsList:n}),Ne.deferredCalls.sort((function(e,t){return e.precedence>2]=n,u()[i+4>>2]=r,u()[i+8>>2]=a,at(e,637534208,t,r,i)}))},getTargetThreadForEventCallback:function(e){switch(e){case 1:return 0;case 2:return ke.currentProxiedOperationCallerThread;default:return e}},getNodeNameForTarget:function(e){return e?e==window?"#window":e==screen?"#screen":e&&e.nodeName?e.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Ee(e,t,n,r){ge((function(){var a,i,s,o=ct(12),c=0;t&&(i=function(e){for(var t=0,n=0;n=55296&&r<=57343&&(r=65536+((1023&r)<<10)|1023&e.charCodeAt(++n)),r<=127?++t:t+=r<=2047?2:r<=65535?3:4}return t}(a=t)+1,s=Ye(i),Z(a,s,i),c=s),u()[o>>2]=c,u()[o+4>>2]=n,u()[o+8>>2]=r,at(e,657457152,0,c,o)}))}var Re=[0,"undefined"!=typeof document?document:0,"undefined"!=typeof window?window:0];function Fe(e){var t;return e=(t=e)>2?Y(t):t,Re[e]||("undefined"!=typeof document?document.querySelector(e):void 0)}function Me(e){return Fe(e)}function De(e,t,n){var r=Me(e);if(!r)return-4;if(r.canvasSharedPtr&&(u()[r.canvasSharedPtr>>2]=t,u()[r.canvasSharedPtr+4>>2]=n),!r.offscreenCanvas&&r.controlTransferredOffscreen)return r.canvasSharedPtr?(function(e,t,n,r){Ee(e,t=t?Y(t):"",n,r)}(u()[r.canvasSharedPtr+8>>2],e,t,n),1):-4;r.offscreenCanvas&&(r=r.offscreenCanvas);var a=!1;if(r.GLctxObject&&r.GLctxObject.GLctx){var i=r.GLctxObject.GLctx.getParameter(2978);a=0===i[0]&&0===i[1]&&i[2]===r.width&&i[3]===r.height}return r.width=t,r.height=n,a&&r.GLctxObject.GLctx.viewport(0,0,t,n),0}function Pe(e,t,n){return C?Te(2,1,e,t,n):De(e,t,n)}var Be,je={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},queries:[],stringCache:{},unpackAlignment:4,recordError:function(e){je.lastError||(je.lastError=e)},getNewId:function(e){for(var t=je.counter++,n=e.length;n>2]:-1;a+=Y(u()[n+4*i>>2],s<0?void 0:s)}return a},createContext:function(e,t){e.getContextSafariWebGL2Fixed||(e.getContextSafariWebGL2Fixed=e.getContext,e.getContext=function(t,n){var r=e.getContextSafariWebGL2Fixed(t,n);return"webgl"==t==r instanceof WebGLRenderingContext?r:null});var n=e.getContext("webgl",t);return n?je.registerContext(n,t):0},registerContext:function(e,t){var n=Ye(8);u()[n+4>>2]=Je();var r={handle:n,attributes:t,version:t.majorVersion,GLctx:e};return e.canvas&&(e.canvas.GLctxObject=r),je.contexts[n]=r,("undefined"==typeof t.enableExtensionsByDefault||t.enableExtensionsByDefault)&&je.initExtensions(r),n},makeContextCurrent:function(e){return je.currentContext=je.contexts[e],h.ctx=Be=je.currentContext&&je.currentContext.GLctx,!(e&&!Be)},getContext:function(e){return je.contexts[e]},deleteContext:function(e){je.currentContext===je.contexts[e]&&(je.currentContext=null),"object"==typeof Ne&&Ne.removeAllHandlersOnTarget(je.contexts[e].GLctx.canvas),je.contexts[e]&&je.contexts[e].GLctx.canvas&&(je.contexts[e].GLctx.canvas.GLctxObject=void 0),Ze(je.contexts[e].handle),je.contexts[e]=null},initExtensions:function(e){if(e||(e=je.currentContext),!e.initExtensionsDone){e.initExtensionsDone=!0;var t,n=e.GLctx;!function(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,n){t.vertexAttribDivisorANGLE(e,n)},e.drawArraysInstanced=function(e,n,r,a){t.drawArraysInstancedANGLE(e,n,r,a)},e.drawElementsInstanced=function(e,n,r,a,i){t.drawElementsInstancedANGLE(e,n,r,a,i)})}(n),function(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}(n),function(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,n){t.drawBuffersWEBGL(e,n)})}(n),n.disjointTimerQueryExt=n.getExtension("EXT_disjoint_timer_query"),(t=n).multiDrawWebgl=t.getExtension("WEBGL_multi_draw"),(n.getSupportedExtensions()||[]).forEach((function(e){e.includes("lose_context")||e.includes("debug")||n.getExtension(e)}))}}},Le=["default","low-power","high-performance"],ze={mappings:{},buffers:[null,[],[]],printChar:function(e,t){var n=ze.buffers[e];0===t||10===t?((1===e?E:R)(X(n,0)),n.length=0):n.push(t)},varargs:void 0,get:function(){return ze.varargs+=4,u()[ze.varargs-4>>2]},getStr:function(e){return Y(e)},get64:function(e,t){return e}};function We(e){return C?Te(3,1,e):0}function Ge(e,t,n,r,a){if(C)return Te(4,1,e,t,n,r,a)}function Ue(e,t,n,r){if(C)return Te(5,1,e,t,n,r);for(var a=0,i=0;i>2],c=u()[t+4>>2];t+=8;for(var l=0;l>2]=a,0}ke.init();var Ve,He,qe,Ke=[null,ye,Pe,We,Ge,Ue],Xe={__clock_gettime:function(e,t){return _e(e,t)},__emscripten_init_main_thread_js:function(e){tt(e,!S,1,!I),ke.threadInit()},__emscripten_thread_cleanup:function(e){C?postMessage({cmd:"cleanupThread",thread:e}):xe(e)},__pthread_create_js:function(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return R("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(C&&0===a.length)return nt(687865856,e,t,n,r);var i={startRoutine:n,pthread_ptr:e,arg:r,transferList:a};return C?(i.cmd="spawnThread",postMessage(i,a),0):Ce(i)},_emscripten_default_pthread_stack_size:function(){return 2097152},_emscripten_notify_thread_queue:function(e,t){if(e==t)postMessage({cmd:"processQueuedMainThreadWork"});else if(C)postMessage({targetThread:e,cmd:"processThreadQueue"});else{var n=ke.pthreads[e],r=n&&n.worker;if(!r)return;r.postMessage({cmd:"processThreadQueue"})}return 1},abort:function(){de("")},emscripten_check_blocking_allowed:function(){_||S||F("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")},emscripten_get_heap_max:Oe,emscripten_get_now:we,emscripten_memcpy_big:function(e,t,n){o().copyWithin(e,t,t+n)},emscripten_num_logical_cores:function(){return _?n(123).cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){$e.length=t;for(var r=n>>3,a=0;a>>=0)<=t)return!1;var n,r,a=2147483648;if(e>a)return!1;for(var i=1;i<=4;i*=2){var s=t*(1+.2/i);if(s=Math.min(s,e+100663296),Ae(Math.min(a,((n=Math.max(e,s))%(r=65536)>0&&(n+=r-n%r),n))))return!0}return!1},emscripten_set_canvas_element_size:function(e,t,n){return Me(e)?De(e,t,n):Pe(e,t,n)},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},emscripten_webgl_create_context:function(e,t){return n=e,r=t>>2,a=u()[r+6],i={alpha:!!u()[r+0],depth:!!u()[r+1],stencil:!!u()[r+2],antialias:!!u()[r+3],premultipliedAlpha:!!u()[r+4],preserveDrawingBuffer:!!u()[r+5],powerPreference:Le[a],failIfMajorPerformanceCaveat:!!u()[r+7],majorVersion:u()[r+8],minorVersion:u()[r+9],enableExtensionsByDefault:u()[r+10],explicitSwapControl:u()[r+11],proxyContextToMainThread:u()[r+12],renderViaOffscreenBackBuffer:u()[r+13]},(s=Me(n))?i.explicitSwapControl?0:je.createContext(s,i):0;var n,r,a,i,s},exit:ve,fd_close:We,fd_seek:Ge,fd_write:Ue,memory:M||h.wasmMemory,setTempRet0:function(e){}},Ye=(function(){var e={env:Xe,wasi_snapshot_preview1:Xe};function t(e,t){var n,r,a=e.exports;if(h.asm=a,n=h.asm.emscripten_tls_init,ke.tlsInitFunctions.push(n),J=h.asm.__indirect_function_table,r=h.asm.__wasm_call_ctors,ne.unshift(r),D=t,!C){var i=ke.unusedWorkers.length;ke.unusedWorkers.forEach((function(e){ke.loadWasmModuleToWorker(e,(function(){--i||function(e){if(ue--,h.monitorRunDependencies&&h.monitorRunDependencies(ue),0==ue&&(null!==ce&&(clearInterval(ce),ce=null),le)){var t=le;le=null,t()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!N&&(I||S)){if("function"==typeof fetch&&!he(oe))return fetch(oe,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+oe+"'";return e.arrayBuffer()})).catch((function(){return fe(oe)}));if(m)return new Promise((function(e,t){m(oe,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return fe(oe)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){R("failed to asynchronously prepare wasm: "+e),de(e)}))}if(C||(ue++,h.monitorRunDependencies&&h.monitorRunDependencies(ue)),h.instantiateWasm)try{return h.instantiateWasm(e,t)}catch(e){return R("Module.instantiateWasm callback failed with error: "+e),!1}(N||"function"!=typeof WebAssembly.instantiateStreaming||pe(oe)||he(oe)||"function"!=typeof fetch?r(n):fetch(oe,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return R("wasm streaming compile failed: "+e),R("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(d)}(),h.___wasm_call_ctors=function(){return(h.___wasm_call_ctors=h.asm.__wasm_call_ctors).apply(null,arguments)},h._init=function(){return(h._init=h.asm.init).apply(null,arguments)},h._init_with_threads_count=function(){return(h._init_with_threads_count=h.asm.init_with_threads_count).apply(null,arguments)},h._get_threads_count=function(){return(h._get_threads_count=h.asm.get_threads_count).apply(null,arguments)},h._register_tensor=function(){return(h._register_tensor=h.asm.register_tensor).apply(null,arguments)},h._dispose_data=function(){return(h._dispose_data=h.asm.dispose_data).apply(null,arguments)},h._dispose=function(){return(h._dispose=h.asm.dispose).apply(null,arguments)},h._Abs=function(){return(h._Abs=h.asm.Abs).apply(null,arguments)},h._Add=function(){return(h._Add=h.asm.Add).apply(null,arguments)},h._AddN=function(){return(h._AddN=h.asm.AddN).apply(null,arguments)},h._All=function(){return(h._All=h.asm.All).apply(null,arguments)},h._Any=function(){return(h._Any=h.asm.Any).apply(null,arguments)},h._ArgMax=function(){return(h._ArgMax=h.asm.ArgMax).apply(null,arguments)},h._AvgPool=function(){return(h._AvgPool=h.asm.AvgPool).apply(null,arguments)},h._BatchMatMul=function(){return(h._BatchMatMul=h.asm.BatchMatMul).apply(null,arguments)},h._Ceil=function(){return(h._Ceil=h.asm.Ceil).apply(null,arguments)},h._ClipByValue=function(){return(h._ClipByValue=h.asm.ClipByValue).apply(null,arguments)},h._Conv2D=function(){return(h._Conv2D=h.asm.Conv2D).apply(null,arguments)},h._Conv2DBackpropInput=function(){return(h._Conv2DBackpropInput=h.asm.Conv2DBackpropInput).apply(null,arguments)},h._Cos=function(){return(h._Cos=h.asm.Cos).apply(null,arguments)},h._Cosh=function(){return(h._Cosh=h.asm.Cosh).apply(null,arguments)},h._CropAndResize=function(){return(h._CropAndResize=h.asm.CropAndResize).apply(null,arguments)},h._Cumprod=function(){return(h._Cumprod=h.asm.Cumprod).apply(null,arguments)},h._Cumsum=function(){return(h._Cumsum=h.asm.Cumsum).apply(null,arguments)},h._DepthToSpace=function(){return(h._DepthToSpace=h.asm.DepthToSpace).apply(null,arguments)},h._DepthwiseConv2dNative=function(){return(h._DepthwiseConv2dNative=h.asm.DepthwiseConv2dNative).apply(null,arguments)},h._Elu=function(){return(h._Elu=h.asm.Elu).apply(null,arguments)},h._Equal=function(){return(h._Equal=h.asm.Equal).apply(null,arguments)},h._Exp=function(){return(h._Exp=h.asm.Exp).apply(null,arguments)},h._FlipLeftRight=function(){return(h._FlipLeftRight=h.asm.FlipLeftRight).apply(null,arguments)},h._Floor=function(){return(h._Floor=h.asm.Floor).apply(null,arguments)},h._FloorDiv=function(){return(h._FloorDiv=h.asm.FloorDiv).apply(null,arguments)},h._FusedBatchNorm=function(){return(h._FusedBatchNorm=h.asm.FusedBatchNorm).apply(null,arguments)},h._FusedConv2D=function(){return(h._FusedConv2D=h.asm.FusedConv2D).apply(null,arguments)},h._FusedDepthwiseConv2D=function(){return(h._FusedDepthwiseConv2D=h.asm.FusedDepthwiseConv2D).apply(null,arguments)},h._Gather=function(){return(h._Gather=h.asm.Gather).apply(null,arguments)},h._GatherNd=function(){return(h._GatherNd=h.asm.GatherNd).apply(null,arguments)},h._Greater=function(){return(h._Greater=h.asm.Greater).apply(null,arguments)},h._GreaterEqual=function(){return(h._GreaterEqual=h.asm.GreaterEqual).apply(null,arguments)},h._LeakyRelu=function(){return(h._LeakyRelu=h.asm.LeakyRelu).apply(null,arguments)},h._Less=function(){return(h._Less=h.asm.Less).apply(null,arguments)},h._LessEqual=function(){return(h._LessEqual=h.asm.LessEqual).apply(null,arguments)},h._Log=function(){return(h._Log=h.asm.Log).apply(null,arguments)},h._LogicalAnd=function(){return(h._LogicalAnd=h.asm.LogicalAnd).apply(null,arguments)},h._Max=function(){return(h._Max=h.asm.Max).apply(null,arguments)},h._MaxPool=function(){return(h._MaxPool=h.asm.MaxPool).apply(null,arguments)},h._Maximum=function(){return(h._Maximum=h.asm.Maximum).apply(null,arguments)},h._Mean=function(){return(h._Mean=h.asm.Mean).apply(null,arguments)},h._Min=function(){return(h._Min=h.asm.Min).apply(null,arguments)},h._Minimum=function(){return(h._Minimum=h.asm.Minimum).apply(null,arguments)},h._MirrorPad=function(){return(h._MirrorPad=h.asm.MirrorPad).apply(null,arguments)},h._Multiply=function(){return(h._Multiply=h.asm.Multiply).apply(null,arguments)},h._Neg=function(){return(h._Neg=h.asm.Neg).apply(null,arguments)},h._NonMaxSuppressionV3=function(){return(h._NonMaxSuppressionV3=h.asm.NonMaxSuppressionV3).apply(null,arguments)},h._NonMaxSuppressionV4=function(){return(h._NonMaxSuppressionV4=h.asm.NonMaxSuppressionV4).apply(null,arguments)},h._NonMaxSuppressionV5=function(){return(h._NonMaxSuppressionV5=h.asm.NonMaxSuppressionV5).apply(null,arguments)},h._NotEqual=function(){return(h._NotEqual=h.asm.NotEqual).apply(null,arguments)},h._OneHot=function(){return(h._OneHot=h.asm.OneHot).apply(null,arguments)},h._PadV2=function(){return(h._PadV2=h.asm.PadV2).apply(null,arguments)},h._Pow=function(){return(h._Pow=h.asm.Pow).apply(null,arguments)},h._Prelu=function(){return(h._Prelu=h.asm.Prelu).apply(null,arguments)},h._Prod=function(){return(h._Prod=h.asm.Prod).apply(null,arguments)},h._RealDiv=function(){return(h._RealDiv=h.asm.RealDiv).apply(null,arguments)},h._Relu=function(){return(h._Relu=h.asm.Relu).apply(null,arguments)},h._Relu6=function(){return(h._Relu6=h.asm.Relu6).apply(null,arguments)},h._ResizeBilinear=function(){return(h._ResizeBilinear=h.asm.ResizeBilinear).apply(null,arguments)},h._Reverse=function(){return(h._Reverse=h.asm.Reverse).apply(null,arguments)},h._RotateWithOffset=function(){return(h._RotateWithOffset=h.asm.RotateWithOffset).apply(null,arguments)},h._Round=function(){return(h._Round=h.asm.Round).apply(null,arguments)},h._Rsqrt=function(){return(h._Rsqrt=h.asm.Rsqrt).apply(null,arguments)},h._ScatterNd=function(){return(h._ScatterNd=h.asm.ScatterNd).apply(null,arguments)},h._SelectV2=function(){return(h._SelectV2=h.asm.SelectV2).apply(null,arguments)},h._Sigmoid=function(){return(h._Sigmoid=h.asm.Sigmoid).apply(null,arguments)},h._Sin=function(){return(h._Sin=h.asm.Sin).apply(null,arguments)},h._Softmax=function(){return(h._Softmax=h.asm.Softmax).apply(null,arguments)},h._SparseFillEmptyRows=function(){return(h._SparseFillEmptyRows=h.asm.SparseFillEmptyRows).apply(null,arguments)},h._SparseReshape=function(){return(h._SparseReshape=h.asm.SparseReshape).apply(null,arguments)},h._SparseSegmentReduction=function(){return(h._SparseSegmentReduction=h.asm.SparseSegmentReduction).apply(null,arguments)},h._Sqrt=function(){return(h._Sqrt=h.asm.Sqrt).apply(null,arguments)},h._Square=function(){return(h._Square=h.asm.Square).apply(null,arguments)},h._SquaredDifference=function(){return(h._SquaredDifference=h.asm.SquaredDifference).apply(null,arguments)},h._Step=function(){return(h._Step=h.asm.Step).apply(null,arguments)},h._StridedSlice=function(){return(h._StridedSlice=h.asm.StridedSlice).apply(null,arguments)},h._Sub=function(){return(h._Sub=h.asm.Sub).apply(null,arguments)},h._Sum=function(){return(h._Sum=h.asm.Sum).apply(null,arguments)},h._Tan=function(){return(h._Tan=h.asm.Tan).apply(null,arguments)},h._Tanh=function(){return(h._Tanh=h.asm.Tanh).apply(null,arguments)},h._Tile=function(){return(h._Tile=h.asm.Tile).apply(null,arguments)},h._TopK=function(){return(h._TopK=h.asm.TopK).apply(null,arguments)},h._Transform=function(){return(h._Transform=h.asm.Transform).apply(null,arguments)},h._Transpose=function(){return(h._Transpose=h.asm.Transpose).apply(null,arguments)},h.__FusedMatMul=function(){return(h.__FusedMatMul=h.asm._FusedMatMul).apply(null,arguments)},h._malloc=function(){return(Ye=h._malloc=h.asm.malloc).apply(null,arguments)}),Ze=h._free=function(){return(Ze=h._free=h.asm.free).apply(null,arguments)},Qe=(h._emscripten_tls_init=function(){return(h._emscripten_tls_init=h.asm.emscripten_tls_init).apply(null,arguments)},h.___errno_location=function(){return(Qe=h.___errno_location=h.asm.__errno_location).apply(null,arguments)}),Je=h._pthread_self=function(){return(Je=h._pthread_self=h.asm.pthread_self).apply(null,arguments)},et=h._emscripten_main_thread_process_queued_calls=function(){return(et=h._emscripten_main_thread_process_queued_calls=h.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},tt=(h.__emscripten_thread_crashed=function(){return(h.__emscripten_thread_crashed=h.asm._emscripten_thread_crashed).apply(null,arguments)},h.__emscripten_thread_init=function(){return(tt=h.__emscripten_thread_init=h.asm._emscripten_thread_init).apply(null,arguments)}),nt=(h._emscripten_current_thread_process_queued_calls=function(){return(h._emscripten_current_thread_process_queued_calls=h.asm.emscripten_current_thread_process_queued_calls).apply(null,arguments)},h._emscripten_main_browser_thread_id=function(){return(h._emscripten_main_browser_thread_id=h.asm.emscripten_main_browser_thread_id).apply(null,arguments)},h._emscripten_sync_run_in_main_thread_2=function(){return(h._emscripten_sync_run_in_main_thread_2=h.asm.emscripten_sync_run_in_main_thread_2).apply(null,arguments)},h._emscripten_sync_run_in_main_thread_4=function(){return(nt=h._emscripten_sync_run_in_main_thread_4=h.asm.emscripten_sync_run_in_main_thread_4).apply(null,arguments)}),rt=h._emscripten_run_in_main_runtime_thread_js=function(){return(rt=h._emscripten_run_in_main_runtime_thread_js=h.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},at=h._emscripten_dispatch_to_thread_=function(){return(at=h._emscripten_dispatch_to_thread_=h.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},it=h.__emscripten_thread_free_data=function(){return(it=h.__emscripten_thread_free_data=h.asm._emscripten_thread_free_data).apply(null,arguments)},st=(h.__emscripten_thread_exit=function(){return(h.__emscripten_thread_exit=h.asm._emscripten_thread_exit).apply(null,arguments)},h._memalign=function(){return(h._memalign=h.asm.memalign).apply(null,arguments)},h._emscripten_stack_set_limits=function(){return(st=h._emscripten_stack_set_limits=h.asm.emscripten_stack_set_limits).apply(null,arguments)}),ot=h.stackSave=function(){return(ot=h.stackSave=h.asm.stackSave).apply(null,arguments)},ut=h.stackRestore=function(){return(ut=h.stackRestore=h.asm.stackRestore).apply(null,arguments)},ct=h.stackAlloc=function(){return(ct=h.stackAlloc=h.asm.stackAlloc).apply(null,arguments)},lt=(h.dynCall_iijjiiii=function(){return(h.dynCall_iijjiiii=h.asm.dynCall_iijjiiii).apply(null,arguments)},h.dynCall_jiji=function(){return(h.dynCall_jiji=h.asm.dynCall_jiji).apply(null,arguments)},h.__emscripten_allow_main_runtime_queued_calls=21464);function dt(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function pt(e){if(e=e||y,!(ue>0)){if(C)return l(h),se(),void postMessage({cmd:"loaded"});!function(){if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;)e=h.preRun.shift(),te.unshift(e);var e;be(te)}(),ue>0||(h.setStatus?(h.setStatus("Running..."),setTimeout((function(){setTimeout((function(){h.setStatus("")}),1),t()}),1)):t())}function t(){Ve||(Ve=!0,h.calledRun=!0,j||(se(),l(h),h.onRuntimeInitialized&&h.onRuntimeInitialized(),function(){if(!C){if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;)e=h.postRun.shift(),ae.unshift(e);var e;be(ae)}}()))}}if(h.cwrap=function(e,t,n,r){var a=(n=n||[]).every((function(e){return"number"===e}));return"string"!==t&&a&&!r?L(e):function(){return z(e,t,n,arguments)}},h.keepRuntimeAlive=ie,h.PThread=ke,h.PThread=ke,h.wasmMemory=M,h.ExitStatus=dt,le=function e(){Ve||pt(),Ve||(le=e)},h.run=pt,h.preInit)for("function"==typeof h.preInit&&(h.preInit=[h.preInit]);h.preInit.length>0;)h.preInit.pop()();if(pt(),p&&(He={uncaughtException:r.listeners("uncaughtException").filter((function(e){return!p.uncaughtException.indexOf(e)>-1})),unhandledRejection:r.listeners("unhandledRejection").filter((function(e){return!p.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof WasmBackendModule)qe=WasmBackendModule;else{if("undefined"==typeof e)throw new Error("Could not find wasm module in post.js");qe=e}if(He){var ht=qe._dispose;qe._dispose=function(){ht(),He.uncaughtException.forEach((function(e){r.removeListener("uncaughtException",e)})),He.unhandledRejection.forEach((function(e){r.removeListener("unhandledRejection",e)}))}}return e.ready});e.exports=o}).call(this,"/index.js",n(38),"/",n(37))},,function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return a})); +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const r="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof e?e:e=>e();function a(){return new Promise((e=>r((()=>e()))))}}).call(this,n(119).setImmediate)},function(e,t){},function(e,t,n){"use strict";var r=n(0); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a={},i={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function s(e,t){if(!(e in a)||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("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e):t;if(n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete a[e]}),!1),1===e)return n.getContext("webgl",i)||n.getContext("experimental-webgl",i);return n.getContext("webgl2",i)} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;a[e]=n}const n=a[e];return null==n||n.isContextLost()?(delete a[e],s(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),a[e])}var o,u,c;function l(e,t){return[t,e]}function d(e){const t=r.util.sizeFromShape(e),n=Math.ceil(t/4);return r.util.sizeToSquarishShape(n)}function p(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function h(e,t){const n=e;let a,i,s,o,u,c,l,d,p,h;return 2===Object(r.env)().getNumber("WEBGL_VERSION")?(a=n.R32F,i=n.R16F,s=n.RGBA16F,o=n.RGBA32F,u=n.RED,l=4,d=1,p=n.HALF_FLOAT,h=n.FLOAT,c=n.RGBA8):(a=e.RGBA,i=e.RGBA,s=e.RGBA,o=n.RGBA,u=e.RGBA,l=4,d=4,p=null!=t?t.HALF_FLOAT_OES:null,h=e.FLOAT,c=e.RGBA),{internalFormatFloat:a,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:u,downloadTextureFormat:c,downloadUnpackNumChannels:l,defaultNumChannels:d,textureTypeHalfFloat:p,textureTypeFloat:h}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f(e,t){const n=t();return Object(r.env)().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(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}`}}(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(o||(o={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(u||(u={})),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"}(c||(c={}));function m(e){return!!(Object(r.env)().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}const g=/ERROR: [0-9]+:([0-9]+):/g;function x(e,t){const n=g.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const a=+n[1],i=e.split("\n"),s=i.length.toString().length+2,o=i.map(((e,t)=>r.util.rightPad((t+1).toString(),s)+e));let u=0;for(let e=0;ee.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function k(e,t,n,r,a,i,s){const o=e.getAttribLocation(t,n);return-1!==o&&(f(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),f(e,(()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,i,s))),f(e,(()=>e.enableVertexAttribArray(o))),!0)}function y(e,t,n,r){f(e,(()=>function(e,t,n){C(e,n),f(e,(()=>e.activeTexture(e.TEXTURE0+n))),f(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),f(e,(()=>e.uniform1i(n,r)))}function w(e,t,n){f(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),f(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function I(e,t){f(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),f(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function S(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(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}`}}(e,t))}function _(e,t,n){const r=f(e,(()=>t()));if(null==r)throw new Error(n);return r}function C(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(rn){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}function O(e,t=2){return r.util.sizeFromShape(e.slice(0,e.length-t))}function T(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 $(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[O(e),...T(e)]),t}function A(e){return e%2==0}function N(e,t){if(e=e.slice(-2),t=t.slice(-2),r.util.arraysEqual(e,t))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.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(A(n)&&A(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&A(e[0])&&A(t[0])}let E,R;function F(e,t){return null!=e.getExtension(t)}function M(e){try{if(null!=s(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function D(e){if(0===e)return!1;const t=s(e);if(1!==e){if(F(t,"EXT_color_buffer_float"))return P(t);const e="EXT_color_buffer_half_float";if(F(t,e)){const n=t.getExtension(e);return function(e,t){const n=h(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);const a=1,i=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,a,i,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),o}(t,n)}return!1}if(!F(t,"OES_texture_float"))return!1;if(!F(t,"WEBGL_color_buffer_float"))return!1;return P(t)}function P(e){const t=h(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 r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),a}function B(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&r.util.assert("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const j=Object(r.env)(); +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function L(){let e,t,n,a,i,s,o,u,c,l;return 2===Object(r.env)().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",a="in",i="texture",s="outputColor",o="out vec4 outputColor;",u="\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 ",c="",l="\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",a="varying",i="texture2D",s="gl_FragColor",o="",u="\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 ",c="\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 ",l="\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:a,texture2D:i,output:s,defineOutput:o,defineSpecialNaN:u,defineSpecialInf:c,defineRound:l}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function z(e,t,n="index"){const a=r.util.computeStrides(t);return a.map(((t,r)=>`${`int ${e[r]} = ${n} / ${t}`}; ${r===a.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${t}`:`index -= ${e[r]} * ${t}`};`)).join("")}function W(e,t,n="index"){const a=r.util.computeStrides(t);return a.map(((t,r)=>`${`int ${e[r]} = ${n} / outShapeStrides[${r}]`}; ${r===a.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * outShapeStrides[${r}]`:`index -= ${e[r]} * outShapeStrides[${r}]`};`)).join("")}function G(e,t,n="index"){const r=function(e,t){const n=e.length,r=e.map((e=>`${t}[${e}]`)),a=new Array(n-1);a[n-2]=r[n-1];for(let e=n-3;e>=0;--e)a[e]=`(${a[e+1]} * ${r[e+1]})`;return a}(e.map(((e,t)=>t)),t);return r.map(((t,a)=>`${`int ${e[a]} = ${n} / ${r[a]}`}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${r[a]}`:`index -= ${e[a]} * ${r[a]}`};`)).join("")}function U(e){const t=r.util.computeStrides(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`}j.registerFlag("HAS_WEBGL",(()=>j.getNumber("WEBGL_VERSION")>0)),j.registerFlag("WEBGL_VERSION",(()=>M(2)?2:M(1)?1:0)),j.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),j.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===j.get("WEBGL_VERSION"))),j.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),j.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),j.registerFlag("WEBGL_PACK",(()=>j.getBool("HAS_WEBGL"))),j.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_CLIP",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_PACK_REDUCE",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_LAZILY_UNPACK",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_CONV_IM2COL",(()=>j.getBool("WEBGL_PACK"))),j.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==E){const t=s(e);E=t.getParameter(t.MAX_TEXTURE_SIZE)}return E}(j.getNumber("WEBGL_VERSION")))),j.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==R){const t=s(e);R=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,R)}(j.getNumber("WEBGL_VERSION")))),j.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=j.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=s(e);return t=F(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:F(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),j.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>j.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!r.device_util.isMobile())),j.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=s(e);if(1===e){if(!F(t,"OES_texture_float"))return!1}else if(!F(t,"EXT_color_buffer_float"))return!1;return P(t)}(j.getNumber("WEBGL_VERSION")))),j.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!j.getBool("WEBGL_FORCE_F16_TEXTURES")&&j.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),j.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>D(j.getNumber("WEBGL_VERSION")))),j.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=j.getNumber("WEBGL_VERSION"))&&null!=s(e).fenceSync;var e})),j.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>j.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),j.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(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}.`)})),j.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>r.device_util.isMobile()?1:-1),(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}.`)})),j.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),j.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),j.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),j.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128));const V="\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:H}=r.backend_util; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function q(e,t,n){const a=[];if(e.forEach((e=>{const t=r.util.sizeFromShape(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?a.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(a.push(`uniform sampler2D ${e.name};`),a.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=ae(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:a.push(`uniform int ${e.name}Shape;`);break;case 2:a.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:a.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:a.push(`uniform ivec4 ${e.name}Shape;`)}a.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:a.push("uniform int outShape;");break;case 2:a.push("uniform ivec2 outShape;"),a.push("uniform int outShapeStrides;");break;case 3:a.push("uniform ivec3 outShape;"),a.push("uniform ivec2 outShapeStrides;");break;case 4:a.push("uniform ivec4 outShape;"),a.push("uniform ivec3 outShapeStrides;")}a.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{a.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const i=a.join("\n"),s=e.map((e=>function(e,t,n=!1,a){let i="";i+=n?X(e,a):K(e,a);const s=e.shapeInfo.logicalShape,o=t.logicalShape;s.length<=o.length&&(i+=n?function(e,t){const n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),i="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,u=H(e.shapeInfo.logicalShape,t.logicalShape),c=re(o),l=o-s;let d;const p=["x","y","z","w","u","v"];d=0===s?"":o<2&&u.length>=1?"coords = 0;":u.map((e=>`coords.${p[e+l]} = 0;`)).join("\n");let h="";h=o<2&&s>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${p[t+l]}`)).join(", ");let f="return outputValue;";const m=1===r.util.sizeFromShape(e.shapeInfo.logicalShape),b=1===r.util.sizeFromShape(t.logicalShape);if(1!==s||m||b){if(m&&!b)f=1===o?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){const e=s-2,t=s-1;u.indexOf(e)>-1&&u.indexOf(t)>-1?f="return vec4(outputValue.x);":u.indexOf(e)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(t)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${i}() {\n ${c} coords = getOutputCoords();\n ${d}\n vec4 outputValue = get${a}(${h});\n ${f}\n }\n `}(e,t):function(e,t){const n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),i="get"+a+"AtOutCoords",s=t.texShape,o=e.shapeInfo.texShape,u=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&u===c&&null==e.shapeInfo.flatOffset&&r.util.arraysEqual(o,s))return`\n float ${i}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=re(c),d=H(e.shapeInfo.logicalShape,t.logicalShape),p=c-u;let h;const f=["x","y","z","w","u","v"];h=0===u?"":c<2&&d.length>=1?"coords = 0;":d.map((e=>`coords.${f[e+p]} = 0;`)).join("\n");let m="";m=c<2&&u>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${f[t+p]}`)).join(", ");return`\n float ${i}() {\n ${l} coords = getOutputCoords();\n ${h}\n return get${a}(${m});\n }\n `}(e,t));return i}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),o=t.texShape,u=L(),c=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(u);let l,d,p=function(e){return`${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 ${Y}\n ${Z}\n ${Q}\n `}(u);t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return ee();case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===r[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 * ${r[1]}.0);\n }\n `;if(1===r[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 * ${r[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(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(r.util.arraysEqual(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(${a[0]}, ${a[1]}));\n }\n `;const i=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(${a[0]}, ${a[1]}));\n\n int index = resTexRC.x * ${a[1]} + resTexRC.y;\n int r = 2 * (index / ${i});\n int c = imod(index, ${i}) * 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 r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),i=a*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${i};\n index -= b * ${i};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 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 r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),i=a*Math.ceil(e[e.length-2]/2);let s=i,o="",u="b, r, c";for(let t=2;t1&&!r.util.arraysEqual(t,n)&&a.lengthe[t])).join(", ")} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function oe(e,t,n,a){const i=n.map(((e,n)=>{const r={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&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),s=i.map((e=>e.shapeInfo)),o={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},u=q(i,o,t),c=function(e,t){const n=_(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(f(e,(()=>e.shaderSource(n,t))),f(e,(()=>e.compileShader(n))),Object(r.env)().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw x(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,u),l=e.createProgram(c);return Object(r.env)().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:c,source:u,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:c,source:u,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},ue(e,t,l))}function ue(e,t,n){const a={},i={},s={},o=[];let u,c,l,d=null,p=null;p=e.getUniformLocation(n,"NAN",!1),1===Object(r.env)().getNumber("WEBGL_VERSION")&&(d=e.getUniformLocation(n,"INFINITY",!1));const h=!1;for(let r=0;r{o[r]=e.getUniformLocation(n,t.name,h)})),{uniformLocations:a,customUniformLocations:o,infLoc:d,nanLoc:p,inShapesLocations:i,inTexShapesLocations:s,outShapeLocation:u,outShapeStridesLocation:l,outTexShapeLocation:c}}function ce(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 a=e.logicalShape,i=t[n],s=i.shape;if(!r.util.arraysEqual(a,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${a} and ${s} must match`);if(e.isUniform&&i.isUniform)return;const o=e.texShape,u=i.isUniform?null:i.texData.texShape;if(!r.util.arraysEqual(o,u))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${u} must match`)}))}function le(e){return Object(r.env)().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class de{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=o.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=L();this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?W(["r","c","d"],e):z(["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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pe{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=o.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=L();this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?W(["r","c","d"],e):z(["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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class he{constructor(e){this.variableNames=["A"],this.outTexUsage=u.DOWNLOAD;const t=L();this.outputShape=e,this.userCode=`\n ${V}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fe{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=u.DOWNLOAD;const t=L();this.outputShape=e,this.userCode=`\n ${V}\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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class me{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=L();this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":U(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int 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 vec4 values = ${n.texture2D}(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n ${n.output} = vec4(${r}, 0., 0., 0.);\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class be{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=L();this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length);let r="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let a=0;a<=1;a++){const i=2*t+a;r+=`\n localCoords = coords;\n if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${a};\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[${i}] = values[0];\n } else if (offset == 1) {\n result[${i}] = values[1];\n } else if (offset == 2) {\n result[${i}] = values[2];\n } else {\n result[${i}] = 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":U(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 ${r}\n\n ${n.output} = ${a};\n }\n `}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ge(e){const t=L();return function(e,t){const n=_(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(f(e,(()=>e.shaderSource(n,t))),f(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}(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 xe(e){return function(e,t){const n=_(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return f(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),f(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ve(e){return function(e,t){const n=_(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return f(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),f(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}function ke(e,t,n,a,i,s){!function(e,t){const n=Object(r.env)().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}].`)}(t,n);const o=function(e){return _(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),u=e.TEXTURE_2D;return f(e,(()=>e.bindTexture(u,o))),f(e,(()=>e.texParameteri(u,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),f(e,(()=>e.texParameteri(u,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),f(e,(()=>e.texParameteri(u,e.TEXTURE_MIN_FILTER,e.NEAREST))),f(e,(()=>e.texParameteri(u,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Object(r.env)().getNumber("WEBGL_VERSION")?f(e,(()=>e.texImage2D(u,0,a,t,n,0,i,s,null))):f(e,(()=>e.texStorage2D(u,1,a,t,n))),f(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:o,texShape:[n,t]}}function ye(e){return e.internalFormatFloat}function we(e){return e.internalFormatHalfFloat}function Ie(e){return e.downloadTextureFormat}function Se(e){return e.internalFormatPackedFloat}function _e(e){return e.internalFormatPackedHalfFloat}function Ce(e,t,n,r,a,i,s,o){const u=e,c=new Float32Array(function(e,t){const[n,r]=p(e,t);return n*r*4}(i,s));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Oe{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=Object(r.env)().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,function(e,t){a[e]=t}(t,e)):this.gl=s(t);let n="WEBGL_color_buffer_float";const i="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Object(r.env)().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=b(this.gl,e),F(this.gl,t))this.textureHalfFloatExtension=b(this.gl,t);else if(Object(r.env)().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),F(this.gl,i))this.colorBufferHalfFloatExtension=b(this.gl,i);else if(Object(r.env)().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",F(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!F(this.gl,i))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(i)}this.vertexBuffer=xe(this.gl),this.indexBuffer=ve(this.gl),this.framebuffer=function(e){return _(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=h(this.gl,this.textureHalfFloatExtension)}get debug(){return Object(r.env)().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;f(e,(()=>e.finish())),f(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),f(e,(()=>e.deleteFramebuffer(this.framebuffer))),f(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),f(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),f(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,i]=l(t,n);return ke(e,a,i,ye(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,i]=l(t,n);return ke(e,a,i,we(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,i]=l(t,n);return ke(e,a,i,Ie(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){f(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Object(r.env)().getNumber("WEBGL_VERSION")?f(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):f(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Object(r.env)().getNumber("WEBGL_VERSION")?f(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):f(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),f(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),function(e,t,n,a,i,s){let o,u,c;f(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),i instanceof Uint8Array?(o=new Uint8Array(n*a*4),u=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*a*4),u=e.FLOAT,c=s.internalFormatPackedFloat),o.set(i),2===Object(r.env)().getNumber("WEBGL_VERSION")?f(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA,u,o))):f(e,(()=>e.texImage2D(e.TEXTURE_2D,0,c,n,a,0,e.RGBA,u,o))),f(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,i]=p(t,n);return ke(e,a,i,_e(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,i]=p(t,n);return ke(e,a,i,Se(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(I(this.gl,this.framebuffer),this.outputTexture=null),f(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[a,i]=l(t,n),s=new Uint8Array(t*n*4);return f(e,(()=>e.readPixels(0,0,a,i,r.downloadTextureFormat,e.UNSIGNED_BYTE,s))),new Float32Array(s.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,a,i){return Ce(this.gl,e,0,0,0,a,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n,r){const a=e.createBuffer();f(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const i=16*t*n;return f(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ))),f(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),f(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Object(r.env)().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const r=new Float32Array(t*n*4);return f(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=ge(t));const n=function(e){return _(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);return f(t,(()=>t.attachShader(n,this.vertexShader))),f(t,(()=>t.attachShader(n,e))),function(e,t){if(f(e,(()=>e.linkProgram(t))),!Object(r.env)().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.")}(t,n),this.debug&&v(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=function(e,t,n){return f(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),k(e,t,"clipSpacePos",n,3,20,0)&&k(e,t,"uv",n,2,20,12)}(t,this.program,this.vertexBuffer)),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&f(this.gl,(()=>this.gl.deleteProgram(e)))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&v(this.gl,this.program),f(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return _(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),f(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(),y(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=p(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&v(this.gl,this.program),S(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),f(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),f(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=b(this.gl,2===Object(r.env)().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===Object(r.env)().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===Object(r.env)().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 r.util.repeatedTry((()=>this.disposed||this.isQueryAvailable(e,Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Object(r.env)().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(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!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(;te.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){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||r.util.repeatedTry((()=>(this.pollItems(),0===this.itemsToPoll.length)))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),w(this.gl,e,this.framebuffer),this.debug&&S(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(w(this.gl,this.outputTexture,this.framebuffer),this.debug&&S(this.gl)):I(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;w(r,e,this.framebuffer),this.debug&&S(r),this.outputTexture=e,f(r,(()=>r.viewport(0,0,t,n))),f(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),f(this.gl,(()=>this.gl.scissor(e,t,n,r)))}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.")}}var Te=n(41); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{addImpl:$e,bincountImpl:Ae,bincountReduceImpl:Ne,ceilImpl:Ee,concatImpl:Re,equalImpl:Fe,expImpl:Me,expm1Impl:De,floorImpl:Pe,gatherNdImpl:Be,gatherV2Impl:je,greaterImpl:Le,greaterEqualImpl:ze,lessImpl:We,lessEqualImpl:Ge,linSpaceImpl:Ue,logImpl:Ve,maxImpl:He,maximumImpl:qe,minimumImpl:Ke,multiplyImpl:Xe,negImpl:Ye,notEqualImpl:Ze,prodImpl:Qe,rangeImpl:Je,rsqrtImpl:et,sigmoidImpl:tt,simpleAbsImpl:nt,sliceImpl:rt,sparseFillEmptyRowsImpl:at,sparseReshapeImpl:it,sparseSegmentReductionImpl:st,sqrtImpl:ot,stridedSliceImpl:ut,stringNGramsImpl:ct,stringSplitImpl:lt,stringToHashBucketFastImpl:dt,subImpl:pt,tileImpl:ht,topKImpl:ft,transposeImpl:mt,uniqueImpl:bt}=Te; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function gt(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function xt(e,t){return 1===t?[e]:gt(e,t)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class vt{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=le(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=xt("rc",this.rank),t=re(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),a=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${a}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let a=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n= ${n};\n bool rEdge = rp1 >= ${r};\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]})`}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kt{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=le(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 r,a; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */this.userCode=`\n ${r=t,a=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${a?G(["r","c","d"],"inputShape"):z(["r","c","d"],r)}\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":U(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 yt{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const r=It(t,n),a=St(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const i=wt(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();const e=this.freeTextures[a].shift();return this.usedTextures[a].push(e),e}let s;return r===c.PACKED_2X2_FLOAT32?s=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===c.PACKED_2X2_FLOAT16?s=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===c.UNPACKED_FLOAT32?s=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===c.UNPACKED_FLOAT16?s=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===c.PACKED_4X1_UNSIGNED_BYTE&&(s=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(s),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),s}releaseTexture(e,t,n,a){if(null==this.freeTextures)return;const i=It(n,a),s=St(t,i,a);s in this.freeTextures||(this.freeTextures[s]=[]);const o=wt(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,a),u=Object(r.env)().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==u&&this._numBytesAllocated>u?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const c=this.usedTextures[s],l=c.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(l,1),this.log()}log(){if(!this.logEnabled)return;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 wt(e,t,n,r,a){const i=function(e,t){switch(e){case c.PACKED_2X2_FLOAT32:return Se(t);case c.PACKED_2X2_FLOAT16:return _e(t);case c.UNPACKED_FLOAT32:return ye(t);case c.UNPACKED_FLOAT16:return we(t);case c.PACKED_4X1_UNSIGNED_BYTE:return Ie(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let s;if(a){const[t,n]=p(e[0],e[1]);s=t*n}else{const[t,n]=l(e[0],e[1]);s=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,i);return s*o}function It(e,t){if(e===u.UPLOAD)return c.PACKED_2X2_FLOAT32;if(e===u.RENDER||null==e)return function(e){return Object(r.env)().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?c.PACKED_2X2_FLOAT32:c.UNPACKED_FLOAT32:e?c.PACKED_2X2_FLOAT16:c.UNPACKED_FLOAT16}(t);if(e===u.DOWNLOAD||e===u.PIXELS)return c.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function St(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _t{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=le(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 Ct="return abs(x);";const Ot="return x;";class Tt{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=le(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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $t{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length);const t=e.length,n=xt("rc",t),r=re(t),a=function(e,t){if(1===e)return"rc";let n="";for(let r=0;rt.push(e)))}const t=this.texData.get(e),{values:n,shape:a,slice:i,dtype:s,complexTensorInfos:o,isPacked:u}=t;if(null!=i){let t;t=u?new Tt(a,Ot):new _t(a,Ot);const n=this.runWebGLProgram(t,[{dataId:e,shape:a,dtype:s}],s),r=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if(Object(r.env)().getBool("DEBUG")&&!Object(r.env)().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Object(r.env)().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c,l,p=null;if("complex64"!==s&&Object(r.env)().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const t=this.texData.get(c.dataId);p=this.gpgpu.createBufferFromTexture(t.texture.texture,...d(a))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),t=e[0],n=e[1];l=r.backend_util.mergeRealAndImagArrays(t,n)}else if(null==p)l=this.getValuesFromTexture(e);else{const e=r.util.sizeFromShape(a);l=this.gpgpu.downloadFloat32MatrixFromBuffer(p,e)}if(null!=c&&this.disposeIntermediateTensorInfo(c),null!=p){const e=this.gpgpu.gl;f(e,(()=>e.deleteBuffer(p)))}const h=this.convertAndCacheOnCPU(e,l),m=this.pendingRead.get(e);return this.pendingRead.delete(e),m.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Object(r.engine)().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:a,shape:i,slice:s,dtype:o,isPacked:u,texture:c}=n;if("complex64"===o)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=s){let n;n=u?new Tt(i,Ot):new _t(i,Ot);const r=this.runWebGLProgram(n,[{dataId:e,shape:i,dtype:o}],o),a=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),a}if(null==c)throw null!=a?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),d=Object(r.engine)().makeTensorFromTensorInfo(l),p=this.texData.get(l.dataId);return Object.assign({tensorRef:d},p.texture)}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>r.util.decodeString(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Object(r.buffer)(e.shape,e.dtype,n)}checkNumericalProblems(e){if(null!=e)for(let t=0;t0}time(e){const t=this.activeTimers,n=[];let a=!1;null==this.programTimersStack?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,e();const i=r.util.flatten(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=r.util.flatten(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,a&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(i);o.kernelMs=r.util.sum(e),o.getExtraProfileInfo=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:r.util.now(),endMs:null}}endTimer(e){return Object(r.env)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=r.util.now(),e)}async getQueryTime(e){if(Object(r.env)().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:r,usage:a,isPacked:i,slice:s}=this.texData.get(e),o=s&&s.origDataId||e,u=this.dataRefCount.get(o);u>1?this.dataRefCount.set(o,u-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,i)));const c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Et){return Object(r.env)().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&r.util.sizeFromShape(e.shape)0&&r.util.isString(n[0])){const i=n.map((e=>r.util.encodeString(e)));a=this.write(i,e,t)}else a=this.write(n,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}}makeOutput(e,t,n){return Object(r.engine)().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new $t(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new vt(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[O(e.shape),...T(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[O(t),...T(t)],i=new kt(a,n),s=[n],o=this.runWebGLProgram(i,[r],e.dtype,s,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:a,shape:i,dtype:s}=n;if(null!=t){const e=r.util.sizeFromShape(i),n=t[0]*t[1]*4;r.util.assert(e<=n,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."))}const o=$(i);let u;u=a?new pe(o):new de(o);const c=[null!=t?t:d(o)];return{dtype:s,shape:i,dataId:this.runWebGLProgram(u,[{shape:o,dtype:s,dataId:e}],s,c,!0,t).dataId}}runWebGLProgram(e,t,n,a,i=!1,s){const u=this.makeTensorInfo(e.outputShape,n),c=this.texData.get(u.dataId);if(e.packedOutput&&(c.isPacked=!0),e.outPackingScheme===o.DENSE){const t=null!=s?s:d(e.outputShape);c.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(c.usage=e.outTexUsage),0===r.util.sizeFromShape(u.shape))return c.values=r.util.getTypedArrayFromDType(u.dtype,0),u;const l=[],p=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&&r.util.sizeFromShape(t.shape)<=Object(r.env)().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&&!N(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),l.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(u.dataId);const h={shape:u.shape,texData:c,isUniform:!1},f=function(e,t,n){let a="";t.concat(n).forEach((t=>{const i=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const s=t.texData.texShape,{useSqueezeShape:o,uniformShape:u,keptDims:c}=ae(e.packedInputs,t.shape,s);let l="",d="",p="";if(1===u.length&&e.packedInputs){const e=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==u.length||e.packedInputs){if(u.length>2&&!e.packedInputs){const e=r.util.computeStrides(u);p=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}}else d=`${u[0]>1}_${u[1]>1}`;const h=t.shape.length,f=2===u.length&&r.util.arraysEqual(t.shape,s),m=1===r.util.sizeFromShape(t.shape),b=r.backend_util.getBroadcastDims(t.shape,n.shape),g=!e.packedInputs&&h===n.shape.length&&r.util.arraysEqual(s,n.texData.texShape),x=e.packedInputs||u.length>2?"":`${s[0]>1}_${s[1]>1}`;a+=`${h}_${g}_${o?c:""}_${u.length}_${m}_${b}_${f}_${l}_${d}_${p}_${x}_${i}`}else{const e=t.isUniform?"uniform":t.texData.texShape;a+=`${t.shape}_${e}_${i}`}}));const i=e.userCode;let s=e.constructor.name;return s+="_"+a+"_"+i+`${Object(r.env)().getNumber("WEBGL_VERSION")}`,s}(e,p,h),m=this.getAndSaveBinary(f,(()=>oe(this.gpgpu,e,p,h))),b=null!=this.activeTimers;let g;b&&(g=this.startTimer()),Object(r.env)().get("ENGINE_COMPILE_ONLY")||function(e,t,n,a,i){t.program.enableShapeUniforms||(ce(t.inShapeInfos,n),ce([t.outShapeInfo],[a]));const s=a.texData.texture,o=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,o[0],o[1]):e.setOutputMatrixTexture(s.texture,o[0],o[1]),e.setProgram(t.webGLProgram),1===Object(r.env)().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach(((n,a)=>{const i=t.program.variableNames[a],s=t.uniformLocations[i],o=t.uniformLocations[`offset${i}`],u=t.inShapesLocations[`${i}Shape`],c=t.inTexShapesLocations[`${i}TexShape`];if(u){const{uniformShape:r}=ae(t.program.packedInputs,n.shape,n.texData.texShape);switch(r.length){case 1:e.gl.uniform1iv(u,new Int32Array(r));break;case 2:e.gl.uniform2iv(u,new Int32Array(r));break;case 3:e.gl.uniform3iv(u,new Int32Array(r));break;case 4:e.gl.uniform4iv(u,new Int32Array(r))}}if(c&&e.gl.uniform2i(c,n.texData.texShape[0],n.texData.texShape[1]),null!=s)if(n.isUniform)if(r.util.sizeFromShape(n.shape)<2)e.gl.uniform1f(s,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(s,t)}else null!=n.texData.slice&&null!=o&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture.texture,s,a)}));const u=t.outShapeLocation;if(u)switch(a.shape.length){case 1:e.gl.uniform1iv(u,new Int32Array(a.shape));break;case 2:e.gl.uniform2iv(u,new Int32Array(a.shape));break;case 3:e.gl.uniform3iv(u,new Int32Array(a.shape));break;case 4:e.gl.uniform4iv(u,new Int32Array(a.shape))}if(t.outShapeStridesLocation){const n=r.util.computeStrides(a.shape);switch(a.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))}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,a.texData.texShape[0],a.texData.texShape[1]),t.program.customUniforms&&i&&t.program.customUniforms.forEach(((n,r)=>{const a=t.customUniformLocations[r],s=i[r];if("float"===n.type)e.gl.uniform1fv(a,s);else if("vec2"===n.type)e.gl.uniform2fv(a,s);else if("vec3"===n.type)e.gl.uniform3fv(a,s);else if("vec4"===n.type)e.gl.uniform4fv(a,s);else if("int"===n.type)e.gl.uniform1iv(a,s);else if("ivec2"===n.type)e.gl.uniform2iv(a,s);else if("ivec3"===n.type)e.gl.uniform3iv(a,s);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(a,s)}})),e.executeProgram()}(this.gpgpu,m,p,h,a),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),b&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)}));const x=Object(r.env)().get("WEBGL_FLUSH_THRESHOLD");if(x>0){const e=r.util.now();e-this.lastGlFlushTime>x&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Object(r.env)().getBool("WEBGL_LAZILY_UNPACK")&&c.isPacked&&!1===i){const e=this.unpackTensor(u);return this.disposeIntermediateTensorInfo(u),e}return u}compileAndRun(e,t,n,r,a=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!Object(r.env)().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=Object(r.tidy)((()=>{if(!Object(r.env)().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Object(r.env)().getBool("DEBUG");Object(r.env)().set("DEBUG",!1);const t=this.abs(Object(r.scalar)(1e-8)).dataSync()[0];if(Object(r.env)().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:a,values:i,texture:s,usage:o,isPacked:c}=t;if(null!=s)return;const l=null!=this.activeTimers;let d;l&&(d=r.util.now());let h=t.texShape;if(null==h&&(h=function(e,t=!1){let n=Object(r.env)().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,1===(e=e.map(((t,n)=>n>=e.length-2?r.util.nearestLargerEven(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=r.util.squeezeShape(e);e=t.newShape}let a=r.util.sizeFromShape(e);if(e.length<=1&&a<=n)return[1,a];if(2===e.length&&e[0]<=n&&e[1]<=n)return e;if(3===e.length&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const t=O(e);let n=2,i=2;return e.length&&([n,i]=T(e)),a=t*(n/2)*(i/2),r.util.sizeToSquarishShape(a).map((e=>2*e))}return r.util.sizeToSquarishShape(a)}(n,c),t.texShape=h),null!=i){const e=$(n);let s,o=h[1],f=h[0];const m=i instanceof Uint8Array||i instanceof Uint8ClampedArray;!c&&m||([o,f]=p(h[0],h[1])),s=c?new be(e,m):new me(e,m);const b=m?[f,o]:h,g=this.makeTensorInfo(b,a),x=this.texData.get(g.dataId);x.usage=m?u.PIXELS:u.UPLOAD,x.texShape=b,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),o,f,i);const v=[[f,o]],k=!0,y=this.runWebGLProgram(s,[g],a,v,k),w=this.texData.get(y.dataId);t.texShape=w.texShape,t.isPacked=w.isPacked,t.usage=w.usage,Object(r.env)().get("ENGINE_COMPILE_ONLY")?this.disposeData(y.dataId):(t.texture=w.texture,t.values=null,this.texData.delete(y.dataId)),this.disposeIntermediateTensorInfo(g),l&&(this.uploadWaitMs+=r.util.now()-d)}else{const e=this.acquireTexture(h,o,a,c);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return this.releaseGPUData(e),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;t1024*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,r)}computeBytes(e,t){return e[0]*e[1]*r.util.bytesPerElement(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 Object(r.nextFrame)(),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 x(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.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,inShapesLocations:i,inTexShapesLocations:s,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:c}=ue(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.inShapesLocations=i,e.inTexShapesLocations=s,e.outShapeLocation=o,e.outShapeStridesLocation=u,e.outTexShapeLocation=c}}}Rt.nextDataId=0, +/** + * @license + * Copyright 2020 Google Inc. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +r.device_util.isBrowser()&&Object(r.registerBackend)("webgl",(()=>new Rt),2);class Ft{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=le(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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Mt{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n);const i=this.outputShape.length;this.enableShapeUniforms=le(i);let s="";if(a)if(0===i||1===r.util.sizeFromShape(this.outputShape))s="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else{if(s=`\n ${re(i)} coords = getOutputCoords();\n `,1===i)this.enableShapeUniforms?s+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":s+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=xt("coords",i);this.enableShapeUniforms?s+=`\n bool nextRowOutOfBounds =\n (${e[i-2]} + 1) >= outShape[${i} - 2];\n bool nextColOutOfBounds =\n (${e[i-1]} + 1) >= outShape[${i} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:s+=`\n bool nextRowOutOfBounds =\n (${e[i-2]} + 1) >= ${this.outputShape[i-2]};\n bool nextColOutOfBounds =\n (${e[i-1]} + 1) >= ${this.outputShape[i-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 ${s}\n\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Dt(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const Pt={kernelName:r.Identity,backendName:"webgl",kernelFunc:Dt}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Bt(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,i=n.makeTensorInfo(r.shape,"complex64"),s=n.texData.get(i.dataId),o=Dt({inputs:{x:r},backend:n}),u=Dt({inputs:{x:a},backend:n});return s.complexTensorInfos={real:o,imag:u},i}const jt={kernelName:r.Complex,backendName:"webgl",kernelFunc:Bt},Lt="return (a < 0.) ? b * a : a;",zt="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wt={kernelName:r.LeakyRelu,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{alpha:s}=a,o=n.makeTensorInfo([],"float32",r.util.createScalarValue(s,"float32")),u=Object(r.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Mt(zt,i.shape,o.shape):new Ft(Lt,i.shape,o.shape),c=n.runWebGLProgram(u,[i,o],"float32");return n.disposeIntermediateTensorInfo(o),c}},Gt="return (a < 0.) ? b * a : a;",Ut="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vt={kernelName:r.Prelu,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:a,alpha:i}=t,s=Object(r.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Mt(Ut,a.shape,i.shape):new Ft(Gt,a.shape,i.shape);return n.runWebGLProgram(s,[a,i],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ht({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:i,backend:s})=>{const{x:o}=i,u=s,c=a||o.dtype;if(u.shouldExecuteOnCPU([o])&&null!=n){const e=u.texData.get(o.dataId),t=n(e.values,c);return u.makeTensorInfo(o.shape,c,t)}let l;return l=Object(r.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new Tt(o.shape,t):new _t(o.shape,e),u.runWebGLProgram(l,[o],c)}}function qt({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:i,dtype:s}){return({inputs:o,backend:u})=>{const{a:c,b:l}=o,d=u;if(a&&"complex64"===c.dtype){const t=d.texData.get(c.dataId),n=d.texData.get(l.dataId),[a,i]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,a]=t,i={dataId:n.dataId,dtype:n.dtype,shape:c.shape},s={dataId:a.dataId,dtype:a.dtype,shape:l.shape},o=new Ft(e,c.shape,l.shape);return d.runWebGLProgram(o,[i,s],Object(r.upcastType)(n.dtype,a.dtype))})),s=Bt({inputs:{real:a,imag:i},backend:d});return d.disposeIntermediateTensorInfo(a),d.disposeIntermediateTensorInfo(i),s}const p=s||Object(r.upcastType)(c.dtype,l.dtype);if(("string"===c.dtype||"string"===l.dtype||d.shouldExecuteOnCPU([c,l]))&&null!=i){const e=d.texData.get(c.dataId).values,t=d.texData.get(l.dataId).values,n="string"===c.dtype?r.backend_util.fromUint8ToStringArray(e):e,a="string"===c.dtype?r.backend_util.fromUint8ToStringArray(t):t,[s,o]=i(c.shape,l.shape,n,a,p),u=d.makeTensorInfo(o,p);return d.texData.get(u.dataId).values=s,u}let h;return h=Object(r.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Mt(t,c.shape,l.shape,n):new Ft(e,c.shape,l.shape),d.runWebGLProgram(h,[c,l],p)}}function Kt(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\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":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\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":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\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":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?Ut:Gt;if("leakyrelu"===e)return t?zt:Lt;if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Xt{constructor(e,t,n,r=!1,a=!1,i=!1,s=null,o=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=le(this.outputShape.length);const c=r?e[1]:e[2],l=Math.ceil(c/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",b="";s&&(m=o?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${s}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${s}\n }`:`vec4 activation(vec4 x) {\n ${s}\n }`,b="result = activation(result);");const g=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let x="rc.x",v="rc.x";e[0]`The new shape (${c}) has ${l} elements and the old shape (${i.shape}) has ${u} elements. The new shape and old shape must have the same number of elements.`));const d=o.texData.get(i.dataId);return!d.isPacked||N(i.shape,c)||null!==d.texture&&N(d.shape,c)?(o.incRef(i.dataId),{dataId:i.dataId,shape:c,dtype:i.dtype}):function(e,t,n){const r=[O(e.shape),...T(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},i=[O(t),...T(t)],s=new kt(i,r),o=[r],u=n.runWebGLProgram(s,[a],e.dtype,o,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(i,c,o)}const rn={kernelName:r.Reshape,backendName:"webgl",kernelFunc:nn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class an{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:a,inSize:i,outSize:s}=e;this.outputShape=[a,s];const o=4*Math.floor(n/4),u=n%4;let c="sumValue += dot(values, ones);";if(null!=t){const e=1/t;c=`sumValue += dot(values * ${r.util.isInt(e)?e.toPrecision(2):e}, ones);`}let l="";i%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${i}) {\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 ${l}\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 < ${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 ${c}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===u}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${c}\n } else if (${2===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${c}\n } else if (${3===u}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${c}\n }\n setOutput(sumValue);\n }\n `}} +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class sn{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:i}=e;this.outputShape=[r,i];let s="0.0",o="";"prod"===t?s="1.0":"min"===t?(s="1.0 / 1e-20",o="min"):"max"===t&&(s="-1.0 / 1e-20",o="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const c=4*Math.floor(n/4),l=n%4;let d=`\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 `,p="vec4";"all"===t?(s="1.0",d="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(s="0.0",d="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let h="";a%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${s};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${h}\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(${s});\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 < ${c}; i += 4) {\n int inIdx = inOffset + i;\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${d}\n }\n\n int inIdx = inOffset + ${c};\n if (${1===l}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${d}\n } else if (${2===l}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${d}\n } else if (${3===l}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${d}\n }\n setOutput(${u});\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function on(e,t,n,a){const i=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],a=r.backend_util.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}(e.shape);let s=e;for(let r=0;r6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=re(this.rank),a=gt("rc",this.rank),i=new Array(this.rank);for(let e=0;e`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`));const y=n?[x,p,f]:[x,f,p],w=a?[v,m,h]:[v,h,m],I=nn({inputs:{x:e},backend:i,attrs:{shape:y}}),S=nn({inputs:{x:t},backend:i,attrs:{shape:w}}),_=[I,S],C=Math.max(x,v),O=n?I.shape[1]:I.shape[2],T=null!=s,$=null!=o,A="leakyrelu"===c,N=null!=c?Kt(c,!0):null;let E;if((1===f||1===m)&&O>1e3&&!1===(T||$||A||null!=N)){let e=I,t=S;n&&(e=hn({inputs:{x:I},backend:i,attrs:{perm:[0,2,1]}}),_.push(e)),a&&(t=hn({inputs:{x:S},backend:i,attrs:{perm:[0,2,1]}}),_.push(t));const r=1===m;let s=e;1!==m&&(s=nn({inputs:{x:e},backend:i,attrs:{shape:[C,O,1]}}),_.push(s));const o=1===m?2:1;let u=t;r&&(u=nn({inputs:{x:t},backend:i,attrs:{shape:[C,1,O]}}),_.push(u));const c=en({inputs:{a:s,b:u},backend:i});E=dn({inputs:{x:c},backend:i,attrs:{axis:o,keepDims:!0}}),_.push(c)}else{const c=Object(r.upcastType)(e.dtype,t.dtype),l=new Xt(y,w,[C,f,m],n,a,T,N,$,A),d=[I,S];if(null!=s&&d.push(s),$&&d.push(o),A){const e=i.makeTensorInfo([],"float32",r.util.createScalarValue(u,"float32"));d.push(e),_.push(e)}E=i.runWebGLProgram(l,d,c)}const R=nn({inputs:{x:E},backend:i,attrs:{shape:k}});_.push(E);for(const e of _)i.disposeIntermediateTensorInfo(e);return R} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bn={kernelName:r._FusedMatMul,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:i,bias:s,preluActivationWeights:o}=t,{transposeA:u,transposeB:c,activation:l,leakyreluAlpha:d}=r;return mn({a:a,b:i,transposeA:u,transposeB:c,backend:n,bias:s,preluActivationWeights:o,leakyreluAlpha:d,activation:l})}},gn="return abs(x);"; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xn={kernelName:r.Abs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&"complex64"!==a.dtype){const e=n.texData.get(a.dataId),t=nt(e.values);return n.makeTensorInfo(a.shape,a.dtype,t)}let i;return i=Object(r.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Tt(a.shape,gn):new _t(a.shape,gn),n.runWebGLProgram(i,[a],a.dtype)}},vn=Ht({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),kn={kernelName:r.Acos,backendName:"webgl",kernelFunc:vn},yn=Ht({opSnippet:"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),wn={kernelName:r.Acosh,backendName:"webgl",kernelFunc:yn},In="return a + b;",Sn=qt({opSnippet:In,packedOpSnippet:In,supportsComplex:!0,cpuKernelImpl:$e}),_n={kernelName:r.Add,backendName:"webgl",kernelFunc:Sn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Cn{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 r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${r};\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class On{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 r=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${r};\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tn={kernelName:r.AddN,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:a}=t,i=n;if(1===i.length)return Dt({inputs:{x:i[0]},backend:a});if(i.length>Object(r.env)().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(i.length/2),n=e({inputs:i.slice(0,t),backend:a}),r=e({inputs:i.slice(t),backend:a});return e({inputs:[n,r],backend:a})}const s=i.map((e=>e.dtype)).reduce(((e,t)=>Object(r.upcastType)(e,t))),o=i.map((e=>e.shape)),u=Object(r.env)().getBool("WEBGL_PACK")?new On(i[0].shape,o):new Cn(i[0].shape,o);return a.runWebGLProgram(u,i,s)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $n={kernelName:r.All,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s,keepDims:o}=a,u=i.shape.length,c=r.util.parseAxisParam(s,i.shape);let l=c;const d=r.backend_util.getAxesPermutation(l,u);let p=i;null!=d&&(p=hn({inputs:{x:i},backend:n,attrs:{perm:d}}),l=r.backend_util.getInnerMostAxes(l.length,u)),r.backend_util.assertAxesAreInnerMostDims("all",l,u);const[h,f]=r.backend_util.computeOutAndReduceShapes(p.shape,l),m=nn({inputs:{x:p},backend:n,attrs:{shape:[-1,r.util.sizeFromShape(f)]}}),b=on(m,m.dtype,"all",n);let g;if(o){g=nn({inputs:{x:b},backend:n,attrs:{shape:r.backend_util.expandShapeToKeepDim(h,c)}})}else g=nn({inputs:{x:b},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),null!=d&&n.disposeIntermediateTensorInfo(p),g}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const An={kernelName:r.Any,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s,keepDims:o}=a,u=i.shape.length,c=r.util.parseAxisParam(s,i.shape);let l=c;const d=r.backend_util.getAxesPermutation(l,u);let p=i;null!=d&&(p=hn({inputs:{x:i},backend:n,attrs:{perm:d}}),l=r.backend_util.getInnerMostAxes(l.length,u)),r.backend_util.assertAxesAreInnerMostDims("any",l,u);const[h,f]=r.backend_util.computeOutAndReduceShapes(p.shape,l),m=nn({inputs:{x:p},backend:n,attrs:{shape:[-1,r.util.sizeFromShape(f)]}}),b=on(m,m.dtype,"any",n);let g;if(o){g=nn({inputs:{x:b},backend:n,attrs:{shape:r.backend_util.expandShapeToKeepDim(h,c)}})}else g=nn({inputs:{x:b},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),null!=d&&n.disposeIntermediateTensorInfo(p),g}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Nn{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:a,outSize:i}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,i];const s="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 * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${o};\n float candidate = getA(batch, inIdx);\n if (candidate ${s} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class En{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,r.util.assert(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const i=e[e.length-1],s=Math.ceil(i/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");const o=this.outputShape,u=o.length,c=re(u),l=xt("coords",u);let d,p;if(1===s){p=u+1;const e=re(p);d=`\n ${e} sourceLocR = ${e}(${l.join()}, 0);\n ++${l[u-1]};\n ${e} sourceLocG = ${e}(${l.join()}, 0);\n ++${l[u-2]};\n ${e} sourceLocA = ${e}(${l.join()}, 0);\n --${l[u-1]};\n ${e} sourceLocB = ${e}(${l.join()}, 0);\n --${l[u-2]};`}else p=u,d=`\n ${c} sourceLocR = coords;\n ++${l[u-1]};\n ${c} sourceLocG = coords;\n ++${l[u-2]};\n ${c} sourceLocA = coords;\n --${l[u-1]};\n ${c} sourceLocB = coords;\n --${l[u-2]};`;const h=["x","y","z","w","u","v"].slice(0,p),f="."+h[p-1],m=h.map((e=>"int "+e)),b=xt("sourceLocR",p-1).concat("inIdx.r"),g=xt("sourceLocG",p-1).concat("inIdx.g"),x=xt("sourceLocB",p-1).concat("inIdx.b"),v=xt("sourceLocA",p-1).concat("inIdx.a"),k="max"===n?"greaterThan":"lessThan",y=a?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${b.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${x.join()}),\n getBestIndicesAChannel(${v.join()})));`,w=`vec4(\n getAChannel(${b.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${x.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${v.join()}) : 0.)`,I=a?"":`\n float getBestIndicesAChannel(${m.join()}) {\n return getChannel(getBestIndicesA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${m.join()}) {\n return getChannel(getA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }\n ${I}\n void main() {\n ${c} coords = getOutputCoords();\n bool hasNextCol = ${l[u-1]} < ${o[u-1]-1};\n bool hasNextRow = ${l[u-2]} < ${o[u-2]-1};\n ${d}\n ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},\n sourceLocB${f}, sourceLocA${f}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${w};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${y}\n vec4 candidate = ${w};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${k}(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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rn(e,t,n,a=null){let i=t.shape[0],s=t.shape[1];null!=a&&(i=a.shape[0],s=a.shape[1]);const o=r.backend_util.computeOptimalWindowSize(s),u={windowSize:o,inSize:s,batchSize:i,outSize:Math.ceil(s/o)},c=new Nn(u,n,null==a),l=[t];null!=a&&l.push(a);const d=e.runWebGLProgram(c,l,"int32");if(1===d.shape[1])return d;const p=Rn(e,t,n,d);return e.disposeIntermediateTensorInfo(d),p}function Fn(e,t,n,a=null){const i=null!=a?a.shape:t.shape,s=i[i.length-1],o=r.backend_util.computeOptimalWindowSize(s),u=new En(i,o,n,null==a),c=null==a?[t]:[t,a],l=e.runWebGLProgram(u,c,"int32");if(l.shape.length===t.shape.length){const r=Fn(e,t,n,l);return e.disposeIntermediateTensorInfo(l),r}return l}function Mn(e,t,n,a){const i=[n];if(r.backend_util.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),i,t.shape.length),!Object(r.env)().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let o=t;null!==s&&s.isPacked&&(o=e.unpackTensor(t),n.push(o));const[u,c]=r.backend_util.computeOutAndReduceShapes(o.shape,i),l=r.util.sizeFromShape(c),d=nn({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(d);const p=Rn(e,d,a);n.push(p);const h=nn({inputs:{x:p},backend:e,attrs:{shape:u}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),h}return Fn(e,t,a)} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Dn={kernelName:r.ArgMax,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s}=a;let o=r.util.parseAxisParam(s,i.shape);const u=r.backend_util.getAxesPermutation(o,i.shape.length);let c=i;const l=[];null!=u&&(c=hn({inputs:{x:i},backend:n,attrs:{perm:u}}),l.push(c),o=r.backend_util.getInnerMostAxes(o.length,c.shape.length)),r.backend_util.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);const d=Mn(n,c,o[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pn={kernelName:r.ArgMin,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s}=a;let o=r.util.parseAxisParam(s,i.shape);const u=r.backend_util.getAxesPermutation(o,i.shape.length);let c=i;const l=[];null!=u&&(c=hn({inputs:{x:i},backend:n,attrs:{perm:u}}),l.push(c),o=r.backend_util.getInnerMostAxes(o.length,c.shape.length)),r.backend_util.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);const d=Mn(n,c,o[0],"min");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},Bn=Ht({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),jn={kernelName:r.Asin,backendName:"webgl",kernelFunc:Bn},Ln=Ht({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"}),zn={kernelName:r.Asinh,backendName:"webgl",kernelFunc:Ln},Wn=Ht({opSnippet:"if (isnan(x)) return x;\n return atan(x);\n"}),Gn={kernelName:r.Atan,backendName:"webgl",kernelFunc:Wn},Un=qt({opSnippet:"\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),Vn={kernelName:r.Atan2,backendName:"webgl",kernelFunc:Un},Hn=Ht({opSnippet:"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),qn={kernelName:r.Atanh,backendName:"webgl",kernelFunc:Hn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Kn{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const i=e.filterWidth,s=e.strideHeight,o=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,l=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,b=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let g="0.0";if(f||(g="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${s}, ${o});\n const ivec2 pads = ivec2(${p}, ${h});\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 < ${l};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${d};\n wC += ${c}) {\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 = ${r?a?m:b:`wR * ${d} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(x="avgValue / count");const v=4*Math.floor(i/4),k=i%4,y=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${s}, ${o});\n const ivec2 pads = ivec2(${p}, ${h});\n const float initializationValue = ${g};\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(${g});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${l};\n wR += ${u}) {\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 * ${c};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n getValue(batch, xR, xC + 2 * ${c}, d),\n getValue(batch, xR, xC + 3 * ${c}, d)\n );\n\n ${y}\n }\n\n int xC = xCCorner + ${v};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${y}\n } else if (${2===k}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n initializationValue,\n initializationValue\n );\n\n ${y}\n } else if (${3===k}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n getValue(batch, xR, xC + 2 * ${c}, d),\n initializationValue\n );\n\n ${y}\n }\n }\n setOutput(${x});\n }\n `}}class Xn{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const i=e.filterWidth,s=e.strideDepth,o=e.strideHeight,u=e.strideWidth,c=e.dilationDepth,l=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,b=e.padInfo.top,g=e.padInfo.left;this.outputShape=e.outShape;const x="avg"===t;let v="0.0";if(x||(v="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${s}, ${o}, ${u});\n const ivec3 pads = ivec3(${m}, ${b}, ${g});\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 < ${p};\n wD += ${c}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h};\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 < ${f};\n wC += ${d}) {\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 = ${r?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(k="avgValue / count");const y=4*Math.floor(i/4),w=i%4,I=`\n if (${x}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${s}, ${o}, ${u});\n const ivec3 pads = ivec3(${m}, ${b}, ${g});\n const float initializationValue = ${v};\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(${v});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${c}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h};\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 < ${y}; wC += 4) {\n int xC = xCCorner + wC * ${d};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n getValue(batch, xD, xR, xC + 3 * ${d}, ch)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${y};\n if (${1===w}) {\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===w}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===w}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${d}, ch),\n getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n initializationValue\n );\n\n ${I}\n }\n }\n setOutput(${k});\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yn={kernelName:r.AvgPool,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t;B(i,"avgPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:c}=a;r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=r.backend_util.computePool2DInfo(i.shape,s,o,1,u,c);if(1===l.filterWidth&&1===l.filterHeight&&r.util.arraysEqual(l.inShape,l.outShape))return Dt({inputs:{x:i},backend:n});const d=new Kn(l,"avg",!1);return n.runWebGLProgram(d,[i],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zn={kernelName:r.AvgPool3D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{filterSize:s,strides:o,pad:u,dimRoundingMode:c,dataFormat:l}=a,d=r.backend_util.computePool3DInfo(i.shape,s,o,[1,1,1],u,c,l),p=new Xn(d,"avg",!1);return n.runWebGLProgram(p,[i],"float32")}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Qn{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,s=e.dilationWidth,o=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=o-1-e.padInfo.top,l=u-1-e.padInfo.left,d=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${c}, ${l});\n const float avgMultiplier = float(${d});\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 += ${i}) {\n float dyR = float(dyRCorner + wR) / ${r}.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 < ${u};\n wC+= ${s}) {\n float dyC = float(dyCCorner + wC) / ${a}.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 Jn{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,i=e.strideHeight,s=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,l=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=l-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,b=1/(t*n*r);this.userCode=`\n const ivec3 pads = ivec3(${h}, ${f}, ${m});\n const float avgMultiplier = float(${b});\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 < ${l};\n wD += ${o}) {\n float dyD = float(dyDCorner + wD) / ${a}.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 < ${d};\n wR += ${u}) {\n float dyR = float(dyRCorner + wR) / ${i}.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 < ${p};\n wC += ${c}) {\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\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const er={kernelName:r.AvgPool3DGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,input:s}=t,o=s,{filterSize:u,strides:c,pad:l,dimRoundingMode:d}=a,p=r.backend_util.computePool3DInfo(o.shape,u,c,[1,1,1],l,d),h=new Jn(p);return n.runWebGLProgram(h,[i],o.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tr={kernelName:r.AvgPoolGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,input:s}=t,o=s;B([i,s],"avgPoolGrad");const{filterSize:u,strides:c,pad:l}=a,d=r.backend_util.computePool2DInfo(o.shape,u,c,1,l),p=new Qn(d);return n.runWebGLProgram(p,[i],o.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nr={kernelName:r.BatchMatMul,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:i}=t,{transposeA:s,transposeB:o}=r;return mn({a:a,b:i,transposeA:s,transposeB:o,backend:n})}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rr{constructor(e,t,n,a,i,s){this.outputShape=[],this.variableNames=["x","mean","variance"],r.backend_util.assertAndGetBroadcastShape(e,t),r.backend_util.assertAndGetBroadcastShape(e,n);let o="0.0";null!=a&&(r.backend_util.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let u="1.0";null!=i&&(r.backend_util.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${o};\n float scale = ${u};\n float inv = scale * inversesqrt(variance + float(${s}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ar{constructor(e,t,n,a,i,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],r.backend_util.assertAndGetBroadcastShape(e,t),r.backend_util.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";null!=a&&(r.backend_util.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let u="vec4(1.0)";null!=i&&(r.backend_util.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${o};\n vec4 scale = ${u};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${s}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ir={kernelName:r.FusedBatchNorm,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:a,mean:i,variance:s,offset:o,scale:u}=e;r.util.assert(i.shape.length===s.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),r.util.assert(null==o||i.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),r.util.assert(null==u||i.shape.length===u.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:c}=n;null==c&&(c=.001);const l=[a,i,s];let d=null;null!=o&&(d=o.shape,l.push(o));let p=null;null!=u&&(p=u.shape,l.push(u));const h=Object(r.env)().getBool("WEBGL_PACK_NORMALIZATION")?new ar(a.shape,i.shape,s.shape,d,p,c):new rr(a.shape,i.shape,s.shape,d,p,c);return t.runWebGLProgram(h,l,l[0].dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class sr{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=re(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return or.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(this.rank);let r;r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${or[t]} = start[${t}] + coords.${or[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const or=["x","y","z","w","u","v"];class ur{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=re(this.rank),n=xt("coords",this.rank),r=xt("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,i=`getChannel(getSource(${r.join()}), ${a})`,s=`\n result.x = ${i};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${i};\n --${r[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 ++${r[this.rank-2]};\n result.z = ${i};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${i};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${s}\n ${o}\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function cr(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{begin:s,size:o}=a,[u,c]=r.slice_util.parseSliceParams(i,s,o);if(r.slice_util.assertParamsValid(i,u,c),0===r.util.sizeFromShape(c))return n.makeTensorInfo(c,i.dtype,[]);if(n.shouldExecuteOnCPU([i])||"string"===i.dtype){const e=n.texData.get(i.dataId),t=rt(e.values,u,c,i.shape,i.dtype);return n.makeTensorInfo(c,i.dtype,t)}const{isPacked:l}=n.texData.get(i.dataId),d=r.slice_util.isSliceContinous(i.shape,u,c);if(l||!d){const e=Object(r.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ur(c):new sr(c),t=[u];return n.runWebGLProgram(e,[i],i.dtype,t)}return n.uploadToGPU(i.dataId),function(e,t,n,a){const i=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),o=a.texData.get(s.dataId);Object.assign(o,i),o.refCount=1,o.shape=n,o.dtype=e.dtype;let u=r.slice_util.computeFlatOffset(t,r.util.computeStrides(e.shape));i.slice&&(u+=i.slice.flatOffset),o.slice={flatOffset:u,origDataId:i.slice&&i.slice.origDataId||e.dataId};const c=a.dataRefCount.get(o.slice.origDataId)||1;return a.dataRefCount.set(o.slice.origDataId,c+1),s}(i,u,c,n)}const lr={kernelName:r.Slice,backendName:"webgl",kernelFunc:cr},dr={kernelName:r.BatchToSpaceND,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{blockShape:s,crops:o}=a;r.util.assert(i.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const u=s.reduce(((e,t)=>e*t)),c=r.backend_util.getReshaped(i.shape,s,u),l=r.backend_util.getPermuted(c.length,s.length),d=r.backend_util.getReshapedPermuted(i.shape,s,u),p=r.backend_util.getSliceBeginCoords(o,s.length),h=r.backend_util.getSliceSize(d,o,s.length),f=[],m=nn({inputs:{x:i},backend:n,attrs:{shape:c}}),b=hn({inputs:{x:m},backend:n,attrs:{perm:l}}),g=nn({inputs:{x:b},backend:n,attrs:{shape:d}}),x=cr({inputs:{x:g},backend:n,attrs:{begin:p,size:h}});return f.push(m),f.push(b),f.push(g),f.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pr={kernelName:r.Bincount,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:i}=t,{size:s}=r,o=n.readSync(a.dataId),u=n.readSync(i.dataId),c=Ae(o,u,i.dtype,i.shape,s);return n.makeTensorInfo([s],i.dtype,c)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hr={kernelName:r.BroadcastArgs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:a,s1:i}=t,s=n.readSync(a.dataId),o=n.readSync(i.dataId),u=r.backend_util.assertAndGetBroadcastShape(Array.from(s),Array.from(o));return n.makeTensorInfo([u.length],"int32",Int32Array.from(u))}},fr=qt({opSnippet:"return float(a != b);",cpuKernelImpl:Ze,dtype:"bool"}),mr={kernelName:r.NotEqual,backendName:"webgl",kernelFunc:fr}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function br(e){const{inputs:t,backend:n}=e,{input:r}=t;return Dt({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const gr={kernelName:r.Real,backendName:"webgl",kernelFunc:br}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xr={kernelName:r.Cast,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e(t){const{inputs:n,backend:a,attrs:i}=t,{x:s}=n,{dtype:o}=i;if("complex64"===o){if("complex64"===s.dtype)return Dt({inputs:{x:s},backend:a});const t=r.zeros(s.shape),n=e({inputs:{x:s},backend:a,attrs:{dtype:"float32"}}),i=Bt({inputs:{real:n,imag:t},backend:a});return t.dispose(),a.disposeIntermediateTensorInfo(n),i}if("complex64"===s.dtype){const t=br({inputs:{input:s},backend:a}),n=e({inputs:{x:t},backend:a,attrs:{dtype:o}});return a.disposeIntermediateTensorInfo(t),n}if(!r.util.hasEncodingLoss(s.dtype,o)){const e=Dt({inputs:{x:s},backend:a});return{dataId:e.dataId,shape:e.shape,dtype:o}}if("int32"===o)return function(e,t){const n=new _t(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,a);if("bool"===o){const e=a.makeTensorInfo([],"bool",r.util.getTypedArrayFromDType("bool",1)),t=fr({inputs:{a:s,b:e},backend:a});return a.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},vr="return ceil(x);",kr=Ht({opSnippet:vr,packedOpSnippet:vr,cpuKernelImpl:Ee}),yr={kernelName:r.Ceil,backendName:"webgl",kernelFunc:kr}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class wr{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 "}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ir{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Sr={kernelName:r.ClipByValue,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{clipValueMin:s,clipValueMax:o}=a;let u;u=Object(r.env)().getBool("WEBGL_PACK_CLIP")?new Ir(i.shape):new wr(i.shape);const c=[[s],[o]];return n.runWebGLProgram(u,[i],i.dtype,c)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class _r{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Cr(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const Or={kernelName:r.ComplexAbs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=n.texData.get(r.dataId),i=new _r(r.shape),s=[Cr(r,a.complexTensorInfos.real),Cr(r,a.complexTensorInfos.imag)];return n.runWebGLProgram(i,s,s[0].dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Tr{constructor(e){this.outputShape=[],this.outputShape=r.backend_util.computeOutShape(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${t}`));const u=new Array(e.length-1);u[0]=e[0][t];for(let n=1;n= ${u[e-1]}) {\n return getChannel(\n getT${e}(${Ar(o,c,t)}),\n vec2(${Ar(l,c,t)}));\n }`}const h=u.length,f=u[u.length-1];p+=`\n return getChannel(\n getT${h}(${Ar(o,c,f)}),\n vec2(${Ar(l,c,f)}));`,this.userCode=`\n float getValue(${o.map((e=>"int "+e))}) {\n ${p}\n }\n\n void main() {\n ${i} coords = getOutputCoords();\n vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n ${s[a-1]} = ${s[a-1]} + 1;\n if (${s[a-1]} < ${n[a-1]}) {\n result.g = getValue(${s});\n }\n\n ${s[a-2]} = ${s[a-2]} + 1;\n if (${s[a-2]} < ${n[a-2]}) {\n result.a = getValue(${s});\n }\n\n ${s[a-1]} = ${s[a-1]} - 1;\n if (${s[a-2]} < ${n[a-2]} &&\n ${s[a-1]} < ${n[a-1]}) {\n result.b = getValue(${s});\n }\n setOutput(result);\n }\n `}}function Ar(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Nr(e){const{inputs:t,backend:n}=e,{input:r}=t;return Dt({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const Er={kernelName:r.Imag,backendName:"webgl",kernelFunc:Nr}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rr(e,t,n){const a=e[0].dtype;if("complex64"===a){const r=e.map((e=>br({inputs:{input:e},backend:n}))),a=e.map((e=>Nr({inputs:{input:e},backend:n}))),i=Rr(r,t,n),s=Rr(a,t,n),o=Bt({inputs:{real:i,imag:s},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),a.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(s),o}let i=n.shouldExecuteOnCPU(e);if("string"===a&&(i=!0),i){const i=e.map((e=>{const a=r.util.sizeFromShape(e.shape.slice(t));return nn({inputs:{x:e},backend:n,attrs:{shape:[-1,a]}})})),s=i.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=r.backend_util.computeOutShape(i.map((e=>e.shape)),1),u=1===i[0].shape[0],c=Re(s,o,a,u),l=r.backend_util.computeOutShape(e.map((e=>e.shape)),t),d=n.makeTensorInfo(l,a,c);return i.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}if(e.length>Object(r.env)().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const r=Math.floor(e.length/2),a=Rr(e.slice(0,r),t,n),i=Rr(e.slice(r),t,n),s=Rr([a,i],t,n);return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),s}if(Object(r.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const r=new $r(e.map((e=>e.shape)),t);return n.runWebGLProgram(r,e,a)}const{tensors2D:s,outShape:o}=function(e,t,n){const a=r.backend_util.computeOutShape(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>nn({inputs:{x:e},attrs:{shape:[-1,r.util.sizeFromShape(e.shape.slice(t))]},backend:n}))),outShape:a}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(e,t,n),u=new Tr(s.map((e=>e.shape))),c=n.runWebGLProgram(u,s,a);s.forEach((e=>n.disposeIntermediateTensorInfo(e)));const l=nn({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),l}function Fr(e){const{inputs:t,backend:n,attrs:a}=e,{axis:i}=a,s=r.util.parseAxisParam(i,t[0].shape)[0],o=r.backend_util.computeOutShape(t.map((e=>e.shape)),s);if(0===r.util.sizeFromShape(o))return n.makeTensorInfo(o,t[0].dtype,[]);const u=t.filter((e=>r.util.sizeFromShape(e.shape)>0));if(1===u.length)return Dt({inputs:{x:u[0]},backend:n});const c=u.map((e=>e.shape));return r.backend_util.assertParamsConsistent(c,s),Rr(u,s,n)}const Mr={kernelName:r.Concat,backendName:"webgl",kernelFunc:Fr}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Dr{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,s=e.padInfo.left,o=e.strideHeight,u=e.strideWidth,c=e.dilationHeight,l=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,b=m?1:2,g=m?2:3,x=m?3:1;let v="",k="";n&&(v=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,k="result = activation(result);");const y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${v}\n\n const ivec2 strides = ivec2(${o}, ${u});\n const ivec2 pads = ivec2(${i}, ${s});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${x}];\n\n ivec2 xRCCorner =\n ivec2(coords[${b}], coords[${g}]) * 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 < ${d}; wR++) {\n int xR = xRCorner + wR * ${c};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${l};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${h}; 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, ${h}) *\n getW(wR, wC, ${h}, d2);\n } else {\n dotProd +=\n getX(batch, ${h}, xR, xC) *\n getW(wR, wC, ${h}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${h}, d2),\n getW(wR, wC, ${h} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${h}),\n getX(batch, xR, xC, ${h} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${h}, xR, xC),\n getX(batch, ${h} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${h}, d2),\n getW(wR, wC, ${h} + 1, d2),\n getW(wR, wC, ${h} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${h}),\n getX(batch, xR, xC, ${h} + 1),\n getX(batch, xR, xC, ${h} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${h}, xR, xC),\n getX(batch, ${h} + 1, xR, xC),\n getX(batch, ${h} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${y}\n ${k}\n setOutput(result);\n }\n `}}class Pr{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,a=e.strideDepth,i=e.strideHeight,s=e.strideWidth,o=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,l=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${a}, ${i}, ${s});\n const ivec3 pads = ivec3(${t}, ${n}, ${r});\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 < ${l}; 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 < ${d}; 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 < ${p}; 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 < ${h}; 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, ${h}) *\n getW(wF, wR, wC, ${h}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${h}),\n getX(batch, xF, xR, xC, ${h} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${h}, d2),\n getW(wF, wR, wC, ${h} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${h}),\n getX(batch, xF, xR, xC, ${h} + 1),\n getX(batch, xF, xR, xC, ${h} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${h}, d2),\n getW(wF, wR, wC, ${h} + 1, d2),\n getW(wF, wR, wC, ${h} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Br{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=le(this.outputShape.length);const{dataFormat:n}=t,r=L(),a="channelsLast"===n,i=a?0:1,s=a?1:2,o=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`;let u="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)u+=`\n blockIndex = rc.y + ${t};\n pos = rc.x + ${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[${i}] && 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[${s}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${a}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${u}\n\n ${r.output} = result;\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function jr(e,t,n,a){const i=e.shape;if(r.util.assert(i.length<=1||3===i.length,(()=>`WebGL conv2d only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${i.length}.`)),1===i.length){const e=n?t[3]:t[1];r.util.assert(1===i[0]||i[0]===e,(()=>`WebGL conv2d PReLU activation weights (${i}) is not compatible with the number of output channels (${e}).`))}else if(3===i.length){try{r.broadcast_util.assertAndGetBroadcastShape(i,t)}catch(e){throw Error(`WebGL conv2d PReLU activation weights (${i}) is not compatible with the output shape of the conv2d (${t}).`)}if(!n)return hn({inputs:{x:e},backend:a,attrs:{perm:[1,2,0]}})}return e}function Lr({x:e,filter:t,convInfo:n,backend:a,bias:i=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:u=null}){const c=e.shape,l=a.texData.get(e.dataId),d=n.inChannels,p=c[0]*c[1]*c[2],h=n.outChannels,f="channelsLast"===n.dataFormat,m=!f;let b;const g=[];if(null!=i&&(r.util.assert(i.shape.length<=1,(()=>`WebGL conv2dByMatMul only supports 1-D Tensor bias but got the bias of rank-${i.shape.length}.`)),r.util.assert(0===i.shape.length||i.shape[0]===n.outChannels,(()=>`WebGL conv2dByMatMul bias shape (${i.shape}) is not compatible with the number of output channels (${n.outChannels})`))),null!=s){const e=jr(s,n.outShape,f,a);e.dataId!==s.dataId&&(g.push(e),s=e)}if(!((1===p||1===h)&&d>1e3)&&l.isPacked&&f&&null!=l.texture&&c[2]%2!=0&&r.util.arraysEqual(l.shape.slice(-3),c.slice(-3))){const d=c[0]*c[1]*(c[2]+1),p={dataId:e.dataId,shape:[1,d,n.inChannels],dtype:e.dtype},h=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,r.util.assert(N(l.shape,p.shape),(()=>`packed reshape ${l.shape} to ${p.shape} isn't free`));const f=nn({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(f);const x=mn({a:p,b:f,backend:a,transposeA:m,transposeB:false,bias:i,activation:u,preluActivationWeights:s,leakyreluAlpha:o}),v=a.texData.get(x.dataId);r.util.assert(v.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=h,v.shape=n.outShape,b=Dt({inputs:{x:x},backend:a}),b.shape=n.outShape,g.push(x)}else{const r=f?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],l=nn({inputs:{x:e},backend:a,attrs:{shape:f?[1,r,n.inChannels]:[1,n.inChannels,r]}}),d=nn({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),p=mn({a:l,b:d,transposeA:m,transposeB:false,backend:a,bias:i,activation:u,preluActivationWeights:s,leakyreluAlpha:o}),h=nn({inputs:{x:p},backend:a,attrs:{shape:[n.batchSize,n.outHeight,n.outWidth,n.outChannels]}});b=f?h:hn({inputs:{x:h},backend:a,attrs:{perm:[0,3,1,2]}}),f||g.push(h),g.push(l),g.push(d),g.push(p)}for(const e of g)a.disposeIntermediateTensorInfo(e);return b}function zr({x:e,filter:t,convInfo:n,backend:a,bias:i=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:u=null}){const{filterWidth:c,filterHeight:l,inChannels:d,outWidth:p,outHeight:h,dataFormat:f}=n,m="channelsLast"===f,b=c*l*d,g=h*p,x=[b,g],v=[];if(null!=i&&(r.util.assert(i.shape.length<=1,(()=>`WebGL conv2dWithIm2Row only supports 1-D Tensor bias but got the bias of rank-${i.shape.length}.`)),r.util.assert(0===i.shape.length||i.shape[0]===n.outChannels,(()=>`WebGL conv2dWithIm2Row bias shape (${i.shape}) is not compatible with the number of output channels (${n.outChannels})`))),null!=s){const e=jr(s,n.outShape,m,a);e.dataId!==s.dataId&&(v.push(e),s=e)}const k=nn({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),y=nn({inputs:{x:t},backend:a,attrs:{shape:[1,b,r.util.sizeFromShape(t.shape)/b]}});v.push(k),v.push(y);const w=new Br(x,n),I=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],S=a.runWebGLProgram(w,[k],"float32",I),_=nn({inputs:{x:S},backend:a,attrs:{shape:[1,x[0],x[1]]}});v.push(S),v.push(_);const C=null!=i,O=null!=s,T="leakyrelu"===u,$=u?Kt(u,!0):null,A=new Xt(_.shape,y.shape,[1,g,n.outChannels],!0,!1,C,$,O,T),N=[_,y];if(i&&N.push(i),O&&N.push(s),T){const e=a.makeTensorInfo([],"float32",r.util.createScalarValue(o,"float32"));N.push(e),v.push(e)}const E=a.runWebGLProgram(A,N,"float32"),R=nn({inputs:{x:E},backend:a,attrs:{shape:[1,h,p,n.outChannels]}}),F=m?R:hn({inputs:{x:R},backend:a,attrs:{perm:[0,3,1,2]}});m||v.push(R),v.push(E);for(const e of v)a.disposeIntermediateTensorInfo(e);return F} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wr={kernelName:r.Conv2D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s}=t,{strides:o,pad:u,dataFormat:c,dilations:l,dimRoundingMode:d}=a,p=r.backend_util.convertConv2DDataFormat(c),h=r.backend_util.computeConv2DInfo(i.shape,s.shape,o,l,u,d,!1,p);let f;if(1!==h.filterHeight||1!==h.filterWidth||1!==h.dilationHeight||1!==h.dilationWidth||1!==h.strideHeight||1!==h.strideWidth||"SAME"!==h.padInfo.type&&"VALID"!==h.padInfo.type)if(Object(r.env)().getBool("WEBGL_CONV_IM2COL")&&1===i.shape[0])f=zr({x:i,filter:s,convInfo:h,backend:n});else{const e=new Dr(h);f=n.runWebGLProgram(e,[i,s],"float32")}else f=Lr({x:i,filter:s,convInfo:h,backend:n});const m=nn({inputs:{x:f},backend:n,attrs:{shape:h.outShape}});return n.disposeIntermediateTensorInfo(f),m}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Gr{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,i="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} - ${r};\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} - ${a};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n if (${i}) {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class Ur{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i="channelsLast"===e.dataFormat,s=t-1-e.padInfo.top,o=n-1-e.padInfo.left,u=i?1:2,c=i?2:3,l=i?3:1;this.userCode=`\n const ivec2 pads = ivec2(${s}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${l}];\n\n ivec2 dyCorner = ivec2(coords[${u}], coords[${c}]) - 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) / ${r}.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) / ${a}.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 (${i}) {\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 Vr{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.padInfo.front,i=e.padInfo.top,s=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} - ${a};\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} - ${i};\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 * ${r} - ${s};\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 Hr{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,i=e.strideHeight,s=e.strideWidth,o=t-1-e.padInfo.front,u=n-1-e.padInfo.top,c=r-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${o}, ${u}, ${c});\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) / ${a}.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) / ${i}.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 < ${r}; wC++) {\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 int wCPerm = ${r} - 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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qr={kernelName:r.Conv2DBackpropFilter,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,dy:s}=t,{strides:o,pad:u,dataFormat:c,dimRoundingMode:l,filterShape:d}=a,p=r.backend_util.convertConv2DDataFormat(c),h=r.backend_util.computeConv2DInfo(i.shape,d,o,1,u,l,!1,p),f=new Gr(h);return n.runWebGLProgram(f,[i,s],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kr={kernelName:r.Conv2DBackpropInput,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,filter:s}=t,{inputShape:o,strides:u,pad:c,dataFormat:l,dimRoundingMode:d}=a,p=r.backend_util.convertConv2DDataFormat(l),h=r.backend_util.computeConv2DInfo(o,s.shape,u,1,c,d,!1,p),f=new Ur(h);return n.runWebGLProgram(f,[i,s],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xr={kernelName:r.Conv3D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s}=t,{strides:o,pad:u,dilations:c}=a,l=r.backend_util.computeConv3DInfo(i.shape,s.shape,o,c,u),d=new Pr(l);return n.runWebGLProgram(d,[i,s],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yr={kernelName:r.Conv3DBackpropFilterV2,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,dy:s}=t,{strides:o,pad:u,filterShape:c}=a,l=r.backend_util.computeConv3DInfo(i.shape,c,o,1,u),d=new Vr(l);return n.runWebGLProgram(d,[i,s],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zr={kernelName:r.Conv3DBackpropInputV2,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,filter:s}=t,{pad:o,strides:u,inputShape:c}=a,l=r.backend_util.computeConv3DInfo(c,s.shape,u,1,o),d=new Hr(l);return n.runWebGLProgram(d,[i,s],"float32")}},Qr=Ht({opSnippet:"if (isnan(x)) return x;\n return cos(x);\n"}),Jr={kernelName:r.Cos,backendName:"webgl",kernelFunc:Qr},ea=Ht({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),ta={kernelName:r.Cosh,backendName:"webgl",kernelFunc:ea}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class na{constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[i,s,o,u]=e,[c]=t,[l,d]=n;this.outputShape=[c,l,d,u];const p="bilinear"===r?1:0,[h,f]=[s-1+".0",o-1+".0"],[m,b,g]=l>1?[""+(s-1)/(l-1),"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[x,v,k]=d>1?[""+(o-1)/(d-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(${x});\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 >= ${i}) {\n return;\n }\n\n float height_scale = ${b};\n float width_scale = ${v};\n\n float in_y = ${g};\n if( in_y < 0.0 || in_y > ${h} ) {\n setOutput(float(${a}));\n return;\n }\n float in_x = ${k};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${a}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${p} == 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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ra={kernelName:r.CropAndResize,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:i,boxInd:s}=t,{cropSize:o,method:u,extrapolationValue:c}=r,l=new na(a.shape,i.shape,o,u,c);return n.runWebGLProgram(l,[a,i,s],"float32")}};var aa;!function(e){e.Prod="*",e.Sum="+"}(aa||(aa={}));class ia{constructor(e,t,n,r){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.op=e,this.outputShape=t;const a=t.length,i=this.op===aa.Prod?"1.0":"0.0",s=n?i:`getX(${sa(a,"coords",this.op)})`,o=t[t.length-1];let u="",c="";n?(u=r?"end != "+(o-1):"end != 0",c=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${o}`:"end >= pow2",c=r?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${re(a)} coords = getOutputCoords();\n int end = ${oa(a,"coords",this.op)};\n float val = ${s};\n int pow2 = int(pow(2.0, index));\n if (${u}) {\n int idx = ${c};\n ${oa(a,"coords",this.op)} = idx;\n val ${this.op}= getX(${sa(a,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function sa(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 Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function oa(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 Error(`Cumulative ${n} for rank ${e} is not yet supported`)} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ua(e,t,n,a,i,s){const o=t.shape.length,u=r.backend_util.getAxesPermutation([a],o);let c=t;null!=u&&(c=hn({inputs:{x:t},backend:n,attrs:{perm:u}}));const l=r.backend_util.getInnerMostAxes(1,o)[0];if(l!==o-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${a}`);const d=c.shape[l];let p=Dt({inputs:{x:c},backend:n});for(let t=0;t<=Math.ceil(Math.log2(d))-1;t++){const r=new ia(e,c.shape,!1,s),a=[[t]],i=p;p=n.runWebGLProgram(r,[p],p.dtype,a),n.disposeIntermediateTensorInfo(i)}if(i){const t=new ia(e,c.shape,i,s),r=p;p=n.runWebGLProgram(t,[p],p.dtype),n.disposeIntermediateTensorInfo(r)}if(null!=u){const e=hn({inputs:{x:p},backend:n,attrs:{perm:r.backend_util.getUndoAxesPermutation(u)}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),e}return p} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ca={kernelName:r.Cumprod,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,exclusive:s,reverse:o}=r;return ua(aa.Prod,a,n,i,s,o)}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const la={kernelName:r.Cumsum,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,exclusive:s,reverse:o}=r;return ua(aa.Sum,a,n,i,s,o)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const da={kernelName:r.DenseBincount,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:i}=t,{size:s,binaryOutput:o}=r;if(1===a.shape.length){const e=n.readSync(a.dataId),t=n.readSync(i.dataId),r=Ae(e,t,i.dtype,i.shape,s);return n.makeTensorInfo([s],i.dtype,r)}if(2===a.shape.length){const e=n.bufferSync(a),t=n.bufferSync(i),r=Ne(e,t,s,o);return n.makeTensorInfo(r.shape,i.dtype,r.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pa{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)"}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ha={kernelName:r.DepthToSpace,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:i,dataFormat:s}=r,o=a.shape[0],u=("NHWC"===s?a.shape[1]:a.shape[2])*i,c=("NHWC"===s?a.shape[2]:a.shape[3])*i,l=("NHWC"===s?a.shape[3]:a.shape[1])/(i*i),d=new pa("NHWC"===s?[o,u,c,l]:[o,l,u,c],i,s);return n.runWebGLProgram(d,[a],a.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fa{constructor(e,t=!1,n=null,r=!1,a=!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=le(this.outputShape.length);const i=e.filterHeight,s=e.filterWidth,o=e.outChannels/e.inChannels;let u="",c="";n&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,c="result = activation(result);");const l=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${u}\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 < ${i}; 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 < ${s}; 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 ${l}\n ${c}\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ma{constructor(e,t=!1,n=null,a=!1,i=!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=le(this.outputShape.length);const s=e.outChannels/e.inChannels,o=e.padInfo.left,u=e.strideWidth,c=e.dilationWidth,l=e.filterHeight,d=e.filterWidth,p=d;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e=0 && xR < inDims[0]) {\n ";for(let e=0;e<(p+1)/2;e++){const t=2*e;if(h+=`\n xC = xCCorner + ${t*c};\n `,1===u){if(t= 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 `,h+=1===c&&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 `):h+=`\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= 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 `,c>1&&(h+=`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n xTexelC${t}Ready = 1;\n }\n `),h+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):h+=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= 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= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(h+=`\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`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`));const p=r.backend_util.computeConv2DInfo(i.shape,s.shape,o,d,u,l,!0);let h;h=Object(r.env)().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new ma(p):new fa(p);const f=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(h,[i,s],"float32",f)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ga{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,i=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 * ${i} + 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} - ${r};\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} - ${a};\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 xa{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,s=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${s});\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) / ${r}.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) / ${a}.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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const va={kernelName:r.DepthwiseConv2dNativeBackpropFilter,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,dy:s}=t,{strides:o,dilations:u,pad:c,dimRoundingMode:l,filterShape:d}=a,p=r.backend_util.computeConv2DInfo(i.shape,d,o,u,c,l,!0),h=new ga(p);return n.runWebGLProgram(h,[i,s],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ka={kernelName:r.DepthwiseConv2dNativeBackpropInput,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,filter:s}=t,{strides:o,dilations:u,pad:c,dimRoundingMode:l,inputShape:d}=a,p=r.backend_util.computeConv2DInfo(d,s.shape,o,u,c,l,!0),h=new xa(p);return n.runWebGLProgram(h,[i,s],"float32")}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ya{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wa={kernelName:r.Diag,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:a}=t,i=[...a.shape,...a.shape],s=r.util.sizeFromShape(a.shape),o=nn({inputs:{x:a},backend:n,attrs:{shape:[s]}}),u=new ya(s),c=n.runWebGLProgram(u,[o],o.dtype),l=nn({inputs:{x:c},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),l}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ia{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:a,strideWidth:i,filterHeight:s,filterWidth:o,dilationHeight:u,dilationWidth:c}=e,{top:l,left:d}=r;this.userCode=`\n const ivec2 strides = ivec2(${a}, ${i});\n const ivec2 pads = ivec2(${l}, ${d});\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 < ${s}; h++) {\n int hIn = hBeg + h * ${u};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${o}; w++) {\n int wIn = wBeg + w * ${c};\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Sa={kernelName:r.Dilation2D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s}=t,{strides:o,pad:u,dilations:c}=a,l=r.backend_util.computeDilation2DInfo(i.shape,s.shape,o,u,"NHWC",c);let d;const p=new Ia(l);d=n.runWebGLProgram(p,[i,s],"float32");const h=nn({inputs:{x:d},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(d),h}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _a={kernelName:r.Einsum,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{equation:i}=a,s=t,{allDims:o,summedDims:u,idDims:c}=r.backend_util.decodeEinsumEquation(i,s.length);r.backend_util.checkEinsumDimSizes(o.length,c,s);const{path:l,steps:d}=r.backend_util.getEinsumComputePath(u,c),p=d.length;let h=null,f=o.length;const m=[];for(let e=0;e=0&&(h=dn({inputs:{x:h},backend:n,attrs:{axis:l[e]-(o.length-f),keepDims:!1}}),m.push(h)),f--)}for(const e of m)e!==h&&n.disposeIntermediateTensorInfo(e);return h}},Ca=Ht({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"}),Oa={kernelName:r.Elu,backendName:"webgl",kernelFunc:Ca},Ta={kernelName:r.EluGrad,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:a,y:i}=t,s=Object(r.env)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Mt("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",a.shape,i.shape):new Ft("return (b >= 1.0) ? a : a * (b + 1.0);",a.shape,i.shape);return n.runWebGLProgram(s,[a,i],a.dtype)}},$a=qt({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:Fe}),Aa={kernelName:r.Equal,backendName:"webgl",kernelFunc:$a},Na=Ht({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 = ${r.backend_util.ERF_P};\n float a1 = ${r.backend_util.ERF_A1};\n float a2 = ${r.backend_util.ERF_A2};\n float a3 = ${r.backend_util.ERF_A3};\n float a4 = ${r.backend_util.ERF_A4};\n float a5 = ${r.backend_util.ERF_A5};\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`}),Ea={kernelName:r.Erf,backendName:"webgl",kernelFunc:Na},Ra=Ht({opSnippet:"if (isnan(x)) return x;\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:Me,dtype:"float32"}),Fa={kernelName:r.Exp,backendName:"webgl",kernelFunc:Ra}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Ma(e){const{inputs:t,attrs:n,backend:a}=e,{dim:i}=n,{input:s}=t,o=s.shape.length,u=s.shape.slice();let c=i;return i<0&&(r.util.assert(-(o+1)<=i,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),c=o+i+1),u.splice(c,0,1),nn({inputs:{x:s},backend:a,attrs:{shape:u}})}const Da={kernelName:r.ExpandDims,backendName:"webgl",kernelFunc:Ma},Pa="return exp(x) - 1.0;",Ba=Ht({opSnippet:Pa,packedOpSnippet:Pa,cpuKernelImpl:De}),ja={kernelName:r.Expm1,backendName:"webgl",kernelFunc:Ba}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class La{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const a=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=n?`${r}.0`:"1.0";let s;if("real"===e)s="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);s="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${a};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${s}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${r});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${r}; 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) / ${i};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function za(e,t,n){const a=n.texData.get(e.dataId),i=r.util.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],o=nn({inputs:{x:e},backend:n,attrs:{shape:[i/s,s]}}),u=o.shape,c=new La("real",u,t),l=new La("imag",u,t),d=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:u},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:u}],p=n.runWebGLProgram(c,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=Bt({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);const m=nn({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(f),m} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wa={kernelName:r.FFT,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return za(r,!1,n)}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ga{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ua(e){const{backend:t,attrs:n}=e,{shape:a,value:i}=n;let{dtype:s}=n;if(s=s||r.util.inferDtype(i),"string"===s){const e=r.util.getArrayFromDType(s,r.util.sizeFromShape(a));return e.fill(i),t.makeTensorInfo(a,s,e)}{const e=new Ga(a,i),n=[[i]];return t.runWebGLProgram(e,[],s,n)}}const Va={kernelName:r.Fill,backendName:"webgl",kernelFunc:Ua}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ha{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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qa={kernelName:r.FlipLeftRight,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,a=new Ha(n.shape);return r.runWebGLProgram(a,[n],n.dtype)}},Ka="return floor(x);",Xa=Ht({opSnippet:Ka,packedOpSnippet:Ka,cpuKernelImpl:Pe}),Ya={kernelName:r.Floor,backendName:"webgl",kernelFunc:Xa},Za=qt({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"}),Qa={kernelName:r.FloorDiv,backendName:"webgl",kernelFunc:Za}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Ja{constructor(e){this.variableNames=["A"];const t=L(),[n,r]=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(${r}.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 `}} +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ei{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=L(),[n,r]=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(${r}.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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ti={kernelName:r.FromPixels,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e;let{pixels:i}=t;const{numChannels:s}=a,o="undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement,c="undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement,[l,d]=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],p=[d,l],h=[d,l,s];(c||o)&&(null==ni&&(ni=document.createElement("canvas").getContext("2d")),ni.canvas.width=l,ni.canvas.height=d,ni.drawImage(i,0,0,l,d),i=ni.canvas);const f=n.makeTensorInfo(p,"int32");n.texData.get(f.dataId).usage=u.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(f.dataId),i);const m=Object(r.env)().getBool("WEBGL_PACK")?new ei(h):new Ja(h),b=n.runWebGLProgram(m,[f],"int32");return n.disposeData(f.dataId),b} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */};let ni;const ri={kernelName:r.FusedConv2D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s,bias:o,preluActivationWeights:u}=t,{strides:c,pad:l,dataFormat:d,dilations:p,dimRoundingMode:h,activation:f,leakyreluAlpha:m}=a,b=r.backend_util.convertConv2DDataFormat(d),g=r.backend_util.computeConv2DInfo(i.shape,s.shape,c,p,l,h,!1,b);let x;const v=[];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(Object(r.env)().getBool("WEBGL_CONV_IM2COL")&&1===i.shape[0])x=zr({x:i,filter:s,convInfo:g,backend:n,bias:o,activation:f,preluActivationWeights:u,leakyreluAlpha:m});else{const e=null!=o,t=null!=u,a="leakyrelu"===f,c=f?Kt(f,!1):null,l=new Dr(g,e,c,t,a),d=[i,s];if(o&&d.push(o),u&&d.push(u),a){const e=n.makeTensorInfo([],"float32",r.util.createScalarValue(m,"float32"));d.push(e),v.push(e)}x=n.runWebGLProgram(l,d,"float32")}else x=Lr({x:i,filter:s,convInfo:g,backend:n,bias:o,activation:f,preluActivationWeights:u,leakyreluAlpha:m});const k=nn({inputs:{x:x},backend:n,attrs:{shape:g.outShape}});return v.push(x),v.forEach((e=>n.disposeIntermediateTensorInfo(e))),k}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ai={kernelName:r.FusedDepthwiseConv2D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s,bias:o,preluActivationWeights:u}=t,{strides:c,pad:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=a,m=[];let b=d;null==b&&(b=[1,1]),r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(c,b),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${b}'`));const g=r.backend_util.computeConv2DInfo(i.shape,s.shape,c,b,l,p,!0),x=Object(r.env)().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,v=h?Kt(h,x):null,k=[i,s],y=null!=o,w=null!=u,I="leakyrelu"===h;if(y&&k.push(o),w&&k.push(u),I){const e=n.makeTensorInfo([],"float32",r.util.createScalarValue(f,"float32"));k.push(e),m.push(e)}let S;S=x?new ma(g,y,v,w,I):new fa(g,y,v,w,I);const _=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],C=n.runWebGLProgram(S,k,"float32",_);return m.forEach((e=>n.disposeIntermediateTensorInfo(e))),C}};class ii{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const r=re(t.length),a=re(n.length),i=this.sliceDim>1?"strides[j]":"strides";this.userCode=`\n ${r} strides = ${r}(${this.strides});\n void main() {\n ${a} coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < ${this.sliceDim}; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * ${i};\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const si={kernelName:r.GatherNd,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:a,indices:i}=t,s=i.shape,o=s[s.length-1],u=r.util.sizeFromShape(a.shape),[c,l,d,p]=r.backend_util.prepareAndValidate(a,i),h=nn({inputs:{x:i},backend:n,attrs:{shape:[l,o]}}),f=nn({inputs:{x:a},backend:n,attrs:{shape:[r.util.sizeFromShape(a.shape)/d,d]}});if(n.shouldExecuteOnCPU([a,i])||"string"===a.dtype){const e=n.readSync(i.dataId),t=n.bufferSync(a),r=Be(e,t,a.dtype,l,o,d,p,a.shape,u);return n.makeTensorInfo(c,a.dtype,r.values)}const m=new ii(o,p,[l,d]),b=n.runWebGLProgram(m,[f,h],f.dtype),g=nn({inputs:{x:b},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),g}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class oi{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=re(this.rank),r=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let t=0;t= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${r}));\n }\n `}}function ui(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,indices:s}=t,{axis:o,batchDims:u}=a,c=r.util.parseAxisParam(o,i.shape)[0];if(Object(r.env)().get("DEBUG")){const e=n.readSync(s.dataId),t=i.shape[c];for(let n=0;n=0,(()=>`GatherV2: the index value ${a} is not in [0, ${t-1}]`))}}const l=r.backend_util.segment_util.collectGatherOpShapeInfo(i,s,c,u),d=r.util.sizeFromShape(s.shape),p=[],h=nn({inputs:{x:i},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),f=nn({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,d/l.batchSize]}});p.push(h),p.push(f);const m=[l.batchSize,l.outerSize,d/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([i,s])||"string"===i.dtype){const e=n.bufferSync(f),t=n.bufferSync(h),r=je(t,e,m);return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(l.outputShape,r.dtype,r.values)}const b=new oi(h.shape,m),g=n.runWebGLProgram(b,[h,f],h.dtype);p.push(g);const x=nn({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}const ci={kernelName:r.GatherV2,backendName:"webgl",kernelFunc:ui},li=qt({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:Le,dtype:"bool"}),di={kernelName:r.Greater,backendName:"webgl",kernelFunc:li},pi=qt({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:ze}),hi={kernelName:r.GreaterEqual,backendName:"webgl",kernelFunc:pi}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fi={kernelName:r.IFFT,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{input:r}=t;return za(r,!0,n)}},mi=Ht({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),bi={kernelName:r.IsFinite,backendName:"webgl",kernelFunc:mi},gi=Ht({opSnippet:"return float(isinf(x));",dtype:"bool"}),xi={kernelName:r.IsInf,backendName:"webgl",kernelFunc:gi},vi=Ht({opSnippet:"return float(isnan(x));",dtype:"bool"}),ki={kernelName:r.IsNan,backendName:"webgl",kernelFunc:vi},yi=qt({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:We,dtype:"bool"}),wi={kernelName:r.Less,backendName:"webgl",kernelFunc:yi},Ii=qt({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:Ge,dtype:"bool"}),Si={kernelName:r.LessEqual,backendName:"webgl",kernelFunc:Ii}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _i={kernelName:r.LinSpace,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:i}=n,s=Ue(r,a,i);return t.makeTensorInfo([s.length],"float32",s)}},Ci=Ht({opSnippet:"if (isnan(x)) return x;\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:Ve}),Oi={kernelName:r.Log,backendName:"webgl",kernelFunc:Ci},Ti=Ht({opSnippet:"if (isnan(x)) return x;\n return log(1.0 + x);\n"}),$i={kernelName:r.Log1p,backendName:"webgl",kernelFunc:Ti},Ai=qt({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"}),Ni={kernelName:r.LogicalAnd,backendName:"webgl",kernelFunc:Ai},Ei=Ht({opSnippet:"return float(!(x >= 1.0));"}),Ri={kernelName:r.LogicalNot,backendName:"webgl",kernelFunc:Ei},Fi=qt({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"}),Mi={kernelName:r.LogicalOr,backendName:"webgl",kernelFunc:Fi}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Di{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];const i=t,s=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,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 = -${i}; j <= ${i}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${s}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${o};\n setOutput(val);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Pi{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const i=t,s=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,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 - ${i};\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 = - ${i}; j <= ${i}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${s}));\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Bi={kernelName:r.LRN,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{depthRadius:s,bias:o,alpha:u,beta:c}=a,l=Object(r.env)().getBool("WEBGL_PACK_NORMALIZATION")?new Pi(i.shape,s,o,u,c):new Di(i.shape,s,o,u,c);return n.runWebGLProgram(l,[i],i.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ji{constructor(e,t,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=a,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(${r}) * 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(${r})\n * float(${a})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${a});\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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Li={kernelName:r.LRNGrad,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a,y:i,dy:s}=t,{depthRadius:o,bias:u,alpha:c,beta:l}=r,d=new ji(a.shape,o,u,c,l);return n.runWebGLProgram(d,[a,i,s],a.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function zi(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{reductionIndices:s,keepDims:o}=a,u=i.shape.length,c=r.util.parseAxisParam(s,i.shape);let l=c;const d=r.backend_util.getAxesPermutation(l,u),p=null!=d,h=n.shouldExecuteOnCPU([i]);let f=i;if(p){if(h){const e=n.texData.get(f.dataId).values,t=new Array(u);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:qe}),Ui={kernelName:r.Maximum,backendName:"webgl",kernelFunc:Gi}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vi={kernelName:r.MaxPool,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t;B(i,"maxPool");const{filterSize:s,strides:o,pad:u,dimRoundingMode:c}=a;r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(o,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=r.backend_util.computePool2DInfo(i.shape,s,o,1,u,c);if(1===l.filterWidth&&1===l.filterHeight&&r.util.arraysEqual(l.inShape,l.outShape))return Dt({inputs:{x:i},backend:n});const d=new Kn(l,"max",!1);return n.runWebGLProgram(d,[i],i.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hi={kernelName:r.MaxPool3D,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{filterSize:s,strides:o,pad:u,dataFormat:c,dimRoundingMode:l}=a,d=r.backend_util.computePool3DInfo(i.shape,s,o,[1,1,1],u,l,c),p=new Xn(d,"max",!1);return n.runWebGLProgram(p,[i],i.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qi{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,a=e.effectiveFilterHeight,i=e.effectiveFilterWidth,s=a-1-e.padInfo.top,o=i-1-e.padInfo.left,u=a*i-1;this.userCode=`\n const ivec2 pads = ivec2(${s}, ${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 < ${a};\n wR += ${r}) {\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 < ${i}; 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 = ${u} - 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 * ${i} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class Ki{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.dilationDepth,i=e.dilationHeight,s=e.dilationWidth,o=e.effectiveFilterDepth,u=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=o-1-e.padInfo.front,d=u-1-e.padInfo.top,p=c-1-e.padInfo.left,h=o*u*c-1;this.userCode=`\n const ivec3 pads = ivec3(${l}, ${d}, ${p});\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 += ${a}) {\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 < ${u};\n wR += ${i}) {\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 < ${c};\n wC += ${s}) {\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(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${h} -\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 * ${u} * ${c} +\n wR * ${c} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Xi={kernelName:r.MaxPool3DGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,input:s}=t,o=s,{filterSize:u,strides:c,pad:l,dimRoundingMode:d}=a,p=r.backend_util.computePool3DInfo(o.shape,u,c,[1,1,1],l,d),h=new Xn(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Ki(p),b=n.runWebGLProgram(m,[i,f],o.dtype);return n.disposeIntermediateTensorInfo(f),b}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yi={kernelName:r.MaxPoolGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,input:s,output:o}=t,u=s;B([s,o],"maxPoolGrad");const{filterSize:c,strides:l,pad:d,dimRoundingMode:p}=a,h=r.backend_util.computePool2DInfo(u.shape,c,l,1,d,p),f=new Kn(h,"max",!0),m=n.runWebGLProgram(f,[u],u.dtype),b=new qi(h),g=n.runWebGLProgram(b,[i,m],u.dtype);return n.disposeIntermediateTensorInfo(m),g}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Zi={kernelName:r.MaxPoolWithArgmax,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:a}=e,{filterSize:i,strides:s,pad:o,includeBatchInIndex:u}=t,c=n;r.util.assert(4===a.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`));const l=[1,1];r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(s,l),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${l}'`));const d=r.backend_util.computePool2DInfo(a.shape,i,s,l,o),[p,h]=function(e,t,n,r){let a=new Kn(n,"max",!1);const i=r.runWebGLProgram(a,[e],"float32");return a=new Kn(n,"max",!0,!0,t),[i,r.runWebGLProgram(a,[e],"float32")]}(a,u,d,c);return[p,h]}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const Qi={kernelName:r.Mean,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:a}=e,{keepDims:i,axis:s}=t,o=n,u=a.shape.length,c=r.util.parseAxisParam(s,a.shape);let l=c;const d=r.backend_util.getAxesPermutation(l,u),p=null!=d,h=o.shouldExecuteOnCPU([a]),f=[];let m=a;if(p){if(h){const e=o.texData.get(m.dataId).values,t=new Array(u);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:Ke}),ts={kernelName:r.Minimum,backendName:"webgl",kernelFunc:es}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ns{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=re(r),i=t.map((e=>e[0])).join(","),s=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===n?0:1;this.userCode=1!==r?`\n ${a} start = ${a}(${i});\n ${a} end = ${a}(${s});\n\n void main() {\n ${a} outC = getOutputCoords();\n for (int i = 0; i < ${r}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${u};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};\n }\n }\n ${a} coords = outC - start;\n setOutput(getX(${o}));\n }\n `:`\n int start = ${i};\n int end = ${s};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${u};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${u};\n }\n setOutput(getX(outC - start));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class rs{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 r=e.length,a=re(r),i=t.map((e=>e[0])).join(","),s=t.map(((t,n)=>t[0]+e[n])).join(","),o=xt("rc",r),u=xt("source",r),c=`${o[r-1]} < ${this.outputShape[r-1]}`,l=1===r?"source":`vec2(${u.slice(-2).join()})`,d="reflect"===n?0:1;let p="";if(1===r){const e=`\n ${a} source = rc;\n if (source < start) {\n source = start * 2 - source - ${d};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${d};\n }\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${l});\n ${o[r-1]} += 1;\n if(${c}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${l});\n }\n `}else{const e=`\n ${a} source = rc;\n ${a} lt = ${a}(lessThan(source, start));\n ${a} gte = ${a}(greaterThanEqual(source, end));\n ${a} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${d}) +\n gte * ((end - 1) * 2 - source + ${d});\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${u.join()}), ${l});\n ${o[r-1]} += 1;\n if(${c}) {\n ${e}\n result[1] = getChannel(getX(${u.join()}), ${l});\n }\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {\n ${e}\n result[2] = getChannel(getX(${u.join()}), ${l});\n ${o[r-1]} += 1;\n if(${c}) {\n ${e}\n result[3] = getChannel(getX(${u.join()}), ${l});\n }\n }\n `}this.userCode=`\n const ${a} start = ${a}(${i});\n const ${a} end = ${a}(${s});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const as={kernelName:r.MirrorPad,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:a}=e,{paddings:i,mode:s}=n,o=Object(r.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rs(a.shape,i,s):new ns(a.shape,i,s);return t.runWebGLProgram(o,[a],a.dtype)}},is=qt({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),ss={kernelName:r.Mod,backendName:"webgl",kernelFunc:is}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class os{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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const us=qt({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}),cs={kernelName:r.RealDiv,backendName:"webgl",kernelFunc:us},ls="return a - b;",ds=qt({opSnippet:ls,packedOpSnippet:ls,supportsComplex:!0,cpuKernelImpl:pt}),ps={kernelName:r.Sub,backendName:"webgl",kernelFunc:ds}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function hs(e){const{inputs:t,backend:n,attrs:a}=e,{logits:i}=t,{dim:s}=a,o=r.util.parseAxisParam([s],i.shape),u=zi({inputs:{x:i},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=r.backend_util.expandShapeToKeepDim(u.shape,o),l=nn({inputs:{x:u},backend:n,attrs:{shape:c}}),d=ds({inputs:{a:i,b:l},backend:n}),p=Ra({inputs:{x:d},backend:n}),h=dn({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),f=nn({inputs:{x:h},backend:n,attrs:{shape:c}}),m=us({inputs:{a:p,b:f},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}const fs={kernelName:r.Softmax,backendName:"webgl",kernelFunc:hs}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ms={kernelName:r.Multinomial,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:i,seed:s,normalized:o}=r,u=o?a:hs({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),c=u.shape[0],l=u.shape[1],d=new os(c,l,i),p=[[s]],h=n.runWebGLProgram(d,[u],"int32",p);return o||n.disposeIntermediateTensorInfo(u),h}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bs={kernelName:r.Neg,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){const e=n.texData.get(a.dataId),[t,r]=Ye(e.values,a.shape,a.dtype);return n.makeTensorInfo(r,a.dtype,t)}let i;return i=Object(r.env)().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Tt(a.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 _t(a.shape,"if (isnan(x)) return x;\n return -x;\n"),n.runWebGLProgram(i,[a],a.dtype)}},gs=r.kernel_impls.nonMaxSuppressionV3Impl; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const xs={kernelName:r.NonMaxSuppressionV3,backendName:"webgl",kernelFunc:function(e){r.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:a}=e,{boxes:i,scores:s}=t,{maxOutputSize:o,iouThreshold:u,scoreThreshold:c}=a,l=n.readSync(i.dataId),d=n.readSync(s.dataId),{selectedIndices:p}=gs(l,d,o,u,c);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}},vs=r.kernel_impls.nonMaxSuppressionV4Impl; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ks={kernelName:r.NonMaxSuppressionV4,backendName:"webgl",kernelFunc:function(e){r.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:a}=e,{boxes:i,scores:s}=t,{maxOutputSize:o,iouThreshold:u,scoreThreshold:c,padToMaxOutputSize:l}=a,d=n.readSync(i.dataId),p=n.readSync(s.dataId),{selectedIndices:h,validOutputs:f}=vs(d,p,o,u,c,l);return[n.makeTensorInfo([h.length],"int32",new Int32Array(h)),n.makeTensorInfo([],"int32",new Int32Array([f]))]}},ys=r.kernel_impls.nonMaxSuppressionV5Impl; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ws={kernelName:r.NonMaxSuppressionV5,backendName:"webgl",kernelFunc:function(e){r.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:a}=e,{boxes:i,scores:s}=t,{maxOutputSize:o,iouThreshold:u,scoreThreshold:c,softNmsSigma:l}=a,d=n.readSync(i.dataId),p=n.readSync(s.dataId),h=o,f=u,m=c,b=l,{selectedIndices:g,selectedScores:x}=ys(d,p,h,f,m,b);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([x.length],"float32",new Float32Array(x))]}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Is{constructor(e,t,n,r){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(${r}), float(${n}),\n float(index == coords.y)));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ss={kernelName:r.OneHot,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{indices:i}=t,{depth:s,onValue:o,offValue:u}=a,c=r.util.sizeFromShape(i.shape),l=new Is(c,s,o,u),d=nn({inputs:{x:i},backend:n,attrs:{shape:[c]}}),p=n.runWebGLProgram(l,[d],i.dtype);n.disposeIntermediateTensorInfo(d);const h=nn({inputs:{x:p},backend:n,attrs:{shape:[...i.shape,s]}});return n.disposeIntermediateTensorInfo(p),h}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function _s(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=br({inputs:{input:r},backend:n}),t=_s({inputs:{x:e},backend:n}),a=Nr({inputs:{input:r},backend:n}),i=_s({inputs:{x:a},backend:n}),s=Bt({inputs:{real:t,imag:i},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),s}return Ua({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const Cs={kernelName:r.ZerosLike,backendName:"webgl",kernelFunc:_s}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Os={kernelName:r.OnesLike,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===a.dtype){const t=br({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),i=Nr({inputs:{input:a},backend:r}),s=_s({inputs:{x:i},backend:r}),o=Bt({inputs:{real:n,imag:s},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(s),o}return Ua({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ts={kernelName:r.Pack,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{axis:i}=a;if(1===t.length)return Ma({inputs:{input:t[0]},backend:n,attrs:{dim:i}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{r.util.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),r.util.assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const u=[],c=Fr({inputs:t.map((e=>{const t=Ma({inputs:{input:e},backend:n,attrs:{dim:i}});return u.push(t),t})),backend:n,attrs:{axis:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class $s{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 r=e.length,a=re(r),i=t.map((e=>e[0])).join(","),s=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${a} start = ${a}(${i});\n ${a} end = ${a}(${s});\n\n void main() {\n ${a} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${a} coords = outC - start;\n setOutput(getX(${o}));\n }\n }\n `:`\n int start = ${i};\n int end = ${s};\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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class As{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 r=e.length,a=re(r),i=t.map((e=>e[0])).join(","),s=t.map(((t,n)=>t[0]+e[n])).join(","),o=xt("rc",r),u=xt("source",r),c=`${o[r-1]} < ${this.outputShape[r-1]}`,l=1===r?"source":`vec2(${u.slice(-2).join()})`,d=[`${a} rc = outputLoc;`,`${o[r-1]} += 1;\n if(${c}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${o[r-2]} += 1;\n if(${o[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${o[r-1]} += 1;\n if(${c}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let h="";for(let e=0,t=1===r?2:4;e{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{paddings:s,constantValue:o}=a;if(0===r.util.sizeFromShape(i.shape)){return Ua({backend:n,attrs:{shape:s.map(((e,t)=>e[0]+i.shape[t]+e[1])),value:o,dtype:i.dtype}})}const u=Object(r.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new As(i.shape,s,o):new $s(i.shape,s,o),c=[[o]];return n.runWebGLProgram(u,[i],i.dtype,c)},Es={kernelName:r.PadV2,backendName:"webgl",kernelFunc:Ns},Rs=qt({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 vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),Fs={kernelName:r.Pow,backendName:"webgl",kernelFunc:Rs};const Ms={kernelName:r.Prod,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s,keepDims:o}=a,u=i.shape.length,c=[],l=r.util.parseAxisParam(s,i.shape);let d=l;const p=r.backend_util.getAxesPermutation(d,u);let h,f=i;if(null!=p&&(f=hn({inputs:{x:i},backend:n,attrs:{perm:p}}),d=r.backend_util.getInnerMostAxes(d.length,u),c.push(f)),r.backend_util.assertAxesAreInnerMostDims("prod",d,u),n.shouldExecuteOnCPU([f])){const e=n.texData.get(f.dataId).values,{outVals:t,outShape:r,outDtype:a}=Qe(f.shape,f.dtype,e,d);h=n.makeTensorInfo(r,a,t)}else{const[e,t]=r.backend_util.computeOutAndReduceShapes(f.shape,d),a=r.util.sizeFromShape(t),s=nn({inputs:{x:f},backend:n,attrs:{shape:[-1,a]}}),o=on(s,Object(r.sumOutType)(i.dtype),"prod",n);h=nn({inputs:{x:o},backend:n,attrs:{shape:e}}),c.push(s),c.push(o)}if(o){c.push(h);const e=r.backend_util.expandShapeToKeepDim(h.shape,l);h=nn({inputs:{x:h},backend:n,attrs:{shape:e}})}return c.forEach((e=>n.disposeIntermediateTensorInfo(e))),h}},Ds=e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:i,dtype:s}=n,o=Je(r,a,i,s);return t.makeTensorInfo([o.length],s,o)},Ps={kernelName:r.Range,backendName:"webgl",kernelFunc:Ds},Bs=Ht({opSnippet:"return 1.0 / x;"}),js={kernelName:r.Reciprocal,backendName:"webgl",kernelFunc:Bs},Ls=Ht({opSnippet:"if (isnan(x)) return x;\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"}),zs={kernelName:r.Relu,backendName:"webgl",kernelFunc:Ls},Ws=Ht({opSnippet:"if (isnan(x)) return x;\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"}),Gs={kernelName:r.Relu6,backendName:"webgl",kernelFunc:Ws}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Us{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[i,s,o,u]=e;this.outputShape=[i,t,n,u];const c=[r&&t>1?s-1:s,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${c[0]/l[0]},\n ${c[1]/l[1]});\n const vec2 inputShapeRC = vec2(${s}.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 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 `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Vs{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,s,o,u]=e;this.outputShape=[i,t,n,u];const c=[r&&t>1?s-1:s,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${c[0]/l[0]},\n ${c[1]/l[1]},\n ${c[1]/l[1]});\n const vec3 inputShapeRC = vec3(${s}.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 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 < ${u-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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hs={kernelName:r.ResizeBilinear,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{images:i}=t,{alignCorners:s,halfPixelCenters:o,size:u}=a,[c,l]=u,d=Object(r.env)().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Vs(i.shape,c,l,s,o):new Us(i.shape,c,l,s,o);return n.runWebGLProgram(d,[i],"float32")}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qs{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,i,s]=e,o=[n&&i>1?r-1:r,n&&s>1?a-1:a],u=[n&&i>1?i-1:i,n&&s>1?s-1:s],c=o[0]/u[0],l=o[1]/u[1],d=1/c,p=1/l,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+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(${c});\n const float widthScale = float(${l});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${h});\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 >= ${i}) {\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 >= ${s}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${r-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), ${a-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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ks={kernelName:r.ResizeBilinearGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:i}=t,{alignCorners:s}=r,o=new qs(i.shape,a.shape,s);return n.runWebGLProgram(o,[i],i.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Xs{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[i,s,o,u]=e;this.outputShape=[i,t,n,u];const c=[r&&t>1?s-1:s,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";let p;p=a?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${c[0]/l[0]},\n ${c[1]/l[1]});\n const vec2 inputShapeRC = vec2(${s}.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 = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ys{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,s,o,u]=e;this.outputShape=[i,t,n,u];const c=[r&&t>1?s-1:s,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";let p;p=a?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${c[0]/l[0]},\n ${c[1]/l[1]},\n ${c[1]/l[1]});\n const vec3 inputShapeRC = vec3(${s}.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 = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zs={kernelName:r.ResizeNearestNeighbor,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{images:i}=t,{alignCorners:s,halfPixelCenters:o,size:u}=a,[c,l]=u,d=Object(r.env)().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Ys(i.shape,c,l,s,o):new Xs(i.shape,c,l,s,o);return n.runWebGLProgram(d,[i],i.dtype)}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Qs{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,i,s]=e,o=[n&&i>1?r-1:r,n&&s>1?a-1:a],u=[n&&i>1?i-1:i,n&&s>1?s-1:s],c=o[0]/u[0],l=o[1]/u[1],d=1/c,p=1/l,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+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(${c});\n const float widthScale = float(${l});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${h});\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 >= ${i}) {\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 >= ${s}) {\n continue;\n }\n\n float sourceFracRow =\n float(${o[0]}) *\n (float(dyR) / float(${u[0]}));\n\n float sourceFracCol =\n float(${o[1]}) *\n (float(dyC) / float(${u[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${r}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${a}) - 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 `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Js={kernelName:r.ResizeNearestNeighborGrad,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:i}=t,{alignCorners:s}=r,o=new Qs(i.shape,a.shape,s);return n.runWebGLProgram(o,[i],i.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class eo{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 r=e.map(((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r))).join(","),a=re(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class to{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 r=xt("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,i=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,s=re(n);function o(n){const r=e.map(((r,a)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(a,n)));return`getChannel(getX(${r.join(",")}), vec2(${r.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(${a}){\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 ${s} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return o(e)}(r.slice())};\n if(${a}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(r.slice())};\n }\n if(${i}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n if(${a}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const no={kernelName:r.Reverse,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{dims:s}=a,o=i.shape.length,u=r.util.parseAxisParam(s,i.shape);if(0===o)return Dt({inputs:{x:i},backend:n});const c=Object(r.env)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new to(i.shape,u):new eo(i.shape,u);return n.runWebGLProgram(c,[i],i.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ro{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],r=e[2];this.outputShape=e;let a="";a="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 ${a}\n if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ao={kernelName:r.RotateWithOffset,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:a}=e,{radians:i,fillValue:s,center:o}=t,u=n,c=new ro(a.shape,s),[l,d]=r.backend_util.getImageCenter(o,a.shape[1],a.shape[2]),p=[[l,d,Math.sin(i),Math.cos(i)]];return u.runWebGLProgram(c,[a],a.dtype,p)}},io=Ht({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"}),so={kernelName:r.Round,backendName:"webgl",kernelFunc:io},oo=Ht({opSnippet:"return inversesqrt(x);",cpuKernelImpl:et}),uo={kernelName:r.Rsqrt,backendName:"webgl",kernelFunc:oo}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class co{constructor(e,t,n,r,a,i,s=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;const o=re(a.length),u=re(i.length);let c="";1===n?c="i":2===n&&(c="i, j");const l=`getIndices(${c})`;let d="";1===r?d="i":2===r&&(d="i, coords[1]");const p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`\n ${o} strides = ${o}(${a});\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(${l});\n flattenedIndex += index * ${h};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${p};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lo={kernelName:r.ScatterNd,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{indices:i,updates:s}=t,{shape:o}=a,{sliceRank:u,numUpdates:c,sliceSize:l,strides:d,outputSize:p}=r.backend_util.calculateShapes(s,i,o),h=[p/l,l];if(0===p)return n.makeTensorInfo(o,i.dtype);const f=nn({inputs:{x:i},backend:n,attrs:{shape:[c,u]}}),m=nn({inputs:{x:s},backend:n,attrs:{shape:[c,l]}}),b=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new co(c,u,f.shape.length,m.shape.length,d,h),x=n.runWebGLProgram(g,[m,f,b],m.dtype),v=nn({inputs:{x:x},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),v}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class po{constructor(e,t,n,a){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const i=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,s=2===Object(r.env)().getNumber("WEBGL_VERSION")?"while (left < right) {":i,o="left"===a?"<":"<=";this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${s}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${o} 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 `}} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ho={kernelName:r.SearchSorted,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:i}=t,{side:s}=r,o=new po(a.shape[0],a.shape[1],i.shape[1],s),u=[[a.shape[1]]];return n.runWebGLProgram(o,[a,i],"int32",u)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class fo{constructor(e,t,n){let r,a;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)a="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[];for(let r=0;r= 1.0) {\n setOutput(getA(${a}));\n } else {\n setOutput(getB(${a}));\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mo={kernelName:r.Select,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:a,t:i,e:s}=t,o=new fo(a.shape.length,i.shape,i.shape.length);return n.runWebGLProgram(o,[a,i,s],Object(r.upcastType)(i.dtype,s.dtype))}},bo=Ht({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${r.backend_util.SELU_SCALEALPHA};\n float scale = ${r.backend_util.SELU_SCALE};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),go={kernelName:r.Selu,backendName:"webgl",kernelFunc:bo},xo=Ht({opSnippet:"if (isnan(x)) return x;\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:tt}),vo={kernelName:r.Sigmoid,backendName:"webgl",kernelFunc:xo},ko=Ht({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),yo={kernelName:r.Sign,backendName:"webgl",kernelFunc:ko},wo=Ht({opSnippet:"if (isnan(x)) return x;\n return sin(x);\n"}),Io={kernelName:r.Sin,backendName:"webgl",kernelFunc:wo},So=Ht({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),_o={kernelName:r.Sinh,backendName:"webgl",kernelFunc:So},Co=Ht({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"}),Oo={kernelName:r.Softplus,backendName:"webgl",kernelFunc:Co},To={kernelName:r.SpaceToBatchND,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{blockShape:s,paddings:o}=a;r.util.assert(i.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const u=s.reduce(((e,t)=>e*t)),c=[[0,0]];c.push(...o);for(let e=1+s.length;en.disposeIntermediateTensorInfo(e))),g}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $o={kernelName:r.SparseFillEmptyRows,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{indices:r,values:a,denseShape:i,defaultValue:s}=t;if(1!==i.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${i.shape}`);if(2!==r.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Values must be a vector, saw:\n ${a.shape}`);if(0!==s.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${s.shape}`);const o=n.readSync(r.dataId),u=n.readSync(a.dataId),c=n.readSync(i.dataId),l=n.readSync(s.dataId)[0],[d,p,h,f,m]=at(o,r.shape,r.dtype,u,a.dtype,c,l);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],a.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ao={kernelName:r.SparseReshape,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:a,newShape:i}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape ${a.shape}`);if(1!==i.shape.length)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const s=Array.from(n.readSync(a.dataId)),o=n.readSync(r.dataId),u=Array.from(n.readSync(i.dataId)),[c,l,d]=it(o,r.shape,r.dtype,s,u);return[n.makeTensorInfo(l,r.dtype,c),n.makeTensorInfo([d.length],i.dtype,new Int32Array(d))]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const No={kernelName:r.SparseSegmentMean,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:i}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);const s=n.readSync(r.dataId),o=n.readSync(a.dataId),u=n.readSync(i.dataId),[c,l]=st(s,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(l,r.dtype,c)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Eo={kernelName:r.SparseSegmentSum,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:i}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);const s=n.readSync(r.dataId),o=n.readSync(a.dataId),u=n.readSync(i.dataId),[c,l]=st(s,r.shape,r.dtype,o,u);return n.makeTensorInfo(l,r.dtype,c)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ro={kernelName:r.SparseToDense,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{sparseIndices:i,sparseValues:s,defaultValue:o}=t,{outputShape:u}=a,{sliceRank:c,numUpdates:l,strides:d,outputSize:p}=r.backend_util.calculateShapes(s,i,u),h=new co(l,c,i.shape.length,s.shape.length,d,[p,1],!1),f=n.runWebGLProgram(h,[s,i,o],s.dtype),m=nn({inputs:{x:f},backend:n,attrs:{shape:u}});return n.disposeIntermediateTensorInfo(f),m}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fo={kernelName:r.SplitV,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{numOrSizeSplits:s,axis:o}=a,u=r.util.parseAxisParam(o,i.shape)[0],c=r.backend_util.prepareSplitSize(i,s,u),l=i.shape.length,d=new Array(l).fill(0),p=i.shape.slice();return c.map((e=>{const t=[...p];t[u]=e;const r=cr({inputs:{x:i},backend:n,attrs:{begin:d,size:t}});return d[u]+=e,r}))}},Mo="return sqrt(x);",Do=Ht({opSnippet:Mo,packedOpSnippet:Mo,cpuKernelImpl:ot}),Po={kernelName:r.Sqrt,backendName:"webgl",kernelFunc:Do},Bo=Ht({opSnippet:"return x * x;"}),jo={kernelName:r.Square,backendName:"webgl",kernelFunc:Bo},Lo="return (a - b) * (a - b);",zo=qt({opSnippet:Lo,packedOpSnippet:Lo}),Wo={kernelName:r.SquaredDifference,backendName:"webgl",kernelFunc:zo}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Go={kernelName:r.Step,backendName:"webgl",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function({inputs:e,attrs:t,backend:n}){const{x:r}=e,a=`if (isnan(x)) return x;\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,i=new _t(r.shape,a);return n.runWebGLProgram(i,[r],r.dtype)}}; +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Uo{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=re(n.length),i=re(n.length);let s="";if(1===r)s="coords * strides + begin";else{let e=0;s=n.map(((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`))).join(",")}this.userCode=`\n ${a} begin = ${a}(${e});\n ${a} strides = ${a}(${t});\n\n void main() {\n ${i} coords = getOutputCoords();\n setOutput(getX(${s}));\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Vo={kernelName:r.StridedSlice,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{begin:s,end:o,strides:u,beginMask:c,endMask:l,ellipsisMask:d,newAxisMask:p,shrinkAxisMask:h}=a,{finalShapeSparse:f,finalShape:m,isIdentity:b,sliceDim0:g,isSimpleSlice:x,begin:v,end:k,strides:y}=r.slice_util.sliceInfo(i.shape,s,o,u,c,l,d,p,h);let w;if(b)w=nn({inputs:{x:i},backend:n,attrs:{shape:m}});else if(g||x){r.util.assert(i.shape.length>=1,(()=>`Input must have rank at least 1, got: ${i.shape.length}`));const e=r.slice_util.computeOutShape(v,k,y),t=cr({inputs:{x:i},backend:n,attrs:{begin:v,size:e}});w=nn({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([i])){const e=n.readSync(i.dataId),t=Object(r.buffer)(i.shape,i.dtype,e),a=ut(f,t,y,v);w=n.makeTensorInfo(m,i.dtype,a.values)}else{const e=new Uo(v,y,f);w=n.runWebGLProgram(e,[i],i.dtype)}}const I=nn({inputs:{x:w},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(w),I}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ho={kernelName:r.StringNGrams,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:i,leftPad:s,rightPad:o,padWidth:u,preserveShortSequences:c}=r,{data:l,dataSplits:d}=t,p=n.readSync(l.dataId),h=n.readSync(d.dataId),[f,m]=ct(p,h,a,i,s,o,u,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qo={kernelName:r.StringSplit,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:i,delimiter:s}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(1!==i.shape.length)throw new Error(`Input must be a vector, got shape: ${i.shape}`);if(0!==s.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${s.shape}`);const o=n.readSync(i.dataId),u=n.readSync(s.dataId)[0],[c,l,d]=lt(o,u,a),p=l.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ko={kernelName:r.StringToHashBucketFast,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:a}=r,{input:i}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");const s=n.readSync(i.dataId),o=dt(s,a);return n.makeTensorInfo(i.shape,"int32",o)}},Xo=Ht({opSnippet:"return tan(x);"}),Yo={kernelName:r.Tan,backendName:"webgl",kernelFunc:Xo},Zo=Ht({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),Qo={kernelName:r.Tanh,backendName:"webgl",kernelFunc:Zo}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2017 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Jo{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r5)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"],r=[];for(let t=0;t5){const e=n.readSync(i.dataId),t="string"===i.dtype?e.map((e=>r.util.decodeString(e))):e,a=Object(r.buffer)(i.shape,i.dtype,t),o=ht(a,s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}const o=new Jo(i.shape,s);return n.runWebGLProgram(o,[i],i.dtype)}const tu={kernelName:r.Tile,backendName:"webgl",kernelFunc:eu};class nu{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 ru{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 "}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function au(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function iu(e){let t=1;for(;tc){const e=n.readSync(i.dataId),[t,r]=ft(e,l,i.dtype,s,o);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(r.shape,r.dtype,r.values)]}if(0===s)return l[l.length-1]=0,[n.makeTensorInfo(l,i.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(1===d)return[i,Ua({attrs:{shape:l,dtype:"int32",value:0},backend:n})];const p=n.texData.get(i.dataId),h=null!==p&&p.isPacked,f=h?n.unpackTensor(i):i,m=r.util.sizeFromShape(l)/d,b=nn({inputs:{x:f},attrs:{shape:[m,d]},backend:n});h&&au(n,f);const g=iu(s),x=iu(d);let v=null;const k=()=>null===v?[b,b]:[b,v],y=(e,t,r)=>{const a=k(),i=new nu(r),s=[[d],[null===v?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=v;v=n.runWebGLProgram(i,a,"int32",s),au(n,o)};for(let e=1;e=1;n/=2)y(t,n,[m,x])}for(let e=x;e>g;e/=2){const t=k(),r=new ru([m,e/2]),a=[[d],[null===v?1:0],[g]],i=v;v=n.runWebGLProgram(r,t,"int32",a),au(n,i);const s=g/2,o=2*s;for(let e=s;e>=1;e/=2)y(o,e,v.shape)}let w=v;v=cr({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,s]}}),au(n,w);let I=ui({inputs:{x:b,indices:v},backend:n,attrs:{axis:1,batchDims:1}});au(n,b);const S=l.slice(0,-1);S.push(s),w=v,v=nn({inputs:{x:v},attrs:{shape:S},backend:n}),au(n,w);const _=I;return I=nn({inputs:{x:I},attrs:{shape:S},backend:n}),au(n,_),[I,v]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ou{constructor(e,t,n,r,a,i){this.variableNames=["Image","Transforms"],this.outputShape=i;const s="nearest"===n?1:2;let o;switch(r){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(${a});\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(${a});\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 (${s} == 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 `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uu={kernelName:r.Transform,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,transforms:i}=t,{interpolation:s,fillMode:o,fillValue:u,outputShape:c}=r,[l,d,p,h]=a.shape,[f,m]=null!=c?c:[d,p],b=new ou(d,p,s,o,u,[l,f,m,h]);return n.runWebGLProgram(b,[a,i],"float32")}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cu={kernelName:r.Unique,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:i}=t;B(i,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const s=r.readSync(i.dataId),{outputValues:o,outputShape:u,indices:c}=bt(s,a,i.shape,i.dtype);return[r.makeTensorInfo(u,i.dtype,o),r.makeTensorInfo([c.length],"int32",c)]}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const lu={kernelName:r.Unpack,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:i}=r;i<0&&(i+=a.shape.length);const s=a,o=s.shape.length,u=a.shape[i],c=new Array(o-1);let l=0;for(let e=0;en.disposeIntermediateTensorInfo(e))),f}}; +/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class du{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,a=e.inSize,i=e.numSegments,s=i*Math.ceil(a/n);this.outputShape=[r,s];const o=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ";let l="";a%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `);let d="";a%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${l}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${d}\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 ${i})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${i})));\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 ${c}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===u}) {\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 ${c}\n } else if (${2===u}) {\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 ${c}\n } else if (${3===u}) {\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 ${c}\n }\n setOutput(sumValue);\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pu=[bn,xn,kn,wn,_n,Tn,$n,An,Dn,Pn,jn,zn,Gn,Vn,qn,Yn,Zn,er,tr,nr,ir,dr,pr,hr,xr,yr,Sr,jt,Or,Mr,Wr,qr,Kr,Xr,Yr,Zr,Jr,ta,ra,ca,la,da,ha,ba,va,ka,wa,Sa,_a,Oa,Ta,Aa,Ea,Fa,Da,ja,Wa,Va,qa,Ya,Qa,ti,ri,ai,si,ci,di,hi,Pt,fi,Er,bi,xi,ki,Wt,wi,Si,_i,Oi,$i,Ni,Ri,Mi,Bi,Li,Wi,Ui,Vi,Hi,Xi,Yi,Zi,Qi,Ji,ts,as,ss,ms,tn,bs,xs,ks,ws,mr,Ss,Os,Ts,Es,Fs,Vt,Ms,Ps,gr,cs,js,zs,Gs,rn,Hs,Ks,Zs,Js,no,ao,so,uo,lo,ho,mo,go,vo,yo,Io,_o,lr,fs,Oo,To,$o,Ao,No,Eo,Ro,Fo,Po,jo,Wo,Go,Vo,Ho,qo,Ko,ps,pn,Yo,Qo,tu,su,uu,fn,cu,lu,{kernelName:r.UnsortedSegmentSum,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,segmentIds:s}=t,{numSegments:o}=a,u=i.shape.length,c=[];let l=0;const d=r.backend_util.getAxesPermutation([l],u);let p=i;null!=d&&(p=hn({inputs:{x:i},backend:n,attrs:{perm:d}}),c.push(p),l=r.backend_util.getInnerMostAxes(1,u)[0]);const h=r.backend_util.segment_util.computeOutShape(p.shape,l,o),f=r.util.sizeFromShape([p.shape[l]]),m=nn({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}});c.push(m);const b=Object(r.sumOutType)(i.dtype),g=(e,t,a,i,s)=>{const o=e.shape[0],u=e.shape[1],l=r.backend_util.segment_util.segOpComputeOptimalWindowSize(u,s),d=new du({windowSize:l,inSize:u,batchSize:o,numSegments:s},t),p=n.compileAndRun(d,[e,a],i);if(c.push(p),p.shape[1]===s)return p;const h=Ds({backend:n,attrs:{start:0,stop:s,step:1,dtype:"float32"}}),f=eu({inputs:{x:h},backend:n,attrs:{reps:[u/l]}});c.push(h),c.push(f);return g(p,t,f,i,s)},x=nn({inputs:{x:g(m,"unsortedSegmentSum",s,b,o)},backend:n,attrs:{shape:h}});let v=x;if(null!=d){c.push(x);const e=r.backend_util.getUndoAxesPermutation(d);v=hn({inputs:{x:v},backend:n,attrs:{perm:e}})}return c.forEach((e=>n.disposeIntermediateTensorInfo(e))),v}},Cs]; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */for(const e of pu)Object(r.registerKernel)(e); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},function(e,t,n){"use strict";var r=n(0); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const a=Object(r.env)(); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var i;a.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",(()=>15)),a.registerFlag("WEBGPU_CPU_FORWARD",(()=>!0)),a.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",(()=>4)),a.registerFlag("WEBGPU_USE_NAIVE_CONV2D",(()=>!1)),a.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",(()=>!1)),a.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",(()=>!1)),a.registerFlag("WEBGPU_USE_LOW_POWER_GPU",(()=>!1)),a.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e3)),a.registerFlag("WEBGPU_USE_PROFILE_TOOL",(()=>!1)),a.registerFlag("WEBGPU_USE_IMPORT",(()=>!1)),function(e){e[e.MUL=0]="MUL",e[e.ADD=1]="ADD",e[e.SUB=2]="SUB",e[e.DIV=3]="DIV",e[e.EQUAL=4]="EQUAL",e[e.GREATER=5]="GREATER",e[e.GREATER_EQUAL=6]="GREATER_EQUAL",e[e.LESS=7]="LESS",e[e.LESS_EQUAL=8]="LESS_EQUAL",e[e.LOGICAL_AND=9]="LOGICAL_AND",e[e.NOT_EQUAL=10]="NOT_EQUAL",e[e.SQUARED_DIFFERENCE=11]="SQUARED_DIFFERENCE",e[e.INT_DIV=12]="INT_DIV",e[e.POW=13]="POW",e[e.PRELU=14]="PRELU",e[e.MAX=15]="MAX",e[e.MIN=16]="MIN",e[e.COMPLEX_MULTIPLY_REAL=17]="COMPLEX_MULTIPLY_REAL",e[e.COMPLEX_MULTIPLY_IMAG=18]="COMPLEX_MULTIPLY_IMAG"}(i||(i={}));const s="\n if (isNaN.r) {\n resultTemp.r = uniforms.NAN;\n }\n if (isNaN.g) {\n resultTemp.g = uniforms.NAN;\n }\n if (isNaN.b) {\n resultTemp.b = uniforms.NAN;\n }\n if (isNaN.a) {\n resultTemp.a = uniforms.NAN;\n }\n ",o=`\n let isModRound1Bool = vec4(round(abs(b) % vec4(2.0))) == vec4(1);\n let isModRound1 = vec4(isModRound1Bool);\n let multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n var resultTemp = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n let isExpZero = b == vec4(0.0);\n if (isExpZero.r) {\n resultTemp.r = 1.0;\n }\n if (isExpZero.g) {\n resultTemp.g = 1.0;\n }\n if (isExpZero.b) {\n resultTemp.b = 1.0;\n }\n if (isExpZero.a) {\n resultTemp.a = 1.0;\n }\n let isNaN = a < vec4(0.0) & floor(b) < b;\n ${s}\n return resultTemp;\n `;function u(e,t){const n=t?s:"\n if (isnan(a)) { return a; }\n if (isnan(b)) { return b; }\n ";return t?`\n var resultTemp = vec4(${e}(a, b));\n let isNaN = isnanVec4(a) | isnanVec4(b);\n `+n+"\n return resultTemp;\n ":n+`\n return ${e}(a, b);\n `}function c(e,t){switch(e){case i.MUL:return"return a * b;";case i.ADD:return"return a + b;";case i.SUB:return"return a - b;";case i.DIV:return"return a / b;";case i.EQUAL:return t?"return vec4(a == b);":"return f32(a == b);";case i.GREATER:return t?"return vec4(a > b);":"return f32(a > b);";case i.GREATER_EQUAL:return t?"return vec4(a >= b);":"return f32(a >= b);";case i.LESS:return t?"return vec4(a < b);":"return f32(a < b);";case i.LESS_EQUAL:return t?"return vec4(a <= b);":"return f32(a <= b);";case i.LOGICAL_AND:return t?"return (vec4(a >= vec4(1.0)) *\n vec4(b >= vec4(1.0)));":"return f32(f32(a) >= 1.0 && f32(b) >= 1.0);";case i.NOT_EQUAL:return t?"return vec4(a != b);":"return f32(a != b);";case i.SQUARED_DIFFERENCE:return"return (a - b) * (a - b);";case i.INT_DIV:return t?"\n let ia = vec4(round(a));\n let ib = vec4(round(b));\n let cond = ib != vec4(0);\n var resultTemp = vec4(0);\n let s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n resultTemp[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n resultTemp[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n resultTemp[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n resultTemp[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(resultTemp);\n ":"\n let s = sign(a) * sign(b);\n let ia = i32(round(a));\n let ib = i32(round(b));\n return f32(idiv(ia, ib, s));\n ";case i.PRELU:return t?"\n let aLessThanZero = vec4(a < vec4(0.0));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n ":"if (a < 0.0) { return b * a; } return a;";case i.MAX:return u("max",t);case i.MIN:return u("min",t);case i.POW:return t?o:"\n if(a < 0.0 && floor(b) < b) {\n return uniforms.NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n if (round(abs(b) % 2.0) != 1.0) {\n return pow(abs(a), b);\n }\n return sign(a) * pow(abs(a), b);\n ";case i.COMPLEX_MULTIPLY_REAL:return"return areal * breal - aimag * bimag;";case i.COMPLEX_MULTIPLY_IMAG:return"return areal * bimag + aimag * breal;";default:throw new Error(`BinaryType ${e} is not implemented!`)}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var l;!function(e){e[e.ABS=0]="ABS",e[e.CEIL=1]="CEIL",e[e.COS=2]="COS",e[e.COSH=3]="COSH",e[e.ELU=4]="ELU",e[e.EXP=5]="EXP",e[e.EXPM1=6]="EXPM1",e[e.FLOOR=7]="FLOOR",e[e.LINEAR=8]="LINEAR",e[e.LOG=9]="LOG",e[e.LOGICAL_NOT=10]="LOGICAL_NOT",e[e.NEG=11]="NEG",e[e.RELU=12]="RELU",e[e.RELU6=13]="RELU6",e[e.LEAKYRELU=14]="LEAKYRELU",e[e.RSQRT=15]="RSQRT",e[e.SIN=16]="SIN",e[e.SINH=17]="SINH",e[e.SIGMOID=18]="SIGMOID",e[e.SQRT=19]="SQRT",e[e.SQUARE=20]="SQUARE",e[e.TANH=21]="TANH",e[e.TO_INT=22]="TO_INT"}(l||(l={}));function d(e,t){switch(e){case l.ABS:return"return abs(a);";case l.COS:return"return cos(a);";case l.COSH:return"\n let e2x = exp(-a);\n return (e2x + 1.0 / e2x) / 2.0;\n";case l.CEIL:return"return ceil(a);";case l.ELU:return t?"\n var resFloat = exp(a) - vec4(1.0);\n if (a.r >= 0.0) {\n resFloat.r = a.r;\n }\n if (a.g >= 0.0) {\n resFloat.g = a.g;\n }\n if (a.b >= 0.0) {\n resFloat.b = a.b;\n }\n if (a.a >= 0.0) {\n resFloat.a = a.a;\n }\n return resFloat;\n":"if (a >= 0.0) { return a; } return (exp(a) - 1.0);";case l.EXP:return"return exp(a);";case l.EXPM1:return"return exp(a) - 1.0;";case l.FLOOR:return"return floor(a);";case l.LINEAR:return"return a;";case l.LOG:return"if (a < 0.0) { return 1.0/0.0; }\n return log(a);";case l.LOGICAL_NOT:return"return f32(!(a >= 1.0));";case l.NEG:return"return -a;";case l.LEAKYRELU:return t?"\n let aLessThanZero = vec4(a < vec4(0.0));\n return (aLessThanZero * (uniforms.alpha * a)) + ((vec4(1.0) - aLessThanZero) * a);\n":"if (a < 0.0) { return uniforms.alpha * a; } return a;";case l.RELU:return t?"\n var resFloat = a * vec4(a >= vec4(0.0));\n let isNaN = isnanVec4(a);\n\n if (isNaN.r) {\n resFloat.r = a.r;\n }\n if (isNaN.g) {\n resFloat.g = a.g;\n }\n if (isNaN.b) {\n resFloat.b = a.b;\n }\n if (isNaN.a) {\n resFloat.a = a.a;\n }\n return resFloat;\n":"if(a < 0.0) { return 0.0; } return a;";case l.RELU6:return t?"return clamp(a, vec4(0.0, 0.0, 0.0, 0.0), vec4(6.0, 6.0, 6.0, 6.0));":"return clamp(a, 0.0, 6.0);";case l.RSQRT:return"return 1.0/sqrt(a);";case l.SIGMOID:return"return 1.0 / (1.0 + exp(-1.0 * a));";case l.SIN:return"return sin(a);";case l.SINH:return"\n let e2x = exp(a);\n return (e2x - 1.0 / e2x) / 2.0;\n";case l.SQRT:return"return sqrt(a);";case l.SQUARE:return"return a * a;";case l.TANH:return"\n let e2x = exp(-2.0 * abs(a));\n return sign(a) * (1.0 - e2x) / (1.0 + e2x);\n";case l.TO_INT:return"return f32(i32((a)));";default:throw new Error(`BinaryType ${e} is not implemented!`)}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function p(e,t=!1){if(null===e)return null;if("linear"===e)return d(l.LINEAR);if("relu"===e)return d(l.RELU,t);if("elu"===e)return d(l.ELU,t);if("relu6"===e)return d(l.RELU6,t);if("prelu"===e)return c(i.PRELU,t);if("sigmoid"===e)return d(l.SIGMOID,t);if("leakyrelu"===e)return d(l.LEAKYRELU,t);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function h(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");const n=e.length,r=e.map((e=>`${t}[${e}]`)),a=new Array(n-1);a[n-2]=r[n-1];for(let e=n-3;e>=0;--e)a[e]=`(${a[e+1]} * ${r[e+1]})`;return a} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function f(e){if(e<=1)return"i32";if(2===e)return"vec2";if(3===e)return"vec3";if(4===e)return"vec4";if(5===e)return"vec5";if(6===e)return"vec6";throw Error(`GPU for rank ${e} is not yet supported`)}function m(e){if(0===e)return"x";if(1===e)return"y";if(2===e)return"z";if(3===e)return"w";if(4===e)return"u";if(5===e)return"v";throw Error(`Index ${e} is not yet supported`)}function b(e,t){return"float32"===e?t?"vec4":"f32":"int32"===e||"bool"===e?t?"vec4":"i32":e}function g(e,t,n,a=!1){const i=[];if(i.push(`\n let workGroupSizeX = ${n.workGroupSize[0]}u;\n let workGroupSizeY = ${n.workGroupSize[1]}u;\n let workGroupSizeZ = ${n.workGroupSize[2]}u;\n\n var localId: vec3;\n var globalId: vec3;\n var numWorkgroups: vec3;\n\n // Only used when the y/z dimension of workgroup size is 1.\n fn getGlobalIndex() -> i32 {\n if (numWorkgroups.y == 1u && numWorkgroups.z == 1u) {\n return i32(globalId.x);\n }\n\n let localInvocationIndex = localId.z * workGroupSizeX * workGroupSizeY +\n localId.y * workGroupSizeX + localId.x;\n let workGroupID = (globalId - localId)/vec3(\n workGroupSizeX, workGroupSizeY, workGroupSizeZ);\n\n return i32((workGroupID.z * numWorkgroups.x * numWorkgroups.y +\n workGroupID.y * numWorkgroups.x + workGroupID.x) *\n (workGroupSizeX * workGroupSizeY * workGroupSizeZ) +\n localInvocationIndex);\n }\n `),!0===a)return i.push(`\n struct Uniform {\n size : i32,\n numChannels : i32,\n outShapeStrides : vec2,\n dispatchSize : vec3,\n };\n\n @group(0) @binding(0) var result: array<${b(t.dtype,n.isVec4)}>;\n @group(0) @binding(2) var uniforms: Uniform;\n `),[x,i.join("\n"),k(t.shape),n.getUserCode()].join("\n");let s=!1,o=!1,u="struct Uniforms { NAN : f32, ";n.variableNames.forEach(((t,n)=>{const r=f(e[n].shape.length);"vec5"!==r&&"vec6"!==r||(o=!0),(s||o)&&(u+="@align(16) "),s=o,u+=`${t.charAt(0).toLowerCase()+t.slice(1)}Shape : ${r}, `}));const c=f(t.shape.length);o="vec5"===c||"vec6"===c,(s||o)&&(u+="@align(16) "),s=o,u+=`outShape : ${c}, `;const l=f(t.shape.length-1);o="vec5"===l||"vec6"===l,(s||o)&&(u+="@align(16) "),s=o,u+=`\n outShapeStrides: ${l}, `,n.size&&(s&&(u+="@align(16) "),s=!1,u+="size : i32, "),n.uniforms&&(s&&(u+="@align(16) "),u+=n.uniforms),u+="};",i.push(u),n.atomic?i.push("\n @group(0) @binding(0) var result: array>;\n "):i.push(`\n @group(0) @binding(0) var result: array<${b(t.dtype,n.isVec4)}>;\n `),n.variableNames.forEach(((t,r)=>{i.push(`\n @group(0) @binding(${1+r}) var ${t}: array<${b(e[r].dtype,n.isVec4)}>;\n `)})),""!==u&&i.push(`\n @group(0) @binding(${1+n.variableNames.length}) var uniforms: Uniforms;\n `);const[d,p]=function(e,t){const{x:n,y:r=[],z:a=[]}=t,i=e.length;if(n.length===i){return[`fn getOutputCoords() -> ${f(i)}{\n let globalIndex = getGlobalIndex();\n return getCoordsFromIndex(globalIndex);\n }\n `,i]}let s="";const o=[n,r,a];let u=0;for(let e=0;e ${l} {\n ${s}\n `;0===c.length?d+=`return ${l}(0); }`:d+=`return ${l}(${c.join(",")}); }`;return[d,u]}(t.shape,n.dispatchLayout),g=[x,i.join("\n"),k(t.shape),d,v(t.shape.length)];if(n.atomic||g.push(function(e,t,n){const r=e.length,a=b(t,n);let i;i=n?`fn setOutputAtIndex(flatIndex : i32, value : vec4) {\n result[flatIndex] = ${a}(value);\n }\n fn setOutputAtIndexI32(flatIndex : i32, value : vec4) {\n result[flatIndex] = ${a}(value);\n }`:`fn setOutputAtIndex(flatIndex : i32, value : f32) {\n result[flatIndex] = ${a}(value);\n }\n fn setOutputAtIndexI32(flatIndex : i32, value : i32) {\n result[flatIndex] = ${a}(value);\n }`;if(r>=2){const e=["d0","d1","d2","d3","d4","d5"].slice(0,r),t=f(r);i+=n?`\n fn setOutputAtCoords(${e.map((e=>`${e} : i32`)).join(", ")}, value : vec4) {\n let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));\n setOutputAtIndex(flatIndex / 4, value);\n }\n fn setOutputAtCoordsI32(${e.map((e=>`${e} : i32`)).join(", ")}, value : vec4) {\n let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));\n setOutputAtIndexI32(flatIndex / 4, value);\n }\n `:`\n fn setOutputAtCoords(${e.map((e=>`${e} : i32`)).join(", ")}, value : f32) {\n let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));\n setOutputAtIndex(flatIndex, value);\n }\n fn setOutputAtCoordsI32(${e.map((e=>`${e} : i32`)).join(", ")}, value : i32) {\n let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));\n setOutputAtIndexI32(flatIndex, value);\n }\n `}return i}(t.shape,t.dtype,n.isVec4)),p===t.shape.length){const a=e.map((e=>function(e,t,n,a){let i=function(e,t){const n=e.name,r=e.shape.length,a=f(r),i="get"+n.charAt(0).toUpperCase()+n.slice(1),s=["d0","d1","d2","d3","d4","d5"].slice(0,r),o=s.map((e=>`${e} : i32`)).join(", ");if(r<1)return t?`\n fn ${i}() -> vec4 {\n return vec4(${n}[0]);\n }\n `:`\n fn ${i}() ->f32 {\n return f32(${n}[0]);\n }\n `;const u=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`;let c=`${r}D`;0===r&&(c="1D");if(t)return`\n fn ${i}(${o}) -> vec4 {\n return vec4(${n}[getIndexFromCoords${c}(${a}(${s.join(",")}),\n ${u}) / 4]);\n }\n `;return`\n fn ${i}(${o}) -> f32 {\n return f32(${n}[getIndexFromCoords${c}(${a}(${s.join(",")}),\n ${u})]);\n }\n `}(e,n);e.shape.length<=t.length&&(i+=function(e,t,n,a){const i=e.name,s=i.charAt(0).toUpperCase()+i.slice(1),o="get"+s+"ByOutput",u=e.shape.length,c=t.length,l=f(c);if(r.util.arraysEqual(e.shape,t)&&a)return n?`\n fn ${o}Index(globalIndex : i32) -> vec4 {\n return vec4(${i}[globalIndex]);\n }\n\n fn ${o}Coords(coords : ${l}) -> vec4 {\n return vec4(${i}[${c>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);\n }\n `:`\n fn ${o}Index(globalIndex : i32) -> f32 {\n return f32(${i}[globalIndex]);\n }\n\n fn ${o}Coords(coords : ${l}) -> f32 {\n return f32(${i}[${c>1?"getOutputIndexFromCoords(coords)":"coords"}]);\n }\n `;const d=r.backend_util.getBroadcastDims(e.shape,t),p=c-u;let h="";if(0===u)return n?`\n fn ${o}Index(globalIndex : i32) -> vec4 {\n return get${s}();\n }\n\n fn ${o}Coords(coords : ${l}) -> vec4 {\n return get${s}();\n }\n `:`\n fn ${o}Index(globalIndex : i32) -> f32{\n return get${s}();\n }\n\n fn ${o}Coords(coords : ${l}) -> f32{\n return get${s}();\n }\n `;h=c<2&&d.length>=1?"coords = 0;":d.map((e=>`coords.${m(e+p)} = 0;`)).join("\n");let b="";if(c<2&&u>0)b="coords";else if(c>1){b=`${f(u)}(${e.shape.map(((e,t)=>`coords.${m(t+p)}`)).join(", ")})`}else b="coords";const g=`uniforms.${i.charAt(0).toLowerCase()+i.slice(1)}Shape`,x=`${u}D`;if(n)return`\n fn ${o}Index(globalIndex : i32) -> vec4 {\n var coords = getCoordsFromIndex(globalIndex);\n ${h}\n return ${i}[getIndexFromCoords${x}(${b}, ${g}) / 4];\n }\n\n fn ${o}Coords(coordsIn : ${l}) -> vec4 {\n var coords = coordsIn;\n ${h}\n return ${i}[getIndexFromCoords${x}(${b}, ${g}) / 4];\n }\n `;return`\n fn ${o}Index(globalIndex : i32) -> f32 {\n var coords = getCoordsFromIndex(globalIndex);\n ${h}\n return f32(${i}[getIndexFromCoords${x}(${b}, ${g})]);\n }\n\n fn ${o}Coords(coordsIn : ${l}) -> f32 {\n var coords = coordsIn;\n ${h}\n return f32(${i}[getIndexFromCoords${x}(${b}, ${g})]);\n }\n `}(e,t,n,a));return i}(e,t.shape,n.isVec4,n.dispatchLayout.x.length===t.shape.length))).join("\n");g.push(a)}g.push(n.getUserCode());return g.join("\n")}const x="\n struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};\n struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};\n\n // Checks whether coordinates lie within the bounds of the shape.\n fn coordsInBounds2D(coord : vec2, shape : vec2) -> bool {\n return all(coord >= vec2(0)) && all(coord < shape);\n }\n fn coordsInBounds3D(coord : vec3, shape : vec3) -> bool {\n return all(coord >= vec3(0)) && all(coord < shape);\n }\n fn coordsInBounds4D(coord : vec4, shape : vec4) -> bool {\n return all(coord >= vec4(0)) && all(coord < shape);\n }\n\n fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {\n return coord;\n }\n fn getIndexFromCoords2D(coords : vec2, shape : vec2) -> i32 {\n return dot(coords, vec2(shape.y, 1));\n }\n fn getIndexFromCoords3D(coords : vec3, shape : vec3) -> i32 {\n return dot(coords, vec3(shape.y * shape.z, shape.z, 1));\n }\n fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n }\n fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {\n let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;\n }\n fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {\n let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;\n }\n\n fn idiv(a: i32, b: i32, sign: f32) -> i32 {\n var res: i32 = a / b;\n let mod: i32 = a % b;\n if (sign < 0. && mod != 0) {\n res = res - 1;\n }\n return res;\n }\n\n // NaN defination in IEEE 754-1985 is :\n // - sign = either 0 or 1.\n // - biased exponent = all 1 bits.\n // - fraction = anything except all 0 bits (since all 0 bits represents infinity).\n // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers\n fn isnan(val: f32) -> bool {\n let floatToUint: u32 = bitcast(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n fn isnanVec4(val : vec4) -> vec4 {\n return vec4(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3]));\n }\n";function v(e){let t="";switch(e){case 0:case 1:t+="\n fn getOutputIndexFromCoords(coords : i32) -> i32 {\n return coords;\n }\n ";break;case 2:t+="\n fn getOutputIndexFromCoords(coords : vec2) -> i32 {\n return dot(coords, vec2(uniforms.outShapeStrides, 1));\n }\n ";break;case 3:t+="\n fn getOutputIndexFromCoords(coords : vec3) -> i32 {\n return dot(coords, vec3(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));\n }\n ";break;case 4:t+="\n fn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));\n }\n ";break;case 5:t+="\n fn getOutputIndexFromCoords(coords : vec5) -> i32 {\n return coords.x * uniforms.outShapeStrides.x +\n coords.y * uniforms.outShapeStrides.y +\n coords.z * uniforms.outShapeStrides.z +\n coords.w * uniforms.outShapeStrides.w +\n coords.u;\n }\n ";break;case 6:t+="\n fn getOutputIndexFromCoords(coords : vec6) -> i32 {\n return coords.x * uniforms.outShapeStrides.x +\n coords.y * uniforms.outShapeStrides.y +\n coords.z * uniforms.outShapeStrides.z +\n coords.w * uniforms.outShapeStrides.w +\n coords.u * uniforms.outShapeStrides.u +\n coords.v;\n }\n ";break;default:r.util.assert(!1,(()=>`Unsupported ${e}D shape`))}return t}function k(e){const t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";const n=r.util.computeStrides(e),a=f(t),i=[];for(let e=0;e vec2 {\n let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;\n return vec2(d0, d1);\n }";let s;return s="var index2 = index;"+n.map(((e,t)=>`${`let ${i[t]} = index2 / uniforms.outShapeStrides.${m(t)}`}; ${t===n.length-1?`let ${i[t+1]} = index2 - ${i[t]} * uniforms.outShapeStrides.${m(t)}`:`index2 = index2 - ${i[t]} * uniforms.outShapeStrides.${m(t)}`};`)).join(""),`\n fn getCoordsFromIndex(index : i32) -> ${a} {\n ${s}\n return ${a}(${i.join(",")});\n }\n `}const y=e=>{let t=1;for(let n=0;nt%e[n]==0))}function I(e,t,n=[1,1,1],r=[1,1,1]){const[a,i,s]=[Math.ceil(y(e.x.map((e=>t[e])))/(n[0]*r[0])),e.y?Math.ceil(y(e.y.map((e=>t[e])))/(n[1]*r[1])):1,e.z?Math.ceil(y(e.z.map((e=>t[e])))/(n[2]*r[2])):1];return[a,i,s]}function S(e,t){const n=y(e.x.map((e=>t[e]))),r=y(e.y.map((e=>t[e])));return n<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function _(e,t){const n=y(e.x.map((e=>t[e]))),r=y(e.y.map((e=>t[e])));return n<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function C(e){return{x:e.map(((e,t)=>t))}}function O(e){if("float32"===e||"int32"===e||"bool"===e||"string"===e)return 4;if("complex64"===e)return 8;throw new Error(`Unknown dtype ${e}`)}function T(){return("undefined"!=typeof window||"undefined"!=typeof WorkerGlobalScope)&&!!navigator.gpu} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function $(e,t,n,a){return r.util.assert(a%4==0&&4===e[0],(()=>"tileInner must be divisible by 4. And ColPerThread must be 4")),`\n var mm_Asub : array, ${a/e[0]}>, ${t}>;\n var mm_Bsub : array, ${n/e[0]}>, ${a}>;\n\n let RowPerThread = ${e[1]};\n let ColPerThread = ${e[0]};\n let TileInner = ${a};\n\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n\n let tileRow = ${1===t?"0":"i32(localId.y) * RowPerThread"};\n let tileCol = i32(localId.x);\n\n let globalRow = ${1===t?"0":"i32(globalId.y) * RowPerThread"};\n let globalCol = i32(globalId.x);\n let numTiles = (uniforms.dimInner - 1) / TileInner + 1;\n\n var acc: array, RowPerThread>;\n var ACached : vec4;\n var BCached : array, 4>;\n\n // Loop over shared dimension.\n var globalColA = tileCol;\n let RowPerThreadB = TileInner / i32(workGroupSizeY);\n let tileRowB = i32(localId.y) * RowPerThreadB;\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n mm_Asub[inputRow][inputCol] = mm_readA(globalRow + innerRow, globalColA, globalId);\n }\n globalColA = globalColA + TileInner / ColPerThread;\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(t * TileInner + inputRow, globalCol, globalId);\n }\n\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < TileInner / ColPerThread; k = k + 1) {\n BCached[0] = mm_Bsub[k * ColPerThread][tileCol];\n BCached[1] = mm_Bsub[k * ColPerThread + 1][tileCol];\n BCached[2] = mm_Bsub[k * ColPerThread + 2][tileCol];\n BCached[3] = mm_Bsub[k * ColPerThread + 3][tileCol];\n\n for (var i = 0; i < RowPerThread; i = i + 1) {\n ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached[0] * ACached.x + acc[i];\n acc[i] = BCached[1] * ACached.y + acc[i];\n acc[i] = BCached[2] * ACached.z + acc[i];\n acc[i] = BCached[3] * ACached.w + acc[i];\n }\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {\n mm_write(globalRow + innerRow,\n globalCol,\n acc[innerRow], globalId);\n }\n }`}class A{constructor(e,t,n,r,a,i=null,s=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[8,8,1],this.isVec4=!0,this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]},1===t[1]?this.elementsPerThread=[4,1,1]:this.elementsPerThread=[4,4,1],this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread);const u=null!=i,c=null!=o;u&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),this.tileAOuter=1===t[1]?1:this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=this.tileBOuter,this.aShape=e,this.addBias=u,this.activation=s,this.hasPreluActivationWeights=c,this.batchAEqualOne=r,this.batchBEqualOne=a,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`matMulPackedVec4_${this.activation}_${this.fitA}_${this.fitB}_${this.elementsPerThread}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getShapeFit(){const e=this.aShape[2],t=this.outputShape[2],n=[this.outputShape[0],e,t],r=[this.tileAOuter,this.tileInner],a=[this.tileInner,this.tileBOuter];return[w(r,this.aShape.slice(1)),w(a,n.slice(1))]}getUserCode(){const e=this.fitA?"return A[batch * batchASize + row * uniforms.dimInner / 4 + col]":"if (coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimAOuter, uniforms.dimInner))) {\n return A[batch * batchASize + row * uniforms.dimInner / 4 + col];\n }\n return vec4(0.0)",t=this.fitB?"return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":"if(coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];\n }\n return vec4(0.0)";let n="",r="";if(this.activation){const e=p(this.activation,this.isVec4);n=this.hasPreluActivationWeights?`fn activation(a : vec4, outCoord : vec3) -> vec4 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${e}\n }`:`\n fn activation(a : vec4, outCoord : vec3) -> vec4 {\n ${e}\n }`,r="value = activation(value, outCoord);"}const a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`\n ${n}\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> vec4 {\n ${this.batchAEqualOne?"\n let batchASize = 0;\n let batch = 0;\n ":"\n let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / 4;\n let batch = i32(globalId.z);\n "}\n\n ${e};\n }\n\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> vec4 {\n ${this.batchBEqualOne?"\n let batchBSize = 0;\n let batch = 0;\n ":"\n let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / 4;\n let batch = i32(globalId.z);\n "}\n ${t};\n }\n\n fn mm_write(row : i32, col : i32, valueIn : vec4, globalId : vec3) {\n if (row < uniforms.aShape[1] && col * 4 < uniforms.bShape[2])\n {\n var value = valueIn;\n let batch = i32(globalId.z);\n let outCoord = vec3(batch, row, col * 4);\n ${a}\n ${r}\n setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);\n }\n }\n ${$(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner)}\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function N(e,t){const n=t[1]*e[1],r=t[0]*e[0],a=n>r?n:r;return`\n var mm_Asub : array, ${n}>;\n var mm_Bsub : array, ${a}>;\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let tileRow = i32(localId.y) * ${e[1]};\n let tileCol = i32(localId.x) * ${e[0]};\n\n let globalRow = i32(globalId.y) * ${e[1]};\n let globalCol = i32(globalId.x) * ${e[0]};\n\n let numTiles = (uniforms.dimInner - 1) / ${a} + 1;\n\n var acc : array, ${e[1]}>;\n var ACached : f32;\n var BCached : array;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n\n let ColPerThreadA = ${a} / ${t[0]};\n let tileColA = i32(localId.x) * ColPerThreadA;\n let RowPerThreadB = ${a} / ${t[1]};\n let tileRowB = i32(localId.y) * RowPerThreadB;\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ColPerThreadA; innerCol = innerCol + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileColA + innerCol;\n\n mm_Asub[inputRow][inputCol] = mm_readA(\n globalRow + innerRow,\n t * ${a} + inputCol, globalId);\n }\n }\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n\n mm_Bsub[inputRow][inputCol] = mm_readB(\n t * ${a} + inputRow,\n globalCol + innerCol, globalId);\n }\n }\n\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < ${a}; k = k + 1) {\n for (var inner = 0; inner < ${e[0]}; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {\n ACached = mm_Asub[tileRow + innerRow][k];\n for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {\n\n if ((globalCol + innerCol) < uniforms.dimBOuter &&\n (globalRow + innerRow) < uniforms.dimAOuter) {\n mm_write(globalRow + innerRow,\n globalCol + innerCol,\n acc[innerRow][innerCol], globalId);\n }\n }\n }\n }\n `}class E{constructor(e,t,n,a,i,s=!1,o=!1,u=null,c=null,l=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[16,16,1],this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};const d=s?e[1]:e[2];this.workGroupSize=function(e,t,n){return 1===e?[32,1,1]:1===n?[1,32,1]:[8,8,1]}(t[1],0,t[2]),1!==t[1]&&1!==t[2]||(n=1),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]),r.util.arraysEqual(this.dispatch,[1,1,1])&&(n=1,this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]));const p=null!=u,h=null!=l;p&&this.variableNames.push("bias"),h&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.transposeA=s,this.transposeB=o,this.addBias=p,this.activation=c,this.hasPreluActivationWeights=h,this.batchAEqualOne=a,this.batchBEqualOne=i;const f=this.outputShape[2],m=this.transposeB?[this.outputShape[0],f,d]:[this.outputShape[0],d,f];[this.fitA,this.fitB]=this.getShapeFit(m),this.shaderKey=`matMulPacked_${this.workPerThread}_${s}_${o}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getShapeFit(e){const t=this.workGroupSize[1]*this.workPerThread,n=this.workGroupSize[0]*this.workPerThread;let a=t>n?t:n;1===this.outputShape[1]&&(a*=4),r.util.assert(a%this.workGroupSize[0]==0&&a%this.workGroupSize[1]==0,(()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y"));const i=[a,n];return[w([t,a],this.aShape.slice(1)),w(i,e.slice(1))]}getUserCode(){let e,t;e=!1===this.transposeA?this.fitA?"return A[batch * batchASize + row * uniforms.dimInner + col];":"if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) {\n return A[batch * batchASize + row * uniforms.dimInner + col];\n }\n return 0.0;":this.fitA?"return A[batch * batchASize + col * uniforms.dimAOuter + row];":"if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) {\n return A[batch* batchASize + col * uniforms.dimAOuter + row];\n }\n return 0.0;",t=!1===this.transposeB?this.fitB?"return B[batch * batchBSize + row * uniforms.dimBOuter + col];":"if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return B[batch * batchBSize + row * uniforms.dimBOuter + col];\n }\n return 0.0;":this.fitB?"return B[batch * batchBSize + col * uniforms.dimInner + row];":"if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return B[batch * batchBSize + col * uniforms.dimInner + row];\n }\n return 0.0;";let n="",r="";if(this.activation){const e=p(this.activation,!1);n=this.hasPreluActivationWeights?`fn activation(a : f32, outCoord : vec3) -> f32 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${e}\n }`:`\n fn activation(a : f32, outCoord : vec3) -> f32 {\n ${e}\n }\n `,r="value = activation(value, outCoord);"}const a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";var i;return`\n ${n}\n\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 {\n ${this.batchAEqualOne?"\n let batch = 0;\n let batchASize = 0;\n ":"\n let batch = i32(globalId.z);\n let batchASize = uniforms.aShape[1] * uniforms.aShape[2];\n "}\n ${e}\n }\n\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 {\n ${this.batchBEqualOne?"\n let batch = 0;\n let batchBSize = 0;\n ":"\n let batch = i32(globalId.z);\n let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];\n "}\n ${t}\n }\n\n fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3) {\n var value = valueIn;\n let batch = i32(globalId.z);\n let outCoord = vec3(batch, row, col);\n ${a}\n ${r}\n setOutputAtCoords(batch, row, col, value);\n }\n ${this.outputShape[1]>1?N([this.workPerThread,this.workPerThread,1],this.workGroupSize):(i=this.workGroupSize,`\n let TileSize = ${4*i[0]};\n var mm_Asub : array, ${i[0]}>;\n\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let tileCol = i32(localId.x);\n let globalCol = i32(globalId.x);\n let globalRow = i32(globalId.y);\n\n let numTiles = (uniforms.dimInner - 1) / TileSize + 1;\n\n // Without this initialization strange values show up in acc.\n var acc = 0.0;\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n let colA = t * TileSize + tileCol * 4;\n mm_Asub[tileCol] = vec4(mm_readA(globalRow, colA, globalId),\n mm_readA(globalRow, colA + 1, globalId),\n mm_readA(globalRow, colA + 2, globalId),\n mm_readA(globalRow, colA + 3, globalId));\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < TileSize / 4; k = k + 1) {\n let rowB = t * TileSize + k * 4;\n let BCached = vec4(mm_readB(rowB, globalCol, globalId),\n mm_readB(rowB + 1, globalCol, globalId),\n mm_readB(rowB + 2, globalCol, globalId),\n mm_readB(rowB + 3, globalCol, globalId));\n\n let ACached = mm_Asub[k];\n acc = acc + dot(ACached, BCached);\n }\n\n workgroupBarrier();\n }\n\n if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) {\n mm_write(globalRow, globalCol, acc, globalId);\n }\n }\n `)}\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class R{constructor(e,t,n,r=!1,a=!1,i=null,s=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize);const u=null!=i,c=null!=o;u&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),this.transposeA=r,this.transposeB=a,this.addBias=u,this.activation=s,this.hasPreluActivationWeights=c,this.batchAEqualOne=t,this.batchBEqualOne=n,this.shaderKey=`matMulReduce_${this.activation}_${r}_${a}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){let e,t;e=!1===this.transposeA?"return f32(A[batch * batchASize + row * uniforms.dimInner + col]);":"return f32(A[batch * batchASize + col * uniforms.dimAOuter + row]);",t=!1===this.transposeB?"return f32(B[batch * batchBSize + row * uniforms.dimBOuter + col]);":"return f32(B[batch * batchBSize + col * uniforms.dimInner + row]);";let n="",r="";if(this.activation){const e=p(this.activation,!1);n=this.hasPreluActivationWeights?`fn activation(a : f32, outCoord : vec3) -> f32 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${e}\n }`:`\n fn activation(a : f32, outCoord : vec3) -> f32 {\n ${e}\n }\n `,r="value = activation(value, outCoord);"}const a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`\n ${n}\n\n fn mm_readA(batchIn: i32, row : i32, col : i32) -> f32 {\n ${this.batchAEqualOne?"\n let batchASize = 0;\n let batch = 0;\n ":"\n let batchASize = uniforms.aShape[1] * uniforms.aShape[2];\n let batch = batchIn;\n "}\n ${e}\n }\n\n fn mm_readB(batchIn: i32, row : i32, col : i32) -> f32 {\n ${this.batchBEqualOne?"\n let batch = 0;\n let batchBSize = 0;\n ":"\n let batch = batchIn;\n let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];\n "}\n ${t}\n }\n\n fn mm_write(batch: i32, row : i32, col : i32, valueIn : f32) {\n var value = valueIn;\n let outCoord = vec3(batch, row, col);\n ${a}\n ${r}\n setOutputAtCoords(batch, row, col, value);\n }\n \n var sumValues : array;\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let coords = getOutputCoords();\n let batch = coords[0];\n let row = coords[1];\n let col = coords[2];\n var sum = 0.0;\n let Length = uniforms.dimInner;\n for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) {\n let dataA = mm_readA(batch, row, k);\n let dataB = mm_readB(batch, k, col);\n sum = sum + dataA * dataB;\n }\n sumValues[localId.x] = sum;\n workgroupBarrier();\n\n for(var currentSize = workGroupSizeX / 2u; currentSize > 1u;\n currentSize = currentSize / 2u) {\n if (localId.x < currentSize)\n {\n sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];\n }\n workgroupBarrier();\n }\n\n if (localId.x == 0u) {\n sum = sumValues[0] + sumValues[1];\n mm_write(batch, row, col, sum);\n }\n }\n \n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class F{constructor(e,t,n,a=null,i=null,s=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[8,16,1],r.util.assert(e[1]<=16||t[2]<=16,(()=>"This program can be only used when A width or B Height are small")),this.outputShape=n,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(n[2]/this.workGroupSize[0]),Math.ceil(2*n[1]/this.workGroupSize[1]),n[0]];const o=null!=a;o&&this.variableNames.push("bias");const u=null!=s;u&&this.variableNames.push("preluActivationWeights"),this.addBias=o,this.activation=i,this.hasPreluActivationWeights=u,this.batchAEqualOne=1===e[0],this.batchBEqualOne=1===t[0],this.shaderKey=`matMulSmallOutputSize_${this.activation}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){let e="",t="";if(this.activation){const n=p(this.activation,!1);e=this.hasPreluActivationWeights?`fn activation(a : f32, outCoord : vec3) -> f32 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${n}\n }`:`fn activation(a : f32, outCoord : vec3) -> f32 {\n ${n}\n }`,t="value = activation(value, outCoord);"}const n=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`\n ${e}\n\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 {\n ${this.batchAEqualOne?"\n let batch = 0;\n let batchASize = 0;\n ":"\n let batchASize = uniforms.aShape[1] * uniforms.aShape[2];\n let batch = i32(globalId.z);\n "}\n if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) {\n return A[batch * batchASize + row * uniforms.dimInner + col];\n }\n return 0.0;\n }\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 {\n ${this.batchBEqualOne?"\n let batch = 0;\n let batchBSize = 0;\n ":"\n let batch = i32(globalId.z);\n let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];\n "}\n if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return B[batch * batchBSize + row * uniforms.dimBOuter + col];\n }\n return 0.0;\n }\n fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3) {\n if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimBOuter))) {\n let batch = i32(globalId.z);\n let outCoord = vec3(batch, row, col);\n var value = valueIn;\n ${n}\n ${t}\n setOutputAtCoords(batch, row, col, value);\n }\n }\n ${function(e){const t=e[1]/2,n=e[0],r=t>n?t:n;return`\n var mm_Asub1 : array, ${t}>;\n var mm_Bsub1 : array, ${r}>;\n var mm_Asub2 : array, ${t}>;\n var mm_Bsub2 : array, ${r}>;\n\n // If the output size is small for matrix multiplication, avoid to use vec4\n // and handle some elements per thread to optimally utilize the ALU.\n // Introduces two shared memory buffers, some logical threads could handle\n // arithmetic operations and others handle IO operations between barrier api,\n // makes ALUs and load/store units work simultaneously, could improves\n // the performance.\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let tileRow = i32(localId.y);\n let tileCol = i32(localId.x);\n let globalRow = i32(globalId.y);\n let globalCol = i32(globalId.x);\n\n // uniforms.dimInner should be greater than 0.\n let numTiles = (uniforms.dimInner - 1) / ${r} + 1;\n var acc = 0.0;\n\n var globalColA = tileCol;\n var globalRowB = tileRow;\n for (var t = 0; t < numTiles; t = t + 1) {\n if (t == 0) {\n if (tileRow < ${t}) {\n // Load one tile of A and B into local memory.\n // globalRow is always greater than or equal tileRow.\n mm_Asub1[tileRow][tileCol] =\n mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);\n globalColA = globalColA + ${r};\n mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);\n globalRowB = globalRowB + ${r};\n }\n } else {\n if (tileRow < ${t}) {\n // Load one tile of A and B into local memory.\n // globalRow is always greater than or equal tileRow.\n mm_Asub1[tileRow][tileCol] =\n mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);\n globalColA = globalColA + ${r};\n mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);\n globalRowB = globalRowB + ${r};\n } else {\n // Compute acc values for a single thread.\n for (var k = 0; k < ${r}; k = k + 1) {\n let subRow = tileRow - ${t};\n if (subRow < 0) {\n continue;\n }\n acc = acc + mm_Asub2[subRow][k] * mm_Bsub2[k][tileCol];\n }\n }\n }\n workgroupBarrier();\n if (t != 0) {\n t = t + 1;\n }\n\n if (t < numTiles) {\n if (tileRow < ${t}) {\n // Load one tile of A and B into local memory.\n // globalRow is always greater than or equal tileRow.\n mm_Asub2[tileRow][tileCol] =\n mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);\n globalColA = globalColA + ${r};\n mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);\n globalRowB = globalRowB + ${r};\n } else {\n // Compute acc values for a single thread.\n for (var k = 0; k < ${r}; k = k + 1) {\n let subRow = tileRow - ${t};\n if (subRow < 0) {\n continue;\n }\n acc = acc + mm_Asub1[subRow][k] * mm_Bsub1[k][tileCol];\n }\n }\n }\n workgroupBarrier();\n }\n let writeCol = (globalRow - tileRow) / 2 + tileRow - ${t};\n if (tileRow >= ${t} && writeCol >= 0) {\n mm_write(writeCol, globalCol, acc, globalId);\n }\n }\n `}(this.workGroupSize)}\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function M(e){const{inputs:t,attrs:n}=e,{x:a}=t,{shape:i}=n,s=r.util.sizeFromShape(a.shape),o=r.util.inferFromImplicitShape(i,s),u=r.util.sizeFromShape(o);return r.util.assert(s===u,(()=>`The new shape (${o}) has ${u} elements and the old shape (${a.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`)),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:o,dtype:a.dtype}}const D={kernelName:r.Reshape,backendName:"webgpu",kernelFunc:M}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function P({a:e,b:t,transposeA:n,transposeB:a,backend:i,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:u=0,activation:c=null}){const l=e.shape.length,d=t.shape.length,p=n?e.shape[l-2]:e.shape[l-1],h=a?t.shape[d-1]:t.shape[d-2],f=n?e.shape[l-1]:e.shape[l-2],m=a?t.shape[d-2]:t.shape[d-1],b=e.shape.slice(0,-2),g=t.shape.slice(0,-2),x=r.util.sizeFromShape(b),v=r.util.sizeFromShape(g),k=r.broadcast_util.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([f,m]);r.util.assert(p===h,(()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`));const y=n?[x,p,f]:[x,f,p],w=a?[v,m,h]:[v,h,m],I=M({inputs:{x:e},backend:i,attrs:{shape:y}}),S=M({inputs:{x:t},backend:i,attrs:{shape:w}}),_=[I,S],C=Math.max(x,v),O=1===x,T=1===v,$=p%4==0&&m%4==0&&!n&&!a;let N;N=f*m<=32?new R([C,f,m],O,T,n,a,s,c,o):n||a||!(f<=16&&(m<=512||h>=2*m)||m<=16&&(f<=512||p>=2*f))?$?new A(y,[C,f,m],Object(r.env)().get("WEBGPU_MATMUL_WORK_PER_THREAD"),O,T,s,c,o):new E(y,[C,f,m],Object(r.env)().get("WEBGPU_MATMUL_WORK_PER_THREAD"),O,T,n,a,s,c,o):new F(y,w,[C,f,m],s,c,o);const D=[I,S];s&&D.push(s),o&&D.push(o);const P=[{type:"int32",data:[f]},{type:"int32",data:[m]},{type:"int32",data:[p]}];"leakyrelu"===c&&(P.push({type:"float32",data:[u]}),N.uniforms+=" alpha : f32,");const B=i.runWebGPUProgram(N,D,e.dtype,P),j=M({inputs:{x:B},backend:i,attrs:{shape:k}});_.push(B);for(const e of _)i.disposeData(e.dataId);return j} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const B={kernelName:r._FusedMatMul,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:i,bias:s,preluActivationWeights:o}=t,{transposeA:u,transposeB:c,activation:l,leakyreluAlpha:d}=r;return P({a:a,b:i,transposeA:u,transposeB:c,backend:n,bias:s,preluActivationWeights:o,leakyreluAlpha:d,activation:l})}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class j{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return`\n fn binaryOpComplex(\n areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {\n ${c(this.op,!1)}\n }\n\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if(index < uniforms.size) {\n let areal = getARealByOutputIndex(index);\n let aimag = getAImagByOutputIndex(index);\n let breal = getBRealByOutputIndex(index);\n let bimag = getBImagByOutputIndex(index);\n setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag));\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class L{constructor(e,t,n,a){this.variableNames=["A","B"],this.size=!0;this.workGroupSize=[256,1,1],this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n),this.dispatchLayout=C(this.outputShape),this.lastDimensionSize=a?n[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=a,this.op=e,this.shaderKey=`binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`}getUserCode(){const e=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",t=this.useSharedMemoryWithB?`let a = getAByOutputCoords(coords);\n let b = sharedBuf[${e}];`:`let a = sharedBuf[${e}];\n let b = getBByOutputCoords(coords);`;return`\n fn binaryOperation(a : f32, b : f32) -> f32 {\n ${c(this.op,!1)}\n }\n var sharedBuf : array;\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n // Fill in the shared memory buffer. Here we need a loop to make sure\n // that all data in A|B are uploaded when |sharedMemorySize| is larger\n // than work group size.\n for(var localIndex = i32(localId.x); localIndex < ${this.lastDimensionSize}; localIndex = localIndex + ${this.workGroupSize[0]}) {\n sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}[localIndex]);\n }\n workgroupBarrier();\n\n for(var i = 0; i < ${this.workPerThread}; i = i + 1) {\n let flatIndex = index * ${this.workPerThread} + i;\n if(flatIndex < uniforms.size) {\n let coords = getCoordsFromIndex(flatIndex);\n\n ${t}\n setOutputAtIndex(flatIndex, binaryOperation(a, b));\n }\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class z{constructor(e,t,n){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;this.workGroupSize=[128,1,1],this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.op=e,this.shaderKey=`binaryVec4_${e}`}getUserCode(){return`\n fn binaryOperation(a : vec4, b : vec4) -> vec4 {\n ${c(this.op,this.isVec4)}\n }\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let a = getAByOutputIndex(index);\n let b = getBByOutputIndex(index);\n setOutputAtIndex(index, binaryOperation(a, b));\n }\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class W{constructor(e,t,n){this.variableNames=["A","B"],this.size=!0;this.workGroupSize=[128,1,1],this.outputShape=r.backend_util.assertAndGetBroadcastShape(t,n),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binary_${e}`,this.op=e}getUserCode(){return`\n fn binaryOperation(a : f32, b : f32) -> f32 {\n ${c(this.op,!1)}\n }\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let a = getAByOutputIndex(index);\n let b = getBByOutputIndex(index);\n setOutputAtIndex(index, binaryOperation(a, b));\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function G(e,t,n){if(r.util.arraysEqual(t,n)&&r.util.sizeFromShape(t)%4==0)return new z(e,t,n);const a=1===t.length&&n.length>1&&t[0]<1024,i=1===n.length&&t.length>1&&n[0]<1024;return a||i?new L(e,t,n,i):new W(e,t,n)} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function U(e){const{inputs:t}=e,{x:n}=t;return e.backend.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const V={kernelName:r.Identity,backendName:"webgpu",kernelFunc:U}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function H(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,i=n.makeTensorInfo(r.shape,"complex64"),s=n.tensorMap.get(i.dataId),o=U({inputs:{x:r},backend:n}),u=U({inputs:{x:a},backend:n});return s.complexTensorInfos={real:o,imag:u},i}const q={kernelName:r.Complex,backendName:"webgpu",kernelFunc:H}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class K{constructor(e,t){this.variableNames=["A"],this.size=!0;this.workGroupSize=[128,1,1],this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`\n fn unaryOperation(a : f32) -> f32 {\n ${d(this.op,!1)}\n }\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let a = getAByOutputIndex(index);\n setOutputAtIndex(index, unaryOperation(a));\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function X({opType:e,cpuKernelImpl:t,dtype:n}){return({inputs:r,backend:a})=>{const{x:i}=r,s=a,o=n||i.dtype;if(s.shouldExecuteOnCPU([i])&&null!=t){const e=s.tensorMap.get(i.dataId),n=t(e.values,o);return s.makeTensorInfo(i.shape,o,n)}const u=new K(i.shape,e);return s.runWebGPUProgram(u,[i],o)}}function Y({opSnippet:e,cpuKernelImpl:t,supportsComplex:n=!1,dtype:a}){return({inputs:s,backend:o})=>{const{a:u,b:c}=s,l=o;if(n&&"complex64"===u.dtype){const t=l.tensorMap.get(u.dataId),n=l.tensorMap.get(c.dataId);let a,s;if(e!==i.MUL)[a,s]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,a]=t,i={dataId:n.dataId,dtype:n.dtype,shape:u.shape},s={dataId:a.dataId,dtype:a.dtype,shape:c.shape},o=G(e,u.shape,c.shape);return l.runWebGPUProgram(o,[i,s],Object(r.upcastType)(n.dtype,a.dtype))}));else{const e=new j(i.COMPLEX_MULTIPLY_REAL,u.shape,c.shape),r=new j(i.COMPLEX_MULTIPLY_IMAG,u.shape,c.shape),o=[{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:u.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:u.shape},{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:c.shape},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:c.shape}];a=l.runWebGPUProgram(e,o,"float32"),s=l.runWebGPUProgram(r,o,"float32")}const o=H({inputs:{real:a,imag:s},backend:l});return l.disposeData(a.dataId),l.disposeData(s.dataId),o}const d=a||Object(r.upcastType)(u.dtype,c.dtype);if(("string"===u.dtype||"string"===c.dtype||l.shouldExecuteOnCPU([u,c]))&&null!=t){const e=l.tensorMap.get(u.dataId).values,n=l.tensorMap.get(c.dataId).values,a="string"===u.dtype?r.backend_util.fromUint8ToStringArray(e):e,i="string"===u.dtype?r.backend_util.fromUint8ToStringArray(n):n,[s,o]=t(u.shape,c.shape,a,i,d);return l.makeTensorInfo(o,d,s)}const p=G(e,u.shape,c.shape);return l.runWebGPUProgram(p,[u,c],d)}}var Z=n(41); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const{addImpl:Q,ceilImpl:J,concatImpl:ee,equalImpl:te,expImpl:ne,expm1Impl:re,floorImpl:ae,gatherNdImpl:ie,gatherV2Impl:se,greaterEqualImpl:oe,greaterImpl:ue,lessEqualImpl:ce,lessImpl:le,logImpl:de,maxImpl:pe,maximumImpl:he,minimumImpl:fe,multiplyImpl:me,negImpl:be,notEqualImpl:ge,prodImpl:xe,rangeImpl:ve,rsqrtImpl:ke,simpleAbsImpl:ye,sliceImpl:we,stridedSliceImpl:Ie,stringNGramsImpl:Se,subImpl:_e,tileImpl:Ce,topKImpl:Oe,transposeImpl:Te,uniqueImpl:$e}=Z,Ae=X({opType:l.ABS,cpuKernelImpl:ye}),Ne={kernelName:r.Abs,backendName:"webgpu",kernelFunc:Ae},Ee=Y({opSnippet:i.ADD,cpuKernelImpl:Q,supportsComplex:!0}),Re={kernelName:r.Add,backendName:"webgpu",kernelFunc:Ee}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Fe{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map(((e,t)=>`T${t}`)),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){const e=[];this.variableNames.forEach((t=>{e.push(`let v${t} = get${t}ByOutputCoords(coords);`)}));const t=this.variableNames.map((e=>`v${e}`)).join(" + ");return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n for (var i = 0; i < ${this.workPerThread}; i = i + 1) {\n let flatIndex = index * ${this.workPerThread} + i;\n if (flatIndex < uniforms.size) {\n let coords = getCoordsFromIndex(flatIndex);\n ${e.join("\n ")}\n setOutputAtIndex(flatIndex, ${t});\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Me={kernelName:r.AddN,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,a=t;if(1===a.length)return U({inputs:{x:a[0]},backend:n});const i=a.map((e=>e.dtype)).reduce(((e,t)=>Object(r.upcastType)(e,t))),s=a.map((e=>e.shape)),o=new Fe(s);return n.runWebGPUProgram(o,a,i)}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class De{constructor(e,t,n){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;const a=[t];r.backend_util.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),a,e.length),this.op="min"===n?"<":">";const[i]=r.backend_util.computeOutAndReduceShapes(e,a);this.outputShape=0===i.length?[1]:i,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,[1,1,1]),this.inputShape=e,this.shaderKey=`argMinMax${this.op}`}getUserCode(){return`\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n\n ${`\n var xBestIndices : array;\n var xBestValues : array;\n `}\n\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n let outputIndex = index / i32(workGroupSizeX);\n let reduceLength = ${(()=>1===this.inputShape.length?"uniforms.xShape":`uniforms.xShape.${m(this.inputShape.length-1)}`)()};\n\n var bestIndex = i32(localId.x);\n var bestValue = uniforms.infinityValue;\n let outputCoords = getCoordsFromIndex(outputIndex);\n for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size;\n k = k + i32(workGroupSizeX)) {\n let candidate = getX(${(()=>{let e="";if(1===this.outputShape.length)1!==this.inputShape.length&&(e+="outputCoords,");else for(let t=0;t 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (localId.x < currentSize) {\n let candidate = xBestValues[localId.x + interval];\n if (candidate ${this.op} bestValue) {\n bestValue = candidate;\n xBestValues[localId.x] = bestValue;\n xBestIndices[localId.x] = xBestIndices[localId.x + interval];\n }\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (localId.x == 0u && outputIndex < uniforms.size) {\n setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]);\n }\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Pe{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];const n=new Array(e.length);for(let r=0;r tile : array, ${this.workGroupSize[0]}>;\n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n var x = i32(workgroupId.x) * TILE_DIM + i32(localId.x);\n var y = i32(workgroupId.y) * TILE_DIM + i32(localId.y);\n let width = uniforms.outShape[0];\n let height = uniforms.outShape[1];\n if (x < width && y < height) {\n tile[localId.y][localId.x] = A[y * width + x];\n }\n workgroupBarrier();\n\n x = i32(workgroupId.y) * TILE_DIM + i32(localId.x);\n y = i32(workgroupId.x) * TILE_DIM + i32(localId.y);\n if (x < height && y < width) {\n setOutputAtIndex((y * height + x), tile[localId.x]\n [localId.y]);\n }\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Be{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0;const n=new Array(e.length);for(let r=0;r6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=new Array(t);for(let t=0;t,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n for(var i = 0; i < ${this.workPerThread}; i = i + 1) {\n let flatIndex = index * ${this.workPerThread} + i;\n if(flatIndex < uniforms.size) {\n let resRC = getCoordsFromIndex(flatIndex);\n setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(\n ${e}(${t}), uniforms.aShape)]);\n }\n }\n }\n `}}function je(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{perm:s}=a,o=n,u=i.shape.length,c=new Array(u);for(let e=0;en.disposeData(e.dataId))),h}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const We={kernelName:r.ArgMin,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s}=a;let o=r.util.parseAxisParam(s,i.shape);const u=r.backend_util.getAxesPermutation(o,i.shape.length);let c=i;const l=[];null!=u&&(c=je({inputs:{x:i},backend:n,attrs:{perm:u}}),l.push(c),o=r.backend_util.getInnerMostAxes(o.length,c.shape.length)),r.backend_util.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);const d=new De(c.shape,o[0],"min"),p=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],h=n.runWebGPUProgram(d,[c],"int32",p);return l.forEach((e=>n.disposeData(e.dataId))),h}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ge{constructor(e,t){this.variableNames=["x"],this.uniforms="stride : vec2, pad : vec2, dilation : vec2, convDims : vec2, filterDims : vec2,",this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`pool2D_${t}`,this.poolType=t}getUserCode(){let e="resultValue = max(value, resultValue);";"avg"===this.poolType&&(e="resultValue = resultValue + value; count = count + 1.0;");let t="resultValue";"avg"===this.poolType&&(t="resultValue / count");return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let batch = coords[0];\n let xRCCorner = vec2(coords.yz) * uniforms.stride - uniforms.pad;\n let xRCorner = xRCCorner.x;\n let xCCorner = xRCCorner.y;\n\n var resultValue = ${"avg"===this.poolType?"0.0":"-1.0 / pow(10.0, -20.0)"};\n var count = 0.0;\n\n for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) {\n let xR = xRCorner + wR;\n\n if (xR < 0 || xR >= uniforms.convDims.x) {\n continue;\n }\n\n for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) {\n let xC = xCCorner + wC;\n if (xC < 0 || xC >= uniforms.convDims.y) {\n continue;\n }\n\n let value = getX(batch, xR, xC, coords[3]);\n ${e}\n }\n }\n\n setOutputAtIndex(index, ${t});\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ue{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2,",this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let batch = coords[0];\n let d = coords[3];\n\n let xRCCorner = coords.yz * uniforms.stride;\n let xRCorner = xRCCorner.x;\n let xCCorner = xRCCorner.y;\n\n let value = getX(batch, xRCorner, xCCorner, d);\n setOutputAtIndex(index, value);\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ve={kernelName:r.AvgPool,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{filterSize:s,strides:o,pad:u,dimRoundingMode:c}=a,l=r.backend_util.computePool2DInfo(i.shape,s,o,1,u,c);if(1===l.filterWidth&&1===l.filterHeight&&r.util.arraysEqual(l.inShape,l.outShape))return U({inputs:{x:i},backend:n});let d;const p=[{type:"int32",data:[l.strideHeight,l.strideWidth]}];return 1===l.filterHeight&&1===l.filterWidth?d=new Ue(l):(d=new Ge(l,"avg"),p.push({type:"int32",data:[l.padInfo.top,l.padInfo.left]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[l.inHeight,l.inWidth]},{type:"int32",data:[l.effectiveFilterHeight,l.effectiveFilterWidth]})),n.runWebGPUProgram(d,[i],i.dtype,p)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const He={kernelName:r.BatchMatMul,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:i}=t,{transposeA:s,transposeB:o}=r;return P({a:a,b:i,transposeA:s,transposeB:o,backend:n})}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class qe{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${f(e.length)}, `,this.shaderKey="slice"}getUserCode(){const e=f(this.rank),t=function(e){if(1===e)return"sourceLoc";if(e<=6)return Ke.slice(0,e).map((e=>`sourceLoc.${e}`)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(this.rank);let n;n=1===this.start.length?this.outputShape.map(((e,t)=>"sourceLoc = uniforms.start + coords;")):this.outputShape.map(((e,t)=>`sourceLoc.${Ke[t]} = uniforms.start[${t}] + coords.${Ke[t]};`));return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n var sourceLoc : ${e};\n let coords = getCoordsFromIndex(index);\n ${n.join("\n")}\n setOutputAtIndex(index, getSource(${t}));\n }\n }\n `}}const Ke=["x","y","z","w","u","v"];function Xe(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{begin:s,size:o}=a,[u,c]=r.slice_util.parseSliceParams(i,s,o);if(r.slice_util.assertParamsValid(i,u,c),n.shouldExecuteOnCPU([i])||"string"===i.dtype){const e=n.tensorMap.get(i.dataId),t=we(e.values,u,c,i.shape,i.dtype);return n.makeTensorInfo(c,i.dtype,t)}if(0===r.util.sizeFromShape(c))return n.makeTensorInfo(c,i.dtype,[]);const l=new qe(u,c),d=[{type:"int32",data:u}];return n.runWebGPUProgram(l,[i],i.dtype,d)}const Ye={kernelName:r.Slice,backendName:"webgpu",kernelFunc:Xe},Ze={kernelName:r.BatchToSpaceND,backendName:"webgpu",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{blockShape:s,crops:o}=a;r.util.assert(i.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet"));const u=s.reduce(((e,t)=>e*t)),c=r.backend_util.getReshaped(i.shape,s,u),l=r.backend_util.getPermuted(c.length,s.length),d=r.backend_util.getReshapedPermuted(i.shape,s,u),p=r.backend_util.getSliceBeginCoords(o,s.length),h=r.backend_util.getSliceSize(d,o,s.length),f=[],m=M({inputs:{x:i},backend:n,attrs:{shape:c}}),b=je({inputs:{x:m},backend:n,attrs:{perm:l}}),g=M({inputs:{x:b},backend:n,attrs:{shape:d}}),x=Xe({inputs:{x:g},backend:n,attrs:{begin:p,size:h}});return f.push(m),f.push(b),f.push(g),f.forEach((e=>n.disposeData(e.dataId))),x}},Qe=Y({opSnippet:i.NOT_EQUAL,dtype:"bool",cpuKernelImpl:ge}),Je={kernelName:r.NotEqual,backendName:"webgpu",kernelFunc:Qe}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function et(e){const{inputs:t,backend:n}=e,{input:r}=t;return U({inputs:{x:n.tensorMap.get(r.dataId).complexTensorInfos.real},backend:n})}const tt={kernelName:r.Real,backendName:"webgpu",kernelFunc:et}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const nt={kernelName:r.Cast,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function e(t){const{inputs:n,backend:a,attrs:i}=t,{x:s}=n,{dtype:o}=i;if("complex64"===o){if("complex64"===s.dtype)return U({inputs:{x:s},backend:a});const t=r.zeros(s.shape),n=e({inputs:{x:s},backend:a,attrs:{dtype:"float32"}}),i=H({inputs:{real:n,imag:t},backend:a});return t.dispose(),a.disposeData(n.dataId),i}if("complex64"===s.dtype){const t=et({inputs:{input:s},backend:a}),n=e({inputs:{x:t},backend:a,attrs:{dtype:o}});return a.disposeData(t.dataId),n}if(!r.util.hasEncodingLoss(s.dtype,o)){const e=U({inputs:{x:s},backend:a});return{dataId:e.dataId,shape:e.shape,dtype:o}}if("int32"===o)return function(e,t){const n=new K(e.shape,l.TO_INT),r=t.runWebGPUProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,a);if("bool"===o){const e=a.makeTensorInfo([],"bool",r.util.getTypedArrayFromDType("bool",1)),t=Qe({inputs:{a:s,b:e},backend:a});return a.disposeData(e.dataId),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},rt=X({opType:l.CEIL,cpuKernelImpl:J}),at={kernelName:r.Ceil,backendName:"webgpu",kernelFunc:rt}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class it{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workGroupSize=[64,1,1],this.isVec4=!0,this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if(index < uniforms.size) {\n let value = getAByOutputIndex(index);\n var clampedValue : vec4;\n for (var i = 0; i < 4; i = i + 1) {\n if (isnan(value[i])) {\n clampedValue[i] = value[i];\n } else {\n clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);\n }\n }\n\n setOutputAtIndex(index, clampedValue);\n }\n }\n "}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class st{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if(index < uniforms.size) {\n let value = getAByOutputIndex(index);\n if (isnan(value)) {\n setOutputAtIndex(index, value);\n return;\n }\n setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ot={kernelName:r.ClipByValue,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{clipValueMin:s,clipValueMax:o}=a;let u;const c=[{type:"float32",data:[s]},{type:"float32",data:[o]}];return u=r.util.sizeFromShape(i.shape)%4==0?new it(i.shape):new st(i.shape),n.runWebGPUProgram(u,[i],i.dtype,c)}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ut{constructor(e){this.uniforms="",this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=r.backend_util.computeOutShape(e,1),this.variableNames=e.map(((e,t)=>`T${t}`)),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let e=0;e0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let t=1;t,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n for(var i = 0; i < ${this.workPerThread}; i = i + 1) {\n let flatIndex = index * ${this.workPerThread} + i;\n if(flatIndex < uniforms.size) {\n let coords = getCoordsFromIndex(flatIndex);\n let yR = coords.x;\n let yC = coords.y;\n\n ${e.join("\n ")}\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ct(e){const{inputs:t,backend:n}=e,{input:r}=t;return U({inputs:{x:n.tensorMap.get(r.dataId).complexTensorInfos.imag},backend:n})}const lt={kernelName:r.Imag,backendName:"webgpu",kernelFunc:ct}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function dt(e,t,n){const a=e[0].dtype;if("complex64"===a){const r=e.map((e=>et({inputs:{input:e},backend:n}))),a=e.map((e=>ct({inputs:{input:e},backend:n}))),i=dt(r,t,n),s=dt(a,t,n),o=H({inputs:{real:i,imag:s},backend:n});return r.forEach((e=>n.disposeData(e.dataId))),a.forEach((e=>n.disposeData(e.dataId))),n.disposeData(i.dataId),n.disposeData(s.dataId),o}let i=n.shouldExecuteOnCPU(e);if("string"===a&&(i=!0),i){const i=e.map((e=>{const a=r.util.sizeFromShape(e.shape.slice(t));return M({inputs:{x:e},backend:n,attrs:{shape:[-1,a]}})})),s=i.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=r.backend_util.computeOutShape(i.map((e=>e.shape)),1),u=1===i[0].shape[0],c=ee(s,o,a,u),l=r.backend_util.computeOutShape(e.map((e=>e.shape)),t),d=n.makeTensorInfo(l,a,c);return i.forEach((e=>n.disposeData(e.dataId))),d}const{tensors2D:s,outShape:o}=function(e,t,n){const a=r.backend_util.computeOutShape(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>M({inputs:{x:e},backend:n,attrs:{shape:[r.util.sizeFromShape(e.shape.slice(0,t)),r.util.sizeFromShape(e.shape.slice(t))]}}))),outShape:a}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */(e,t,n),u=s.map((e=>e.shape)),c=new ut(u),l=[],d=new Array(u.length-1);if(d.length>0){d[0]=u[0][1],l.push({type:"int32",data:[d[0]]});for(let e=1;en.disposeData(e.dataId)));const h=M({inputs:{x:p},backend:n,attrs:{shape:o}});return n.disposeData(p.dataId),h}function pt(e){const{inputs:t,backend:n,attrs:a}=e,{axis:i}=a,s=r.util.parseAxisParam(i,t[0].shape)[0],o=r.backend_util.computeOutShape(t.map((e=>e.shape)),s);if(0===r.util.sizeFromShape(o))return n.makeTensorInfo(o,t[0].dtype,[]);const u=t.filter((e=>r.util.sizeFromShape(e.shape)>0));if(1===u.length)return U({inputs:{x:u[0]},backend:n});const c=u.map((e=>e.shape));return r.backend_util.assertParamsConsistent(c,s),dt(u,s,n)}const ht={kernelName:r.Concat,backendName:"webgpu",kernelFunc:pt}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ft{constructor(e,t=!1,n=null,a=!1,i=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pad : vec2, stride : vec2, dilation : vec2,\n dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[8,8,1],this.isVec4=!0,this.outputShape=e.outShape,r.util.assert("channelsLast"===e.dataFormat,(()=>"TODO: NCHW is unimplemented")),this.dispatchLayout={x:[3],y:[1,2],z:[0]},1===this.outputShape[1]?this.elementsPerThread=[4,1,1]:this.elementsPerThread=[4,4,1],this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=a,this.hasLeakyreluAlpha=i,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.hasLeakyreluAlpha&&this.variableNames.push("leakyreluAlpha"),this.tileAOuter=1===this.outputShape[1]?1:this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=this.tileBOuter,[this.fitA,this.fitB]=this.getShapeFit(),this.remainder=this.convInfo.inChannels%4==0,this.shaderKey=`conv2DMMVec4_${this.activation}_${this.fitA}_${this.fitB}_${this.elementsPerThread}_${this.remainder}`}getShapeFit(){const e=[this.tileAOuter,this.tileInner],t=[this.tileInner,this.tileBOuter],n=this.outputShape[1]*this.outputShape[2],r=this.outputShape[3],a=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[w(e,[n,a]),w(t,[a,r])]}getSampleAWithRemainder(e){return`let flatIndex${e} = getIndexFromCoords4D(coord, uniforms.xShape);\n let divBy4Remainder${e} = flatIndex${e} % 4;\n let divBy4Index${e} = flatIndex${e} / 4;\n let curData${e} = x[divBy4Index${e}];\n if (divBy4Remainder${e} == 0) {\n temp = curData${e};\n } else {\n // TODO: This could end up being a redundant load with another one in\n // the same shader invocation. Perhaps there's an opportunity for\n // optimization\n let nextData${e} = x[divBy4Index${e} + 1];\n if (divBy4Remainder${e} == 1) {\n temp = vec4(curData${e}.yzw, nextData${e}.x);\n } else if (divBy4Remainder${e} == 2) {\n temp = vec4(curData${e}.zw, nextData${e}.xy);\n } else if (divBy4Remainder${e} == 3) {\n temp = vec4(curData${e}.w, nextData${e}.xyz);\n }\n }\n `}getUserCode(){const e=$(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner),t=`let outRow = r / uniforms.outShape[2];\n let outCol = r % uniforms.outShape[2];\n let WRow = c / (uniforms.filterDims[1] * uniforms.xShape[3]);\n let WCol = c / uniforms.xShape[3] % uniforms.filterDims[1];\n let inChCoord = c % uniforms.xShape[3];\n var coord = vec4(\n batch,\n outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0],\n outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1],\n inChCoord);\n var resData = vec4(0.0);\n ${this.remainder?"// The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (coordsInBounds4D(coord, uniforms.xShape)) {\n resData = x[getIndexFromCoords4D(coord, uniforms.xShape) / 4];\n } else {\n resData = vec4(0.0); }":`var temp = vec4(0.0);\n ${this.getSampleAWithRemainder(1)}\n resData = temp;\n if (WCol == (uniforms.filterDims[1] - 1)) {\n coord = vec4(\n coord.x, coord.y + 1, coord.z + 1 - uniforms.filterDims[1], 0);\n ${this.getSampleAWithRemainder(2)}\n if (inChCoord == 0) {\n resData = vec4(resData.xyz, temp.x);\n } else if (inChCoord == 1) {\n resData = vec4(resData.xy, temp.xy);\n } else {\n resData = vec4(resData.x, temp.xyz);\n }\n }\n `}\n return resData;`,n=this.fitA?`${t}`:`if (r < uniforms.dimAOuter && c < uniforms.dimInner) {\n ${t}\n }\n return vec4(0.0);\n `,r=this.fitB?"return W[row * uniforms.dimBOuter / 4 + col];":"if(coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return W[row * uniforms.dimBOuter / 4 + col];\n }\n return vec4(0.0);\n ";let a="",i="";if(this.activation){const e=p(this.activation,this.isVec4);if(this.hasPreluActivationWeights)a=`fn activation(a : vec4, outCoord : vec4) -> vec4 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${e}\n }`;else{if(this.hasLeakyreluAlpha)throw a=`fn activation(outCoord: vec4) -> vec4 {\n let b = getLeakyreluAlphaByOutputCoords(outCoord);\n ${e}\n }`,new Error("Leakyrelu is not supported.");a=`\n fn activation(a : vec4, outCoord : vec4) -> vec4 {\n ${e}\n }`}i="value = activation(value, outCoord);"}return`\n ${a}\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> vec4 {\n let r = row;\n let c = col * 4;\n var batch = i32(globalId.z);\n ${n}\n }\n\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> vec4 {\n ${r}\n }\n\n fn mm_write(row : i32, col : i32, valueInput : vec4, globalId : vec3) {\n var batch = i32(globalId.z);\n var value = valueInput;\n if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)\n {\n let outCoord = vec4(\n batch,\n row / uniforms.outShape[2],\n row % uniforms.outShape[2],\n col * 4);\n ${this.addBias?"value = value + getBiasByOutputCoords(outCoord);":""}\n ${i}\n setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], outCoord[3],\n value);\n }\n }\n ${e}\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class mt{constructor(e,t=!1,n=null,r=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pad : vec2, stride : vec2, dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.outShape,this.isChannelsLast="channelsLast"===e.dataFormat,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[1],y:[2,3],z:[0]},this.workGroupSize=S(this.dispatchLayout,this.outputShape),this.elementsPerThread=_(this.dispatchLayout,this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=r,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}_${this.fitA}_${this.fitB}_${this.isChannelsLast}`}getShapeFit(){const e=this.workGroupSize[1]*this.elementsPerThread[1],t=this.workGroupSize[0]*this.elementsPerThread[0],n=e>t?e:t;r.util.assert(n%this.workGroupSize[0]==0&&n%this.workGroupSize[1]==0,(()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y"));const a=[e,n],i=[n,t],s=this.convInfo.outHeight*this.convInfo.outWidth,o=this.convInfo.outChannels,u=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[w(a,[s,u]),w(i,[u,o])]}getUserCode(){const e=this.isChannelsLast?"\n let coord = vec4(batch, xRow, xCol, col % inChannels);\n ":"\n let coord = vec4(batch, col % inChannels, xRow, xCol);\n ",t=this.isChannelsLast?"\n let outCoord = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let outCoord = vec4(\n batch,\n col,\n row / outWidth,\n row % outWidth);\n ",n=N(this.elementsPerThread,this.workGroupSize),r=`\n let inChannels = uniforms.wShape[2];\n let outWidth = ${this.isChannelsLast?"uniforms.outShape[2]":"uniforms.outShape[3]"};\n let outRow = row / outWidth;\n let outCol = row % outWidth;\n\n let WRow = col / (uniforms.filterDims[1] * inChannels);\n let WCol = col / inChannels % uniforms.filterDims[1];\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n ${e}\n // The bounds checking is always needed since we use it to pad zero for the\n // 'same' padding type.\n if(coordsInBounds4D(coord, uniforms.xShape)) {\n return x[getIndexFromCoords4D(coord, uniforms.xShape)];\n }\n return 0.0;`,a=this.fitA?`${r}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${r}\n }\n return 0.0;\n `,i=this.fitB?"return W[row * uniforms.dimBOuter + col];":"if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) {\n return W[row * uniforms.dimBOuter + col];\n\t }\n\t return 0.0;\n\t ";let s="",o="";if(this.activation){const e=p(this.activation,!1);s=this.hasPreluActivationWeights?`fn activation(a: f32, outCoord : vec4) -> f32 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${e}\n }`:`\n fn activation(a : f32, outCoord : vec4) -> f32 {\n ${e}\n }\n `,o="value = activation(value, outCoord);"}const u=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`\n ${s}\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 {\n var batch = i32(globalId.z);\n ${a}\n }\n\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 {\n ${i}\n }\n\n fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3) {\n var batch = i32(globalId.z);\n var value = valueInput;\n let outWidth = ${this.isChannelsLast?"uniforms.outShape[2]":"uniforms.outShape[3]"};\n ${t}\n ${u}\n ${o}\n result[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;\n }\n ${n}\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class bt{constructor(e,t=!1,n=null,a=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pad : vec2, stride : vec2, dilation : vec2,",this.workGroupSize=[128,1,1],this.outputShape=e.outShape,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),r.util.assert("channelsLast"===e.dataFormat,(()=>"TODO: NCHW is unimplemented")),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=a,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){const n=p(this.activation);e=this.hasPreluActivationWeights?`fn activation(a : f32, outCoord : vec4) -> f32{\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${n}\n }`:`\n fn activation(a : f32, outCoord : vec4) -> f32{\n ${n}\n }\n `,t="value = activation(value, outCoord);"}return`\n ${e}\n fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32 {\n let coord = vec4(batch, row, col, chan);\n if(coordsInBounds4D(coord, uniforms.xShape)) {\n return getX(batch, row, col, chan);\n }\n return 0.0;\n }\n\n fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{\n let coord = vec4(row, col, xChannel, outChannel);\n if(coordsInBounds4D(coord, uniforms.wShape)) {\n return getW(row, col, xChannel, outChannel);\n }\n return 0.0;\n }\n\n fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) {\n let coord = vec4(batch, row, col, chan);\n if (coordsInBounds4D(coord, uniforms.outShape)) {\n ${this.addBias?"value = value + getBiasByOutputCoords(outCoord);":""}\n ${t}\n setOutputAtCoords(batch, row, col, chan, value);\n }\n }\n\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let coords = getOutputCoords();\n let batch = coords[0];\n let outChannel = coords[3];\n\n var acc = 0.0;\n\n for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) {\n for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) {\n for (var xChannel = 0; xChannel < uniforms.xShape[3]; xChannel = xChannel + 1) {\n let coordRow = coords[1] * uniforms.stride[0] + uniforms.dilation[0] * row - uniforms.pad[0];\n let coordCol = coords[2] * uniforms.stride[1] + uniforms.dilation[1] * col - uniforms.pad[1];\n let v = readInp(batch, coordRow, coordCol, xChannel);\n let f = readFilt(row, col, xChannel, outChannel);\n acc = acc + v * f;\n }\n }\n }\n\n writeResult(batch, coords[1], coords[2], outChannel, acc);\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class gt{constructor(e,t){this.variableNames=["A"],this.uniforms="pad : vec2, stride : vec2, dilation : vec2, outWidth : i32, itemsPerBlockRow : i32,\n inChannels : i32,",this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?0:1,t=this.isChannelsLast?1:2;return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n for(var i = 0; i<${this.workPerThread}; i = i + 1) {\n let flatIndex = index * ${this.workPerThread} + i;\n\n let rc = getCoordsFromIndex(flatIndex);\n\n if(flatIndex < uniforms.size) {\n let blockIndex = rc[0];\n let pos = rc[1];\n\n let offsetY = blockIndex / uniforms.outWidth * uniforms.stride[1] - uniforms.pad[1];\n let d0 = offsetY + uniforms.dilation[1] * pos / uniforms.itemsPerBlockRow;\n var value = 0.0;\n if(d0 < uniforms.aShape[${e}] && d0 >= 0) {\n let offsetX = (blockIndex % uniforms.outWidth) * uniforms.stride[0] -\n uniforms.pad[0];\n let d1 = offsetX + uniforms.dilation[0] * ((pos %\n uniforms.itemsPerBlockRow) / uniforms.inChannels);\n let ch = pos % uniforms.inChannels;\n if(d1 < uniforms.aShape[${t}] && d1 >= 0) {\n value = getA(d0, d1, ch);\n }\n }\n setOutputAtIndex(flatIndex, value);\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function xt({x:e,filter:t,convInfo:n,backend:a,bias:i=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:u=null}){const c=null!=i,l=null!=s,d="channelsLast"===n.dataFormat;let p;if(d&&n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&"VALID"===n.padInfo.type||1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return function({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:s=0,activation:o=null}){const u="channelsLast"===n.dataFormat,c=!u;let l,d;if(u&&n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&"VALID"===n.padInfo.type){const a=n.inHeight*n.inWidth*n.inChannels;l=M({inputs:{x:e},backend:r,attrs:{shape:[1,n.batchSize,a]}}),d=M({inputs:{x:t},backend:r,attrs:{shape:[1,a,n.outChannels]}})}else l=M({inputs:{x:e},backend:r,attrs:{shape:u?[n.batchSize,n.inHeight*n.inWidth,n.inChannels]:[n.batchSize,n.inChannels,n.inHeight*n.inWidth]}}),d=M({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});const p=P({a:u?l:d,b:u?d:l,transposeA:c,transposeB:!1,backend:r,bias:a,activation:o,preluActivationWeights:i,leakyreluAlpha:s}),h=M({inputs:{x:p},backend:r,attrs:{shape:n.outShape}});return r.disposeData(l.dataId),r.disposeData(d.dataId),r.disposeData(p.dataId),h}({x:e,filter:t,convInfo:n,backend:a,bias:i,activation:u,preluActivationWeights:s,leakyreluAlpha:o});if(Object(r.env)().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&1===e.shape[0])return r.util.assert(d,(()=>"TODO: NCHW is unimplemented")),function({x:e,filter:t,convInfo:n,backend:a,bias:i=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:u=null}){const{filterWidth:c,filterHeight:l,inChannels:d,strideWidth:p,strideHeight:h,padInfo:f,outWidth:m,outHeight:b,dilationWidth:g,dilationHeight:x,dataFormat:v}=n,k="channelsLast"===v,y=c*l*d,w=b*m,I=[w,y],S=[],_=M({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),C=M({inputs:{x:t},backend:a,attrs:{shape:[1,y,-1]}});S.push(_),S.push(C);const O=new gt(I,k),T=[{type:"int32",data:[f.left,f.top]},{type:"int32",data:[p,h]},{type:"int32",data:[g,x]},{type:"int32",data:[m]},{type:"int32",data:[d*c]},{type:"int32",data:[d]}],$=a.runWebGPUProgram(O,[_],_.dtype,T),A=M({inputs:{x:$},backend:a,attrs:{shape:[1,I[0],I[1]]}});S.push($),S.push(A);const N=[1,I[0],I[1]],R=new E(N,[1,w,n.outChannels],Object(r.env)().get("WEBGPU_MATMUL_WORK_PER_THREAD"),!0,!0,!1,!1,i,u,s),F=N[2],D=[{type:"int32",data:[N[1]]},{type:"int32",data:[n.outChannels]},{type:"int32",data:[F]}],P=[A,C];i&&P.push(i),s&&P.push(s),"leakyrelu"===u&&(T.push({type:"float32",data:[o]}),R.uniforms+=" alpha : f32,");const B=a.runWebGPUProgram(R,P,A.dtype,D),j=M({inputs:{x:B},backend:a,attrs:{shape:k?[1,b,m,n.outChannels]:[1,n.outChannels,b,m]}});S.push(B);for(const e of S)a.disposeData(e.dataId);return j}({x:e,filter:t,convInfo:n,backend:a,bias:i,preluActivationWeights:s,leakyreluAlpha:o,activation:u});const h=Object(r.env)().getBool("WEBGPU_USE_NAIVE_CONV2D"),f=(n.inChannels%4==0||3===n.inChannels&&"VALID"===n.padInfo.type)&&n.outChannels%4==0&&d,m=[n.padInfo.top,n.padInfo.left],b=[{type:"int32",data:[n.filterHeight,n.filterWidth]},{type:"int32",data:[...m]},{type:"int32",data:[n.strideHeight,n.strideWidth]},{type:"int32",data:[n.dilationHeight,n.dilationWidth]}];if(h)r.util.assert(d,(()=>"TODO: NCHW is unimplemented")),p=new bt(n,c,u,l);else{p=f?new ft(n,c,u,l):new mt(n,c,u,l);const e=n.outHeight*n.outWidth,t=n.outChannels,r=n.filterHeight*n.filterWidth*n.inChannels;b.push({type:"int32",data:[e]},{type:"int32",data:[t]},{type:"int32",data:[r]})}const g=[e,t];return c&&g.push(i),l&&g.push(s),"leakyrelu"===u&&(b.push({type:"float32",data:[o]}),p.uniforms+=" alpha : f32,"),a.runWebGPUProgram(p,g,e.dtype,b)} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vt={kernelName:r.Conv2D,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:a}=e,{x:i,filter:s}=t,{strides:o,pad:u,dataFormat:c,dilations:l,dimRoundingMode:d}=n,p=r.backend_util.convertConv2DDataFormat(c);return xt({x:i,filter:s,convInfo:r.backend_util.computeConv2DInfo(i.shape,s.shape,o,l,u,d,!1,p),backend:a})}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class kt{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2, pads : vec2, stride : vec2, outBackprop : vec4, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.inShape,r.util.assert("channelsLast"===e.dataFormat,(()=>"TODO: NCHW is unimplemented")),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=S(this.dispatchLayout,this.outputShape),this.elementsPerThread=_(this.dispatchLayout,this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.shaderKey=`conv2DDerInputMM_${this.elementsPerThread}`}getUserCode(){return`\n fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 {\n var batch = i32(globalId.z);\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n \n let outRow = row / uniforms.outShape[2];\n let outCol = row % uniforms.outShape[2];\n\n let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);\n let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];\n let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.stride[0]);\n let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.stride[1]);\n if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {\n return 0.0;\n }\n if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {\n return 0.0;\n }\n let coord = vec4(\n batch,\n i32(xR),\n i32(xC),\n col % uniforms.outBackprop[3]);\n return x[getIndexFromCoords4D(coord, uniforms.xShape)];\n }\n return 0.0;\n }\n\n fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 {\n let coordX = uniforms.filterDims.x - 1 -\n row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);\n let coordY = uniforms.filterDims.y - 1 -\n (row / uniforms.outBackprop[3]) % uniforms.filterDims[1];\n if (row < uniforms.dimInner && col < uniforms.dimBOuter &&\n coordX >= 0 && coordY >= 0) {\n let coord = vec4(coordX, coordY, col,\n row % uniforms.outBackprop[3]);\n return W[getIndexFromCoords4D(coord, uniforms.wShape)];\n }\n return 0.0;\n }\n\n fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3) {\n var batch = i32(globalId.z);\n var value = valueInput;\n let outCoord = vec4(\n batch,\n row / uniforms.outShape[2],\n row % uniforms.outShape[2],\n col);\n result[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;\n }\n\n ${N(this.elementsPerThread,this.workGroupSize)}\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class yt{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2, pads : vec2, stride : vec2, outBackprop : vec4,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast="channelsLast"===e.dataFormat,this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){const e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3;return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n {\n if(index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let batch = coords[0];\n let d1 = coords[${this.isChannelsLast?3:1}];\n\n let dyCorner = vec2(coords[${e}]), coords[${t}]) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let 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 var dotProd = 0.0;\n for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {\n let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x);\n let wRPerm = uniforms.filterDims.x - 1 - wR;\n if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR = dyR;\n\n for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {\n let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.stride.y);\n let wCPerm = uniforms.filterDims.y - 1 - wC;\n if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC = dyC;\n\n for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {\n if (${this.isChannelsLast}) {\n let xValue = getDy(batch, idyR, idyC, d2);\n let wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd = dotProd + xValue * wValue;\n } else {\n let xValue = getDy(batch, d2, idyR, idyC);\n let wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd = dotProd + xValue * wValue;\n }\n\n }\n }\n }\n setOutputAtIndex(index, dotProd);\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const wt={kernelName:r.Conv2DBackpropInput,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{dy:i,filter:s}=t,{inputShape:o,strides:u,pad:c,dataFormat:l,dimRoundingMode:d}=a,p=r.backend_util.convertConv2DDataFormat(l),h=r.backend_util.computeConv2DInfo(o,s.shape,u,1,c,d,!1,p),f=[{type:"int32",data:[h.filterHeight,h.filterWidth]},{type:"int32",data:[h.filterHeight-1-h.padInfo.top,h.filterWidth-1-h.padInfo.left]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.batchSize,h.outHeight,h.outWidth,h.outChannels]}];let m;if(Object(r.env)().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))m=new yt(h);else{m=new kt(h);const e=h.inShape[1]*h.inShape[2],t=h.inShape[3],n=h.filterHeight*h.filterWidth*h.outChannels;f.push({type:"uint32",data:[e]},{type:"uint32",data:[t]},{type:"uint32",data:[n]})}return n.runWebGPUProgram(m,[i,s],"float32",f)}},It=X({opType:l.COS}),St={kernelName:r.Cos,backendName:"webgpu",kernelFunc:It},_t=X({opType:l.COSH}),Ct={kernelName:r.Cosh,backendName:"webgpu",kernelFunc:_t}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Ot{constructor(e,t,n,r){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workGroupSize=[64,1,1],this.size=!0;const[a]=t;this.outputShape=[a,n[0],n[1],e],this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId="bilinear"===r?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){const[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[n,r,a]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[i,s,o]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let height_ratio = f32(${n});\n let width_ratio = f32(${i});\n let b = coords[0];\n let y = coords[1];\n let x = coords[2];\n let d = coords[3];\n // get box vals\n let y1 = getBoxes(b, 0);\n let x1 = getBoxes(b, 1);\n let y2 = getBoxes(b, 2);\n let x2 = getBoxes(b, 3);\n // get image in batch index\n let bInd = i32(round(getBoxInd(b)));\n if(bInd < 0 || bInd >= uniforms.outShape[0]) {\n return;\n }\n let height_scale = ${r};\n let width_scale = ${s};\n let in_y = ${a};\n if( in_y < 0.0 || in_y > ${e} ) {\n setOutputAtIndex(index, uniforms.extrapolationValue);\n return;\n }\n let in_x = ${o};\n if( in_x < 0.0 || in_x > ${t} ) {\n setOutputAtIndex(index, uniforms.extrapolationValue);\n return;\n }\n let sourceFracIndexCR = vec2(in_x,in_y);\n if(${this.methodId} == 1) {\n // Compute the four integer indices.\n let sourceFloorCR = vec2(sourceFracIndexCR);\n let sourceCeilCR = vec2(ceil(sourceFracIndexCR));\n let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);\n let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);\n let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);\n let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);\n let fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n let top = topLeft + (topRight - topLeft) * fracCR.x;\n let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n let newValue = top + (bottom - top) * fracCR.y;\n setOutputAtIndex(index, newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n let sourceNearestCR = vec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n let newValue = getImage(\n bInd, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutputAtIndex(index, newValue);\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tt={kernelName:r.CropAndResize,backendName:"webgpu",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:i,boxInd:s}=t,{cropSize:o,method:u,extrapolationValue:c}=r,l=new Ot(a.shape[3],i.shape,o,u),d=[{type:"float32",data:[c]}];return n.runWebGPUProgram(l,[a,i,s],"float32",d)}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +var $t;!function(e){e.Prod="*",e.Sum="+"}($t||($t={}));class At{constructor(e,t,n,r){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0;this.workGroupSize=[128,1,1],this.outputShape=t,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.exclusive=n,this.reverse=r,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){const e=this.outputShape.length,t=this.op===$t.Prod?"1.0":"0.0",n=this.exclusive?t:`getX(${Nt(e,"coords",this.op)})`,r=this.outputShape[this.outputShape.length-1];let a="",i="";return this.exclusive?(a=this.reverse?"end != "+(r-1):"end != 0",i=this.reverse?"end + 1":"end - 1"):(a=this.reverse?`end + pow2 < ${r}`:"end >= pow2",i=this.reverse?"end + pow2":"end - pow2"),`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n var coords = getCoordsFromIndex(index);\n\n let end = ${Et(e,"coords",this.op)};\n var val = ${n};\n let pow2 = i32(pow(2.0, uniforms.index));\n if (${a}) {\n let idx = ${i};\n ${Et(e,"coords",this.op)} = idx;\n val ${this.op}= getX(${Nt(e,"coords",this.op)});\n }\n setOutputAtIndex(index, val);\n }\n }\n `}}function Nt(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 Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function Et(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 Error(`Cumulative ${n} for rank ${e} is not yet supported`)} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Rt(e,t,n,a,i,s){const o=t.shape.length,u=r.backend_util.getAxesPermutation([a],o);let c=t;null!=u&&(c=je({inputs:{x:t},backend:n,attrs:{perm:u}}));const l=r.backend_util.getInnerMostAxes(1,o)[0];if(l!==o-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${a}`);const d=c.shape[l];let p=U({inputs:{x:c},backend:n});for(let t=0;t<=Math.ceil(Math.log2(d))-1;t++){const r=new At(e,c.shape,!1,s),a=p,i=[{type:"float32",data:[t]}];p=n.runWebGPUProgram(r,[p],p.dtype,i),n.disposeData(a.dataId)}if(i){const t=new At(e,c.shape,i,s),r=p,a=[{type:"float32",data:[0]}];p=n.runWebGPUProgram(t,[p],p.dtype,a),n.disposeData(r.dataId)}if(null!=u){const e=je({inputs:{x:p},backend:n,attrs:{perm:r.backend_util.getUndoAxesPermutation(u)}});return n.disposeData(p.dataId),n.disposeData(c.dataId),e}return p} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ft={kernelName:r.Cumprod,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,exclusive:s,reverse:o}=r;return Rt($t.Prod,a,n,i,s,o)}}; +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mt={kernelName:r.Cumsum,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,exclusive:s,reverse:o}=r;return Rt($t.Sum,a,n,i,s,o)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Dt{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let b = coords[0];\n let h = ${this.getHeightCoordString()};\n let w = ${this.getWidthCoordString()};\n let d = ${this.getDepthCoordString()};\n\n let in_h = h / uniforms.blockSize;\n let offset_h = h % uniforms.blockSize;\n let in_w = w / uniforms.blockSize;\n let offset_w = w % uniforms.blockSize;\n let offset_d = (offset_h * uniforms.blockSize + offset_w) *\n ${this.getOutputDepthSize()};\n let in_d = d + offset_d;\n\n let rlt = ${this.getInputSamplingString()};\n setOutputAtIndex(index, rlt);\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?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Pt={kernelName:r.DepthToSpace,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:i,dataFormat:s}=r,o=a.shape[0],u=("NHWC"===s?a.shape[1]:a.shape[2])*i,c=("NHWC"===s?a.shape[2]:a.shape[3])*i,l=("NHWC"===s?a.shape[3]:a.shape[1])/(i*i),d=[{type:"int32",data:[i]}],p=new Dt("NHWC"===s?[o,u,c,l]:[o,l,u,c],s);return n.runWebGPUProgram(p,[a],a.dtype,d)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Bt{constructor(e,t=!1,n=null,a=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2, stride : vec2, dilation : vec2, inDims : vec2,",this.workGroupSize=[4,4,4],this.isVec4=!0,this.outputShape=e.outShape,this.dispatchLayout={x:[0,1],y:[2],z:[3]},this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),r.util.assert("channelsLast"===e.dataFormat,(()=>"TODO: NCHW is unimplemented")),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=a,this.shaderKey=`depthwise3x3_${n}`}getUserCode(){let e="",t="";if(this.activation){const n=p(this.activation,this.isVec4);e=this.hasPreluActivation?`fn activation(a : vec4, outCoord : vec4) -> vec4 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${n}\n }`:`\n fn activation(a : vec4, outCoord : vec4) -> vec4 {\n ${n}\n }\n `,t="dotProd[i] = activation(dotProd[i], coords);"}return`\n ${e}\n\n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(global_invocation_id) globalId: vec3) {\n let batch = 0;\n let r = i32(globalId.x);\n let c = i32(globalId.y) * 4;\n let d2 = i32(globalId.z) * 4;\n let xRCCorner = vec2(r, c) * uniforms.stride - uniforms.pad;\n let d1 = d2;\n let q = 0;\n\n let xRCorner = xRCCorner.x;\n let xCCorner = xRCCorner.y;\n\n var wVals : array, 9>;\n wVals[0] = getW(0, 0, d1, q);\n wVals[1] = getW(0, 1, d1, q);\n wVals[2] = getW(0, 2, d1, q);\n wVals[3] = getW(1, 0, d1, q);\n wVals[4] = getW(1, 1, d1, q);\n wVals[5] = getW(1, 2, d1, q);\n wVals[6] = getW(2, 0, d1, q);\n wVals[7] = getW(2, 1, d1, q);\n wVals[8] = getW(2, 2, d1, q);\n\n var xVals : array, 6>, 3>;\n for (var wR = 0; wR < 3; wR = wR + 1) {\n let xR = xRCorner + wR * uniforms.dilation[0];\n for (var wC = 0; wC < 6; wC = wC + 1) {\n let xC = xCCorner + wC * uniforms.dilation[1];\n if (xR < 0 || xR >= uniforms.inDims[0] || xC < 0 || xC >= uniforms.inDims[1]) {\n xVals[wR][wC] = vec4(0.0);\n } else {\n xVals[wR][wC] = getX(batch, xR, xC, d1);\n }\n }\n }\n\n var dotProd : array, 4>;\n dotProd[0] = vec4(0.0);\n dotProd[1] = vec4(0.0);\n dotProd[2] = vec4(0.0);\n dotProd[3] = vec4(0.0);\n\n for (var wR = 0; wR < 3; wR = wR + 1) {\n for (var wC = 0; wC < 3; wC = wC + 1) {\n let indexW = wR * 3 + wC;\n dotProd[0] = dotProd[0] + xVals[wR][0 + wC] * wVals[indexW];\n dotProd[1] = dotProd[1] + xVals[wR][1 + wC] * wVals[indexW];\n dotProd[2] = dotProd[2] + xVals[wR][2 + wC] * wVals[indexW];\n dotProd[3] = dotProd[3] + xVals[wR][3 + wC] * wVals[indexW];\n }\n }\n\n for (var i = 0; i < 4; i = i + 1) {\n let coords = vec4(batch, r, c + i, d2);\n if (coordsInBounds4D(coords, uniforms.outShape)) {\n ${this.addBias?"dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);":""}\n ${t}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);\n }\n }\n }\n `}} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class jt{constructor(e,t=!1,n=null,a=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2, stride : vec2, dilation : vec2,\n inDims : vec2, filterHeight : i32, filterWidth : i32,\n channelMul : i32,",this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),r.util.assert("channelsLast"===e.dataFormat,(()=>"TODO: NCHW is unimplemented")),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=a,this.shaderKey=`depthwise_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){const n=p(this.activation,!1);e=this.hasPreluActivation?`fn activation(a : f32, outCoord : vec4) -> f32 {\n let b = getPreluActivationWeightsByOutputCoords(outCoord);\n ${n}\n }`:`\n fn activation(a : f32, outCoord : vec4) -> f32 {\n ${n}\n }\n `,t="dotProd = activation(dotProd, coords);"}return`\n ${e}\n\n fn writeResult(batch : i32, row : i32, col : i32, chan : i32,\n value : f32) {\n let coord = vec4(batch, row, col, chan);\n if (coordsInBounds4D(coord, uniforms.outShape)) {\n setOutputAtCoords(batch, row, col, chan, value);\n }\n }\n\n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let coords = getOutputCoords();\n let batch = coords[0];\n let xRCCorner = vec2(coords.yz) * uniforms.stride - uniforms.pad;\n let d2 = coords[3];\n let d1 = d2 / uniforms.channelMul;\n let q = d2 - d1 * uniforms.channelMul;\n\n let inputRowStart = xRCCorner.x;\n let inputColStart = xRCCorner.y;\n let inputRowEnd = inputRowStart + uniforms.filterHeight *\n uniforms.dilation[0];\n let inputColEnd = inputColStart + uniforms.filterWidth *\n uniforms.dilation[1];\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 var dotProd = 0.0;\n\n // Extract if checking out of for loop for performance.\n if (inputRowStart >= 0 && inputColStart >= 0 &&\n inputRowEnd < uniforms.inDims[0] &&\n inputColEnd < uniforms.inDims[1]) {\n // Here using a constant value |this.convInfo.filterHeight| instead\n // of uniform value is in order to loop unrolling.\n for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {\n let xR = inputRowStart + wR * uniforms.dilation[0];\n\n for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {\n let xC = inputColStart + wC * uniforms.dilation[1];\n\n let xVal = getX(batch, xR, xC, d1);\n let wVal = getW(wR, wC, d1, q);\n dotProd = dotProd + xVal * wVal;\n }\n }\n } else {\n for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {\n let xR = inputRowStart + wR * uniforms.dilation[0];\n\n if (xR < 0 || xR >= uniforms.inDims[0]) {\n continue;\n }\n\n for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {\n let xC = inputColStart + wC * uniforms.dilation[1];\n\n if (xC < 0 || xC >= uniforms.inDims[1]) {\n continue;\n }\n\n let xVal = getX(batch, xR, xC, d1);\n let wVal = getW(wR, wC, d1, q);\n dotProd = dotProd + xVal * wVal;\n }\n }\n }\n\n ${this.addBias?"dotProd = dotProd + getBiasByOutputCoords(coords);":""}\n ${t}\n writeResult(batch, coords[1], coords[2], d2, dotProd);\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lt={kernelName:r.DepthwiseConv2dNative,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s}=t,{strides:o,pad:u,dilations:c,dimRoundingMode:l}=a;let d=c;null==d&&(d=[1,1]);const p=r.backend_util.computeConv2DInfo(i.shape,s.shape,o,d,u,l,!0),h=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.inHeight,p.inWidth]}];let f;return 1===p.batchSize&&p.inHeight===p.outHeight&&p.inWidth===p.outWidth&&1===p.strideHeight&&1===p.strideWidth&&p.filterHeight===p.filterWidth&&p.inChannels===p.outChannels&&1===p.dilationHeight&&1===p.dilationWidth&&3===p.filterHeight&&p.inChannels%4==0?f=new Bt(p):(f=new jt(p),h.push({type:"int32",data:[p.filterHeight]},{type:"int32",data:[p.filterWidth]},{type:"int32",data:[p.outChannels/p.inChannels]})),n.runWebGPUProgram(f,[i,s],i.dtype,h)}},zt=Y({opSnippet:i.MUL,cpuKernelImpl:me,supportsComplex:!0}),Wt={kernelName:r.Multiply,backendName:"webgpu",kernelFunc:zt}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Gt{constructor(e,t){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];const[n]=r.backend_util.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=0===n.length?[1]:n,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";"min"===this.reduceType||"max"===this.reduceType?(e=`\n if (isnan(candidate)) {\n bestValue = uniforms.NAN;\n } else if (!isnan(bestValue) && candidate ${"min"===this.reduceType?"<":">"} bestValue)\n { bestValue = candidate; }`,t="f32(x[offset])"):"sum"===this.reduceType||"mean"===this.reduceType?e=" bestValue = bestValue + candidate; ":"prod"===this.reduceType&&(e=" bestValue = bestValue * candidate; ",t="1.0");const n="mean"===this.reduceType?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n\n ${`\n var xBestValues : array;\n `}\n fn getOffset(outputIndex : i32) -> i32 {\n let outputCoords = getCoordsFromIndex(outputIndex);\n let offset = ${1===this.outputShape.length?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;\n return offset;\n }\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n let outputIndex = index / i32(workGroupSizeX);\n let offset = getOffset(outputIndex);\n var bestValue = ${t};\n let Length = uniforms.reduceSize;\n let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);\n for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;\n k = k + i32(workGroupSizeX)) {\n let candidate = f32(x[offset + k]);\n ${e}\n }\n xBestValues[localId.x] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(u32(Length), workGroupSizeX);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (localId.x < currentSize) {\n let candidate = xBestValues[localId.x + interval];\n ${e}\n xBestValues[localId.x] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (localId.x == 0u && outputIndex < uniforms.size) {\n ${n}\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ut(e,t,n,a,i){const s=e.shape.length,o=[],u=r.util.parseAxisParam(t,e.shape);let c=u;const l=r.backend_util.getAxesPermutation(c,s);let d=e;null!=l&&(d=je({inputs:{x:e},attrs:{perm:l},backend:i}),c=r.backend_util.getInnerMostAxes(c.length,s),o.push(d)),r.backend_util.assertAxesAreInnerMostDims(a,c,s);const[p,h]=r.backend_util.computeOutAndReduceShapes(d.shape,c);let f,m=p;if(n&&(m=r.backend_util.expandShapeToKeepDim(p,u)),"max"!==a&&"prod"!==a||!i.shouldExecuteOnCPU([d])){const t=r.util.sizeFromShape(h),n={windowSize:t,inSize:t,batchSize:r.util.sizeFromShape(d.shape)/t,outSize:1},s="mean"===a?"float32":Object(r.sumOutType)(e.dtype),u=[{type:"int32",data:[t]}],c=new Gt(n,a),l=i.runWebGPUProgram(c,[d],s,u);o.push(l),f=M({inputs:{x:l},attrs:{shape:m},backend:i})}else{const t=i.tensorMap.get(d.dataId).values;switch(a){case"max":const n=pe(t,r.util.sizeFromShape(h),m,e.dtype);f=i.makeTensorInfo(m,e.dtype,n);break;case"prod":const{outVals:s,outShape:o,outDtype:u}=xe(d.shape,d.dtype,t,c);f=i.makeTensorInfo(o,u,s);break;default:throw new Error(`${a} CPU implementation is not yet supported.`)}}return o.forEach((e=>i.disposeData(e.dataId))),f} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Vt(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,keepDims:s}=r;return Ut(a,i,s,"sum",n)}const Ht={kernelName:r.Sum,backendName:"webgpu",kernelFunc:Vt}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qt={kernelName:r.Einsum,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{equation:i}=a,s=t,{allDims:o,summedDims:u,idDims:c}=r.backend_util.decodeEinsumEquation(i,s.length);r.backend_util.checkEinsumDimSizes(o.length,c,s);const{path:l,steps:d}=r.backend_util.getEinsumComputePath(u,c),p=d.length;let h=null,f=o.length;const m=[];for(let e=0;e=0&&(h=Vt({inputs:{x:h},backend:n,attrs:{axis:l[e]-(o.length-f),keepDims:!1}}),m.push(h)),f--)}for(const e of m)e!==h&&n.disposeData(e.dataId);return h}},Kt=X({opType:l.ELU}),Xt={kernelName:r.Elu,backendName:"webgpu",kernelFunc:Kt},Yt=Y({opSnippet:i.EQUAL,dtype:"bool",cpuKernelImpl:te}),Zt={kernelName:r.Equal,backendName:"webgpu",kernelFunc:Yt},Qt=X({opType:l.EXP,cpuKernelImpl:ne,dtype:"float32"}),Jt={kernelName:r.Exp,backendName:"webgpu",kernelFunc:Qt}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function en(e){const{inputs:t,attrs:n,backend:a}=e,{dim:i}=n,{input:s}=t,o=s.shape.length,u=s.shape.slice();let c=i;return i<0&&(r.util.assert(-(o+1)<=i,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),c=o+i+1),u.splice(c,0,1),M({inputs:{x:s},backend:a,attrs:{shape:u}})}const tn={kernelName:r.ExpandDims,backendName:"webgpu",kernelFunc:en},nn=X({opType:l.EXPM1,cpuKernelImpl:re}),rn={kernelName:r.Expm1,backendName:"webgpu",kernelFunc:nn}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class an{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n setOutputAtIndex(index, uniforms.value);\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function sn(e){const{backend:t,attrs:n}=e,{shape:a,value:i}=n;let{dtype:s}=n;if(s=s||r.util.inferDtype(i),"string"===s){const e=r.util.getArrayFromDType(s,r.util.sizeFromShape(a));return e.fill(i),t.makeTensorInfo(a,s,e)}{const e=new an(a),n=[{type:"float32",data:[i]}];return t.runWebGPUProgram(e,[],s,n)}}const on={kernelName:r.Fill,backendName:"webgpu",kernelFunc:sn}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class un{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let coordX = uniforms.xShape[2] - coords[2] - 1;\n let outputValue = getX(coords[0], coords[1], coordX, coords[3]);\n setOutputAtIndex(index, outputValue);\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const cn={kernelName:r.FlipLeftRight,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,a=new un(n.shape);return r.runWebGPUProgram(a,[n],n.dtype)}},ln=X({opType:l.FLOOR,cpuKernelImpl:ae}),dn={kernelName:r.Floor,backendName:"webgpu",kernelFunc:ln},pn=Y({opSnippet:i.INT_DIV,dtype:"int32"}),hn={kernelName:r.FloorDiv,backendName:"webgpu",kernelFunc:pn}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class fn{constructor(e,t=!1){this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.useImport=t,this.shaderKey=`fromPixels_${this.useImport}`}getUserCode(){const e=this.useImport?"textureLoad(src, vec2(coords.yx));":"textureLoad(src, vec2(coords.yx), 0)";return`\n @binding(1) @group(0) var src: ${this.useImport?"texture_external":"texture_2d"};\n\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n let flatIndexBase = index * uniforms.numChannels;\n for (var i = 0; i < uniforms.numChannels; i = i + 1) {\n let flatIndex = flatIndexBase + i;\n if (flatIndex < uniforms.size) {\n let coords = getCoordsFromIndex(flatIndexBase);\n let values = ${e};\n result[flatIndex] = i32(floor(255.0 * values[i]));\n }\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use backend file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const mn={kernelName:r.FromPixels,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e;let{pixels:i}=t;const{numChannels:s}=a;if(null==i)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");const o="undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement,c="undefined"!=typeof HTMLCanvasElement&&i instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&i instanceof OffscreenCanvas,l="undefined"!=typeof ImageBitmap&&i instanceof ImageBitmap,[d,p]=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],h=[p,d,s];if(Object(r.env)().getBool("WEBGPU_USE_IMPORT")&&o)return gn({externalImage:i,backend:n,attrs:a,outShape:h,useImport:!0});(o||u)&&(null==bn&&(bn=document.createElement("canvas").getContext("2d")),bn.canvas.width=d,bn.canvas.height=p,bn.drawImage(i,0,0,d,p),i=bn.canvas);if(l||c||o||u)return gn({externalImage:i,backend:n,attrs:a,outShape:h,useImport:!1});const f=i.data;let m=f;if(null!=s&&4!==s){m=new Uint8Array(i.width*i.height*s);const e=f.length;let t=0;for(let n=0;n,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size)\n {\n let xValue = getXByOutputIndex(index);\n let meanValue = getMeanByOutputIndex(index);\n let varianValue = getVarianceByOutputIndex(index);\n let offsetValue = ${e};\n let scaleValue = ${t};\n let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));\n setOutputAtIndex(index,dot(vec3(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0)));\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const vn={kernelName:r.FusedBatchNorm,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r,scale:a,offset:i,mean:s,variance:o}=e,{varianceEpsilon:u}=t,c=n,l=[r,s,o];let d=null;null!=i&&(d=i.shape,l.push(i));let p=null;null!=a&&(p=a.shape,l.push(a));const h=new xn(r.shape,s.shape,o.shape,d,p),f=[{type:"float32",data:[u]}];return c.runWebGPUProgram(h,l,r.dtype,f)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const kn={kernelName:r.FusedConv2D,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s,bias:o,preluActivationWeights:u}=t,{strides:c,pad:l,dataFormat:d,dilations:p,dimRoundingMode:h,activation:f,leakyreluAlpha:m}=a,b=r.backend_util.convertConv2DDataFormat(d);return xt({x:i,filter:s,convInfo:r.backend_util.computeConv2DInfo(i.shape,s.shape,c,p,l,h,!1,b),backend:n,bias:o,preluActivationWeights:u,leakyreluAlpha:m,activation:f})}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yn={kernelName:r.FusedDepthwiseConv2D,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:s,bias:o,preluActivationWeights:u}=t,{strides:c,pad:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=a;let m=d;null==m&&(m=[1,1]),r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(c,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`));const b=r.backend_util.computeConv2DInfo(i.shape,s.shape,c,m,l,p,!0),g=[i,s],x=null!=o,v=null!=u;x&&g.push(o),v&&g.push(u);const k=[{type:"int32",data:[b.padInfo.top,b.padInfo.left]},{type:"int32",data:[b.strideHeight,b.strideWidth]},{type:"int32",data:[b.dilationHeight,b.dilationWidth]},{type:"int32",data:[b.inHeight,b.inWidth]}];let y;return 1===b.batchSize&&b.inHeight===b.outHeight&&b.inWidth===b.outWidth&&1===b.strideHeight&&1===b.strideWidth&&b.filterHeight===b.filterWidth&&b.inChannels===b.outChannels&&1===b.dilationHeight&&1===b.dilationWidth&&3===b.filterHeight&&b.inChannels%4==0?y=new Bt(b,x,h,v):(y=new jt(b,x,h,v),k.push({type:"int32",data:[b.filterHeight]},{type:"int32",data:[b.filterWidth]},{type:"int32",data:[b.outChannels/b.inChannels]})),"leakyrelu"===h&&(k.push({type:"float32",data:[f]}),y.uniforms+=" alpha : f32,"),n.runWebGPUProgram(y,g,"float32",k)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wn{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${f(e)},`}getUserCode(){let e;e=this.sliceDim>1?"uniforms.strides[j]":"uniforms.strides";return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n var flattenIndex = 0;\n for (var j = 0; j < uniforms.sliceDim; j = j + 1) {\n let indexTemp = i32(round(getIndices(coords[0], j)));\n let strideNum = ${e};\n flattenIndex = flattenIndex + indexTemp * strideNum;\n }\n\n setOutputAtIndex(index, getA(flattenIndex, coords[1]));\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const In={kernelName:r.GatherNd,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:a,indices:i}=t,s=i.shape,o=s[s.length-1],u=r.util.sizeFromShape(a.shape),[c,l,d,p]=r.backend_util.prepareAndValidate(a,i),h=M({inputs:{x:i},backend:n,attrs:{shape:[l,o]}}),f=M({inputs:{x:a},backend:n,attrs:{shape:[r.util.sizeFromShape(a.shape)/d,d]}});if(n.shouldExecuteOnCPU([a,i])||"string"===a.dtype){const e=n.readSync(i.dataId),t=n.bufferSync(a),r=ie(e,t,a.dtype,l,o,d,p,a.shape,u);return n.makeTensorInfo(c,a.dtype,r.values)}const m=new wn(o,[l,d]),b=[{type:"int32",data:[o]},{type:"int32",data:p}],g=n.runWebGPUProgram(m,[f,h],f.dtype,b),x=M({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(g.dataId),x}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Sn{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let resRC = getCoordsFromIndex(index);\n let indexZ = i32(getIndices(resRC.x, resRC.z));\n let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);\n setOutputAtIndex(index, inBounds * getA(${function(e){const t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;rn.disposeData(e.dataId))),n.makeTensorInfo(l.outputShape,s.dtype,s.values)}const b=new Sn(h.shape,m),g=n.runWebGPUProgram(b,[h,f],h.dtype);p.push(g);const x=M({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return p.forEach((e=>n.disposeData(e.dataId))),x}const Cn={kernelName:r.GatherV2,backendName:"webgpu",kernelFunc:_n},On=Y({opSnippet:i.GREATER,cpuKernelImpl:ue,dtype:"bool"}),Tn={kernelName:r.Greater,backendName:"webgpu",kernelFunc:On},$n=Y({opSnippet:i.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:oe}),An={kernelName:r.GreaterEqual,backendName:"webgpu",kernelFunc:$n}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nn={kernelName:r.LeakyRelu,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:i}=r,s=[{type:"float32",data:[i]}],o=new K(a.shape,l.LEAKYRELU);return o.uniforms="alpha : f32,",n.runWebGPUProgram(o,[a],"float32",s)}},En=Y({opSnippet:i.LESS,dtype:"bool",cpuKernelImpl:le}),Rn={kernelName:r.Less,backendName:"webgpu",kernelFunc:En},Fn=Y({opSnippet:i.LESS_EQUAL,dtype:"bool",cpuKernelImpl:ce}),Mn={kernelName:r.LessEqual,backendName:"webgpu",kernelFunc:Fn},Dn=X({opType:l.LOG,cpuKernelImpl:de}),Pn={kernelName:r.Log,backendName:"webgpu",kernelFunc:Dn},Bn=Y({opSnippet:i.LOGICAL_AND,dtype:"bool"}),jn={kernelName:r.LogicalAnd,backendName:"webgpu",kernelFunc:Bn},Ln=X({opType:l.LOGICAL_NOT}),zn={kernelName:r.LogicalNot,backendName:"webgpu",kernelFunc:Ln}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Wn(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:i,keepDims:s}=r;return Ut(a,i,s,"max",n)}const Gn={kernelName:r.Max,backendName:"webgpu",kernelFunc:Wn},Un=Y({opSnippet:i.MAX,cpuKernelImpl:he}),Vn={kernelName:r.Maximum,backendName:"webgpu",kernelFunc:Un}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hn={kernelName:r.MaxPool,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{filterSize:s,strides:o,pad:u,dimRoundingMode:c}=a,l=r.backend_util.computePool2DInfo(i.shape,s,o,1,u,c);let d;const p=[];if(1===l.filterHeight&&1===l.filterWidth){if(r.util.arraysEqual(l.inShape,l.outShape))return U({inputs:{x:i},backend:n});d=new Ue(l),p.push({type:"int32",data:[l.strideHeight,l.strideWidth]})}else d=new Ge(l,"max"),p.push({type:"int32",data:[l.strideHeight,l.strideWidth]},{type:"int32",data:[l.padInfo.top,l.padInfo.left]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[l.inHeight,l.inWidth]},{type:"int32",data:[l.effectiveFilterHeight,l.effectiveFilterWidth]});return n.runWebGPUProgram(d,[i],i.dtype,p)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qn={kernelName:r.Mean,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{keepDims:i,axis:s}=r;return Ut(a,s,i,"mean",n)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Kn={kernelName:r.Min,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,keepDims:s}=r;return Ut(a,i,s,"min",n)}},Xn=Y({opSnippet:i.MIN,cpuKernelImpl:fe}),Yn={kernelName:r.Minimum,backendName:"webgpu",kernelFunc:Xn}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Zn{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1])),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map(((e,t)=>{this.uniforms+=` pad${t} : vec2,`})),this.offset="reflect"===n?0:1,this.shaderKey=`mirrorPad_${n}`}getUserCode(){const e=this.xShape.length,t=this.xShape.map(((e,t)=>`uniforms.pad${t}[0]`)).join(","),n=this.xShape.map(((t,n)=>`uniforms.pad${n}[0] + uniforms.xShape${e>1?`[${n}]`:""}`)).join(","),r=1===e?"start":"start[i]",a=1===e?"end":"end[i]",i=1===e?"outC":"outC[i]",s=f(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let start = ${s}(${t});\n let end = ${s}(${n});\n var outC = getCoordsFromIndex(index);\n for (var i = 0; i < ${e}; i = i + 1) {\n if (${i} < ${r}) {\n ${i} = ${r} * 2 - ${i} - ${this.offset};\n } else if(${i} >= ${a}) {\n ${i} = (${a} - 1) * 2 - ${i} + ${this.offset};\n }\n }\n let coords = outC - start;\n setOutputAtIndex(index, getX(${o}));\n }\n }\n `}} +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qn={kernelName:r.MirrorPad,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{paddings:a,mode:i}=t,s=n,o=a.map((e=>({type:"int32",data:[e[0],e[1]]}))),u=new Zn(r.shape,a,i);return s.runWebGPUProgram(u,[r],r.dtype,o)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Jn={kernelName:r.Neg,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.tensorMap.get(r.dataId),[t,a]=be(e.values,r.shape,r.dtype);return n.makeTensorInfo(a,r.dtype,t)}const a=new K(r.shape,l.NEG);return n.runWebGPUProgram(a,[r],r.dtype)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const er={kernelName:r.NonMaxSuppressionV3,backendName:"webgpu",kernelFunc:function(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:a}=e,{boxes:i,scores:s}=t,{maxOutputSize:o,iouThreshold:u,scoreThreshold:c}=a,l=n.readSync(i.dataId),d=n.readSync(s.dataId),{selectedIndices:p}=r.kernel_impls.nonMaxSuppressionV3Impl(l,d,o,u,c);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const tr={kernelName:r.NonMaxSuppressionV5,backendName:"webgpu",kernelFunc:function(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:a}=e,{boxes:i,scores:s}=t,{maxOutputSize:o,iouThreshold:u,scoreThreshold:c,softNmsSigma:l}=a,d=n.readSync(i.dataId),p=n.readSync(s.dataId),h=o,f=u,m=c,b=l,{selectedIndices:g,selectedScores:x}=r.kernel_impls.nonMaxSuppressionV5Impl(d,p,h,f,m,b);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([x.length],"float32",new Float32Array(x))]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function nr(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=et({inputs:{input:r},backend:n}),t=nr({inputs:{x:e},backend:n}),a=ct({inputs:{input:r},backend:n}),i=nr({inputs:{x:a},backend:n}),s=H({inputs:{real:t,imag:i},backend:n});return n.disposeData(e.dataId),n.disposeData(t.dataId),n.disposeData(a.dataId),n.disposeData(i.dataId),s}return sn({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const rr={kernelName:r.ZerosLike,backendName:"webgpu",kernelFunc:nr}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ar={kernelName:r.OnesLike,backendName:"webgpu",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===a.dtype){const t=et({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),i=ct({inputs:{input:a},backend:r}),s=nr({inputs:{x:i},backend:r}),o=H({inputs:{real:n,imag:s},backend:r});return r.disposeData(t.dataId),r.disposeData(n.dataId),r.disposeData(i.dataId),r.disposeData(s.dataId),o}return sn({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ir={kernelName:r.Pack,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{axis:i}=a;if(1===t.length)return en({inputs:{input:t[0]},backend:n,attrs:{dim:i}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{r.util.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),r.util.assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const u=[],c=pt({inputs:t.map((e=>{const t=en({inputs:{input:e},backend:n,attrs:{dim:i}});return u.push(t),t})),backend:n,attrs:{axis:i}});return u.forEach((e=>n.disposeData(e.dataId))),c}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class sr{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1])),this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map(((e,t)=>{this.uniforms+=` pad${t} : vec2,`})),this.xShape=e,this.shaderKey="pad"}getUserCode(){const e=this.xShape.length,t=f(e),n=this.xShape.map(((e,t)=>`uniforms.pad${t}[0]`)).join(","),r=this.xShape.map(((t,n)=>`uniforms.pad${n}[0] + uniforms.xShape${e>1?`[${n}]`:""}`)).join(",");return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let start = ${e>1?`${t}(${n})`:`${n}`};\n let end = ${e>1?`${t}(${r})`:`${r}`};\n let outC = getCoordsFromIndex(index);\n\n if (${e>1?"any(outC < start)":"outC < start"} || ${e>1?"any(outC >= end)":"outC >= end"}) {\n setOutputAtIndex(index, uniforms.constantValue);\n } else {\n let coords = outC - start;\n setOutputAtIndex(index, getX(${e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords"}));\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const or=e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{paddings:s,constantValue:o}=a;if(s.every((e=>r.util.arraysEqual(e,[0,0]))))return U({inputs:{x:i},backend:n});if(0===r.util.sizeFromShape(i.shape)){return sn({backend:n,attrs:{shape:s.map(((e,t)=>e[0]+i.shape[t]+e[1])),value:o,dtype:i.dtype}})}const u=[{type:"float32",data:[o]}];s.map((e=>u.push({type:"int32",data:[e[0],e[1]]})));const c=new sr(i.shape,s);return n.runWebGPUProgram(c,[i],i.dtype,u)},ur={kernelName:r.PadV2,backendName:"webgpu",kernelFunc:or},cr=Y({opSnippet:i.POW}),lr={kernelName:r.Pow,backendName:"webgpu",kernelFunc:cr};const dr={kernelName:r.Prelu,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=new W(i.PRELU,r.shape,a.shape);return n.runWebGPUProgram(s,[r,a],"float32")}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pr={kernelName:r.Prod,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:i,keepDims:s}=r;return Ut(a,i,s,"prod",n)}},hr={kernelName:r.Range,backendName:"webgpu",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:i,dtype:s}=n,o=ve(r,a,i,s);return t.makeTensorInfo([o.length],s,o)}},fr=Y({opSnippet:i.DIV}),mr={kernelName:r.RealDiv,backendName:"webgpu",kernelFunc:fr},br=X({opType:l.RELU}),gr={kernelName:r.Relu,backendName:"webgpu",kernelFunc:br},xr=X({opType:l.RELU6}),vr={kernelName:r.Relu6,backendName:"webgpu",kernelFunc:xr}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class kr{constructor(e,t,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, halfPixelCenters : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let b = coords[0];\n let d = coords[3];\n let rc = coords.yz;\n\n let effectiveInSize = vec2(\n f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],\n f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);\n\n let effectiveOutSize = vec2(\n f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],\n f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);\n\n let effectiveInputOverOutputRatioRC =\n effectiveInSize / effectiveOutSize;\n\n // Fractional source index\n let sourceFracIndexRC =\n (vec2(rc) + vec2(uniforms.halfPixelCenters)) *\n effectiveInputOverOutputRatioRC - vec2(uniforms.halfPixelCenters);\n\n // Compute the four integer indices.\n let sourceFloorRC = vec2(sourceFracIndexRC);\n let sourceCeilRC = vec2(\n min(vec2(uniforms.xShape.yz) - vec2(1.0), ceil(sourceFracIndexRC)));\n\n let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);\n let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);\n let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);\n let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n let fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n let top = topLeft + (topRight - topLeft) * fracRC.y;\n let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n let newValue = top + (bottom - top) * fracRC.x;\n\n setOutputAtIndex(index, newValue);\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const yr={kernelName:r.ResizeBilinear,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:i,size:s,halfPixelCenters:o}=r,[u,c]=s,l=[{type:"float32",data:[i&&u>1?1:0,i&&c>1?1:0]},{type:"float32",data:[o?.5:0]}],d=new kr(a.shape,u,c);return n.runWebGPUProgram(d,[a],"float32",l)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class wr{constructor(e,t,n,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, roundBase : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=r,this.shaderKey=`resizeNearest_${r}`}getUserCode(){let e;e=this.halfPixelCenters?"max((vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(rc) * effectiveInputOverOutputRatioRC";return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let b = coords[0];\n let d = coords[3];\n let rc = coords.yz;\n\n let effectiveInSize = vec2(\n f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],\n f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);\n\n let effectiveOutSize = vec2(\n f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],\n f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);\n\n let effectiveInputOverOutputRatioRC =\n effectiveInSize / effectiveOutSize;\n\n // Fractional source index\n let sourceFracIndexRC = ${e};\n\n // Compute the coordinators of nearest neighbor point.\n let inputShapeRC = vec2(f32(uniforms.xShape.y), f32(uniforms.xShape.z));\n let sourceNearestRC = vec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase)));\n let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutputAtIndex(index, newValue);\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ir={kernelName:r.ResizeNearestNeighbor,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:i,halfPixelCenters:s,size:o}=r,[u,c]=o,l=[{type:"float32",data:[i&&u>1?1:0,i&&c>1?1:0]},{type:"float32",data:[i?.5:0]}],d=new wr(a.shape,u,c,s);return n.runWebGPUProgram(d,[a],a.dtype,l)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Sr{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="centerX : f32, centerY : f32, sinRadians : f32,\n cosRadians : f32,",this.shaderKey="rotate",this.outputShape=e,"number"==typeof t?(this.uniforms+=" fillValue : f32,",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3,",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n let coordXFloat = (f32(coords[2]) - uniforms.centerX) *\n uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) *\n uniforms.sinRadians;\n let coordYFloat = (f32(coords[2]) - uniforms.centerX) *\n uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) *\n uniforms.cosRadians;\n let coordX = i32(round(coordXFloat + uniforms.centerX));\n let coordY = i32(round(coordYFloat + uniforms.centerY));\n ${this.fillSnippet}\n if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 &&\n coordY < uniforms.xShape[1]) {\n outputValue = getX(coords[0], coordY, coordX, coords[3]);\n }\n setOutputAtIndex(index, outputValue);\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const _r={kernelName:r.RotateWithOffset,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:a}=e,{radians:i,fillValue:s,center:o}=t,u=n,c=new Sr(a.shape,s),[l,d]=r.backend_util.getImageCenter(o,a.shape[1],a.shape[2]),p=[{type:"float32",data:[l]},{type:"float32",data:[d]},{type:"float32",data:[Math.sin(i)]},{type:"float32",data:[Math.cos(i)]}];"number"==typeof s?p.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):p.push({type:"float32",data:s});return u.runWebGPUProgram(c,[a],a.dtype,p)}},Cr=X({opType:l.RSQRT,cpuKernelImpl:ke}),Or={kernelName:r.Rsqrt,backendName:"webgpu",kernelFunc:Cr}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Tr{constructor(e,t,n,r,a,i,s){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=i,this.type=s,this.dispatchLayout=C(e),this.dispatch=I(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${n}_${r}_${this.sliceDimGreaterThanOne}_${s}`;const o=f(a.length);this.uniforms=`sliceDim : i32, strides: ${o}, size: i32,`,this.updatesRank=r,this.indicesRank=n}getUserCode(){let e="";1===this.indicesRank?e="coords[0]":2===this.indicesRank&&(e="coords[0], j");const t=`getIndices(${e})`,n=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides";let r="",a="",i="";1===this.updatesRank?(r="coords[0]",a="flattenedIndex",i="\n fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {\n return index;\n }\n "):2===this.updatesRank&&(r="coords[0], coords[1]",a="vec2(flattenedIndex, coords[1])",i="\n fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2 {\n let d0 = index / uniforms.updatesShape[1];\n let d1 = index - d0 * uniforms.updatesShape[1];\n return vec2(d0, d1);\n }\n ");return`\n ${i}\n\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n if (index < uniforms.size) {\n let coords = getUpdatesCoordsFromFlatIndex(index);\n var flattenedIndex = 0;\n for (var j = 0; j < uniforms.sliceDim; j = j + 1) {\n let indexInside = i32(round(${t}));\n flattenedIndex = flattenedIndex + indexInside * ${n};\n }\n let updateValue = ${`getUpdates(${r})`};\n let flatIndex = getOutputIndexFromCoords(${a});\n\n ${"int32"===this.type?"atomicAdd(&(result[flatIndex]), i32(updateValue));":"\n var assumed = atomicLoad(&(result[flatIndex]));\n var success = 0;\n for (; success == 0;) {\n let new = bitcast(assumed) + updateValue;\n let newI32 = bitcast(new);\n let resValue = atomicCompareExchangeWeak(&(result[flatIndex]), assumed, newI32);\n assumed = resValue[0];\n success = resValue[1];\n }\n "}\n }\n }`}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const $r={kernelName:r.ScatterNd,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{indices:i,updates:s}=t,{shape:o}=a,{sliceRank:u,numUpdates:c,sliceSize:l,strides:d,outputSize:p}=r.backend_util.calculateShapes(s,i,o),h=[p/l,l];if(0===p)return n.makeTensorInfo(o,i.dtype);const f=M({inputs:{x:i},backend:n,attrs:{shape:[c,u]}}),m=M({inputs:{x:s},backend:n,attrs:{shape:[c,l]}}),b=m.dtype,g=sn({backend:n,attrs:{shape:h,value:0,dtype:b}}),x=[{type:"int32",data:[u]},{type:"int32",data:d},{type:"int32",data:[r.util.sizeFromShape(m.shape)]}],v=new Tr(m.shape,u,f.shape.length,m.shape.length,d,h,b),k=n.runWebGPUProgram(v,[m,f],b,x,g),y=M({inputs:{x:k},backend:n,attrs:{shape:o}});return n.disposeData(f.dataId),n.disposeData(m.dataId),n.disposeData(k.dataId),y}}; +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class Ar{constructor(e,t,n){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=n,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(1===this.rank)t="resRC",e="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=[];for(let e=0;e,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let resRC = getCoordsFromIndex(index);\n let cVal = getC(${e});\n if (cVal >= 1.0) {\n setOutputAtIndex(index, getA(${t}));\n } else {\n setOutputAtIndex(index, getB(${t}));\n }\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nr={kernelName:r.Select,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:a,t:i,e:s}=t,o=new Ar(a.shape.length,i.shape,i.shape.length);return n.runWebGPUProgram(o,[a,i,s],Object(r.upcastType)(i.dtype,s.dtype))}},Er=X({opType:l.SIGMOID}),Rr={kernelName:r.Sigmoid,backendName:"webgpu",kernelFunc:Er},Fr=X({opType:l.SIN}),Mr={kernelName:r.Sin,backendName:"webgpu",kernelFunc:Fr},Dr=X({opType:l.SINH}),Pr={kernelName:r.Sinh,backendName:"webgpu",kernelFunc:Dr},Br=Y({opSnippet:i.SUB,cpuKernelImpl:_e,supportsComplex:!0}),jr={kernelName:r.Sub,backendName:"webgpu",kernelFunc:Br}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lr={kernelName:r.Softmax,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:a}=e,{logits:i}=t,{dim:s}=a,o=r.util.parseAxisParam([s],i.shape),u=Wn({inputs:{x:i},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=r.backend_util.expandShapeToKeepDim(u.shape,o),l=M({inputs:{x:u},backend:n,attrs:{shape:c}}),d=Br({inputs:{a:i,b:l},backend:n}),p=Qt({inputs:{x:d},backend:n}),h=Vt({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),f=M({inputs:{x:h},backend:n,attrs:{shape:c}}),m=fr({inputs:{a:p,b:f},backend:n});return n.disposeData(u.dataId),n.disposeData(l.dataId),n.disposeData(d.dataId),n.disposeData(p.dataId),n.disposeData(h.dataId),n.disposeData(f.dataId),m}},zr={kernelName:r.SpaceToBatchND,backendName:"webgpu",kernelFunc:e=>{const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{blockShape:s,paddings:o}=a;r.util.assert(i.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet"));const u=s.reduce(((e,t)=>e*t)),c=[[0,0]];c.push(...o);for(let e=1+s.length;en.disposeData(e.dataId))),g}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Wr{constructor(e,t,n,r,a,i,s=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=i,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);const o=t>1;this.shaderKey=`scatter_${n}_${r}_${o}`;const u=f(a.length);this.uniforms=`updateSize : i32, sliceDim : i32, strides: ${u},`;let c="";1===n?c="i":2===n&&(c="i, j"),this.indicesSnippet=`getIndices(${c})`;let l="";1===r?l="i":2===r&&(l="i, coords[1]"),this.updatesSnippet=`getUpdates(${l})`,this.strideString=o?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n\n let globalIndex = index * ${this.workPerThread};\n if (globalIndex < uniforms.size) {\n var sum = vec4(0.0);\n var found = vec4(false);\n for (var i = 0; i < uniforms.updateSize; i = i + 1) {\n var flattenedIndex = 0;\n for (var j = 0; j < uniforms.sliceDim; j = j + 1) {\n let indexInside = i32(round(${this.indicesSnippet}));\n flattenedIndex = flattenedIndex + indexInside * ${this.strideString};\n }\n for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {\n let curIndex = globalIndex + innerIndex;\n let coords = getCoordsFromIndex(curIndex);\n if (flattenedIndex == coords[0]) {\n sum[innerIndex] = sum[innerIndex] + ${this.updatesSnippet};\n found[innerIndex] = true;\n }\n }\n }\n for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {\n let curIndex = globalIndex + innerIndex;\n if (curIndex < uniforms.size)\n {\n setOutputAtIndex(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex])));\n }\n }\n }\n }`}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Gr={kernelName:r.SparseToDense,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{sparseIndices:i,sparseValues:s,defaultValue:o}=t,{outputShape:u}=a,{sliceRank:c,numUpdates:l,strides:d,outputSize:p}=r.backend_util.calculateShapes(s,i,u),h=[{type:"int32",data:[l]},{type:"int32",data:[c]},{type:"int32",data:d}],f=new Wr(l,c,i.shape.length,s.shape.length,d,[p,1],!1),m=n.runWebGPUProgram(f,[s,i,o],s.dtype,h),b=M({inputs:{x:m},backend:n,attrs:{shape:u}});return n.disposeData(m.dataId),b}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ur={kernelName:r.SplitV,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{numOrSizeSplits:s,axis:o}=a,u=r.util.parseAxisParam(o,i.shape)[0],c=r.backend_util.prepareSplitSize(i,s,u),l=i.shape.length,d=new Array(l).fill(0),p=i.shape.slice();return c.map((e=>{const t=[...p];t[u]=e;const r=Xe({inputs:{x:i},backend:n,attrs:{begin:d,size:t}});return d[u]+=e,r}))}},Vr=X({opType:l.SQRT}),Hr={kernelName:r.Sqrt,backendName:"webgpu",kernelFunc:Vr},qr={kernelName:r.Square,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t,a=new K(n.shape,l.SQUARE);return r.runWebGPUProgram(a,[n],n.dtype)}},Kr=Y({opSnippet:i.SQUARED_DIFFERENCE}),Xr={kernelName:r.SquaredDifference,backendName:"webgpu",kernelFunc:Kr}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class Yr{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);const t=f(this.outputShape.length);this.uniforms=`begin : ${t}, strides : ${t}, `,this.shaderKey="stridedSlice"}getUserCode(){let e="";if(1===this.outputShape.length)e="coords * uniforms.strides + uniforms.begin";else{let t=0;e=this.outputShape.map(((e,n)=>(t++,1===this.outputShape.length?`coords * uniforms.strides[${n}] + uniforms.begin[${n}]`:`coords[${t-1}] * uniforms.strides[${n}] + uniforms.begin[${n}]`))).join(",")}return`\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n setOutputAtIndex(index, getX(${e}));\n }\n }\n `}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Zr={kernelName:r.StridedSlice,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{begin:s,end:o,strides:u,beginMask:c,endMask:l,ellipsisMask:d,newAxisMask:p,shrinkAxisMask:h}=a,{finalShapeSparse:f,finalShape:m,isIdentity:b,sliceDim0:g,isSimpleSlice:x,begin:v,end:k,strides:y}=r.slice_util.sliceInfo(i.shape,s,o,u,c,l,d,p,h);let w;if(b)w=M({inputs:{x:i},backend:n,attrs:{shape:m}});else if(g||x){r.util.assert(i.shape.length>=1,(()=>`Input must have rank at least 1, got: ${i.shape.length}`));const e=r.slice_util.computeOutShape(v,k,y),t=Xe({inputs:{x:i},backend:n,attrs:{begin:v,size:e}});w=M({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeData(t.dataId)}else{if(n.shouldExecuteOnCPU([i])){const e=n.readSync(i.dataId),t=Object(r.buffer)(i.shape,i.dtype,e),a=Ie(f,t,y,v);w=n.makeTensorInfo(m,i.dtype,a.values)}else{const e=new Yr(f),t=[{type:"int32",data:v},{type:"int32",data:y}],r=n.runWebGPUProgram(e,[i],i.dtype,t);w=M({inputs:{x:r},backend:n,attrs:{shape:m}}),n.disposeData(r.dataId)}}return w}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qr={kernelName:r.StringNGrams,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:i,leftPad:s,rightPad:o,padWidth:u,preserveShortSequences:c}=r,{data:l,dataSplits:d}=t,p=n.readSync(l.dataId),h=n.readSync(d.dataId),[f,m]=Se(p,h,a,i,s,o,u,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}},Jr=X({opType:l.TANH}),ea={kernelName:r.Tanh,backendName:"webgpu",kernelFunc:Jr}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +class ta{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;const n=new Array(e.length);for(let r=0;r,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let resRC = getCoordsFromIndex(index);\n setOutputAtIndex(index, getA(${function(e,t=""){if(e>=5)throw Error(`Tile for rank ${e} is not yet supported`);if(1===e)return`(resRC % ${t}aShape)`;const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let a=0;a=5){const e=n.readSync(i.dataId),t="string"===i.dtype?e.map((e=>r.util.decodeString(e))):e,a=Object(r.buffer)(i.shape,i.dtype,t),o=Ce(a,s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}const o=new ta(i.shape,s);return n.runWebGPUProgram(o,[i],i.dtype)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ra{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, negativeInf : f32,\n dir : i32, inc : i32,",this.shaderKey="swap"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let outC = getCoordsFromIndex(index);\n let batch = outC[0];\n let elemIdx = outC[1];\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\n // above, Figure5(a) shows that element[1] is in the second half of\n // the group when group size is 2, but it is in the first half of\n // the group when group size is 4.\n let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc;\n var i = 0;\n if (isFirstInPair) {\n i = elemIdx;\n } else {\n i = elemIdx - uniforms.inc;\n }\n\n var i0 = 0;\n if (uniforms.firstPass == 1) {\n i0 = i;\n } else {\n i0 = i32(getIndices(batch, i));\n }\n\n var i1 = 0;\n if (uniforms.firstPass == 1) {\n i1 = i + uniforms.inc;\n } else {\n i1 = i32(getIndices(batch, i + uniforms.inc));\n }\n\n var x0 = f32(0.0);\n var x1 = f32(0.0);\n if (i0 < uniforms.inputSize) {\n x0 = getX(batch, i0);\n } else {\n x0 = uniforms.negativeInf;\n }\n if (i1 < uniforms.inputSize) {\n x1 = getX(batch, i1);\n } else {\n x1 = uniforms.negativeInf;\n }\n\n let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir;\n let isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) {\n // Elements in opposite order of direction\n let iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutputAtIndex(index, f32(i0));\n } else {\n setOutputAtIndex(index, f32(i1));\n }\n }\n }\n "}}class aa{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return"\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let outC = getCoordsFromIndex(index);\n let batch = outC[0];\n let elemIdx = outC[1];\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _\n // (k=4), we only need to output the indices at positions |, the\n // indices at positions _ can be thrown away, see Figure5(b) After\n // Phase 2 (Merge phase) in the Bitonic Top K paper referenced\n // above.\n // For example, the paper shows we only need to output the orange\n // bars. The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back to\n // the previous sequence to find the corresponding value, we need\n // to double the index. When we double the index, we basically\n // interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k\n // position of each 2k positions by - elemIdx % k. E.g. for output\n // at 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 var i = 0;\n if (elemIdx < uniforms.k) {\n i = elemIdx;\n } else {\n i = elemIdx * 2 - elemIdx % uniforms.k;\n }\n var i0 = 0;\n if (uniforms.firstPass == 1) {\n i0 = i;\n } else {\n i0 = i32(getIndices(batch, i));\n }\n var i1 = 0;\n if (uniforms.firstPass == 1) {\n i1 = i + uniforms.k;\n } else {\n i1 = i32(getIndices(batch, i + uniforms.k));\n }\n\n let x0 = getX(batch, i0);\n var x1 = f32(0.0);\n if (i1 < uniforms.inputSize) {\n x1 = getX(batch, i1);\n } else {\n x1 = x0;\n }\n\n if (x0 >= x1) {\n setOutputAtIndex(index, f32(i0));\n } else {\n setOutputAtIndex(index, f32(i1));\n }\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ia(e,t){null!==t&&e.disposeData(t.dataId)}function sa(e){let t=1;for(;tnull===f?[d,d]:[d,f],b=(e,t,r)=>{const a=m(),i=new ra(r),s=[{type:"int32",data:[c]},{type:"int32",data:[null===f?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[e]},{type:"int32",data:[t]}],o=f;f=n.runWebGPUProgram(i,a,"int32",s),ia(n,o)};for(let e=1;e=1;n/=2)b(t,n,[l,h])}for(let e=h;e>p;e/=2){const t=m(),r=new aa([l,e/2]),a=[{type:"int32",data:[c]},{type:"int32",data:[null===f?1:0]},{type:"int32",data:[p]}],i=f;f=n.runWebGPUProgram(r,t,"int32",a),ia(n,i);const s=p/2,o=2*s;for(let e=s;e>=1;e/=2)b(o,e,f.shape)}let g=f;f=Xe({inputs:{x:f},backend:n,attrs:{begin:0,size:[l,s]}}),ia(n,g);let x=_n({inputs:{x:d,indices:f},backend:n,attrs:{axis:1,batchDims:1}});ia(n,d);const v=u.slice(0,-1);v.push(s),g=f,f=M({inputs:{x:f},attrs:{shape:v},backend:n}),ia(n,g);const k=x;return x=M({inputs:{x:x},attrs:{shape:v},backend:n}),ia(n,k),[x,f]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class ua{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32, fillModeId : i32, fillValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=C(this.outputShape),this.dispatch=I(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return"\n fn mapCoord(outCoord : f32, len : f32) -> f32{\n var inCoord = outCoord;\n if(uniforms.fillModeId == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n let sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +\n inCoord;\n }\n if (inCoord < -len) {\n inCoord = inCoord + sz2;\n } else {\n inCoord = -inCoord - 1.0;\n }\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n let sz2 = 2.0 * len;\n inCoord = inCoord - sz2 * f32(i32(f32(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 (uniforms.fillModeId == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n let sz = len - 1.0;\n inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n let sz = len - 1.0;\n inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (uniforms.fillModeId == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n }\n return outCoord;\n }\n fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,\n channel : i32) -> f32 {\n var outputValue : f32;\n if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = uniforms.fillValue;\n }\n return outputValue;\n }\n\n \n \n \n @stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)\n\n fn main(@builtin(local_invocation_id) LocalId : vec3,\n @builtin(global_invocation_id) GlobalId : vec3,\n @builtin(num_workgroups) NumWorkgroups: vec3) {\n localId = LocalId;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n\n let index = getGlobalIndex();\n\n if (index < uniforms.size) {\n let coords = getCoordsFromIndex(index);\n var outputValue : f32;\n let batch = coords[0];\n let x = coords[2];\n let y = coords[1];\n let channel = coords[3];\n let xf = f32(x);\n let yf = f32(y);\n let a1 = getTransforms(batch, 0);\n let a2 = getTransforms(batch, 1);\n let a3 = getTransforms(batch, 2);\n let b1 = getTransforms(batch, 3);\n let b2 = getTransforms(batch, 4);\n let b3 = getTransforms(batch, 5);\n let c1 = getTransforms(batch, 6);\n let c2 = getTransforms(batch, 7);\n let projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = uniforms.fillValue;\n } else {\n let inX = (a1 * xf + a2 * yf + a3) / projection;\n let inY = (b1 * xf + b2 * yf + b3) / projection;\n let mapX = mapCoord(inX, f32(uniforms.imageShape[2]));\n let mapY = mapCoord(inY, f32(uniforms.imageShape[1]));\n\n if (uniforms.interpolationModeId == 1) {\n let coordY = i32(round(mapY));\n let coordX = i32(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n let yFloor = floor(mapY);\n let xFloor = floor(mapX);\n let yCeil = yFloor + 1.0;\n let xCeil = xFloor + 1.0;\n let valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, i32(yFloor), i32(xCeil), channel);\n let valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, i32(yCeil), i32(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutputAtIndex(index, outputValue);\n }\n }\n "}} +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ca=[B,Ne,Re,Me,ze,We,Ve,He,Ze,nt,at,ot,q,ht,vt,wt,St,Ct,Tt,Ft,Mt,Pt,Lt,qt,Xt,Zt,Jt,tn,rn,on,cn,mn,dn,hn,vn,kn,yn,In,Cn,Tn,An,V,lt,Nn,Rn,Mn,Pn,jn,zn,Gn,Vn,Hn,qn,Kn,Yn,Qn,Wt,Jn,er,tr,Je,ar,ir,ur,lr,dr,pr,hr,tt,mr,gr,vr,D,yr,Ir,_r,Or,$r,Nr,Rr,Mr,Pr,Ye,Zr,Qr,Lr,zr,Gr,Ur,Hr,qr,Xr,jr,Ht,ea,na,oa,{kernelName:r.Transform,backendName:"webgpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,transforms:i}=t,{interpolation:s,fillMode:o,fillValue:u,outputShape:c}=r,[l,d,p,h]=a.shape,[f,m]=null!=c?c:[d,p],b=new ua([l,f,m,h]),g="nearest"===s?1:2;let x;switch(o){case"constant":default:x=1;break;case"reflect":x=2;break;case"wrap":x=3;break;case"nearest":x=4}const v=[{type:"int32",data:[g]},{type:"int32",data:[x]},{type:"float32",data:[u]}];return n.runWebGPUProgram(b,[a,i],"float32",v)}},Le,{kernelName:r.Unpack,backendName:"webgpu",kernelFunc: +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:i}=r;i<0&&(i+=a.shape.length);const s=a,o=s.shape.length,u=a.shape[i],c=new Array(o-1);let l=0;for(let e=0;en.disposeData(e.dataId))),f}},rr]; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */for(const e of ca)Object(r.registerKernel)(e); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class la{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireUploadBuffer(e,t){return this.acquireBuffer(e,t,!0)}acquireBuffer(e,t,n=!1){const r=da(e,t);if(this.freeBuffers.has(r)||this.freeBuffers.set(r,[]),this.usedBuffers.has(r)||this.usedBuffers.set(r,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(r).length>0){this.numFreeBuffers--;const e=this.freeBuffers.get(r).shift();return this.usedBuffers.get(r).push(e),e}this.numBytesAllocated+=e;const a=this.device.createBuffer({mappedAtCreation:n,size:e,usage:t});return this.usedBuffers.get(r).push(a),a}releaseBuffer(e,t,n){if(0===this.freeBuffers.size)return;const r=da(t,n);this.freeBuffers.has(r)||this.freeBuffers.set(r,[]),this.freeBuffers.get(r).push(e),this.numFreeBuffers++,this.numUsedBuffers--;const a=this.usedBuffers.get(r),i=a.indexOf(e);if(i<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");a.splice(i,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,n){e.mapAsync(GPUMapMode.WRITE).then((()=>{this.releaseBuffer(e,t,n)}),(e=>{}))}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach(((e,t)=>{e.forEach((e=>{e.destroy()}))})),this.usedBuffers.forEach(((e,t)=>{e.forEach((e=>{e.destroy()}))})),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function da(e,t){return`${e}_${t}`} +/** + * @license + * Copyright 2022 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */class pa{constructor(e){this.device=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures=new Map,this.usedTextures=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireTexture(e,t,n,r){const a=e*t*fa(n),i=ha(e,t,n,r);if(this.freeTextures.has(i)||this.freeTextures.set(i,[]),this.usedTextures.has(i)||this.usedTextures.set(i,[]),this.numBytesUsed+=a,this.numUsedTextures++,this.freeTextures.get(i).length>0){this.numFreeTextures--;const e=this.freeTextures.get(i).shift();return this.usedTextures.get(i).push(e),e}this.numBytesAllocated+=a;const s=this.device.createTexture({size:[e,t],format:n,usage:r});return this.usedTextures.get(i).push(s),s}releaseTexture(e,t,n,r,a){if(0===this.freeTextures.size)return;const i=ha(t,n,r,a);this.freeTextures.has(i)||this.freeTextures.set(i,[]),this.freeTextures.get(i).push(e),this.numFreeTextures++,this.numUsedTextures--;const s=this.usedTextures.get(i),o=s.indexOf(e);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");s.splice(o,1);const u=t*n*fa(r);this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach(((e,t)=>{e.forEach((e=>{e.destroy()}))})),this.usedTextures.forEach(((e,t)=>{e.forEach((e=>{e.destroy()}))})),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}}function ha(e,t,n,r){return`${e}_${t}_${n}_${r}`}function fa(e){if("rgba8unorm"===e)return 16;throw new Error(`${e} is not supported!`)} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ma=(e,t,n,r,a,i=!1)=>{const s=g(r,{dtype:a.dtype,shape:a.shape},t,i),o=e.createShaderModule({code:s,label:t.constructor.name});return e.createComputePipeline({layout:n,compute:{module:o,entryPoint:"main"},label:t.constructor.name})};function ba(e,t,n=[],r="",a=""){return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map((e=>e.length)).join(",")+n.join(",")+e.variableNames.join(",")+r+a} +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ga=Object(r.env)().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),xa=(e,t)=>{const n=e.limits.maxComputeWorkgroupsPerDimension,a=t.dispatchLayout,i=t.dispatch;if(i.every((e=>e<=n)))return i;r.util.assert(i[0]>n&&void 0===a.y&&void 0===a.z,(()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension."));let s=Math.ceil(Math.sqrt(i[0]));return s>n?(s=Math.ceil(Math.cbrt(i[0])),r.util.assert(s<=n,(()=>"Total dispatch size exceeds WebGPU maximum.")),[s,s,s]):[s,s,1]};class va extends r.KernelBackend{constructor(e,t=!1){if(super(),this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.textureDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,this.fromPixelTextureLayout=null,this.fromPixelImportTextureLayout=null,!T())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new la(this.device),this.textureManager=new pa(this.device),this.tensorMap=new r.DataStorage(this,Object(r.engine)()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),Object(r.env)().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return va.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach((e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)})),this.uniformDisposalQueue.forEach((e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage))),this.stagingDisposalQueue.forEach((e=>this.bufferManager.releaseUploadBuffer(e.buffer,e.byteSize,e.usage))),this.textureDisposalQueue.forEach((e=>this.textureManager.releaseTexture(e.texture,e.width,e.height,e.format,e.usage))),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.textureDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){const n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);const{complexTensorInfos:r}=this.tensorMap.get(e);null!=r&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}getTextureManager(){return this.textureManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){const t=this.tensorMap.get(e);null!=t&&null!=t.bufferInfo.buffer&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){if(this.tensorMap.has(e)){return this.tensorMap.get(e).refCount}return 0}incRef(e){this.tensorMap.get(e).refCount++}decRef(e){if(this.tensorMap.has(e)){this.tensorMap.get(e).refCount--}}write(e,t,n){if("complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const a={id:this.nextDataId()},i=r.util.sizeFromShape(t)*O(n);return this.tensorMap.set(a,{dtype:n,values:e,bufferInfo:{byteSize:i,usage:this.defaultGpuBufferUsage()},refCount:1}),a}move(e,t,n,a,i){if("complex64"===a)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s=r.util.sizeFromShape(n)*O(a);this.tensorMap.set(e,{dtype:a,values:t,bufferInfo:{byteSize:s,usage:this.defaultGpuBufferUsage()},refCount:i})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.end(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(null!=e.values)return e.values;const t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);const n=t.getMappedRange().slice(0);return t.unmap(),null!=t&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),Object(r.env)().getBool("WEBGPU_USE_PROFILE_TOOL")&&(r.util.assert(void 0!==this.dummyContext,(()=>"Fail to get context for profiling tool")),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){const n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){const t=this.tensorMap.get(e),{values:n}=t;if(null==n)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);const t=this.tensorMap.get(e),{values:n}=t;if(null!=n)return this.convertAndCacheOnCPU(e,n);let a;if("complex64"===t.dtype){const e=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),n=e[0],i=e[1];a=r.backend_util.mergeRealAndImagArrays(n,i)}else{a=function(e,t){if("float32"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(await this.getBufferData(t),t.dtype)}return this.convertAndCacheOnCPU(e,a),a}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>r.util.decodeString(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Object(r.buffer)(e.shape,e.dtype,n)}async time(e){const t=this.activeTimers,n=[];let a=!1;null==this.programTimersStack?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,e();const i=r.util.flatten(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=r.util.flatten(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,a&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},u=await Promise.all(i);return o.kernelMs=r.util.sum(u),o.getExtraProfileInfo=()=>u.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let a;if("string"===t&&null!=n&&n.length>0&&r.util.isString(n[0])){const i=n.map((e=>r.util.encodeString(e)));a=this.write(i,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;const t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){const t=this.tensorMap.get(e);if(null==t.bufferInfo.buffer&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values)){const e=this.bufferManager.acquireUploadBuffer(t.bufferInfo.byteSize,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),n=e.getMappedRange();"int32"===t.dtype||"bool"===t.dtype?new Int32Array(n).set(t.values):new Float32Array(n).set(t.values),e.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e,0,t.bufferInfo.buffer,0,t.bufferInfo.byteSize);const r={byteSize:t.bufferInfo.byteSize,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:e};this.stagingDisposalQueue.push(r)}}makeUniforms(e){let t=0,n=0;const a=[];e.forEach((e=>{let i;switch(0===e.data.length&&(e.data=[1]),e.data.length){case 1:i=4;break;case 2:i=8;break;case 3:case 4:case 5:case 6:i=16;break;default:r.util.assert(!1,(()=>`Unsupported ${e.data.length}D shape`))}5!==n&&6!==n||(i=16),t=Math.ceil(t/i)*i,n=e.data.length,a.push(t),t+=4*e.data.length}));const i=new ArrayBuffer(t);e.forEach(((e,t)=>{const n=a[t];"int32"===e.type?new Int32Array(i,n,e.data.length).set(e.data):"uint32"===e.type?new Uint32Array(i,n,e.data.length).set(e.data):new Float32Array(i,n,e.data.length).set(e.data)}));const s=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.queue.writeBuffer(s,0,i,0,t);const o={byteSize:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:s};return this.uniformDisposalQueue.push(o),{offset:0,size:t,buffer:s}}createLayout(e){const t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let n=0;ne.shape)),u="int32";o.map((e=>{s.push({type:u,data:e})}));const c=r.util.computeStrides(i.shape);if(s.push({type:u,data:c}),e.size){const t=r.util.sizeFromShape(e.outputShape);s.push({type:u,data:[e.isVec4?t/4:t]})}a&&(s=[...s,...a]);const l=this.makeUniforms(s),d=t.map(((t,n)=>{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.");return this.uploadToGPU(t.dataId),{dtype:this.tensorMap.get(t.dataId).dtype,shape:t.shape,name:e.variableNames[n]}})),p=d.map((e=>e.dtype)).concat(i.dtype),h=d.map((e=>r.backend_util.getBroadcastDims(e.shape,i.shape))),f=d.map((e=>r.util.arraysEqual(e.shape,i.shape))).join("_"),m=h.map((e=>e.join("_"))).join(";"),b=ba(e,o,p,m,f),{bindGroupLayout:g,pipelineLayout:x}=this.getCachedOrCreateLayout(e.variableNames.length),v=this.getAndSavePipeline(b,(()=>ma(this.device,e,x,d,i))),k=null!=this.activeTimers,y=((e,t,n,r,a)=>{const i=[r,...n];return a&&i.push(a),e.createBindGroup({layout:t,entries:i.map(((e,t)=>({binding:t,resource:e})))})})(this.device,g,t.map((e=>this.tensorToBinding(e))),this.tensorToBinding(i),l);this.ensureCommandEncoderReady();const w=this.getComputePass();return k&&this.supportTimeQuery&&w.writeTimestamp(this.querySet,0),w.setPipeline(v),w.setBindGroup(0,y),w.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),k&&this.supportTimeQuery&&w.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach((e=>{this.commandQueueOwnedIds.add(e.dataId)})),this.commandQueueOwnedIds.add(i.dataId),Object(r.env)().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),k&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),i}getFromPixelTextureLayout(e){return e?(null===this.fromPixelImportTextureLayout&&(this.fromPixelImportTextureLayout=this.createFromPixelTextureLayout(!0)),this.fromPixelImportTextureLayout):(null===this.fromPixelTextureLayout&&(this.fromPixelTextureLayout=this.createFromPixelTextureLayout(!1)),this.fromPixelTextureLayout)}createFromPixelTextureLayout(e){const t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),e?t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}):t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});const n=this.device.createBindGroupLayout({entries:t});return{bindGroupLayout:n,pipelineLayout:this.device.createPipelineLayout({bindGroupLayouts:[n]})}}copyExternalImageToTexture(e,t){const n=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,r="rgba8unorm",a=this.textureManager.acquireTexture(t[1],t[0],r,n),i=a.createView();this.queue.copyExternalImageToTexture({source:e},{texture:a},[t[1],t[0]]);const s={width:t[1],height:t[0],format:r,usage:n,texture:a};return this.textureDisposalQueue.push(s),i}runFromPixelsProgram(e,t,n,a,i){e.dispatch=xa(this.device,e);const s=this.makeTensorInfo(t,"int32");if(0===r.util.sizeFromShape(s.shape)){return this.tensorMap.get(s.dataId).values=r.util.getTypedArrayFromDType(s.dtype,0),s}this.uploadToGPU(s.dataId);const o=ba(e,[s.shape]),u=this.getFromPixelTextureLayout(a),c=this.getAndSavePipeline(o,(()=>ma(this.device,e,u.pipelineLayout,[],s,!0)));let l;if(a){const e={source:i};l=this.device.importExternalTexture(e)}else l=this.copyExternalImageToTexture(i,s.shape);const d=this.tensorToBinding(s),p=this.makeUniforms(n),h=this.device.createBindGroup({layout:u.bindGroupLayout,entries:[{binding:0,resource:{buffer:d.buffer}},{binding:1,resource:l},{binding:2,resource:{buffer:p.buffer}}]});this.ensureCommandEncoderReady();const f=this.getComputePass(),m=null!=this.activeTimers;return m&&this.supportTimeQuery&&f.writeTimestamp(this.querySet,0),f.setPipeline(c),f.setBindGroup(0,h),f.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),m&&this.supportTimeQuery&&f.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(s.dataId),this.dispatchNumberInEncoder++,Object(r.env)().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),m&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),s}async getTimeFromQuerySet(e){const t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);const r=new BigUint64Array(n.getMappedRange()),a=Number(r[1]-r[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),a/1e6}shouldExecuteOnCPU(e,t=ga){return Object(r.env)().getBool("WEBGPU_CPU_FORWARD")&&e.every((e=>null==this.tensorMap.get(e.dataId).bufferInfo.buffer&&r.util.sizeFromShape(e.shape){Object(r.env)().set("CHECK_COMPUTATION_FOR_ERRORS",!1);const e={powerPreference:Object(r.env)().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n=t.limits,a={},i=t.features.has("timestamp-query");a.requiredLimits={maxComputeWorkgroupStorageSize:n.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:n.maxComputeWorkgroupsPerDimension},i?a.requiredFeatures=["timestamp-query"]:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");const s=await t.requestDevice(a);return new va(s,i)}),3)},function(e,t,n){"use strict";var r=n(0),a=n(7); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const i=r.kernel_impls.whereImpl;class s extends r.KernelBackend{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new r.DataStorage(this,Object(r.engine)())}nextDataId(){return s.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Object(r.env)().get("IS_NODE")&&r.backend_util.warn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));const a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if("string"===t&&null!=n&&n.length>0&&r.util.isString(n[0])){const i=n.map((e=>r.util.encodeString(e)));a=this.write(i,e,t)}else a=this.write(n,e,t);return{dataId:a,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,r,a){this.data.set(e,{values:t,dtype:r,refCount:a})}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){const e=this.readSync(n.real.dataId),t=this.readSync(n.imag.dataId);return r.backend_util.mergeRealAndImagArrays(e,t)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>r.util.decodeString(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Object(r.buffer)(e.shape,e.dtype,n)}makeOutput(e,t,n){return Object(r.engine)().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=r.util.now();e();return{kernelMs:r.util.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Object(a.a)([e],"where");const t=this.readSync(e.dataId);return i(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}s.nextDataId=0, +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +Object(r.registerBackend)("cpu",(()=>new s),1);var o=n(8); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const u=Object(o.a)(r.Elu,(e=>e>=0?e:Math.exp(e)-1)),c={kernelName:r.Elu,backendName:"cpu",kernelFunc:u};var l=n(19); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function d(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{alpha:o}=i;Object(a.a)([s],"leakyRelu");const u=r.util.sizeFromShape(s.shape),c=n.data.get(s.dataId).values,l=r.util.getTypedArrayFromDType("float32",u);for(let e=0;ee<0?t*e:e));function m(e){const{inputs:t,backend:n}=e,{x:r,alpha:i}=t;Object(a.a)([r,i],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(i.dataId).values,[u,c]=f(r.shape,i.shape,s,o,"float32");return n.makeTensorInfo(c,"float32",u)}const b={kernelName:r.Prelu,backendName:"cpu",kernelFunc:m},g=Object(o.a)(r.Relu,(e=>Math.max(0,e))),x={kernelName:r.Relu,backendName:"cpu",kernelFunc:g},v=Object(o.a)(r.Relu6,(e=>Math.min(Math.max(0,e),6))),k={kernelName:r.Relu6,backendName:"cpu",kernelFunc:v}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var y=n(45); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function w(e,t,n,r,a){if("linear"===n)return Object(l.a)({inputs:{x:t},backend:e});if("relu"===n)return g({inputs:{x:t},backend:e});if("elu"===n)return u({inputs:{x:t},backend:e});if("relu6"===n)return v({inputs:{x:t},backend:e});if("prelu"===n)return m({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return d({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return Object(y.a)({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}var I=n(26); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function S(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{shape:s}=a,o=r.util.sizeFromShape(i.shape),u=r.util.inferFromImplicitShape(s,o),c=r.util.sizeFromShape(u);r.util.assert(o===c,(()=>`The new shape (${u}) has ${c} elements and the old shape (${i.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(i.dataId);const l=n.data.get(i.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=u,t.shape=u}return{dataId:i.dataId,shape:u,dtype:i.dtype}}const _={kernelName:r.Reshape,backendName:"cpu",kernelFunc:S}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function C(e){const{inputs:t,backend:n,attrs:i}=e,{a:s,b:o}=t,{transposeA:u,transposeB:c}=i;Object(a.a)([s,o],"matMul");const l=s.shape.length,d=o.shape.length,p=u?s.shape[l-2]:s.shape[l-1],h=c?o.shape[d-1]:o.shape[d-2],f=u?s.shape[l-1]:s.shape[l-2],m=c?o.shape[d-2]:o.shape[d-1],b=s.shape.slice(0,-2),g=o.shape.slice(0,-2),x=r.util.sizeFromShape(b),v=r.util.sizeFromShape(g),k=r.broadcast_util.assertAndGetBroadcastShape(s.shape.slice(0,-2),o.shape.slice(0,-2)).concat([f,m]);r.util.assert(p===h,(()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${s.shape} and ${o.shape} and transposeA=${u} and transposeB=${c} must match.`));const y=c?[v,m,h]:[v,h,m],w=S({inputs:{x:s},backend:n,attrs:{shape:u?[x,p,f]:[x,f,p]}}),I=S({inputs:{x:o},backend:n,attrs:{shape:y}}),_=u?w.shape[1]:w.shape[2],C=u?w.shape[2]:w.shape[1],O=c?I.shape[1]:I.shape[2],T=Math.max(x,v),$=n.data.get(w.dataId).values,A=n.data.get(I.dataId).values,N=r.util.computeStrides(w.shape),E=r.util.computeStrides(I.shape),[R,F,M]=u?[N[0],1,N[1]]:[N[0],N[1],1],[D,P,B]=c?[1,E[1],E[0]]:[E[1],1,E[0]],j=C*O,L=Object(r.buffer)([T,C,O],w.dtype),z=L.values,W=n.blockSize;for(let e=0;eMath.acos(e))),N={kernelName:r.Acos,backendName:"cpu",kernelFunc:A},E=Object(o.a)(r.Acosh,(e=>Math.acosh(e))),R={kernelName:r.Acosh,backendName:"cpu",kernelFunc:E};const F={kernelName:r.AddN,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,i=t;Object(a.a)(t,"addN");const s=i.map((e=>n.data.get(e.dataId).values)),o=Object(r.buffer)(i[0].shape,i[0].dtype),u=o.values;for(let e=0;en&&(n=a,r=e)}m[e]=r}return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(p,"int32",m)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const j={kernelName:r.ArgMin,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{axis:o}=i;Object(a.a)(s,"argMin");let u=r.util.parseAxisParam(o,s.shape);const c=r.backend_util.getAxesPermutation(u,s.shape.length);let l=s;const d=[];null!=c&&(l=Object(M.a)({inputs:{x:s},backend:n,attrs:{perm:c}}),d.push(l),u=r.backend_util.getInnerMostAxes(u.length,l.shape.length)),u=[u[0]],r.backend_util.assertAxesAreInnerMostDims("argMin",u,l.shape.length);const[p,h]=r.backend_util.computeOutAndReduceShapes(l.shape,u),f=r.util.sizeFromShape(p),m=r.util.makeZerosTypedArray(f,"int32"),b=r.util.sizeFromShape(h),g=n.data.get(l.dataId).values;for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(p,"int32",m)}},L=Object(o.a)(r.Asin,(e=>Math.asin(e))),z={kernelName:r.Asin,backendName:"cpu",kernelFunc:L},W=Object(o.a)(r.Asinh,(e=>Math.asinh(e))),G={kernelName:r.Asinh,backendName:"cpu",kernelFunc:W},U=Object(o.a)(r.Atan,(e=>Math.atan(e))),V={kernelName:r.Atan,backendName:"cpu",kernelFunc:U}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var H=n(13); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const q=Object(h.a)(((e,t)=>Math.atan2(e,t))),K=Object(H.a)(r.Atan2,q),X={kernelName:r.Atan2,backendName:"cpu",kernelFunc:K},Y=Object(o.a)(r.Atanh,(e=>Math.atanh(e))),Z={kernelName:r.Atanh,backendName:"cpu",kernelFunc:Y}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Q(e,t,n,a,i,s){const o=i.strideHeight,u=i.strideWidth,c=i.dilationHeight,l=i.dilationWidth,d=i.effectiveFilterHeight,p=i.effectiveFilterWidth,h=i.padInfo.top,f=i.padInfo.left,m="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,b=Object(r.buffer)(i.outShape,n),g=b.values,x=i.outShape[1]*i.outShape[2]*i.outShape[3],v=i.outShape[2]*i.outShape[3],k=i.outShape[3];for(let t=0;tb?b=r:"avg"===s&&(x+=r,v++)}if(isNaN(b))break}g[I+n*k+t]="avg"===s?x/v:b}}}return b}function J(e,t,n,a,i=!1,s=!1){const o=Object(r.buffer)(a.outShape,"int32"),u=a.strideHeight,c=a.strideWidth,l=a.dilationHeight,d=a.dilationWidth,p=a.effectiveFilterHeight,h=a.effectiveFilterWidth,f=a.padInfo.top,m=a.padInfo.left,b=Object(r.buffer)(t,n,e);for(let e=0;ek&&(k=c,y=i?s?((e*a.inHeight+n)*a.inWidth+r)*a.inChannels+t:(n*a.inWidth+r)*a.inChannels+t:o*h+u)}}o.set(y,e,n,u,t)}}return o}function ee(e,t,n,a,i,s){const o=i.strideDepth,u=i.strideHeight,c=i.strideWidth,l=i.dilationDepth,d=i.dilationHeight,p=i.dilationWidth,h=i.effectiveFilterDepth,f=i.effectiveFilterHeight,m=i.effectiveFilterWidth,b=i.padInfo.front,g=i.padInfo.top,x=i.padInfo.left,v="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,k=Object(r.buffer)(i.outShape,n),y=k.values,w=i.outShape[1]*i.outShape[2]*i.outShape[3]*i.outShape[4],I=i.outShape[2]*i.outShape[3]*i.outShape[4],S=i.outShape[3]*i.outShape[4],_=i.outShape[4];for(let t=0;tw?w=i:"avg"===s&&(I+=i,S++),isNaN(w))break}if(isNaN(w))break}if(isNaN(w))break}y[g+t]="avg"===s?I/S:w}}}}return k}const te={kernelName:r.AvgPool,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t;Object(a.a)(s,"avgPool");const{filterSize:o,strides:u,pad:c,dimRoundingMode:d}=i;r.util.assert(r.backend_util.eitherStridesOrDilationsAreOne(u,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${u} and dilations '1'`));const p=r.backend_util.computePool2DInfo(s.shape,o,u,1,c,d);let h;if(1===p.filterWidth&&1===p.filterHeight&&r.util.arraysEqual(p.inShape,p.outShape))h=Object(l.a)({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=r.util.computeStrides(s.shape),a=Q(e,s.shape,s.dtype,t,p,"avg");h=n.makeTensorInfo(p.outShape,s.dtype,a.values)}return h}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ne={kernelName:r.AvgPool3D,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{filterSize:o,strides:u,pad:c,dimRoundingMode:l,dataFormat:d}=i;Object(a.a)(s,"avgPool3d");const p=r.backend_util.computePool3DInfo(s.shape,o,u,1,c,l,d),h=ee(n.data.get(s.dataId).values,s.shape,s.dtype,r.util.computeStrides(s.shape),p,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const re={kernelName:r.AvgPool3DGrad,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{dy:s,input:o}=t,{filterSize:u,strides:c,pad:l,dimRoundingMode:d}=i;Object(a.a)([s,o],"avgPool3DGrad");const p=r.backend_util.computePool3DInfo(o.shape,u,c,1,l,d),h=p.strideDepth,f=p.strideHeight,m=p.strideWidth,b=p.filterDepth,g=p.filterHeight,x=p.filterWidth,v=p.dilationDepth,k=p.dilationHeight,y=p.dilationWidth,w=p.effectiveFilterDepth,I=p.effectiveFilterHeight,S=p.effectiveFilterWidth,_=w-1-p.padInfo.front,C=S-1-p.padInfo.left,O=I-1-p.padInfo.top,T=Object(r.buffer)(o.shape,"float32"),$=1/(b*g*x),A=n.bufferSync(s);for(let e=0;e=p.outDepth||Math.floor(r)!==r))for(let n=0;n=p.outHeight||Math.floor(a)!==a))for(let n=0;n=p.outWidth||Math.floor(i)!==i)continue;u+=A.get(e,r,a,i,t)}}}T.set(u*$,e,n,r,a,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ae={kernelName:r.AvgPoolGrad,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{dy:s,input:o}=t,u=o;Object(a.a)([s,o],"avgPoolGrad");const{filterSize:c,strides:l,pad:d}=i,p=r.backend_util.computePool2DInfo(u.shape,c,l,1,d),h=p.strideHeight,f=p.strideWidth,m=p.filterHeight,b=p.filterWidth,g=p.dilationHeight,x=p.dilationWidth,v=p.effectiveFilterHeight,k=p.effectiveFilterWidth,y=k-1-p.padInfo.left,w=v-1-p.padInfo.top,I=Object(r.buffer)(u.shape,"float32"),S=1/(m*b),_=n.data.get(s.dataId).values,C=Object(r.buffer)(s.shape,"float32",_);for(let e=0;e=p.outHeight||Math.floor(r)!==r))for(let n=0;n=p.outWidth||Math.floor(a)!==a)continue;s+=C.get(e,r,a,t)}}I.set(s*S,e,n,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ie={kernelName:r.FusedBatchNorm,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s,scale:o,offset:u,mean:c,variance:l}=t;r.util.assert(c.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),r.util.assert(null==u||c.shape.length===u.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),r.util.assert(null==o||c.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),Object(a.a)([s,c,l,o,u],"batchNorm");let{varianceEpsilon:d}=i;null==d&&(d=.001);const p=n.data.get(s.dataId).values,h=n.data.get(c.dataId).values,f=n.data.get(l.dataId).values,m=o?n.data.get(o.dataId).values:new Float32Array([1]),b=u?n.data.get(u.dataId).values:new Float32Array([0]),g=new Float32Array(p.length),x=b.length,v=m.length,k=f.length,y=h.length;let w=0,I=0,S=0,_=0;for(let e=0;e=x&&(w=0),I>=y&&(I=0),S>=v&&(S=0),_>=k&&(_=0);return n.makeTensorInfo(s.shape,s.dtype,g)}};var se=n(22); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const oe={kernelName:r.BatchToSpaceND,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{blockShape:o,crops:u}=i;Object(a.a)([s],"batchToSpaceND");const c=o.reduce(((e,t)=>e*t)),l=r.backend_util.getReshaped(s.shape,o,c),d=r.backend_util.getPermuted(l.length,o.length),p=r.backend_util.getReshapedPermuted(s.shape,o,c),h=r.backend_util.getSliceBeginCoords(u,o.length),f=r.backend_util.getSliceSize(p,u,o.length),m=S({inputs:{x:s},backend:n,attrs:{shape:l}}),b=Object(M.a)({inputs:{x:m},backend:n,attrs:{perm:d}}),g=S({inputs:{x:b},backend:n,attrs:{shape:p}}),x=Object(se.a)({inputs:{x:g},backend:n,attrs:{begin:h,size:f}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(g),x}};var ue=n(33); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ce={kernelName:r.Bincount,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:i}=t,{size:s}=r,o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values,c=Object(ue.a)(o,u,i.dtype,i.shape,s);return n.makeTensorInfo([s],i.dtype,c)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const le={kernelName:r.BroadcastArgs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:a,s1:i}=t,s=n.data.get(a.dataId).values,o=n.data.get(i.dataId).values,u=r.backend_util.assertAndGetBroadcastShape(Array.from(s),Array.from(o));return n.makeTensorInfo([u.length],"int32",Int32Array.from(u))}};var de=n(28),pe=n(55); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const he=Object(o.a)(r.ClipByValue,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e{const{x:t}=e.inputs,n=e.backend,a=new Float32Array(r.util.sizeFromShape(t.shape)),i=n.data.get(t.dataId),s=i.complexTensorInfos.real,o=i.complexTensorInfos.imag,u=n.data.get(s.dataId).values,c=n.data.get(o.dataId).values;for(let e=0;ee.shape)),s);if(0===r.util.sizeFromShape(o))return n.makeTensorInfo(o,t[0].dtype,[]);const u=t.filter((e=>r.util.sizeFromShape(e.shape)>0));if(1===u.length)return Object(l.a)({inputs:{x:u[0]},backend:n});const c=u.map((e=>e.shape));if(r.backend_util.assertParamsConsistent(c,s),"complex64"===u[0].dtype){const e=u.map((e=>Object(ke.a)({inputs:{input:e},backend:n}))),t=u.map((e=>xe({inputs:{input:e},backend:n}))),r=ye({inputs:e,backend:n,attrs:{axis:s}}),a=ye({inputs:t,backend:n,attrs:{axis:s}}),i=Object(me.a)({inputs:{real:r,imag:a},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}const d=u.map((e=>{const t=r.util.sizeFromShape(e.shape.slice(s));return S({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),p=d.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=r.backend_util.computeOutShape(d.map((e=>e.shape)),1);const h=1===d[0].shape[0],f=Object(ge.a)(p,o,t[0].dtype,h),m=r.backend_util.computeOutShape(u.map((e=>e.shape)),s),b=n.makeTensorInfo(m,t[0].dtype,f);return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}const we={kernelName:r.Concat,backendName:"cpu",kernelFunc:ye}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Ie(e){const{inputs:t,backend:n,attrs:i}=e,{x:s,filter:o}=t,{strides:u,pad:c,dataFormat:l,dilations:d,dimRoundingMode:p}=i;Object(a.a)([s,o],"conv2d");const h=r.backend_util.convertConv2DDataFormat(l),f=r.backend_util.computeConv2DInfo(s.shape,o.shape,u,d,c,p,!1,h),m=f.filterHeight,b=f.filterWidth,g=f.dilationHeight,x=f.dilationWidth,v=f.padInfo.left,k=f.padInfo.top,y="channelsLast"===f.dataFormat,w=new r.TensorBuffer(f.outShape,s.dtype),I=r.util.computeStrides(s.shape),S=r.util.computeStrides(o.shape),_=I[0],C=y?I[1]:I[2],O=y?I[2]:1,T=y?1:I[1],$=w.strides[0],A=y?w.strides[1]:w.strides[2],N=y?w.strides[2]:1,E=y?1:w.strides[1],R=n.data.get(s.dataId).values,F=n.data.get(o.dataId).values,M=w.values;for(let e=0;e=f.inHeight)continue;const i=e*S[0],s=t+n*C;for(let e=0;e=f.inWidth)continue;const a=s+r*O;let o=i+e*S[1];for(let e=0;e=d.inDepth)continue;const i=e*O[0],s=t+n*C[1];for(let e=0;e=d.inHeight)continue;const a=i+e*O[1],o=s+r*C[2];for(let e=0;e=d.inWidth)continue;const i=a+e*O[2],s=o+t*d.inChannels;let u=i;for(let e=0;eMath.cos(e))),Ne={kernelName:r.Cos,backendName:"cpu",kernelFunc:Ae},Ee=Object(o.a)(r.Cosh,(e=>Math.cosh(e))),Re={kernelName:r.Cosh,backendName:"cpu",kernelFunc:Ee}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Fe={kernelName:r.CropAndResize,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:a}=e,{image:i,boxes:s,boxInd:o}=t,{cropSize:u,method:c,extrapolationValue:l}=a,[d,p,h,f]=i.shape,m=s.shape[0],[b,g]=u,x=Object(r.buffer)([m,b,g,f],"float32"),v=n.data.get(s.dataId).values,k=n.data.get(o.dataId).values,y=n.data.get(i.dataId).values,w=r.util.computeStrides(i.shape),I=r.util.computeStrides(x.shape);for(let e=0;e=d)continue;const o=b>1?(a-n)*(p-1)/(b-1):0,u=g>1?(i-r)*(h-1)/(g-1):0;for(let t=0;t1?n*(p-1)+t*o:.5*(n+a)*(p-1);if(d<0||d>p-1)for(let n=0;n1?r*(h-1)+c*u:.5*(r+i)*(h-1);if(d<0||d>h-1){for(let n=0;n1?r*(h-1)+n*u:.5*(r+i)*(h-1);if(a<0||a>h-1){for(let r=0;re+b-t-1:(e,t)=>e+t;for(let e=0;ee+b-t-1:(e,t)=>e+t;for(let e=0;e`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`));const u=i.shape[0],c=i.shape[1],l=i.shape[2],d=i.shape[3],p=c*s,h=l*s,f=d/(s*s),m=n.data.get(i.dataId).values,b=new Float32Array(u*p*h*f);let g=0;for(let e=0;e`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${f}'`));const m=r.backend_util.computeConv2DInfo(s.shape,o.shape,u,f,c,d,!0),{filterHeight:b,filterWidth:g,dilationHeight:x,dilationWidth:v,padInfo:k}=m,y=k.left,w=k.top,I=m.outChannels/m.inChannels,S=new r.TensorBuffer(m.outShape,s.dtype),_=n.data.get(s.dataId).values,C=n.data.get(o.dataId).values,O=S.values;for(let e=0;e=m.inHeight)continue;const i=e*h[0],s=t+n*p[1];for(let e=0;e=m.inWidth)continue;const a=i+e*h[1],o=s+r*m.inChannels;let u=t,c=a;for(let e=0;e{const{x:a,filter:i}=e,{strides:s,pad:o,dilations:u}=n,c=t,l=c.data.get(a.dataId).values,d=a.shape.length,p=c.data.get(i.dataId).values,h=i.shape.length,{batchSize:f,inHeight:m,inWidth:b,inChannels:g,outHeight:x,outWidth:v,padInfo:k,strideHeight:y,strideWidth:w,filterHeight:I,filterWidth:S,dilationHeight:_,dilationWidth:C,outShape:O}=r.backend_util.computeDilation2DInfo(a.shape,i.shape,s,o,"NHWC",u),T=r.util.sizeFromShape(O),$=O.length,A=r.util.getArrayFromDType(a.dtype,T);for(let e=0;e=0&&s=0&&fc&&(c=b)}}}A[r.util.locToIndex([e,t,s,u],$,r.util.computeStrides(O))]=c}}}return{dataId:c.write(r.util.toTypedArray(A,a.dtype),O,a.dtype),shape:O,dtype:a.dtype}}},Ve={kernelName:r.Dilation2DBackpropFilter,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:a,filter:i,dy:s}=e,{strides:o,pad:u,dilations:c}=n,l=t,d=r.util.toNestedArray(a.shape,l.data.get(a.dataId).values),p=r.util.toNestedArray(i.shape,l.data.get(i.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:b,outHeight:g,outWidth:x,padInfo:v,strideHeight:k,strideWidth:y,filterHeight:w,filterWidth:I,dilationHeight:S,dilationWidth:_,outShape:C}=r.backend_util.computeDilation2DInfo(a.shape,i.shape,o,u,"NHWC",c);r.util.assert(s.rank===C.length,(()=>`Error in ${r.Dilation2DBackpropFilter}, dy must have the same rank as output ${C.length}, but got ${s.rank}`));const O=r.util.toNestedArray(C,l.data.get(s.dataId).values),T=r.util.makeZerosNestedTypedArray(i.shape,i.dtype);for(let e=0;e=0&&r=0&&cs&&(s=a,o=t,u=n)}}}T[o][u][i]+=O[e][t][r][i]}}}return{dataId:l.write(r.util.toTypedArray(T,a.dtype),i.shape,i.dtype),shape:i.shape,dtype:i.dtype}}},He={kernelName:r.Dilation2DBackpropInput,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:a,filter:i,dy:s}=e,{strides:o,pad:u,dilations:c}=n,l=t,d=r.util.toNestedArray(a.shape,l.data.get(a.dataId).values),p=r.util.toNestedArray(i.shape,l.data.get(i.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:b,outHeight:g,outWidth:x,padInfo:v,strideHeight:k,strideWidth:y,filterHeight:w,filterWidth:I,dilationHeight:S,dilationWidth:_,outShape:C}=r.backend_util.computeDilation2DInfo(a.shape,i.shape,o,u,"NHWC",c);r.util.assert(s.rank===C.length,(()=>`Error in ${r.Dilation2DBackpropInput}, dy must have the same rank as output ${C.length}, but got ${s.rank}`));const O=r.util.toNestedArray(C,l.data.get(s.dataId).values),T=r.util.makeZerosNestedTypedArray(a.shape,a.dtype);for(let e=0;e=0&&r=0&&cs&&(s=a,o=r,u=c)}}}T[e][o][u][i]+=O[e][t][r][i]}}}return{dataId:l.write(r.util.toTypedArray(T,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var qe=n(27),Ke=n(86); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function Xe(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{axis:o,keepDims:u}=i;let c;Object(a.a)(s,"sum"),c="bool"===s.dtype?Object(de.a)({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):Object(l.a)({inputs:{x:s},backend:n});const d=c.shape.length,p=r.util.parseAxisParam(o,c.shape),h=r.backend_util.getAxesPermutation(p,d);let f=p,m=c;null!=h&&(m=Object(M.a)({inputs:{x:c},backend:n,attrs:{perm:h}}),f=r.backend_util.getInnerMostAxes(f.length,d)),r.backend_util.assertAxesAreInnerMostDims("sum",f,m.shape.length);const[b,g]=r.backend_util.computeOutAndReduceShapes(m.shape,f),x=r.backend_util.upcastType(m.dtype,"int32");let v=Object(Ke.a)(n,b,x);const k=r.util.sizeFromShape(g),y=n.data.get(v.dataId).values,w=n.data.get(m.dataId).values;for(let e=0;e=0&&(h=Xe({inputs:{x:h},backend:n,attrs:{axis:l[e]-(o.length-f),keepDims:!1}}),m.push(h)),f--)}for(const e of m)e!==h&&n.disposeIntermediateTensorInfo(e);return h}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qe={kernelName:r.EluGrad,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:i,y:s}=t;Object(a.a)([i,s],"eluGrad");const o=new Float32Array(r.util.sizeFromShape(s.shape)),u=n.data.get(s.dataId).values,c=n.data.get(i.dataId).values;for(let e=0;e=1?c[e]:c[e]*(t+1)}return n.makeTensorInfo(s.shape,"float32",o)}};var Je=n(42); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const et=r.backend_util.ERF_P,tt=r.backend_util.ERF_A1,nt=r.backend_util.ERF_A2,rt=r.backend_util.ERF_A3,at=r.backend_util.ERF_A4,it=r.backend_util.ERF_A5,st=Object(o.a)(r.Erf,(e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+et*n);return t*(1-((((it*r+at)*r+rt)*r+nt)*r+tt)*r*Math.exp(-n*n))})),ot={kernelName:r.Erf,backendName:"cpu",kernelFunc:st};var ut=n(43); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ct(e){const{inputs:t,backend:n,attrs:a}=e,{input:i}=t,{dim:s}=a,o=i.shape.length,u=i.shape.slice();let c=s;return s<0&&(r.util.assert(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),c=o+s+1),u.splice(c,0,1),S({inputs:{x:i},backend:n,attrs:{shape:u}})}const lt={kernelName:r.ExpandDims,backendName:"cpu",kernelFunc:ct};var dt=n(57); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pt=Object(h.a)(((e,t)=>e/t)),ht=Object(H.a)(r.RealDiv,pt),ft={kernelName:r.RealDiv,backendName:"cpu",kernelFunc:ht};var mt=n(34); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function bt(e,t,n){const a=e.shape,i=a[0],s=a[1],o=n.data.get(e.dataId),u=o.complexTensorInfos.real,c=o.complexTensorInfos.imag,l=[i,s],d=r.util.sizeFromShape(l),p=r.util.getTypedArrayFromDType("float32",d),h=r.util.getTypedArrayFromDType("float32",d);for(let e=0;e{const{image:a}=e,i=n,s=r.util.getTypedArrayFromDType(a.dtype,r.util.sizeFromShape(a.shape)),[o,u,c,l]=a.shape,d=i.data.get(a.dataId).values;for(let e=0;e=0&&iMath.floor(e/t))),_t=Object(H.a)(r.FloorDiv,St,null,"int32"),Ct={kernelName:r.FloorDiv,backendName:"cpu",kernelFunc:_t};const Ot={kernelName:r.FusedConv2D,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:i,bias:s,preluActivationWeights:o}=t,{strides:u,pad:c,dataFormat:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=Ie({inputs:{x:a,filter:i},backend:n,attrs:{strides:u,pad:c,dataFormat:l,dilations:d,dimRoundingMode:p}});if(s){const e=m;m=Object(I.a)({inputs:{a:m,b:s},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=w(n,m,h,o,f),n.disposeIntermediateTensorInfo(e)}return m}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tt={kernelName:r.FusedDepthwiseConv2D,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:i,bias:s,preluActivationWeights:o}=t,{strides:u,pad:c,dataFormat:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=je({inputs:{x:a,filter:i},backend:n,attrs:{strides:u,pad:c,dataFormat:l,dilations:d,dimRoundingMode:p}});if(s){const e=m;m=Object(I.a)({inputs:{a:m,b:s},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=w(n,m,h,o,f),n.disposeIntermediateTensorInfo(e)}return m}};var $t=n(59); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const At={kernelName:r.GatherNd,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:a,indices:i}=t,s=r.util.sizeFromShape(a.shape),o=i.shape,u=o[o.length-1],[c,l,d,p]=r.backend_util.prepareAndValidate(a,i);if(0===l)return n.makeTensorInfo(c,a.dtype,[]);const h=n.data.get(i.dataId).values,f=n.bufferSync(a),m=Object($t.a)(h,f,a.dtype,l,u,d,p,a.shape,s);return n.makeTensorInfo(c,a.dtype,m.values)}};var Nt=n(60); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Et={kernelName:r.GatherV2,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s,indices:o}=t,{axis:u,batchDims:c}=i;Object(a.a)([s,o],"gatherV2");const l=r.util.parseAxisParam(u,s.shape)[0],d=n.data.get(o.dataId).values,p=s.shape[l];for(let e=0;e=0,(()=>`GatherV2: the index value ${t} is not in [0, ${p-1}]`))}let h=c;null==c&&(h=0);const f=r.util.sizeFromShape(o.shape),m=r.backend_util.segment_util.collectGatherOpShapeInfo(s,o,l,h),b=S({inputs:{x:s},backend:n,attrs:{shape:[m.batchSize,m.outerSize,m.dimSize,m.sliceSize]}}),g=S({inputs:{x:o},backend:n,attrs:{shape:[m.batchSize,f/m.batchSize]}}),x=[m.batchSize,m.outerSize,f/m.batchSize,m.sliceSize],v=n.bufferSync(g),k=n.bufferSync(b),y=Object(Nt.a)(k,v,x);return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(g),n.makeTensorInfo(m.outputShape,y.dtype,y.values)}};var Rt=n(61),Ft=n(62);const Mt={kernelName:r.IFFT,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n}=e,{input:a}=t,i=r.util.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],o=S({inputs:{x:a},backend:n,attrs:{shape:[i/s,s]}}),u=bt(o,!0,n),c=S({inputs:{x:u},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),c}},Dt=Object(o.a)(r.IsFinite,(e=>Number.isFinite(e)?1:0),"bool"),Pt={kernelName:r.IsFinite,backendName:"cpu",kernelFunc:Dt},Bt=Object(o.a)(r.IsInf,(e=>Math.abs(e)===1/0?1:0),"bool"),jt={kernelName:r.IsInf,backendName:"cpu",kernelFunc:Bt},Lt=Object(o.a)(r.IsNan,(e=>Number.isNaN(e)?1:0),"bool"),zt={kernelName:r.IsNan,backendName:"cpu",kernelFunc:Lt}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Wt=n(63),Gt=n(64),Ut=n(65);const Vt={kernelName:r.LinSpace,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:i}=n,s=Object(Ut.a)(r,a,i);return t.makeTensorInfo([s.length],"float32",s)}};var Ht=n(66); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const qt=Object(o.a)(r.Log1p,(e=>Math.log1p(e))),Kt={kernelName:r.Log1p,backendName:"cpu",kernelFunc:qt},Xt=Object(h.a)(((e,t)=>e&&t)),Yt=Object(H.a)(r.LogicalAnd,Xt,null,"bool"),Zt={kernelName:r.LogicalAnd,backendName:"cpu",kernelFunc:Yt},Qt=Object(o.a)(r.LogicalNot,(e=>e?0:1),"bool"),Jt={kernelName:r.LogicalNot,backendName:"cpu",kernelFunc:Qt},en=Object(h.a)(((e,t)=>e||t)),tn=Object(H.a)(r.LogicalOr,en,null,"bool"),nn={kernelName:r.LogicalOr,backendName:"cpu",kernelFunc:tn};const rn={kernelName:r.LRN,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{depthRadius:o,bias:u,alpha:c,beta:l}=i;Object(a.a)(s,"LRN");const d=s.shape[3],p=d-1,h=n.data.get(s.dataId).values,f=r.util.sizeFromShape(s.shape),m=new Float32Array(f);function b(e){const t=e%d;let n=e-t+Math.max(0,t-o);const r=e-t+Math.min(t+o,p);let a=0;for(;n<=r;n++){const e=h[n];a+=e*e}return a}for(let e=0;e`Error in maxPool: Either strides or dilations must be 1. Got strides ${u} and dilations '1'`));const p=r.backend_util.computePool2DInfo(s.shape,o,u,1,c,d);let h;if(1===p.filterWidth&&1===p.filterHeight&&r.util.arraysEqual(p.inShape,p.outShape))h=Object(l.a)({inputs:{x:s},backend:n});else{const e=n.data.get(s.dataId).values,t=r.util.computeStrides(s.shape),a=Q(e,s.shape,s.dtype,t,p,"max");h=n.makeTensorInfo(p.outShape,s.dtype,a.values)}return h}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const pn={kernelName:r.MaxPool3D,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{filterSize:o,strides:u,pad:c,dimRoundingMode:l,dataFormat:d}=i;Object(a.a)(s,"maxPool3d");const p=r.backend_util.computePool3DInfo(s.shape,o,u,1,c,l,d),h=ee(n.data.get(s.dataId).values,s.shape,s.dtype,r.util.computeStrides(s.shape),p,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const hn={kernelName:r.MaxPool3DGrad,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{dy:s,input:o}=t,{filterSize:u,strides:c,pad:l,dimRoundingMode:d}=i;Object(a.a)([s,o],"maxPool3DGrad");const p=r.backend_util.computePool3DInfo(o.shape,u,c,1,l,d),h=function(e,t){const n=Object(r.buffer)(t.outShape,"int32"),a=t.strideDepth,i=t.strideHeight,s=t.strideWidth,o=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth,h=t.padInfo.front,f=t.padInfo.top,m=t.padInfo.left;for(let r=0;r=S&&(S=u,_=n*d*p+i*d+o)}}}n.set(_,r,g,a,i,b)}}}return n}(n.bufferSync(o),p),f=p.strideDepth,m=p.strideHeight,b=p.strideWidth,g=p.dilationDepth,x=p.dilationHeight,v=p.dilationWidth,k=p.effectiveFilterDepth,y=p.effectiveFilterHeight,w=p.effectiveFilterWidth,I=k-1-p.padInfo.front,S=w-1-p.padInfo.left,_=y-1-p.padInfo.top,C=Object(r.buffer)(o.shape,"float32"),O=n.bufferSync(s);for(let e=0;e=p.outDepth||Math.floor(r)!==r))for(let a=0;a=p.outHeight||Math.floor(i)!==i))for(let s=0;s=p.outWidth||Math.floor(c)!==c)continue;const l=k*y*w-1-h.get(e,r,i,c,t)===n*y*w+a*w+s?1:0;if(0===l)continue;u+=O.get(e,r,i,c,t)*l}}}C.set(u,e,n,r,a,t)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const fn={kernelName:r.MaxPoolGrad,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{dy:s,input:o,output:u}=t,c=o;Object(a.a)([o,u],"maxPoolGrad");const{filterSize:l,strides:d,pad:p,dimRoundingMode:h}=i,f=r.backend_util.computePool2DInfo(c.shape,l,d,1,p,h),m=n.data.get(c.dataId).values,b=Object(r.buffer)(f.outShape,c.dtype,J(m,c.shape,c.dtype,f).values),g=f.strideHeight,x=f.strideWidth,v=f.dilationHeight,k=f.dilationWidth,y=f.effectiveFilterHeight,w=f.effectiveFilterWidth,I=w-1-f.padInfo.left,S=y-1-f.padInfo.top,_=Object(r.buffer)(c.shape,"float32"),C=n.data.get(s.dataId).values,O=Object(r.buffer)(s.shape,"float32",C);for(let e=0;e=f.outHeight||Math.floor(r)!==r))for(let a=0;a=f.outWidth||Math.floor(o)!==o)continue;const u=y*w-1-b.get(e,r,o,t)===n*w+a?1:0;if(0===u)continue;s+=O.get(e,r,o,t)*u}}_.set(s,e,n,r,t)}return n.makeTensorInfo(_.shape,_.dtype,_.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +const mn={kernelName:r.MaxPoolWithArgmax,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:i}=e,{filterSize:s,strides:o,pad:u,includeBatchInIndex:c}=t,l=n;Object(a.a)(i,"MaxPoolWithArgmax");const d=l.data.get(i.dataId).values,p=r.backend_util.computePool2DInfo(i.shape,s,o,[1,1],u),[h,f]=function(e,t,n,a,i){const s=Q(e,0,n,r.util.computeStrides(t),i,"max"),o=J(e,t,n,i,!0,a);return[s.values,o.values]}(d,i.shape,i.dtype,c,p),m=l.write(h,p.outShape,i.dtype),b=l.write(f,p.outShape,i.dtype);return[{dataId:m,shape:p.outShape,dtype:i.dtype},{dataId:b,shape:p.outShape,dtype:"int32"}]}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const bn={kernelName:r.Mean,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:s,keepDims:o}=a,u=r.util.parseAxisParam(s,i.shape),c=r.backend_util.computeOutAndReduceShapes(i.shape,u)[1],l=r.util.sizeFromShape(c),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([l]));d.push(p);const h=Object(de.a)({inputs:{x:i},backend:n,attrs:{dtype:"float32"}});d.push(h);const f=ht({inputs:{a:h,b:p},backend:n});d.push(f);const m=Xe({inputs:{x:f},backend:n,attrs:{axis:s,keepDims:o}});return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),m}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const gn={kernelName:r.Min,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{axis:o,keepDims:u}=i;Object(a.a)(s,"min");const c=r.util.parseAxisParam(o,s.shape);let l=c;const d=r.backend_util.getAxesPermutation(l,s.shape.length);let p=s;null!=d&&(p=Object(M.a)({inputs:{x:s},backend:n,attrs:{perm:d}}),l=r.backend_util.getInnerMostAxes(l.length,s.shape.length)),r.backend_util.assertAxesAreInnerMostDims("min",l,p.shape.length);const[h,f]=r.backend_util.computeOutAndReduceShapes(p.shape,l),m=r.util.sizeFromShape(f),b=r.util.makeZerosTypedArray(r.util.sizeFromShape(h),p.dtype),g=n.data.get(p.dataId).values;for(let e=0;ee[0]+s.shape[t]+e[1])),l=o.map((e=>e[0])),d=o.map(((e,t)=>e[0]+s.shape[t])),p="reflect"===u?0:1,h=n.data.get(s.dataId).values,f=s.shape.length,m=r.util.computeStrides(s.shape),b=r.util.sizeFromShape(c),g=c.length,x=r.util.computeStrides(c),v=r.util.getTypedArrayFromDType(s.dtype,b);for(let e=0;e=d[e]&&(t[e]=2*(d[e]-1)-t[e]+p);t=t.map(((e,t)=>e-l[t]));const n=r.util.locToIndex(t,f,m);v[e]=h[n]}return{dataId:n.write(v,c,s.dtype),shape:c,dtype:s.dtype}}},kn=Object(h.a)(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),yn=Object(H.a)(r.Mod,kn),wn={kernelName:r.Mod,backendName:"cpu",kernelFunc:yn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var In=n(48); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function Sn(e){const{inputs:t,backend:n,attrs:a}=e,{logits:i}=t,{dim:s}=a,o=i.shape.length;let u=s;if(-1===u&&(u=o-1),u!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${u}`);const c=r.util.parseAxisParam([u],i.shape),l=un({inputs:{x:i},backend:n,attrs:{reductionIndices:c,keepDims:!1}}),d=r.backend_util.expandShapeToKeepDim(l.shape,c),p=S({inputs:{x:l},backend:n,attrs:{shape:d}}),h=Object(mt.a)({inputs:{a:i,b:p},backend:n}),f=Object(ut.a)({inputs:{x:h},backend:n}),m=Xe({inputs:{x:f},backend:n,attrs:{axis:c,keepDims:!1}}),b=S({inputs:{x:m},backend:n,attrs:{shape:d}}),g=ht({inputs:{a:f,b:b},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(b),g}const _n={kernelName:r.Softmax,backendName:"cpu",kernelFunc:Sn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Cn={kernelName:r.Multinomial,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{logits:s}=t,{numSamples:o,seed:u,normalized:c}=i;Object(a.a)(s,"multinomial");const l=c?s:Sn({inputs:{logits:s},backend:n,attrs:{dim:-1}}),d=l.shape[0],p=l.shape[1],h=n.data.get(l.dataId).values,f=[d,o],m=r.util.makeZerosTypedArray(r.util.sizeFromShape(f),"int32");for(let e=0;e=0&&p[e]{r.util.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),r.util.assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const u=[],c=ye({inputs:t.map((e=>{const t=ct({inputs:{input:e},backend:n,attrs:{dim:i}});return u.push(t),t})),backend:n,attrs:{axis:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const Ln={kernelName:r.Pack,backendName:"cpu",kernelFunc:jn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const zn={kernelName:r.PadV2,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{paddings:o,constantValue:u}=i;Object(a.a)(s,"pad");const c=o.map(((e,t)=>e[0]+s.shape[t]+e[1])),l=o.map((e=>e[0])),d=n.data.get(s.dataId).values,p=r.util.sizeFromShape(s.shape),h=s.shape.length,f=r.util.computeStrides(s.shape),m=r.util.sizeFromShape(c),b=c.length,g=r.util.computeStrides(c),x=r.util.getTypedArrayFromDType(s.dtype,m);0!==u&&x.fill(u);for(let e=0;ee+l[t]));x[r.util.locToIndex(t,b,g)]=d[e]}return{dataId:n.write(x,c,s.dtype),shape:c,dtype:s.dtype}}},Wn=Object(h.a)(((e,t)=>Math.pow(e,t))),Gn=Object(H.a)(r.Pow,Wn),Un={kernelName:r.Pow,backendName:"cpu",kernelFunc:Gn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Vn=n(72),Hn=n(73);const qn={kernelName:r.Range,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,dtype:i,step:s}=n,o=Object(Hn.a)(r,a,s,i);return t.makeTensorInfo([o.length],i,o)}},Kn=Object(o.a)(r.Reciprocal,(e=>1/e)),Xn={kernelName:r.Reciprocal,backendName:"cpu",kernelFunc:Kn}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Yn={kernelName:r.ResizeBilinear,backendName:"cpu",kernelFunc: +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ +function(e){const{inputs:t,backend:n,attrs:i}=e,{images:s}=t,{alignCorners:o,halfPixelCenters:u,size:c}=i;Object(a.a)(s,"resizeBilinear");const l=r.util.computeStrides(s.shape),[d,p]=c,[h,f,m,b]=s.shape,g=n.data.get(s.dataId).values,x=new Float32Array(r.util.sizeFromShape([h,d,p,b])),v=[o&&d>1?f-1:f,o&&p>1?m-1:m],k=[o&&d>1?d-1:d,o&&p>1?p-1:p];let y=0;const w=v[0]/k[0],I=v[1]/k[1];for(let e=0;e1?d-1:d,u&&m>1?p-1:p],x=[u&&f>1?f-1:f,u&&m>1?m-1:m],v=g[0]/x[0],k=g[1]/x[1],y=n.data.get(o.dataId).values;let w=0;for(let e=0;e1?f-1:f,o&&p>1?m-1:m],k=[o&&d>1?d-1:d,o&&p>1?p-1:p],y=v[0]/k[0],w=v[1]/k[1];let I=0;for(let e=0;e1?p-1:p,u&&b>1?h-1:h],k=[u&&m>1?m-1:m,u&&b>1?b-1:b],y=v[0]/k[0],w=v[1]/k[1],I=1/y,S=1/w,_=2*Math.ceil(I)+2,C=2*Math.ceil(S)+2;for(let e=0;e=m)continue;const d=t+c*l[1],f=c*y;if(e===Math.min(p-1,u?Math.round(f):Math.floor(f)))for(let e=0;e=b)continue;const a=d+t*l[2],i=t*w;r===Math.min(h-1,u?Math.round(i):Math.floor(i))&&(s+=x[a+n])}}g[i+n]=s}}}}return n.makeTensorInfo(s.shape,s.dtype,g)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const er={kernelName:r.Reverse,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{dims:o}=i;Object(a.a)(s,"reverse");const u=s.shape.length,c=r.util.parseAxisParam(o,s.shape);if(0===u)return Object(l.a)({inputs:{x:s},backend:n});const d=new r.TensorBuffer(s.shape,s.dtype),p=n.bufferSync(s);for(let e=0;en[e]=s.shape[e]-1-n[e])),d.set(p.get(...n),...t)}return n.makeTensorInfo(d.shape,d.dtype,d.values)}},tr={kernelName:r.RotateWithOffset,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:a}=e,{radians:i,fillValue:s,center:o}=t,u=n,c=r.util.getTypedArrayFromDType(a.dtype,r.util.sizeFromShape(a.shape)),[l,d,p,h]=a.shape,[f,m]=r.backend_util.getImageCenter(o,d,p),b=Math.sin(i),g=Math.cos(i),x=u.data.get(a.dataId).values;for(let e=0;e=0&&k=0&&y{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),rr={kernelName:r.Round,backendName:"cpu",kernelFunc:nr}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var ar=n(74); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */function ir(e,t,n,a,i,s,o,u,c,l){const d=[a/i,i],p=e.values,h=t.values;if(0===a)return Object(r.buffer)(n,t.dtype);const f=Object(r.buffer)(d,t.dtype);f.values.fill(c);for(let e=0;e=a/i)throw new Error(`Invalid indices: ${r} does not index into ${n}`);for(let n=0;n1||1===s.shape.length?1:r.util.sizeFromShape(s.shape.slice(1));for(let e=0;ee>=0?pr*e:dr*(Math.exp(e)-1))),fr={kernelName:r.Selu,backendName:"cpu",kernelFunc:hr},mr=Object(o.a)(r.Sign,(e=>e<0?-1:e>0?1:0)),br={kernelName:r.Sign,backendName:"cpu",kernelFunc:mr},gr=Object(o.a)(r.Sin,(e=>Math.sin(e))),xr={kernelName:r.Sin,backendName:"cpu",kernelFunc:gr},vr=Object(o.a)(r.Sinh,(e=>Math.sinh(e))),kr={kernelName:r.Sinh,backendName:"cpu",kernelFunc:vr},yr=Math.log(1.1920928955078125e-7)+2,wr=Object(o.a)(r.Softplus,(e=>{const t=e>-yr,n=eNumber(e))))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}};var Or=n(76); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Tr={kernelName:r.SparseReshape,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:r,inputShape:a,newShape:i}=t;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${a.shape}`);if(1!==i.shape.length)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const s=Array.from(n.data.get(a.dataId).values),o=n.data.get(r.dataId).values,u=Array.from(n.data.get(i.dataId).values),[c,l,d]=Object(Or.a)(o,r.shape,r.dtype,s,u);return[n.makeTensorInfo(l,r.dtype,c),n.makeTensorInfo([d.length],i.dtype,new Int32Array(d))]}};var $r=n(46); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ar={kernelName:r.SparseSegmentMean,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:i}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);if(a.shape[0]!==i.shape[0])throw new Error("segmentIds and indices should have same size.");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values,[c,l]=Object($r.a)(s,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(l,r.dtype,c)}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Nr={kernelName:r.SparseSegmentSum,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:r,indices:a,segmentIds:i}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.shape.length)throw new Error(`Indices should be a vector but received shape\n ${a.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);if(a.shape[0]!==i.shape[0])throw new Error("segmentIds and indices should have same size.");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,u=n.data.get(i.dataId).values,[c,l]=Object($r.a)(s,r.shape,r.dtype,o,u);return n.makeTensorInfo(l,r.dtype,c)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Er={kernelName:r.SparseToDense,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{sparseIndices:i,sparseValues:s,defaultValue:o}=t,{outputShape:u}=a,{sliceRank:c,numUpdates:l,sliceSize:d,strides:p,outputSize:h}=r.backend_util.calculateShapes(s,i,u),f=ir(n.bufferSync(i),n.bufferSync(s),u,h,d,l,c,p,n.data.get(o.dataId).values[0],!1);return n.makeTensorInfo(u,f.dtype,f.values)}}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Rr={kernelName:r.SplitV,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{numOrSizeSplits:s,axis:o}=a,u=r.util.parseAxisParam(o,i.shape)[0],c=r.backend_util.prepareSplitSize(i,s,u),l=new Array(i.shape.length).fill(0),d=i.shape.slice();return c.map((e=>{const t=[...d];t[u]=e;const r=Object(se.a)({inputs:{x:i},backend:n,attrs:{begin:l,size:t}});return l[u]+=e,r}))}};var Fr=n(77); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Mr={kernelName:r.Square,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;Object(a.a)(n,"square");const i=r.data.get(n.dataId).values,s=new Float32Array(i.length);for(let e=0;e{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),Br={kernelName:r.Step,backendName:"cpu",kernelFunc:Pr};var jr=n(79); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Lr={kernelName:r.StridedSlice,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:s}=t,{begin:o,end:u,strides:c,beginMask:l,endMask:d,ellipsisMask:p,newAxisMask:h,shrinkAxisMask:f}=i;Object(a.a)(s,"stridedSlice");const{finalShapeSparse:m,finalShape:b,isIdentity:g,sliceDim0:x,isSimpleSlice:v,begin:k,end:y,strides:w}=r.slice_util.sliceInfo(s.shape,o,u,c,l,d,p,h,f);let I;if(g)I=S({inputs:{x:s},backend:n,attrs:{shape:b}});else if(x||v){r.util.assert(s.shape.length>=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=r.slice_util.computeOutShape(k,y,w),t=Object(se.a)({inputs:{x:s},backend:n,attrs:{begin:k,size:e}});I=S({inputs:{x:t},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(t)}else{const e=n.bufferSync(s),t=Object(jr.a)(m,e,w,k);I=n.makeTensorInfo(b,t.dtype,t.values)}return I}};var zr=n(80); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Wr={kernelName:r.StringNGrams,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:i,leftPad:s,rightPad:o,padWidth:u,preserveShortSequences:c}=r,{data:l,dataSplits:d}=t,p=n.data.get(l.dataId).values,h=n.data.get(d.dataId).values,[f,m]=Object(zr.a)(p,h,a,i,s,o,u,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}};var Gr=n(81); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Ur={kernelName:r.StringSplit,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:i,delimiter:s}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(1!==i.shape.length)throw new Error(`Input must be a vector, got shape: ${i.shape}`);if(0!==s.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${s.shape}`);const o=n.data.get(i.dataId).values,u=n.data.get(s.dataId).values[0],[c,l,d]=Object(Gr.a)(o,u,a),p=l.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}};var Vr=n(82); +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Hr={kernelName:r.StringToHashBucketFast,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{numBuckets:a}=r,{input:i}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");const s=n.data.get(i.dataId).values,o=Object(Vr.a)(s,a);return n.makeTensorInfo(i.shape,"int32",o)}},qr=Object(o.a)(r.Tan,(e=>Math.tan(e))),Kr={kernelName:r.Tan,backendName:"cpu",kernelFunc:qr},Xr=Object(o.a)(r.Tanh,(e=>Math.tanh(e))),Yr={kernelName:r.Tanh,backendName:"cpu",kernelFunc:Xr}; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Zr=n(83); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const Qr={kernelName:r.Tile,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:i}=t,{reps:s}=r;Object(a.a)(i,"tile");const o=Object(Zr.a)(n.bufferSync(i),s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}};var Jr=n(84); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ea={kernelName:r.TopK,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:i}=t,{k:s,sorted:o}=r;Object(a.a)(i,"topk");const u=n.data.get(i.dataId).values,[c,l]=Object(Jr.a)(u,i.shape,i.dtype,s,o);return[n.makeTensorInfo(c.shape,c.dtype,c.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}}; +/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const ta={kernelName:r.Transform,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:a}=e,{image:i,transforms:s}=t,{interpolation:o,fillMode:u,fillValue:c,outputShape:l}=n,[d,p,h,f]=i.shape,[m,b]=null!=l?l:[p,h],g=[d,m,b,f],x=r.util.computeStrides(i.shape),v=x[0],k=x[1],y=x[2],w=r.util.getTypedArrayFromDType(i.dtype,r.util.sizeFromShape(g));w.fill(c);const I=a.data.get(i.dataId).values,S=a.data.get(s.dataId).values;for(let e=0;et-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return r.util.clamp(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 r.util.clamp(0,n,t-1)}(e,t);case"nearest":return function(e,t){return r.util.clamp(0,e,t-1)}(e,t);default:return function(e,t){return e}(e)}}function ra(e,t,n,r,a,i,s,o,u,c,l){return 0<=o&&on.disposeIntermediateTensorInfo(e))),h}},la=[T,$.a,N,R,I.b,F,D,P,B,j,z,G,V,X,Z,te,ne,re,ae,O,ie,oe,ce,le,de.b,pe.a,fe,me.b,be,we,Se,_e,Ce,Oe,Te,$e,Ne,Re,Fe,Me,De,Pe,Be,Le,ze,We,Ge,Ue,Ve,He,Ze,c,Qe,Je.b,ot,ut.b,lt,dt.a,vt,yt,wt,It.a,Ct,Ot,Tt,At,Et,Rt.a,Ft.a,l.b,Mt,ve,Pt,jt,zt,p,Wt.a,Gt.a,Vt,Ht.a,Kt,Zt,Jt,nn,rn,an,cn,ln.a,dn,pn,hn,fn,mn,bn,gn,xn.a,vn,wn,Cn,qe.b,On.a,$n,Nn,Rn,Fn.a,Mn,Bn,Ln,zn,Un,b,Vn.a,qn,ke.b,ft,Xn,x,k,_,Yn,Zn,Qn,Jn,er,tr,rr,ar.a,sr,cr,lr,fr,y.b,br,xr,kr,se.b,_n,Ir,Sr,Cr,Tr,Ar,Nr,Er,Rr,Fr.a,Mr,Dr.a,Br,Lr,Wr,Ur,Hr,mt.b,Ye,Kr,Yr,Qr,ea,ta,M.b,oa,ua,ca,Pn]; +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */for(const e of la)Object(r.registerKernel)(e); +/** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},function(e,t,n){(function(t,r,a){var i,s=(i=(i="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||t,function(e){var t,s,o,u="undefined"!=typeof(e=e||{})?e:{};u.ready=new Promise((function(e,n){t=e,s=n})),"undefined"!=typeof r&&r.listeners&&(o={uncaughtException:r.listeners("uncaughtException"),unhandledRejection:r.listeners("unhandledRejection")});var c,l,d,p,h,f,m=Object.assign({},u),b=[],g="object"==typeof window,x="function"==typeof importScripts,v="object"==typeof r&&"object"==typeof r.versions&&"string"==typeof r.versions.node,k="";v?(k=x?n(52).dirname(k)+"/":a+"/",f=()=>{h||(p=n(94),h=n(52))},c=function(e,t){return f(),e=h.normalize(e),p.readFileSync(e,t?void 0:"utf8")},d=e=>{var t=c(e,!0);return t.buffer||(t=new Uint8Array(t)),t},l=(e,t,n)=>{f(),e=h.normalize(e),p.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},r.argv.length>1&&r.argv[1].replace(/\\/g,"/"),b=r.argv.slice(2),r.on("uncaughtException",(function(e){if(!(e instanceof ue))throw e})),r.on("unhandledRejection",(function(e){throw e})),u.inspect=function(){return"[Emscripten Module object]"}):(g||x)&&(x?k=self.location.href:"undefined"!=typeof document&&document.currentScript&&(k=document.currentScript.src),i&&(k=i),k=0!==k.indexOf("blob:")?k.substr(0,k.replace(/[?#].*/,"").lastIndexOf("/")+1):"",c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},x&&(d=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),l=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var y,w=u.print||console.log.bind(console),I=u.printErr||console.warn.bind(console);Object.assign(u,m),m=null,u.arguments&&(b=u.arguments),u.thisProgram&&u.thisProgram,u.quit&&u.quit,u.wasmBinary&&(y=u.wasmBinary);var S;u.noExitRuntime;"object"!=typeof WebAssembly&&V("no native wasm support detected");var _=!1;function C(e){return u["_"+e]}function O(e,t,n,r,a){var i={string:function(e){var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);!function(e,t,n){!function(e,t,n,r){if(!(r>0))return 0;for(var a=n+r-1,i=0;i=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+3>=a)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}t[n]=0}(e,A,t,n)}(e,t=oe(n),n)}return t},array:function(e){var t=oe(e.length);return function(e,t){$.set(e,t)}(e,t),t}},s=C(e),o=[],u=0;if(r)for(var c=0;c=r);)++a;if(a-t>16&&e.subarray&&E)return E.decode(e.subarray(t,a));for(var i="";t>10,56320|1023&c)}}else i+=String.fromCharCode((31&s)<<6|o)}else i+=String.fromCharCode(s)}return i}function F(e,t){return e?R(A,e,t):""}function M(e){T=e,u.HEAP8=$=new Int8Array(e),u.HEAP16=new Int16Array(e),u.HEAP32=N=new Int32Array(e),u.HEAPU8=A=new Uint8Array(e),u.HEAPU16=new Uint16Array(e),u.HEAPU32=new Uint32Array(e),u.HEAPF32=new Float32Array(e),u.HEAPF64=new Float64Array(e)}"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le"),u.INITIAL_MEMORY;var D,P=[],B=[],j=[];var L,z,W=0,G=null,U=null;function V(e){u.onAbort&&u.onAbort(e),I(e="Aborted("+e+")"),_=!0,e+=". Build with -s ASSERTIONS=1 for more info.";var t=new WebAssembly.RuntimeError(e);throw s(t),t}function H(e){return e.startsWith("data:application/octet-stream;base64,")}function q(e){return e.startsWith("file://")}function K(e){try{if(e==L&&y)return new Uint8Array(y);if(d)return d(e);throw"both async and sync fetching of the wasm failed"}catch(e){V(e)}}function X(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var n=t.func;"number"==typeof n?void 0===t.arg?Z(n)():Z(n)(t.arg):n(void 0===t.arg?null:t.arg)}else t(u)}}u.preloadedImages={},u.preloadedAudios={},H(L="tfjs-backend-wasm.wasm")||(z=L,L=u.locateFile?u.locateFile(z,k):k+z);var Y=[];function Z(e){var t=Y[e];return t||(e>=Y.length&&(Y.length=e+1),Y[e]=t=D.get(e)),t}function Q(){return 2147483648}function J(e){try{return S.grow(e-T.byteLength+65535>>>16),M(S.buffer),1}catch(e){}}var ee,te,ne,re={mappings:{},buffers:[null,[],[]],printChar:function(e,t){var n=re.buffers[e];0===t||10===t?((1===e?w:I)(R(n,0)),n.length=0):n.push(t)},varargs:void 0,get:function(){return re.varargs+=4,N[re.varargs-4>>2]},getStr:function(e){return F(e)},get64:function(e,t){return e}},ae={abort:function(){V("")},emscripten_get_heap_max:Q,emscripten_memcpy_big:function(e,t,n){A.copyWithin(e,t,t+n)},emscripten_resize_heap:function(e){var t,n,r=A.length,a=2147483648;if((e>>>=0)>a)return!1;for(var i=1;i<=4;i*=2){var s=r*(1+.2/i);if(s=Math.min(s,e+100663296),J(Math.min(a,((t=Math.max(e,s))%(n=65536)>0&&(t+=n-t%n),t))))return!0}return!1},fd_close:function(e){return 0},fd_seek:function(e,t,n,r,a){},fd_write:function(e,t,n,r){for(var a=0,i=0;i>2],o=N[t+4>>2];t+=8;for(var u=0;u>2]=a,0},setTempRet0:function(e){}},ie=(function(){var e={env:ae,wasi_snapshot_preview1:ae};function t(e,t){var n,r=e.exports;u.asm=r,M((S=u.asm.memory).buffer),D=u.asm.__indirect_function_table,n=u.asm.__wasm_call_ctors,B.unshift(n),function(e){if(W--,u.monitorRunDependencies&&u.monitorRunDependencies(W),0==W&&(null!==G&&(clearInterval(G),G=null),U)){var t=U;U=null,t()}}()}function n(e){t(e.instance)}function r(t){return function(){if(!y&&(g||x)){if("function"==typeof fetch&&!q(L))return fetch(L,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+L+"'";return e.arrayBuffer()})).catch((function(){return K(L)}));if(l)return new Promise((function(e,t){l(L,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return K(L)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){I("failed to asynchronously prepare wasm: "+e),V(e)}))}if(W++,u.monitorRunDependencies&&u.monitorRunDependencies(W),u.instantiateWasm)try{return u.instantiateWasm(e,t)}catch(e){return I("Module.instantiateWasm callback failed with error: "+e),!1}(y||"function"!=typeof WebAssembly.instantiateStreaming||H(L)||q(L)||"function"!=typeof fetch?r(n):fetch(L,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return I("wasm streaming compile failed: "+e),I("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.__wasm_call_ctors).apply(null,arguments)},u._init=function(){return(u._init=u.asm.init).apply(null,arguments)},u._init_with_threads_count=function(){return(u._init_with_threads_count=u.asm.init_with_threads_count).apply(null,arguments)},u._get_threads_count=function(){return(u._get_threads_count=u.asm.get_threads_count).apply(null,arguments)},u._register_tensor=function(){return(u._register_tensor=u.asm.register_tensor).apply(null,arguments)},u._dispose_data=function(){return(u._dispose_data=u.asm.dispose_data).apply(null,arguments)},u._dispose=function(){return(u._dispose=u.asm.dispose).apply(null,arguments)},u._Abs=function(){return(u._Abs=u.asm.Abs).apply(null,arguments)},u._Add=function(){return(u._Add=u.asm.Add).apply(null,arguments)},u._AddN=function(){return(u._AddN=u.asm.AddN).apply(null,arguments)},u._All=function(){return(u._All=u.asm.All).apply(null,arguments)},u._Any=function(){return(u._Any=u.asm.Any).apply(null,arguments)},u._ArgMax=function(){return(u._ArgMax=u.asm.ArgMax).apply(null,arguments)},u._AvgPool=function(){return(u._AvgPool=u.asm.AvgPool).apply(null,arguments)},u._BatchMatMul=function(){return(u._BatchMatMul=u.asm.BatchMatMul).apply(null,arguments)},u._Ceil=function(){return(u._Ceil=u.asm.Ceil).apply(null,arguments)},u._ClipByValue=function(){return(u._ClipByValue=u.asm.ClipByValue).apply(null,arguments)},u._Conv2D=function(){return(u._Conv2D=u.asm.Conv2D).apply(null,arguments)},u._Conv2DBackpropInput=function(){return(u._Conv2DBackpropInput=u.asm.Conv2DBackpropInput).apply(null,arguments)},u._Cos=function(){return(u._Cos=u.asm.Cos).apply(null,arguments)},u._Cosh=function(){return(u._Cosh=u.asm.Cosh).apply(null,arguments)},u._CropAndResize=function(){return(u._CropAndResize=u.asm.CropAndResize).apply(null,arguments)},u._Cumprod=function(){return(u._Cumprod=u.asm.Cumprod).apply(null,arguments)},u._Cumsum=function(){return(u._Cumsum=u.asm.Cumsum).apply(null,arguments)},u._DepthToSpace=function(){return(u._DepthToSpace=u.asm.DepthToSpace).apply(null,arguments)},u._DepthwiseConv2dNative=function(){return(u._DepthwiseConv2dNative=u.asm.DepthwiseConv2dNative).apply(null,arguments)},u._Elu=function(){return(u._Elu=u.asm.Elu).apply(null,arguments)},u._Equal=function(){return(u._Equal=u.asm.Equal).apply(null,arguments)},u._Exp=function(){return(u._Exp=u.asm.Exp).apply(null,arguments)},u._FlipLeftRight=function(){return(u._FlipLeftRight=u.asm.FlipLeftRight).apply(null,arguments)},u._Floor=function(){return(u._Floor=u.asm.Floor).apply(null,arguments)},u._FloorDiv=function(){return(u._FloorDiv=u.asm.FloorDiv).apply(null,arguments)},u._FusedBatchNorm=function(){return(u._FusedBatchNorm=u.asm.FusedBatchNorm).apply(null,arguments)},u._FusedConv2D=function(){return(u._FusedConv2D=u.asm.FusedConv2D).apply(null,arguments)},u._FusedDepthwiseConv2D=function(){return(u._FusedDepthwiseConv2D=u.asm.FusedDepthwiseConv2D).apply(null,arguments)},u._Gather=function(){return(u._Gather=u.asm.Gather).apply(null,arguments)},u._GatherNd=function(){return(u._GatherNd=u.asm.GatherNd).apply(null,arguments)},u._Greater=function(){return(u._Greater=u.asm.Greater).apply(null,arguments)},u._GreaterEqual=function(){return(u._GreaterEqual=u.asm.GreaterEqual).apply(null,arguments)},u._LeakyRelu=function(){return(u._LeakyRelu=u.asm.LeakyRelu).apply(null,arguments)},u._Less=function(){return(u._Less=u.asm.Less).apply(null,arguments)},u._LessEqual=function(){return(u._LessEqual=u.asm.LessEqual).apply(null,arguments)},u._Log=function(){return(u._Log=u.asm.Log).apply(null,arguments)},u._LogicalAnd=function(){return(u._LogicalAnd=u.asm.LogicalAnd).apply(null,arguments)},u._Max=function(){return(u._Max=u.asm.Max).apply(null,arguments)},u._MaxPool=function(){return(u._MaxPool=u.asm.MaxPool).apply(null,arguments)},u._Maximum=function(){return(u._Maximum=u.asm.Maximum).apply(null,arguments)},u._Mean=function(){return(u._Mean=u.asm.Mean).apply(null,arguments)},u._Min=function(){return(u._Min=u.asm.Min).apply(null,arguments)},u._Minimum=function(){return(u._Minimum=u.asm.Minimum).apply(null,arguments)},u._MirrorPad=function(){return(u._MirrorPad=u.asm.MirrorPad).apply(null,arguments)},u._Multiply=function(){return(u._Multiply=u.asm.Multiply).apply(null,arguments)},u._Neg=function(){return(u._Neg=u.asm.Neg).apply(null,arguments)},u._NonMaxSuppressionV3=function(){return(u._NonMaxSuppressionV3=u.asm.NonMaxSuppressionV3).apply(null,arguments)},u._NonMaxSuppressionV4=function(){return(u._NonMaxSuppressionV4=u.asm.NonMaxSuppressionV4).apply(null,arguments)},u._NonMaxSuppressionV5=function(){return(u._NonMaxSuppressionV5=u.asm.NonMaxSuppressionV5).apply(null,arguments)},u._NotEqual=function(){return(u._NotEqual=u.asm.NotEqual).apply(null,arguments)},u._OneHot=function(){return(u._OneHot=u.asm.OneHot).apply(null,arguments)},u._PadV2=function(){return(u._PadV2=u.asm.PadV2).apply(null,arguments)},u._Pow=function(){return(u._Pow=u.asm.Pow).apply(null,arguments)},u._Prelu=function(){return(u._Prelu=u.asm.Prelu).apply(null,arguments)},u._Prod=function(){return(u._Prod=u.asm.Prod).apply(null,arguments)},u._RealDiv=function(){return(u._RealDiv=u.asm.RealDiv).apply(null,arguments)},u._Relu=function(){return(u._Relu=u.asm.Relu).apply(null,arguments)},u._Relu6=function(){return(u._Relu6=u.asm.Relu6).apply(null,arguments)},u._ResizeBilinear=function(){return(u._ResizeBilinear=u.asm.ResizeBilinear).apply(null,arguments)},u._Reverse=function(){return(u._Reverse=u.asm.Reverse).apply(null,arguments)},u._RotateWithOffset=function(){return(u._RotateWithOffset=u.asm.RotateWithOffset).apply(null,arguments)},u._Round=function(){return(u._Round=u.asm.Round).apply(null,arguments)},u._Rsqrt=function(){return(u._Rsqrt=u.asm.Rsqrt).apply(null,arguments)},u._ScatterNd=function(){return(u._ScatterNd=u.asm.ScatterNd).apply(null,arguments)},u._SelectV2=function(){return(u._SelectV2=u.asm.SelectV2).apply(null,arguments)},u._Sigmoid=function(){return(u._Sigmoid=u.asm.Sigmoid).apply(null,arguments)},u._Sin=function(){return(u._Sin=u.asm.Sin).apply(null,arguments)},u._Softmax=function(){return(u._Softmax=u.asm.Softmax).apply(null,arguments)},u._SparseFillEmptyRows=function(){return(u._SparseFillEmptyRows=u.asm.SparseFillEmptyRows).apply(null,arguments)},u._SparseReshape=function(){return(u._SparseReshape=u.asm.SparseReshape).apply(null,arguments)},u._SparseSegmentReduction=function(){return(u._SparseSegmentReduction=u.asm.SparseSegmentReduction).apply(null,arguments)},u._Sqrt=function(){return(u._Sqrt=u.asm.Sqrt).apply(null,arguments)},u._Square=function(){return(u._Square=u.asm.Square).apply(null,arguments)},u._SquaredDifference=function(){return(u._SquaredDifference=u.asm.SquaredDifference).apply(null,arguments)},u._Step=function(){return(u._Step=u.asm.Step).apply(null,arguments)},u._StridedSlice=function(){return(u._StridedSlice=u.asm.StridedSlice).apply(null,arguments)},u._Sub=function(){return(u._Sub=u.asm.Sub).apply(null,arguments)},u._Sum=function(){return(u._Sum=u.asm.Sum).apply(null,arguments)},u._Tan=function(){return(u._Tan=u.asm.Tan).apply(null,arguments)},u._Tanh=function(){return(u._Tanh=u.asm.Tanh).apply(null,arguments)},u._Tile=function(){return(u._Tile=u.asm.Tile).apply(null,arguments)},u._TopK=function(){return(u._TopK=u.asm.TopK).apply(null,arguments)},u._Transform=function(){return(u._Transform=u.asm.Transform).apply(null,arguments)},u._Transpose=function(){return(u._Transpose=u.asm.Transpose).apply(null,arguments)},u.__FusedMatMul=function(){return(u.__FusedMatMul=u.asm._FusedMatMul).apply(null,arguments)},u._malloc=function(){return(u._malloc=u.asm.malloc).apply(null,arguments)},u._free=function(){return(u._free=u.asm.free).apply(null,arguments)},u.___errno_location=function(){return(u.___errno_location=u.asm.__errno_location).apply(null,arguments)},u._emscripten_main_thread_process_queued_calls=function(){return(u._emscripten_main_thread_process_queued_calls=u.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},u.stackSave=function(){return(ie=u.stackSave=u.asm.stackSave).apply(null,arguments)}),se=u.stackRestore=function(){return(se=u.stackRestore=u.asm.stackRestore).apply(null,arguments)},oe=u.stackAlloc=function(){return(oe=u.stackAlloc=u.asm.stackAlloc).apply(null,arguments)};function ue(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ce(e){function n(){ee||(ee=!0,u.calledRun=!0,_||(X(B),t(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),function(){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;)e=u.postRun.shift(),j.unshift(e);var e;X(j)}()))}e=e||b,W>0||(function(){if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)e=u.preRun.shift(),P.unshift(e);var e;X(P)}(),W>0||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),n()}),1)):n()))}if(u.dynCall_iijjiiii=function(){return(u.dynCall_iijjiiii=u.asm.dynCall_iijjiiii).apply(null,arguments)},u.dynCall_jiji=function(){return(u.dynCall_jiji=u.asm.dynCall_jiji).apply(null,arguments)},u.cwrap=function(e,t,n,r){var a=(n=n||[]).every((function(e){return"number"===e}));return"string"!==t&&a&&!r?C(e):function(){return O(e,t,n,arguments)}},U=function e(){ee||ce(),ee||(U=e)},u.run=ce,u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();if(ce(),o&&(te={uncaughtException:r.listeners("uncaughtException").filter((function(e){return!o.uncaughtException.indexOf(e)>-1})),unhandledRejection:r.listeners("unhandledRejection").filter((function(e){return!o.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof e)ne=e;else{if("undefined"==typeof WasmBackendModuleThreadedSimd)throw new Error("Could not find wasm module in post.js");ne=WasmBackendModuleThreadedSimd}if(te){var le=ne._dispose;ne._dispose=function(){le(),te.uncaughtException.forEach((function(e){r.removeListener("uncaughtException",e)})),te.unhandledRejection.forEach((function(e){r.removeListener("unhandledRejection",e)}))}}return e.ready});e.exports=s}).call(this,"/index.js",n(38),"/")},,,,function(e,t,n){e.exports=n(103)},function(e,t,n){"use strict";n.r(t),function(e){var t=n(89),r=n(47),a=n(87),i=n(36),s=n(11);navigator.ml=new t.a,null==e.ML&&(e.ML=t.a),null==e.MLContext&&(e.MLContext=r.a),null==e.MLGraphBuilder&&(e.MLGraphBuilder=i.d),null==e.MLGraph&&(e.MLGraph=a.a),null==e.MLOperand&&(e.MLOperand=s.c)}.call(this,n(37))},function(e,t,n){"use strict";(function(e){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +var r=n(105),a=n(106),i=n(107);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(r)return z(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return $(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function b(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=u.from(t,r)),u.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,a);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,a){var i,s=1,o=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,o/=2,u/=2,n/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){var l=-1;for(i=n;io&&(n=o-u),i=n;i>=0;i--){for(var d=!0,p=0;pa&&(r=a):r=a;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var s=0;s>8,a=n%256,i.push(a),i.push(r);return i}(t,e.length-n),e,n,r)}function _(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function C(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a239?4:c>223?3:c>191?2:1;if(a+d<=n)switch(d){case 1:c<128&&(l=c);break;case 2:128==(192&(i=e[a+1]))&&(u=(31&c)<<6|63&i)>127&&(l=u);break;case 3:i=e[a+1],s=e[a+2],128==(192&i)&&128==(192&s)&&(u=(15&c)<<12|(63&i)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:i=e[a+1],s=e[a+2],o=e[a+3],128==(192&i)&&128==(192&s)&&128==(192&o)&&(u=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&o)>65535&&u<1114112&&(l=u)}null===l?(l=65533,d=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),a+=d}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},u.prototype.compare=function(e,t,n,r,a){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),o=Math.min(i,s),c=this.slice(r,a),l=e.slice(t,n),d=0;da)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return y(this,e,t,n);case"latin1":case"binary":return w(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function T(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;ar)&&(n=r);for(var a="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,r,a,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||te.length)throw new RangeError("Index out of range")}function F(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,i=Math.min(e.length-n,2);a>>8*(r?a:1-a)}function M(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,i=Math.min(e.length-n,4);a>>8*(r?a:3-a)&255}function D(e,t,n,r,a,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,n,r,i){return i||D(e,0,n,4),a.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,i){return i||D(e,0,n,8),a.write(e,t,n,r,52,8),n+8}u.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(a*=256);)r+=this[e+--t]*a;return r},u.prototype.readUInt8=function(e,t){return t||E(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||E(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||E(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||E(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||E(e,t,this.length);for(var r=this[e],a=1,i=0;++i=(a*=128)&&(r-=Math.pow(2,8*t)),r},u.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||E(e,t,this.length);for(var r=t,a=1,i=this[e+--r];r>0&&(a*=256);)i+=this[e+--r]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return t||E(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||E(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(e,t){t||E(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(e,t){return t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||E(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||E(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||E(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||E(e,8,this.length),a.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||R(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+a]=e/i&255;return t+n},u.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):M(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);R(this,e,t,n,a-1,-a)}var i=0,s=1,o=0;for(this[t]=255&e;++i>0)-o&255;return t+n},u.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);R(this,e,t,n,a-1,-a)}var i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):M(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--a)e[a+t]=this[a+n];else if(i<1e3||!u.TYPED_ARRAY_SUPPORT)for(a=0;a>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&i.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&i.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function W(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function G(e,t,n,r){for(var a=0;a=t.length||a>=e.length);++a)t[a+n]=e[a];return a}}).call(this,n(37))},function(e,t,n){"use strict";t.byteLength=function(e){var t=c(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,r=c(e),s=r[0],o=r[1],u=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,o)),l=0,d=o>0?s-4:s;for(n=0;n>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,u[l++]=255&t);1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,n=e.length,a=n%3,i=[],s=16383,o=0,u=n-a;ou?u:o+s));1===a?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],a=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,u=s.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var a,i,s=[],o=t;o>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},function(e,t){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +t.read=function(e,t,n,r,a){var i,s,o=8*a-r-1,u=(1<>1,l=-7,d=n?a-1:0,p=n?-1:1,h=e[t+d];for(d+=p,i=h&(1<<-l)-1,h>>=-l,l+=o;l>0;i=256*i+e[t+d],d+=p,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=r;l>0;s=256*s+e[t+d],d+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=c}return(h?-1:1)*s*Math.pow(2,i-r)},t.write=function(e,t,n,r,a,i){var s,o,u,c=8*i-a-1,l=(1<>1,p=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+d>=1?p/u:p*Math.pow(2,1-d))*u>=2&&(s++,u/=2),s+d>=l?(o=0,s=l):s+d>=1?(o=(t*u-1)*Math.pow(2,a),s+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,a),s=0));a>=8;e[n+h]=255&o,h+=f,o/=256,a-=8);for(s=s<0;e[n+h]=255&s,h+=f,s/=256,c-=8);e[n+h-f]|=128*m}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";(function(e){var t=n(9); +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const r=()=>n(109);let a;class i{constructor(){this.util=n(110),this.textEncoder=new this.util.TextEncoder}fetch(e,n){return null!=Object(t.c)().global.fetch?Object(t.c)().global.fetch(e,n):(null==a&&(a=r()),a(e,n))}now(){const t=e.hrtime();return 1e3*t[0]+t[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)}}Object(t.c)().get("IS_NODE")&&!Object(t.c)().get("IS_BROWSER")&&Object(t.c)().setPlatform("node",new i)}).call(this,n(38))},function(e,t){},function(e,t){},function(e,t,n){(function(e){var r;!function(e,a,i){function s(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function u(e,t){var n=new s(e),r=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,r&&("object"==typeof r&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.alea=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){(function(e){var r;!function(e,a,i){function s(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 r=0;r>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.xor128=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){(function(e){var r;!function(e,a,i){function s(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 r=0;r>>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 u(e,t){var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.xorwow=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){(function(e){var r;!function(e,a,i){function s(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function u(e,t){null==e&&(e=+new Date);var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&(r.x&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.xorshift7=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){(function(e){var r;!function(e,a,i){function s(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0},function(e,t){var n,r,a,i,s,o=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(s=s+1640531527|0,a=0==(n=o[127&i]^=r+s)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=o[a+34&127],n=o[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[a]=r^n;e.w=s,e.X=o,e.i=a}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function u(e,t){null==e&&(e=+new Date);var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&(r.X&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.xor4096=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){(function(e){var r;!function(e,a,i){function s(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-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 r=0;r>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&o(r,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=u:n(25)&&n(40)?void 0===(r=function(){return u}.call(t,n,t,a))||(a.exports=r):this.tychei=u}(0,e,n(25))}).call(this,n(39)(e))},function(e,t,n){var r;!function(a,i){var s,o=this,u=256,c=i.pow(u,6),l=i.pow(2,52),d=2*l,p=255;function h(e,t,n){var r=[],p=g(b((t=1==t?{entropy:!0}:t||{}).entropy?[e,x(a)]:null==e?function(){try{var e;return s&&(e=s.randomBytes)?e=e(u):(e=new Uint8Array(u),(o.crypto||o.msCrypto).getRandomValues(e)),x(e)}catch(e){var t=o.navigator,n=t&&t.plugins;return[+new Date,o,n,o.screen,x(a)]}}():e,3),r),h=new f(r),v=function(){for(var e=h.g(6),t=c,n=0;e=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return v.int32=function(){return 0|h.g(4)},v.quick=function(){return h.g(4)/4294967296},v.double=v,g(x(h.S),a),(t.pass||n||function(e,t,n,r){return r&&(r.S&&m(r,h),e.state=function(){return m(h,{})}),n?(i.random=e,t):e})(v,p,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n(120),t.setImmediate="undefined"!=typeof self&&self.setImmediate||"undefined"!=typeof e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||"undefined"!=typeof e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(37))},function(e,t,n){(function(e,t){!function(e,n){"use strict";if(!e.setImmediate){var r,a,i,s,o,u=1,c={},l=!1,d=e.document,p=Object.getPrototypeOf&&Object.getPrototypeOf(e);p=p&&p.setTimeout?p:e,"[object process]"==={}.toString.call(e.process)?r=function(e){t.nextTick((function(){f(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?e.MessageChannel?((i=new MessageChannel).port1.onmessage=function(e){f(e.data)},r=function(e){i.port2.postMessage(e)}):d&&"onreadystatechange"in d.createElement("script")?(a=d.documentElement,r=function(e){var t=d.createElement("script");t.onreadystatechange=function(){f(e),t.onreadystatechange=null,a.removeChild(t),t=null},a.appendChild(t)}):r=function(e){setTimeout(f,0,e)}:(s="setImmediate$"+Math.random()+"$",o=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(s)&&f(+t.data.slice(s.length))},e.addEventListener?e.addEventListener("message",o,!1):e.attachEvent("onmessage",o),r=function(t){e.postMessage(s+t,"*")}),p.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\nexport const registerSaveRouter = (loudRouter) => IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter) => IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url) => IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers = (url, loadOptions) => IORouterRegistry.getLoadHandlers(url, loadOptions);\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicm91dGVyX3JlZ2lzdHJ5LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vdGZqcy1jb3JlL3NyYy9pby9yb3V0ZXJfcmVnaXN0cnkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBT0gsTUFBTSxPQUFPLGdCQUFnQjtJQU8zQjtRQUNFLElBQUksQ0FBQyxXQUFXLEdBQUcsRUFBRSxDQUFDO1FBQ3RCLElBQUksQ0FBQyxXQUFXLEdBQUcsRUFBRSxDQUFDO0lBQ3hCLENBQUM7SUFFTyxNQUFNLENBQUMsV0FBVztRQUN4QixJQUFJLGdCQUFnQixDQUFDLFFBQVEsSUFBSSxJQUFJLEVBQUU7WUFDckMsZ0JBQWdCLENBQUMsUUFBUSxHQUFHLElBQUksZ0JBQWdCLEVBQUUsQ0FBQztTQUNwRDtRQUNELE9BQU8sZ0JBQWdCLENBQUMsUUFBUSxDQUFDO0lBQ25DLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNILE1BQU0sQ0FBQyxrQkFBa0IsQ0FBQyxVQUFvQjtRQUM1QyxnQkFBZ0IsQ0FBQyxXQUFXLEVBQUUsQ0FBQyxXQUFXLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxDQUFDO0lBQzlELENBQUM7SUFFRDs7Ozs7T0FLRztJQUNILE1BQU0sQ0FBQyxr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SA9PlxuICAgIElPUm91dGVyUmVnaXN0cnkucmVnaXN0ZXJMb2FkUm91dGVyKGxvdWRSb3V0ZXIpO1xuZXhwb3J0IGNvbnN0IGdldFNhdmVIYW5kbGVycyA9ICh1cmw6IHN0cmluZ3xzdHJpbmdbXSkgPT5cbiAgICBJT1JvdXRlclJlZ2lzdHJ5LmdldFNhdmVIYW5kbGVycyh1cmwpO1xuZXhwb3J0IGNvbnN0IGdldExvYWRIYW5kbGVycyA9XG4gICAgKHVybDogc3RyaW5nfHN0cmluZ1tdLCBsb2FkT3B0aW9ucz86IExvYWRPcHRpb25zKSA9PlxuICAgICAgICBJT1JvdXRlclJlZ2lzdHJ5LmdldExvYWRIYW5kbGVycyh1cmwsIGxvYWRPcHRpb25zKTtcbiJdfQ==","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport '../flags';\nimport { env } from '../environment';\nimport { getModelArtifactsInfoForJSON } from './io_utils';\nimport { IORouterRegistry } from './router_registry';\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase() {\n const idbFactory = getIndexedDBFactory();\n return new Promise((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\nfunction getIndexedDBFactory() {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error('Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error('The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\nfunction setUpDatabase(openRequest) {\n const db = openRequest.result;\n db.createObjectStore(MODEL_STORE_NAME, { keyPath: 'modelPath' });\n db.createObjectStore(INFO_STORE_NAME, { keyPath: 'modelPath' });\n}\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB {\n constructor(modelPath) {\n this.indexedDB = getIndexedDBFactory();\n if (modelPath == null || !modelPath) {\n throw new Error('For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n async save(modelArtifacts) {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n return this.databaseAction(this.modelPath, modelArtifacts);\n }\n async load() {\n return this.databaseAction(this.modelPath);\n }\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n databaseAction(modelPath, modelArtifacts) {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(`Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n }\n else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n }\n else {\n // Put model into object store.\n const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const putInfoRequest = infoStore.put({ modelPath: this.modelPath, modelArtifactsInfo });\n let modelTx;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n putModelRequest.onsuccess = () => resolve({ modelArtifactsInfo });\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n }\n else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\nBrowserIndexedDB.URL_SCHEME = 'indexeddb://';\nexport const indexedDBRouter = (url) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n }\n else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n }\n else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath) {\n return new BrowserIndexedDB(modelPath);\n}\nfunction maybeStripScheme(key) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\nexport class BrowserIndexedDBManager {\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n async listModels() {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = store.getAll();\n getAllInfoRequest.onsuccess = () => {\n const out = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n async removeModel(path) {\n path = maybeStripScheme(path);\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const getInfoRequest = infoStore.get(path);\n let modelTx;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(`Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n }\n else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () => resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error => reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n }\n else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXhlZF9kYi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvaW8vaW5kZXhlZF9kYi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFFSCxPQUFPLFVBQVUsQ0FBQztBQUVsQixPQUFPLEVBQUMsR0FBRyxFQUFDLE1BQU0sZ0JBQWdCLENBQUM7QUFFbkMsT0FBTyxFQUFDLDRCQUE0QixFQUFDLE1BQU0sWUFBWSxDQUFDO0FBQ3hELE9BQU8sRUFBVyxnQkFBZ0IsRUFBQyxNQUFNLG1CQUFtQixDQUFDO0FBRzdELE1BQU0sYUFBYSxHQUFHLGNBQWMsQ0FBQztBQUNyQyxNQUFNLGdCQUFnQixHQUFHLENBQUMsQ0FBQztBQUUzQiwwRUFBMEU7QUFDMUUsK0VBQStFO0FBQy9FLDhFQUE4RTtBQUM5RSxNQUFNLGdCQUFnQixHQUFHLGNBQWMsQ0FBQztBQUN4Qyw4RUFBOEU7QUFDOUUsK0VBQStFO0FBQy9FLCtCQUErQjtBQUMvQixNQUFNLGVBQWUsR0FBRyxrQkFBa0IsQ0FBQztBQUUzQzs7R0FFRztBQUNILE1BQU0sQ0FBQyxLQUFLLFVBQVUsY0FBYztJQUNsQyxNQUFNLFVBQVUsR0FBRyxtQkFBbUIsRUFBRSxDQUFDO0lBRXpDLE9BQU8sSUFBSSxPQUFPLENBQU8sQ0FBQyxPQUFPLEVBQUUsTUFBT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XG4gICAgICAgICAgICAgICAgcmV0dXJuIHJlamVjdChwdXRNb2RlbFJlcXVlc3QuZXJyb3IpO1xuICAgICAgICAgICAgICB9O1xuICAgICAgICAgICAgICBkZWxldGVJbmZvUmVxdWVzdC5vbmVycm9yID0gZXJyb3IgPT4ge1xuICAgICAgICAgICAgICAgIGRiLmNsb3NlKCk7XG4gICAgICAgICAgICAgICAgcmV0dXJuIHJlamVjdChwdXRNb2RlbFJlcXVlc3QuZXJyb3IpO1xuICAgICAgICAgICAgICB9O1xuICAgICAgICAgICAgfTtcbiAgICAgICAgICB9O1xuICAgICAgICAgIHB1dEluZm9SZXF1ZXN0Lm9uZXJyb3IgPSBlcnJvciA9PiB7XG4gICAgICAgICAgICBkYi5jbG9zZSgpO1xuICAgICAgICAgICAgcmV0dXJuIHJlamVjdChwdXRJbmZvUmVxdWVzdC5lcnJvcik7XG4gICAgICAgICAgfTtcbiAgICAgICAgICBpbmZvVHgub25jb21wbGV0ZSA9ICgpID0+IHtcbiAgICAgICAgICAgIGlmIChtb2RlbFR4ID09IG51bGwpIHtcbiAgICAgICAgICAgICAgZGIuY2xvc2UoKTtcbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgIG1vZGVsVHgub25jb21wbGV0ZSA9ICgpID0+IGRiLmNsb3NlKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfTtcbiAgICAgICAgfVxuICAgICAgfTtcbiAgICAgIG9wZW5SZXF1ZXN0Lm9uZXJyb3IgPSBlcnJvciA9PiByZWplY3Qob3BlblJlcXVlc3QuZXJyb3IpO1xuICAgIH0pO1xuICB9XG59XG5cbmV4cG9ydCBjb25zdCBpbmRleGVkREJSb3V0ZXI6IElPUm91dGVyID0gKHVybDogc3RyaW5nfHN0cmluZ1tdKSA9PiB7XG4gIGlmICghZW52KCkuZ2V0Qm9vbCgnSVNfQlJPV1NFUicpKSB7XG4gICAgcmV0dXJuIG51bGw7XG4gIH0gZWxzZSB7XG4gICAgaWYg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ICAgICAgICAgcmV0dXJuIHJlamVjdChnZXRJbmZvUmVxdWVzdC5lcnJvcik7XG4gICAgICAgICAgICB9O1xuICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgICAgZ2V0SW5mb1JlcXVlc3Qub25lcnJvciA9IGVycm9yID0+IHtcbiAgICAgICAgICBkYi5jbG9zZSgpO1xuICAgICAgICAgIHJldHVybiByZWplY3QoZ2V0SW5mb1JlcXVlc3QuZXJyb3IpO1xuICAgICAgICB9O1xuXG4gICAgICAgIGluZm9UeC5vbmNvbXBsZXRlID0gKCkgPT4ge1xuICAgICAgICAgIGlmIChtb2RlbFR4ID09IG51bGwpIHtcbiAgICAgICAgICAgIGRiLmNsb3NlKCk7XG4gICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIG1vZGVsVHgub25jb21wbGV0ZSA9ICgpID0+IGRiLmNsb3NlKCk7XG4gICAgICAgICAgfVxuICAgICAgICB9O1xuICAgICAgfTtcbiAgICAgIG9wZW5SZXF1ZXN0Lm9uZXJyb3IgPSBlcnJvciA9PiByZWplY3Qob3BlblJlcXVlc3QuZXJyb3IpO1xuICAgIH0pO1xuICB9XG59XG4iXX0=","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport '../flags';\nimport { env } from '../environment';\nimport { assert } from '../util';\nimport { arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON } from './io_utils';\nimport { IORouterRegistry } from './router_registry';\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts() {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error('purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\nfunction getModelKeys(path) {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\nfunction removeItems(keys) {\n for (const key of Object.values(keys)) {\n window.localStorage.removeItem(key);\n }\n}\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\nfunction maybeStripScheme(key) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage {\n constructor(modelPath) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error('The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n if (modelPath == null || !modelPath) {\n throw new Error('For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts) {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(modelArtifacts.weightData));\n // Note that JSON.stringify doesn't write out keys that have undefined\n // values, so for some keys, we set undefined instead of a null-ish\n // value.\n const metadata = {\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n signature: modelArtifacts.signature != null ?\n modelArtifacts.signature :\n undefined,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n modelArtifacts.userDefinedMetadata :\n undefined,\n modelInitializer: modelArtifacts.modelInitializer != null ?\n modelArtifacts.modelInitializer :\n undefined,\n trainingConfig: modelArtifacts.trainingConfig != null ?\n modelArtifacts.trainingConfig :\n undefined\n };\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n return { modelArtifactsInfo };\n }\n catch (err) {\n // If saving failed, clean up all items saved so far.\n removeItems(this.keys);\n throw new Error(`Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load() {\n const info = JSON.parse(this.LS.getItem(this.keys.info));\n if (info == null) {\n throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);\n }\n if (info.modelTopologyType !== 'JSON') {\n throw new Error('BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n const out = {};\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(`In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(`In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString);\n out.format = metadata.format;\n out.generatedBy = metadata.generatedBy;\n out.convertedBy = metadata.convertedBy;\n if (metadata.signature != null) {\n out.signature = metadata.signature;\n }\n if (metadata.userDefinedMetadata != null) {\n out.userDefinedMetadata = metadata.userDefinedMetadata;\n }\n if (metadata.modelInitializer != null) {\n out.modelInitializer = metadata.modelInitializer;\n }\n if (metadata.trainingConfig != null) {\n out.trainingConfig = metadata.trainingConfig;\n }\n }\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(`In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n return out;\n }\n}\nBrowserLocalStorage.URL_SCHEME = 'localstorage://';\nexport const localStorageRouter = (url) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n }\n else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));\n }\n else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath) {\n return new BrowserLocalStorage(modelPath);\n}\nexport class BrowserLocalStorageManager {\n constructor() {\n assert(env().getBool('IS_BROWSER'), () => 'Current environment is not a web browser');\n assert(typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined', () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n async listModels() {\n const out = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key));\n }\n }\n return out;\n }\n async removeModel(path) {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info));\n removeItems(keys);\n return info;\n }\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9jYWxfc3RvcmFnZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvaW8vbG9jYWxfc3RvcmFnZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFFSCxPQUFPLFVBQVUsQ0FBQztBQUNsQixPQUFPLEVBQUMsR0FBRyxFQUFDLE1BQU0sZ0JBQWdCLENBQUM7QUFFbkMsT0FBTyxFQUFDLE1BQU0sRUFBQyxNQUFNLFNBQVMsQ0FBQztBQUMvQixPQUFPLEVBQUMseUJBQXlCLEVBQUUseUJBQXlCLEVBQUUsNEJBQTRCLEVBQUMsTUFBTSxZQUFZLENBQUM7QUFDOUcsT0FBTyxFQUFXLGdCQUFnQixFQUFDLE1BQU0sbUJBQW1CLENBQUM7QUFHN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CeTogbW9kZWxBcnRpZmFjdHMuZ2VuZXJhdGVkQnksXG4gICAgICAgICAgY29udmVydGVkQnk6IG1vZGVsQXJ0aWZhY3RzLmNvbnZlcnRlZEJ5LFxuICAgICAgICAgIHNpZ25hdHVyZTogbW9kZWxBcnRpZmFjdHMuc2lnbmF0dXJlICE9IG51bGwgP1xuICAgICAgICAgICAgICBtb2RlbEFydGlmYWN0cy5zaWduYXR1cmUgOlxuICAgICAgICAgICAgICB1bmRlZmluZWQsXG4gICAgICAgICAgdXNlckRlZmluZWRNZXRhZGF0YTogbW9kZWxBcnRpZmFjdHMudXNlckRlZmluZWRNZXRhZGF0YSAhPSBudWxsID9cbiAgICAgICAgICAgICAgbW9kZWxBcnRpZmFjdHMudXNlckRlZmluZWRNZXRhZGF0YSA6XG4gICAgICAgICAgICAgIHVuZGVmaW5lZCxcbiAgICAgICAgICBtb2RlbEluaXRpYWxpemVyOiBtb2RlbEFydGlmYWN0cy5tb2RlbEluaXRpYWxpemVyICE9IG51bGwgP1xuICAgICAgICAgICAgICBtb2RlbEFydGlmYWN0cy5tb2RlbEluaXRpYWxpemVyIDpcbiAgICAgICAgICAgICAgdW5kZWZpbmVkLFxuICAgICAgICAgIHRyYWluaW5nQ29uZmlnOiBtb2RlbEFydGlmYWN0cy50cmFpbmluZ0NvbmZpZyAhPSBudWxsID9cbiAgICAgICAgICAgICAgbW9kZWxBcnRpZmFjdHMudHJhaW5pbmdDb25maWcgOlxuICAgICAgICAgICAgICB1bmRlZmluZWRcbiAgICAgICAgfTtcbiAgICAgICAgdGhpcy5MUy5zZXRJdGVtKHRoaXMua2V5cy5tb2RlbE1ldGFkYXRhLCBKU09OLnN0cmluZ2lmeShtZXRhZGF0YSkpO1xuXG4gICAgICAgIHJldHVybiB7bW9kZWxBcnRpZmFjdHNJbmZvfTtcbiAgICAgIH0gY2F0Y2ggKGVycikge1xuICAgICAgICAvLyBJZiBzYXZpbmcgZmFpbGVkLCBjbGVhbiB1cCBhbGwgaXRlb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gIH1cblxuICBhc3luYyByZW1vdmVNb2RlbChwYXRoOiBzdHJpbmcpOiBQcm9taXNlPE1vZGVsQXJ0aWZhY3RzSW5mbz4ge1xuICAgIHBhdGggPSBtYXliZVN0cmlwU2NoZW1lKHBhdGgpO1xuICAgIGNvbnN0IGtleXMgPSBnZXRNb2RlbEtleXMocGF0aCk7XG4gICAgaWYgKHRoaXMuTFMuZ2V0SXRlbShrZXlzLmluZm8pID09IG51bGwpIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcihgQ2Fubm90IGZpbmQgbW9kZWwgYXQgcGF0aCAnJHtwYXRofSdgKTtcbiAgICB9XG4gICAgY29uc3QgaW5mbyA9IEpTT04ucGFyc2UodGhpcy5MUy5nZXRJdGVtKGtleXMuaW5mbykpIGFzIE1vZGVsQXJ0aWZhY3RzSW5mbztcbiAgICByZW1vdmVJdGVtcyhrZXlzKTtcbiAgICByZXR1cm4gaW5mbztcbiAgfVxufVxuIl19","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\nimport { assert } from '../util';\nimport { IORouterRegistry } from './router_registry';\nconst URL_SCHEME_SUFFIX = '://';\nexport class ModelStoreManagerRegistry {\n constructor() {\n this.managers = {};\n }\n static getInstance() {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme, manager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(registry.managers[scheme] == null, () => `A model store manager is already registered for scheme '${scheme}'.`);\n registry.managers[scheme] = manager;\n }\n static getManager(scheme) {\n const manager = this.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n static getSchemes() {\n return Object.keys(this.getInstance().managers);\n }\n}\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url) {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(`The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\nasync function cloneModelInternal(sourceURL, destURL, deleteSource = false) {\n assert(sourceURL !== destURL, () => `Old path and new path are the same: '${sourceURL}'`);\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(loadHandlers.length > 0, () => `Copying failed because no load handler is found for source URL ${sourceURL}.`);\n assert(loadHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(saveHandlers.length > 0, () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(saveHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n const modelArtifacts = await loadHandler.load();\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n const saveResult = await saveHandler.save(modelArtifacts);\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n return saveResult.modelArtifactsInfo;\n}\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels() {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out = {};\n for (const scheme of schemes) {\n const schemeOut = await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n/**\n * Remove a model specified by URL from a reigstered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url) {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(sourceURL, destURL) {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(sourceURL, destURL) {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\nexport { moveModel, copyModel, removeModel, listModels };\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxfbWFuYWdlbWVudC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvaW8vbW9kZWxfbWFuYWdlbWVudC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFFSDs7Ozs7Ozs7O0dBU0c7QUFFSCxPQUFPLEVBQUMsTUFBTSxFQUFDLE1BQU0sU0FBUyxDQUFDO0FBRS9CLE9BQU8sRUFBQyxnQkFBZ0IsRUFBQyxNQUFNLG1CQUFtQixDQUFDO0FBR25ELE1BQU0saUJBQWlCLEdBQUcsS0FBSyxDQUFDO0FBRWhDLE1BQU0sT0FBTyx5QkFBeUI7SUFNcEM7UUFDRSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUNyQixDQUFDO0lBRU8sTUFBTSxDQUFDLFdBQVc7UUFDeEIsSUFBSSx5QkFBeUIsQ0FBQyxRQUFRLElBQUksSUFBSSxFQUFFO1lBQzlDLHlCQUF5QixDQUFDLFFBQVEsR0FBRyxJQUFJLHlCQUF5QixFQUFFLENBQUM7U0FDdEU7UUFDRCxPQUFPLHlCQUF5QixDQUFDLFFBQVEsQ0FBQztJQUM1QyxDQUFDO0lBRUQ7Ozs7O09BS0c7SUFDSCxNQUFNLENBQUMsZUFBZSxDQUFDLE1BQWMsRUFBRSxPQUEwQjtRQUMvRCxNQUFNLENBQUMsTUFBTSxJQUFJLElBQUksRUFBRSxHQUFHLEVBQUUsQ0FBQyx1Q0FBdUMsQ0FBQyxDQUFDO1FBQ3RFLElBQUksTUFBTSxDQUFDLFFBQVEsQ0FBQyxpQkF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Rlc3RVUkwsIGRlbGV0ZVNvdXJjZSk7XG59XG5cbmV4cG9ydCB7bW92ZU1vZGVsLCBjb3B5TW9kZWwsIHJlbW92ZU1vZGVsLCBsaXN0TW9kZWxzfTtcbiJdfQ==","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport '../flags';\nimport { env } from '../environment';\nimport { BrowserIndexedDB, BrowserIndexedDBManager } from '../io/indexed_db';\nimport { BrowserLocalStorage, BrowserLocalStorageManager } from '../io/local_storage';\nimport { ModelStoreManagerRegistry } from '../io/model_management';\nexport class PlatformBrowser {\n fetch(path, init) {\n return fetch(path, init);\n }\n now() {\n return performance.now();\n }\n encode(text, encoding) {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(`Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes, encoding) {\n return new TextDecoder(encoding).decode(bytes);\n }\n}\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n }\n catch (err) {\n }\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n }\n catch (err) {\n }\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGxhdGZvcm1fYnJ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hBcnJheSwgZW5jb2Rpbmc6IHN0cmluZyk6IHN0cmluZyB7XG4gICAgcmV0dXJuIG5ldyBUZXh0RGVjb2RlcihlbmNvZGluZykuZGVjb2RlKGJ5dGVzKTtcbiAgfVxufVxuXG5pZiAoZW52KCkuZ2V0KCdJU19CUk9XU0VSJykpIHtcbiAgZW52KCkuc2V0UGxhdGZvcm0oJ2Jyb3dzZXInLCBuZXcgUGxhdGZvcm1Ccm93c2VyKCkpO1xuXG4gIC8vIFJlZ2lzdGVyIExvY2FsU3RvcmFnZSBJT0hhbmRsZXJcbiAgdHJ5IHtcbiAgICBNb2RlbFN0b3JlTWFuYWdlclJlZ2lzdHJ5LnJlZ2lzdGVyTWFuYWdlcihcbiAgICAgICAgQnJvd3NlckxvY2FsU3RvcmFnZS5VUkxfU0NIRU1FLCBuZXcgQnJvd3NlckxvY2FsU3RvcmFnZU1hbmFnZXIoKSk7XG4gIH0gY2F0Y2ggKGVycikge1xuICB9XG5cbiAgLy8gUmVnaXN0ZXIgSW5kZXhlZERCIElPSGFuZGxlclxuICB0cnkge1xuICAgIE1vZGVsU3RvcmVNYW5hZ2VyUmVnaXN0cnkucmVnaXN0ZXJNYW5hZ2VyKFxuICAgICAgICBCcm93c2VySW5kZXhlZERCLlVSTF9TQ0hFTUUsIG5ldyBCcm93c2VySW5kZXhlZERCTWFuYWdlcigpKTtcbiAgfSBjYXRjaCAoZXJyKSB7XG4gIH1cbn1cbiJdfQ==","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorBuffer } from '../tensor';\nimport * as util from '../util';\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(shape, dtype = 'float32', values) {\n dtype = dtype || 'float32';\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVmZmVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vdGZqcy1jb3JlL3NyYy9vcHMvYnVmZmVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUVILE9BQU8sRUFBQyxZQUFZLEVBQUMsTUFBTSxXQUFXLENBQUM7QUFFdkMsT0FBTyxLQUFLLElBQUksTUFBTSxTQUFTLENBQUM7QUFFaEM7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0F5Qkc7QUFDSCxNQUFNLFVBQVUsTUFBTSxDQUNsQixLQUFrQixFQUFFLFFBQVcsU0FBYyxFQUM3QyxNQUF1QjtJQUN6QixLQUFLLEdBQUcsS0FBSyxJQUFJLFNBQWMsQ0FBQztJQUNoQyxJQUFJLENBQUMsa0NBQWtDLENBQUM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lbnNvciBzaGFwZS5cbiAqIEBwYXJhbSBkdHlwZSBUaGUgZHR5cGUgb2YgdGhlIGJ1ZmZlci4gRGVmYXVsdHMgdG8gJ2Zsb2F0MzInLlxuICogQHBhcmFtIHZhbHVlcyBUaGUgdmFsdWVzIG9mIHRoZSBidWZmZXIgYXMgYFR5cGVkQXJyYXlgLiBEZWZhdWx0cyB0b1xuICogemVyb3MuXG4gKlxuICogQGRvYyB7aGVhZGluZzogJ1RlbnNvcnMnLCBzdWJoZWFkaW5nOiAnQ3JlYXRpb24nfVxuICovXG5leHBvcnQgZnVuY3Rpb24gYnVmZmVyPFIgZXh0ZW5kcyBSYW5rLCBEIGV4dGVuZHMgRGF0YVR5cGUgPSAnZmxvYXQzMic+KFxuICAgIHNoYXBlOiBTaGFwZU1hcFtSXSwgZHR5cGU6IEQgPSAnZmxvYXQzMicgYXMgRCxcbiAgICB2YWx1ZXM/OiBEYXRhVHlwZU1hcFtEXSk6IFRlbnNvckJ1ZmZlcjxSLCBEPiB7XG4gIGR0eXBlID0gZHR5cGUgfHwgJ2Zsb2F0MzInIGFzIEQ7XG4gIHV0aWwuYXNzZXJ0Tm9uTmVnYXRpdmVJbnRlZ2VyRGltZW5zaW9ucyhzaGFwZSk7XG4gIHJldHVybiBuZXcgVGVuc29yQnVmZmVyPFIsIEQ+KHNoYXBlLCBkdHlwZSwgdmFsdWVzKTtcbn1cbiJdfQ==","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { Cast } from '../kernel_names';\nimport { convertToTensor } from '../tensor_util_env';\nimport * as util from '../util';\nimport { op } from './operation';\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x, dtype) {\n const $x = convertToTensor(x, 'x', 'cast');\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n const inputs = { x: $x };\n const attrs = { dtype };\n return ENGINE.runKernel(Cast, inputs, attrs);\n}\nexport const cast = op({ cast_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2FzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvb3BzL2Nhc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBQ0gsT0FBTyxFQUFDLE1BQU0sRUFBQyxNQUFNLFdBQVcsQ0FBQztBQUNqQyxPQUFPLEVBQUMsSUFBSSxFQUF3QixNQUFNLGlCQUFpQixDQUFDO0FBSTVELE9BQU8sRUFBQyxlQUFlLEVBQUMsTUFBTSxvQkFBb0IsQ0FBQztBQUVuRCxPQUFPLEtBQUssSUFBSSxNQUFNLFNBQVMsQ0FBQztBQUVoQyxPQUFPLEVBQUMsRUFBRSxFQUFDLE1BQU0sYUFBYSxDQUFDO0FBRS9COzs7Ozs7Ozs7OztHQVdHO0FBQ0gsU0FBUyxLQUFLLENBQW1CLENBQWUsRUFBRSxLQUFlO0lBQy9ELE1BQ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5IHN0cmluZ3MgY2FuIGJlIGNhc3RlZCB0byBzdHJpbmdzJyk7XG4gIH1cblxuICBjb25zdCBpbnB1dHM6IENhc3RJbnB1dHMgPSB7eDogJHh9O1xuICBjb25zdCBhdHRyczogQ2FzdEF0dHJzID0ge2R0eXBlfTtcblxuICByZXR1cm4gRU5HSU5FLnJ1bktlcm5lbChcbiAgICAgIENhc3QsIGlucHV0cyBhcyB7fSBhcyBOYW1lZFRlbnNvck1hcCwgYXR0cnMgYXMge30gYXMgTmFtZWRBdHRyTWFwKTtcbn1cblxuZXhwb3J0IGNvbnN0IGNhc3QgPSBvcCh7Y2FzdF99KTtcbiJdfQ==","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { Identity } from '../kernel_names';\nimport { convertToTensor } from '../tensor_util_env';\nimport { op } from './operation';\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x) {\n const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n const inputs = { x: $x };\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernel(Identity, inputs);\n}\nexport const clone = op({ clone_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2xvbmUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuL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lcyc7XG5cbmltcG9ydCB7b3B9IGZyb20gJy4vb3BlcmF0aW9uJztcblxuLyoqXG4gKiBDcmVhdGVzIGEgbmV3IHRlbnNvciB3aXRoIHRoZSBzYW1lIHZhbHVlcyBhbmQgc2hhcGUgYXMgdGhlIHNwZWNpZmllZFxuICogdGVuc29yLlxuICpcbiAqIGBgYGpzXG4gKiBjb25zdCB4ID0gdGYudGVuc29yKFsxLCAyXSk7XG4gKlxuICogeC5jbG9uZSgpLnByaW50KCk7XG4gKiBgYGBcbiAqXG4gKiBAcGFyYW0geCBUaGUgdGVuc29yIHRvIGNsb25lLlxuICpcbiAqIEBkb2Mge2hlYWRpbmc6ICdUZW5zb3JzJywgc3ViaGVhZGluZzogJ0NyZWF0aW9uJ31cbiAqL1xuZnVuY3Rpb24gY2xvbmVfPFQgZXh0ZW5kcyBUZW5zb3I+KHg6IFR8VGVuc29yTGlrZSk6IFQge1xuICBjb25zdCAkeCA9IGNvbnZlcnRUb1RlbnNvcih4LCAneCcsICdjbG9uZScsICdzdHJpbmdfb3JfbnVtZXJpYycpO1xuICBjb25zdCBpbnB1dHM6IElkZW50aXR5SW5wdXRzID0ge3g6ICR4fTtcblxuICAvLyBOb3RlIHRoaXMgb3AgaXMgY2FsbGVkIHRmLmlkZW50aXR5IGluIHB5dGhvbi4gSGVuY2UgdGhlIGtlcm5lbCBuYW1lIHVzZWRcbiAgLy8gaGVyZS5cbiAgcmV0dXJuIEVOR0lORS5ydW5LZXJuZWwoSWRlbnRpdHksIGlucHV0cyBhcyB7fSBhcyBOYW1lZFRlbnNvck1hcCk7XG59XG5cbmV4cG9ydCBjb25zdCBjbG9uZSA9IG9wKHtjbG9uZV99KTtcbiJdfQ==","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x, verbose = false) {\n console.log(x.toString(verbose));\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJpbnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi90ZmpzLWNvcmUvc3JjL29wcy9wcmludC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFJSDs7Ozs7Ozs7Ozs7O0dBWUc7QUFDSCxNQUFNLFVBQVUsS0FBSyxDQUFtQixDQUFJLEVBQUUsT0FBTyxHQUFHLEtBQUs7SUFDM0QsT0FBTyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsUUFBUSxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUM7QUFDbkMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCAyMDIwIEdvb2dsZSBJbmMuIEFsbCBSaWdodHMgUmVzZXJ2ZWQuXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgQXBhY2hlIExpY2Vuc2UsIFZlcnNpb24gMi4wICh0aGUgXCJMaWNlbnNlXCIpO1xuICogeW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLlx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XQgdGhlIGAgVGVuc29yYCxcbiAqIGluY2x1ZGluZyBkdHlwZSBhbmQgc2l6ZS5cbiAqXG4gKiBAZG9jIHtoZWFkaW5nOiAnVGVuc29ycycsIHN1YmhlYWRpbmc6ICdDcmVhdGlvbid9XG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBwcmludDxUIGV4dGVuZHMgVGVuc29yPih4OiBULCB2ZXJib3NlID0gZmFsc2UpOiB2b2lkIHtcbiAgY29uc29sZS5sb2coeC50b1N0cmluZyh2ZXJib3NlKSk7XG59XG4iXX0=","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Required side effectful code for tfjs-core\n// Set up Engine and ENV\nimport { getOrMakeEngine } from './engine';\ngetOrMakeEngine();\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n// Set up OpHandler\nimport { buffer } from './ops/buffer';\nimport { cast } from './ops/cast';\nimport { clone } from './ops/clone';\nimport { print } from './ops/print';\nimport { setOpHandler } from './tensor';\nconst opHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzZV9zaWRlX2VmZmVjdHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi90ZmpzLWNvcmUvc3JjL2Jhc2Vfc2lkZV9lZmZlY3RzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO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lclxuaW1wb3J0IHtidWZmZXJ9IGZyb20gJy4vb3BzL2J1ZmZlcic7XG5pbXBvcnQge2Nhc3R9IGZyb20gJy4vb3BzL2Nhc3QnO1xuaW1wb3J0IHtjbG9uZX0gZnJvbSAnLi9vcHMvY2xvbmUnO1xuaW1wb3J0IHtwcmludH0gZnJvbSAnLi9vcHMvcHJpbnQnO1xuaW1wb3J0IHtPcEhhbmRsZXIsIHNldE9wSGFuZGxlcn0gZnJvbSAnLi90ZW5zb3InO1xuY29uc3Qgb3BIYW5kbGVyOiBPcEhhbmRsZXIgPSB7XG4gIGJ1ZmZlcixcbiAgY2FzdCxcbiAgY2xvbmUsXG4gIHByaW50XG59O1xuc2V0T3BIYW5kbGVyKG9wSGFuZGxlcik7XG4iXX0=","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\nimport '../flags';\nimport { env } from '../environment';\nimport { basename, concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts } from './io_utils';\nimport { IORouterRegistry } from './router_registry';\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\nfunction defer(f) {\n return new Promise(resolve => setTimeout(resolve)).then(f);\n}\nexport class BrowserDownloads {\n constructor(fileNamePrefix) {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Provide info on what IOHandlers are available under the\n // current environment.\n throw new Error('browserDownloads() cannot proceed because the current environment ' +\n 'is not a browser.');\n }\n if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {\n fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);\n }\n if (fileNamePrefix == null || fileNamePrefix.length === 0) {\n fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;\n }\n this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;\n this.weightDataFileName =\n fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;\n }\n async save(modelArtifacts) {\n if (typeof (document) === 'undefined') {\n throw new Error('Browser downloads are not supported in ' +\n 'this environment since `document` is not present');\n }\n const weightsURL = window.URL.createObjectURL(new Blob([modelArtifacts.weightData], { type: 'application/octet-stream' }));\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('BrowserDownloads.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n else {\n const weightsManifest = [{\n paths: ['./' + this.weightDataFileName],\n weights: modelArtifacts.weightSpecs\n }];\n const modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n const modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: 'application/json' }));\n // If anchor elements are not provided, create them without attaching them\n // to parents, so that the downloaded file names can be controlled.\n const jsonAnchor = this.modelJsonAnchor == null ?\n document.createElement('a') :\n this.modelJsonAnchor;\n jsonAnchor.download = this.modelJsonFileName;\n jsonAnchor.href = modelJsonURL;\n // Trigger downloads by evoking a click event on the download anchors.\n // When multiple downloads are started synchronously, Firefox will only\n // save the last one.\n await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n if (modelArtifacts.weightData != null) {\n const weightDataAnchor = this.weightDataAnchor == null ?\n document.createElement('a') :\n this.weightDataAnchor;\n weightDataAnchor.download = this.weightDataFileName;\n weightDataAnchor.href = weightsURL;\n await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n }\n return { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) };\n }\n }\n}\nBrowserDownloads.URL_SCHEME = 'downloads://';\nclass BrowserFiles {\n constructor(files) {\n if (files == null || files.length < 1) {\n throw new Error(`When calling browserFiles, at least 1 file is required, ` +\n `but received ${files}`);\n }\n this.jsonFile = files[0];\n this.weightsFiles = files.slice(1);\n }\n async load() {\n return new Promise((resolve, reject) => {\n const jsonReader = new FileReader();\n jsonReader.onload = (event) => {\n // tslint:disable-next-line:no-any\n const modelJSON = JSON.parse(event.target.result);\n const modelTopology = modelJSON.modelTopology;\n if (modelTopology == null) {\n reject(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));\n return;\n }\n const weightsManifest = modelJSON.weightsManifest;\n if (weightsManifest == null) {\n reject(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));\n return;\n }\n if (this.weightsFiles.length === 0) {\n resolve({ modelTopology });\n return;\n }\n const modelArtifactsPromise = getModelArtifactsForJSON(modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n resolve(modelArtifactsPromise);\n };\n jsonReader.onerror = error => reject(`Failed to read model topology and weights manifest JSON ` +\n `from file '${this.jsonFile.name}'. BrowserFiles supports loading ` +\n `Keras-style tf.Model artifacts only.`);\n jsonReader.readAsText(this.jsonFile);\n });\n }\n loadWeights(weightsManifest) {\n const weightSpecs = [];\n const paths = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n paths.push(...entry.paths);\n }\n const pathToFile = this.checkManifestAndWeightFiles(weightsManifest);\n const promises = paths.map(path => this.loadWeightsFile(path, pathToFile[path]));\n return Promise.all(promises).then(buffers => [weightSpecs, concatenateArrayBuffers(buffers)]);\n }\n loadWeightsFile(path, file) {\n return new Promise((resolve, reject) => {\n const weightFileReader = new FileReader();\n weightFileReader.onload = (event) => {\n // tslint:disable-next-line:no-any\n const weightData = event.target.result;\n resolve(weightData);\n };\n weightFileReader.onerror = error => reject(`Failed to weights data from file of path '${path}'.`);\n weightFileReader.readAsArrayBuffer(file);\n });\n }\n /**\n * Check the compatibility between weights manifest and weight files.\n */\n checkManifestAndWeightFiles(manifest) {\n const basenames = [];\n const fileNames = this.weightsFiles.map(file => basename(file.name));\n const pathToFile = {};\n for (const group of manifest) {\n group.paths.forEach(path => {\n const pathBasename = basename(path);\n if (basenames.indexOf(pathBasename) !== -1) {\n throw new Error(`Duplicate file basename found in weights manifest: ` +\n `'${pathBasename}'`);\n }\n basenames.push(pathBasename);\n if (fileNames.indexOf(pathBasename) === -1) {\n throw new Error(`Weight file with basename '${pathBasename}' is not provided.`);\n }\n else {\n pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)];\n }\n });\n }\n if (basenames.length !== this.weightsFiles.length) {\n throw new Error(`Mismatch in the number of files in weights manifest ` +\n `(${basenames.length}) and the number of weight files provided ` +\n `(${this.weightsFiles.length}).`);\n }\n return pathToFile;\n }\n}\nexport const browserDownloadsRouter = (url) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n }\n else {\n if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {\n return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));\n }\n else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(browserDownloadsRouter);\n/**\n * Creates an IOHandler that triggers file downloads from the browser.\n *\n * The returned `IOHandler` instance can be used as model exporting methods such\n * as `tf.Model.save` and supports only saving.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * const saveResult = await model.save('downloads://mymodel');\n * // This will trigger downloading of two files:\n * // 'mymodel.json' and 'mymodel.weights.bin'.\n * console.log(saveResult);\n * ```\n *\n * @param fileNamePrefix Prefix name of the files to be downloaded. For use with\n * `tf.Model`, `fileNamePrefix` should follow either of the following two\n * formats:\n * 1. `null` or `undefined`, in which case the default file\n * names will be used:\n * - 'model.json' for the JSON file containing the model topology and\n * weights manifest.\n * - 'model.weights.bin' for the binary file containing the binary weight\n * values.\n * 2. A single string or an Array of a single string, as the file name prefix.\n * For example, if `'foo'` is provided, the downloaded JSON\n * file and binary weights file will be named 'foo.json' and\n * 'foo.weights.bin', respectively.\n * @param config Additional configuration for triggering downloads.\n * @returns An instance of `BrowserDownloads` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserDownloads(fileNamePrefix = 'model') {\n return new BrowserDownloads(fileNamePrefix);\n}\n/**\n * Creates an IOHandler that loads model artifacts from user-selected files.\n *\n * This method can be used for loading from files such as user-selected files\n * in the browser.\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * // Note: This code snippet won't run properly without the actual file input\n * // elements in the HTML DOM.\n *\n * // Suppose there are two HTML file input (``)\n * // elements.\n * const uploadJSONInput = document.getElementById('upload-json');\n * const uploadWeightsInput = document.getElementById('upload-weights');\n * const model = await tf.loadLayersModel(tf.io.browserFiles(\n * [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));\n * ```\n *\n * @param files `File`s to load from. Currently, this function supports only\n * loading from files that contain Keras-style models (i.e., `tf.Model`s), for\n * which an `Array` of `File`s is expected (in that order):\n * - A JSON file containing the model topology and weight manifest.\n * - Optionally, One or more binary files containing the binary weights.\n * These files must have names that match the paths in the `weightsManifest`\n * contained by the aforementioned JSON file, or errors will be thrown\n * during loading. These weights files have the same format as the ones\n * generated by `tensorflowjs_converter` that comes with the `tensorflowjs`\n * Python PIP package. If no weights files are provided, only the model\n * topology will be loaded from the JSON file above.\n * @returns An instance of `Files` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserFiles(files) {\n return new BrowserFiles(files);\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLC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lcyhmaWxlcyk7XG59XG4iXX0=","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { assert } from '../util';\n/**\n * Monitor Promise.all progress, fire onProgress callback function.\n *\n * @param promises Promise list going to be monitored\n * @param onProgress Callback function. Fired when a promise resolved.\n * @param startFraction Optional fraction start. Default to 0.\n * @param endFraction Optional fraction end. Default to 1.\n */\nexport function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {\n checkPromises(promises);\n startFraction = startFraction == null ? 0 : startFraction;\n endFraction = endFraction == null ? 1 : endFraction;\n checkFraction(startFraction, endFraction);\n let resolvedPromise = 0;\n const registerMonitor = (promise) => {\n promise.then(value => {\n const fraction = startFraction +\n ++resolvedPromise / promises.length * (endFraction - startFraction);\n // pass fraction as parameter to callback function.\n onProgress(fraction);\n return value;\n });\n return promise;\n };\n function checkPromises(promises) {\n assert(promises != null && Array.isArray(promises) && promises.length > 0, () => 'promises must be a none empty array');\n }\n function checkFraction(startFraction, endFraction) {\n assert(startFraction >= 0 && startFraction <= 1, () => `Progress fraction must be in range [0, 1], but ` +\n `got startFraction ${startFraction}`);\n assert(endFraction >= 0 && endFraction <= 1, () => `Progress fraction must be in range [0, 1], but ` +\n `got endFraction ${endFraction}`);\n assert(endFraction >= startFraction, () => `startFraction must be no more than endFraction, but ` +\n `got startFraction ${startFraction} and endFraction ` +\n `${endFraction}`);\n }\n return Promise.all(promises.map(registerMonitor));\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJvZ3Jlc3MuanMi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W5kRnJhY3Rpb259YCk7XG4gICAgYXNzZXJ0KFxuICAgICAgICBlbmRGcmFjdGlvbiA+PSBzdGFydEZyYWN0aW9uLFxuICAgICAgICAoKSA9PiBgc3RhcnRGcmFjdGlvbiBtdXN0IGJlIG5vIG1vcmUgdGhhbiBlbmRGcmFjdGlvbiwgYnV0IGAgK1xuICAgICAgICAgICAgYGdvdCBzdGFydEZyYWN0aW9uICR7c3RhcnRGcmFjdGlvbn0gYW5kIGVuZEZyYWN0aW9uIGAgK1xuICAgICAgICAgICAgYCR7ZW5kRnJhY3Rpb259YCk7XG4gIH1cblxuICByZXR1cm4gUHJvbWlzZS5hbGwocHJvbWlzZXMubWFwKHJlZ2lzdGVyTW9uaXRvcikpO1xufVxuIl19","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { env } from '../environment';\nimport * as util from '../util';\nimport { decodeWeights } from './io_utils';\nimport { monitorPromisesProgress } from './progress';\nimport { DTYPE_VALUE_SIZE_MAP } from './types';\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n * length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n // Create the requests for all of the weights in parallel.\n const requests = fetchURLs.map(fetchURL => fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true }));\n const fetchStartFraction = 0;\n const fetchEndFraction = 0.5;\n const responses = loadOptions.onProgress == null ?\n await Promise.all(requests) :\n await monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction);\n const bufferPromises = responses.map(response => response.arrayBuffer());\n const bufferStartFraction = 0.5;\n const bufferEndFraction = 1;\n const buffers = loadOptions.onProgress == null ?\n await Promise.all(bufferPromises) :\n await monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction);\n return buffers;\n}\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n * Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(manifest, filePathPrefix = '', weightNames, requestInit) {\n // TODO(nsthorat): Groups are currently fetched atomically. If you need a\n // single weight from a group, the whole group will be fetched. At a future\n // date, we should support fetching only the individual shards within a\n // group that are needed to reconstruct the requested weight.\n // TODO(cais): Use `decodeWeights` for implementation.\n const fetchWeights = (fetchUrls) => loadWeightsAsArrayBuffer(fetchUrls, { requestInit });\n const loadWeights = weightsLoaderFactory(fetchWeights);\n return loadWeights(manifest, filePathPrefix, weightNames);\n}\n/**\n * Creates a function, which reads a weights manifest JSON configuration,\n * fetches the weight files using the specified function and returns them as\n * `Tensor`s.\n *\n * ```js\n * // example for creating a nodejs weight loader, which reads the weight files\n * // from disk using fs.readFileSync\n *\n * import * as fs from 'fs'\n *\n * const fetchWeightsFromDisk = (filePaths: string[]) =>\n * filePaths.map(filePath => fs.readFileSync(filePath).buffer)\n *\n * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)\n *\n * const manifest = JSON.parse(\n * fs.readFileSync('./my_model-weights_manifest').toString()\n * )\n * const weightMap = await loadWeights(manifest, './')\n * ```\n * @param fetchWeightsFunction The function used for fetching the weight files.\n * @returns Weight loading function.\n */\nexport function weightsLoaderFactory(fetchWeightsFunction) {\n return async (manifest, filePathPrefix = '', weightNames) => {\n // Collect all the groups, weights, and their relative offsets to be\n // fetched.\n const groupIndicesToFetchMap = manifest.map(() => false);\n const groupWeightsToFetch = {};\n const weightsFound = weightNames != null ? weightNames.map(() => false) : [];\n const allManifestWeightNames = [];\n manifest.forEach((manifestGroupConfig, groupIndex) => {\n let groupOffset = 0;\n manifestGroupConfig.weights.forEach(weightsEntry => {\n const rawDtype = ('quantization' in weightsEntry) ?\n weightsEntry.quantization.dtype :\n weightsEntry.dtype;\n const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n util.sizeFromShape(weightsEntry.shape);\n const enqueueWeightsForFetchingFn = () => {\n groupIndicesToFetchMap[groupIndex] = true;\n if (groupWeightsToFetch[groupIndex] == null) {\n groupWeightsToFetch[groupIndex] = [];\n }\n groupWeightsToFetch[groupIndex].push({\n manifestEntry: weightsEntry,\n groupOffset,\n sizeBytes: weightsBytes\n });\n };\n if (weightNames != null) {\n weightNames.forEach((weightName, weightIndex) => {\n if (weightName === weightsEntry.name) {\n enqueueWeightsForFetchingFn();\n weightsFound[weightIndex] = true;\n }\n });\n }\n else {\n enqueueWeightsForFetchingFn();\n }\n allManifestWeightNames.push(weightsEntry.name);\n groupOffset += weightsBytes;\n });\n });\n if (!weightsFound.every(found => found)) {\n const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n throw new Error(`Could not find weights in manifest with names: ` +\n `${weightsNotFound.join(', ')}. \\n` +\n `Manifest JSON has weights with names: ` +\n `${allManifestWeightNames.join(', ')}.`);\n }\n // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n // IDs.\n const groupIndicesToFetch = groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n if (shouldFetch) {\n accumulator.push(i);\n }\n return accumulator;\n }, []);\n const fetchUrls = [];\n groupIndicesToFetch.forEach(i => {\n manifest[i].paths.forEach(filepath => {\n const fetchUrl = filePathPrefix +\n (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n fetchUrls.push(fetchUrl);\n });\n });\n const buffers = await fetchWeightsFunction(fetchUrls);\n const weightsTensorMap = {};\n let bufferIndexOffset = 0;\n groupIndicesToFetch.forEach(i => {\n const numBuffers = manifest[i].paths.length;\n let groupBytes = 0;\n for (let i = 0; i < numBuffers; i++) {\n groupBytes += buffers[bufferIndexOffset + i].byteLength;\n }\n // Create a buffer for the whole group.\n const groupBuffer = new ArrayBuffer(groupBytes);\n const groupByteBuffer = new Uint8Array(groupBuffer);\n let groupBufferOffset = 0;\n for (let i = 0; i < numBuffers; i++) {\n const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);\n groupByteBuffer.set(buffer, groupBufferOffset);\n groupBufferOffset += buffer.byteLength;\n }\n const weightsEntries = groupWeightsToFetch[i];\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = groupBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes);\n const nameToTensorMap = decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n for (const name in nameToTensorMap) {\n weightsTensorMap[name] = nameToTensorMap[name];\n }\n });\n bufferIndexOffset += numBuffers;\n });\n return weightsTensorMap;\n };\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2VpZ2h0c19sb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi90ZmpzLWNvcmUvc3JjL2lvL3dlaWdodHNfbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUVILE9BQU8sRUFBQyxHQUFHLEVBQUMsTUFBTSxnQkFBZ0IsQ0FBQztBQUduQyxP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HJ5Lm1hbmlmZXN0RW50cnldKTtcbiAgICAgICAgZm9yIChjb25zdCBuYW1lIGluIG5hbWVUb1RlbnNvck1hcCkge1xuICAgICAgICAgIHdlaWdodHNUZW5zb3JNYXBbbmFtZV0gPSBuYW1lVG9UZW5zb3JNYXBbbmFtZV07XG4gICAgICAgIH1cbiAgICAgIH0pO1xuXG4gICAgICBidWZmZXJJbmRleE9mZnNldCArPSBudW1CdWZmZXJzO1xuICAgIH0pO1xuXG4gICAgcmV0dXJuIHdlaWdodHNUZW5zb3JNYXA7XG4gIH07XG59XG4iXX0=","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\nimport { env } from '../environment';\nimport { assert } from '../util';\nimport { concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts } from './io_utils';\nimport { IORouterRegistry } from './router_registry';\nimport { loadWeightsAsArrayBuffer } from './weights_loader';\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest {\n constructor(path, loadOptions) {\n this.DEFAULT_METHOD = 'POST';\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.onProgress = loadOptions.onProgress;\n this.weightUrlConverter = loadOptions.weightUrlConverter;\n if (loadOptions.fetchFunc != null) {\n assert(typeof loadOptions.fetchFunc === 'function', () => 'Must pass a function that matches the signature of ' +\n '`fetch` (see ' +\n 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n this.fetch = loadOptions.fetchFunc;\n }\n else {\n this.fetch = env().platform.fetch;\n }\n assert(path != null && path.length > 0, () => 'URL path for http must not be null, undefined or ' +\n 'empty.');\n if (Array.isArray(path)) {\n assert(path.length === 2, () => 'URL paths for http must have a length of 2, ' +\n `(actual length is ${path.length}).`);\n }\n this.path = path;\n if (loadOptions.requestInit != null &&\n loadOptions.requestInit.body != null) {\n throw new Error('requestInit is expected to have no pre-existing body, but has one.');\n }\n this.requestInit = loadOptions.requestInit || {};\n }\n async save(modelArtifacts) {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('BrowserHTTPRequest.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n const init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);\n init.body = new FormData();\n const weightsManifest = [{\n paths: ['./model.weights.bin'],\n weights: modelArtifacts.weightSpecs,\n }];\n const modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n init.body.append('model.json', new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), 'model.json');\n if (modelArtifacts.weightData != null) {\n init.body.append('model.weights.bin', new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }), 'model.weights.bin');\n }\n const response = await this.fetch(this.path, init);\n if (response.ok) {\n return {\n modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n responses: [response],\n };\n }\n else {\n throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ` +\n `${response.status}.`);\n }\n }\n /**\n * Load model artifacts via HTTP request(s).\n *\n * See the documentation to `tf.io.http` for details on the saved\n * artifacts.\n *\n * @returns The loaded model artifacts (if loading succeeds).\n */\n async load() {\n const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n if (!modelConfigRequest.ok) {\n throw new Error(`Request to ${this.path} failed with status code ` +\n `${modelConfigRequest.status}. Please verify this URL points to ` +\n `the model JSON of the model to load.`);\n }\n let modelJSON;\n try {\n modelJSON = await modelConfigRequest.json();\n }\n catch (e) {\n let message = `Failed to parse model JSON of response from ${this.path}.`;\n // TODO(nsthorat): Remove this after some time when we're comfortable that\n // .pb files are mostly gone.\n if (this.path.endsWith('.pb')) {\n message += ' Your path contains a .pb file extension. ' +\n 'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n 'in favor of .json models. You can re-convert your Python ' +\n 'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n 'or you can convert your.pb models with the \\'pb2json\\'' +\n 'NPM script in the tensorflow/tfjs-converter repository.';\n }\n else {\n message += ' Please make sure the server is serving valid ' +\n 'JSON for this request.';\n }\n throw new Error(message);\n }\n // We do not allow both modelTopology and weightsManifest to be missing.\n const modelTopology = modelJSON.modelTopology;\n const weightsManifest = modelJSON.weightsManifest;\n if (modelTopology == null && weightsManifest == null) {\n throw new Error(`The JSON from HTTP path ${this.path} contains neither model ` +\n `topology or manifest for weights.`);\n }\n return getModelArtifactsForJSON(modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n }\n async loadWeights(weightsManifest) {\n const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n const [prefix, suffix] = parseUrl(weightPath);\n const pathPrefix = this.weightPathPrefix || prefix;\n const weightSpecs = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n const fetchURLs = [];\n const urlPromises = [];\n for (const weightsGroup of weightsManifest) {\n for (const path of weightsGroup.paths) {\n if (this.weightUrlConverter != null) {\n urlPromises.push(this.weightUrlConverter(path));\n }\n else {\n fetchURLs.push(pathPrefix + path + suffix);\n }\n }\n }\n if (this.weightUrlConverter) {\n fetchURLs.push(...await Promise.all(urlPromises));\n }\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {\n requestInit: this.requestInit,\n fetchFunc: this.fetch,\n onProgress: this.onProgress\n });\n return [weightSpecs, concatenateArrayBuffers(buffers)];\n }\n}\nHTTPRequest.URL_SCHEME_REGEX = /^https?:\\/\\//;\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url) {\n const lastSlash = url.lastIndexOf('/');\n const lastSearchParam = url.lastIndexOf('?');\n const prefix = url.substring(0, lastSlash);\n const suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n return [prefix + '/', suffix];\n}\nexport function isHTTPScheme(url) {\n return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\nexport const httpRouter = (url, loadOptions) => {\n if (typeof fetch === 'undefined' &&\n (loadOptions == null || loadOptions.fetchFunc == null)) {\n // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n // an environment that is not the browser or node they have to setup a\n // global fetch polyfill.\n return null;\n }\n else {\n let isHTTP = true;\n if (Array.isArray(url)) {\n isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n }\n else {\n isHTTP = isHTTPScheme(url);\n }\n if (isHTTP) {\n return http(url, loadOptions);\n }\n }\n return null;\n};\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n * - A JSON file consisting of `modelTopology` and `weightsManifest`.\n * - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the requst,\n * this particular server reconsistutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path, loadOptions) {\n return new HTTPRequest(path, loadOptions);\n}\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nex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bWVzcGFjZTogJ2lvJyxcbiAqICAgaWdub3JlQ0k6IHRydWVcbiAqIH1cbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGh0dHAocGF0aDogc3RyaW5nLCBsb2FkT3B0aW9ucz86IExvYWRPcHRpb25zKTogSU9IYW5kbGVyIHtcbiAgcmV0dXJuIG5ldyBIVFRQUmVxdWVzdChwYXRoLCBsb2FkT3B0aW9ucyk7XG59XG5cbi8qKlxuICogRGVwcmVjYXRlZC4gVXNlIGB0Zi5pby5odHRwYC5cbiAqIEBwYXJhbSBwYXRoXG4gKiBAcGFyYW0gbG9hZE9wdGlvbnNcbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGJyb3dzZXJIVFRQUmVxdWVzdChcbiAgICBwYXRoOiBzdHJpbmcsIGxvYWRPcHRpb25zPzogTG9hZE9wdGlvbnMpOiBJT0hhbmRsZXIge1xuICByZXR1cm4gaHR0cChwYXRoLCBsb2FkT3B0aW9ucyk7XG59XG4iXX0=","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nclass PassthroughLoader {\n constructor(modelArtifacts) {\n this.modelArtifacts = modelArtifacts;\n }\n async load() {\n return this.modelArtifacts;\n }\n}\nclass PassthroughSaver {\n constructor(saveHandler) {\n this.saveHandler = saveHandler;\n }\n async save(modelArtifacts) {\n return this.saveHandler(modelArtifacts);\n }\n}\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) {\n if (arguments.length === 1) {\n const isModelArtifacts = modelArtifacts.modelTopology != null ||\n modelArtifacts.weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts);\n }\n else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn('Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({ modelTopology: modelArtifacts });\n }\n }\n else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn('Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts,\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandler(saveHandler) {\n return new PassthroughSaver(saveHandler);\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uI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hY3RzKSA9PlxuICAgICAgICBQcm9taXNlPFNhdmVSZXN1bHQ+KTogSU9IYW5kbGVyIHtcbiAgcmV0dXJuIG5ldyBQYXNzdGhyb3VnaFNhdmVyKHNhdmVIYW5kbGVyKTtcbn1cbiJdfQ==","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { BatchMatMul } from '../kernel_names';\nimport { makeTypesMatch } from '../tensor_util';\nimport { convertToTensor } from '../tensor_util_env';\nimport { op } from './operation';\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print(); // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_(a, b, transposeA = false, transposeB = false) {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n const inputs = { a: $a, b: $b };\n const attrs = { transposeA, transposeB };\n return ENGINE.runKernel(BatchMatMul, inputs, attrs);\n}\nexport const matMul = op({ matMul_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWF0X211bC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3Vy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Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { OneHot } from '../kernel_names';\nimport { convertToTensor } from '../tensor_util_env';\nimport { op } from './operation';\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n * `indices` used to encode prediction class must start from 0. For example,\n * if you have 3 classes of data, class 1 should be encoded as 0, class 2\n * should be 1, and class 3 should be 2.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`. Indices must\n * start from 0.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(indices, depth, onValue = 1, offValue = 0) {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n const inputs = { indices: $indices };\n const attrs = { depth, onValue, offValue };\n return ENGINE.runKernel(OneHot, inputs, attrs);\n}\nexport const oneHot = op({ oneHot_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib25lX2hvdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvb3BzL29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nN0IGF0dHJzOiBPbmVIb3RBdHRycyA9IHtkZXB0aCwgb25WYWx1ZSwgb2ZmVmFsdWV9O1xuXG4gIHJldHVybiBFTkdJTkUucnVuS2VybmVsKFxuICAgICAgT25lSG90LCBpbnB1dHMgYXMgdW5rbm93biBhcyBOYW1lZFRlbnNvck1hcCxcbiAgICAgIGF0dHJzIGFzIHVua25vd24gYXMgTmFtZWRBdHRyTWFwKTtcbn1cblxuZXhwb3J0IGNvbnN0IG9uZUhvdCA9IG9wKHtvbmVIb3RffSk7XG4iXX0=","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { Transpose } from '../kernel_names';\nimport { convertToTensor } from '../tensor_util_env';\nimport * as util from '../util';\nimport { op } from './operation';\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(x, perm) {\n const $x = convertToTensor(x, 'x', 'transpose');\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n if ($x.rank <= 1) {\n return $x.clone();\n }\n const inputs = { x: $x };\n const attrs = { perm };\n return ENGINE.runKernel(Transpose, inputs, attrs);\n}\nexport const transpose = op({ transpose_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhbnNwb3NlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vdGZqcy1jb3JlL3NyYy9vcHMvdHJhbnNwb3NlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUVILE9BQU8sRUFBQyxNQUFNLEVBQUMsTUFBTSxXQUFXLENBQUM7QUFDakMsT0FBTyxFQUFDLFNBQVMsRUFBa0MsTUFBTSxpQkFBaUIsQ0FBQztBQUkzRSxPQUFPLEVBQUMsZUFBZSxFQUFDLE1BQU0sb0JBQW9CLENBQUM7QUFFbkQsT0FBTyxLQUFLLElBQUksTUFBTSxTQUFTLENBQUM7QUFFaEMsT0FBTyxFQUFDLEVBQUUsRUFBQyxNQUFNLGFBQWEsQ0FBQztBQUUvQjs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBa0JHO0FBQ0gsU0FBUyxVQUFVLENBQW1CLENBQWUsRUFBRSxJQUFlO0lBQ3BFLE1BQU0sRUFBRSxHQUFHLGVBQWUsQ0FBQyxDQUFDLEVBQUUsR0FBRyxFQUFFLFdBQVcsQ0FBQyxDQUFDO0lBRWhELElBQUksSUFBSSxJQUFJLElBQUksRUFBRTtRQUNoQixJQUFJLEdBQUcsRUFBRSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQy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9zZUlucHV0cyA9IHt4OiAkeH07XG4gIGNvbnN0IGF0dHJzOiBUcmFuc3Bvc2VBdHRycyA9IHtwZXJtfTtcblxuICByZXR1cm4gRU5HSU5FLnJ1bktlcm5lbChcbiAgICAgIFRyYW5zcG9zZSwgaW5wdXRzIGFzIHt9IGFzIE5hbWVkVGVuc29yTWFwLCBhdHRycyBhcyB7fSBhcyBOYW1lZEF0dHJNYXApO1xufVxuXG5leHBvcnQgY29uc3QgdHJhbnNwb3NlID0gb3Aoe3RyYW5zcG9zZV99KTtcbiJdfQ==","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { convertToTensor } from '../tensor_util_env';\nimport * as util from '../util';\nimport { cast } from './cast';\nimport { matMul } from './mat_mul';\nimport { oneHot } from './one_hot';\nimport { op } from './operation';\nimport { transpose } from './transpose';\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * // [0, 1, 1],\n * // [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n * for the classes. The shape is `[numExamples]`, where\n * `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n * 0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n * Its value must be larger than the largest element in `labels` and\n * `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n * row `r` and column `c` is the number of times examples of actual class\n * `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(labels, predictions, numClasses) {\n const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n const $predictions = convertToTensor(predictions, 'predictions', 'confusionMatrix');\n util.assert(numClasses == null || numClasses > 0 && Number.isInteger(numClasses), () => `If provided, numClasses must be a positive integer, ` +\n `but got ${numClasses}`);\n util.assert($labels.rank === 1, () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n util.assert($predictions.rank === 1, () => `Expected the rank of predictions to be 1, ` +\n `but got ${$predictions.rank}`);\n util.assert($labels.shape[0] === $predictions.shape[0], () => `Mismatch in the number of examples: ` +\n `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n `Labels and predictions should have the same number of elements.`);\n util.assert(numClasses > 0 && Number.isInteger(numClasses), () => `numClasses is required to be a positive integer, but got ` +\n `${numClasses}`);\n // TODO(cais): In the future, if oneHot supports tensors inputs for\n // `numClasses`, `confusionMatrix` can make `numClasses` optional.\n const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses);\n const oneHotPredictions = oneHot(cast($predictions, 'int32'), numClasses);\n const oneHotLabelsT = transpose(oneHotLabels);\n const product = matMul(oneHotLabelsT, oneHotPredictions);\n return cast(product, 'int32');\n}\nexport const confusionMatrix = op({ confusionMatrix_ });\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZnVzaW9uX21hdHJpeC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3RmanMtY29yZS9zcmMvb3BzL2NvbmZ1c2lvbl9tYXRyaXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBR0gsT0FBTy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zdChwcm9kdWN0LCAnaW50MzInKTtcbn1cblxuZXhwb3J0IGNvbnN0IGNvbmZ1c2lvbk1hdHJpeCA9IG9wKHtjb25mdXNpb25NYXRyaXhffSk7XG4iXX0=","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(inShape, outShape) {\n const inRank = inShape.length;\n const dims = [];\n for (let i = 0; i < inRank; i++) {\n const dim = inRank - 1 - i;\n const a = inShape[dim] || 1;\n const b = outShape[outShape.length - 1 - i] || 1;\n if (b > 1 && a === 1) {\n dims.unshift(dim);\n }\n }\n return dims;\n}\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(inShape, outShape) {\n const result = [];\n for (let i = 0; i < outShape.length; i++) {\n const inDim = inShape[inShape.length - i - 1];\n const outAxis = outShape.length - i - 1;\n const outDim = outShape[outAxis];\n if (inDim == null || (inDim === 1 && outDim > 1)) {\n result.unshift(outAxis);\n }\n }\n return result;\n}\nexport function assertAndGetBroadcastShape(shapeA, shapeB) {\n const result = [];\n const l = Math.max(shapeA.length, shapeB.length);\n for (let i = 0; i < l; i++) {\n let a = shapeA[shapeA.length - i - 1];\n if (a == null) {\n a = 1;\n }\n let b = shapeB[shapeB.length - i - 1];\n if (b == null) {\n b = 1;\n }\n if (a === 1) {\n result.unshift(b);\n }\n else if (b === 1) {\n result.unshift(a);\n }\n else if (a !== b) {\n const errMsg = `Operands could not be broadcast together with shapes ` +\n `${shapeA} and ${shapeB}.`;\n throw Error(errMsg);\n }\n else {\n result.unshift(a);\n }\n }\n return result;\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnJvYWRjYXN0X3V0aWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi90ZmpzLWNvcmUvc3JjL29wcy9icm9hZGNhc3RfdXRpbC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFFSDs7Ozs7Ozs7R0FRRztBQUNILE1BQU0sVUFBVSxnQkFBZ0IsQ0FDNUIsT0FBaUIsRUFBRSxRQUFrQjtJQUN2QyxNQUFNLE1BQU0sR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDO0lBQzlCLE1BQU0sSUFBSSxHQUFhLEVBQUUsQ0FBQztJQUMxQixLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsTUFBTSxFQUFFLENBQUMsRUFBRSxFQUFFO1FBQy9CLE1BQU0sR0FBRyxHQUFHLE1BQU0sR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQzNCLE1BQU0sQ0FBQyxHQUFHLE9BQU8sQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDNUIsTUFBTSxDQUFDLEdBQUcsUUFBUSxDQUFDLFFBQVEsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQztRQUNqRCxJQUFJLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsRUFBRTtZQUNwQixJQUFJLENBQUMsT0FBT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gY291bGQgbm90IGJlIGJyb2FkY2FzdCB0b2dldGhlciB3aXRoIHNoYXBlcyBgICtcbiAgICAgICAgICBgJHtzaGFwZUF9IGFuZCAke3NoYXBlQn0uYDtcbiAgICAgIHRocm93IEVycm9yKGVyck1zZyk7XG4gICAgfSBlbHNlIHtcbiAgICAgIHJlc3VsdC51bnNoaWZ0KGEpO1xuICAgIH1cbiAgfVxuICByZXR1cm4gcmVzdWx0O1xufVxuIl19","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { inferShape } from '../tensor_util_env';\nimport { assertNonNull } from '../util';\nimport { makeTensor } from './tensor_ops_util';\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(values, shape, dtype) {\n assertNonNull(values);\n if (shape != null && shape.length !== 3) {\n throw new Error('tensor3d() requires shape to have three numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error('tensor3d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype);\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVuc29yM2QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi90ZmpzLWNvcmUvc3JjL29wcy90ZW5zb3IzZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFHSCxPQUFPLEVBQUMsVUFBVSxFQUFDLE1BQU0sb0JBQW9CLENBQUM7QUFHOUMsT0FBTyxFQUFDLGFBQWEsRUFBQyxNQUFNLFNBQVMsQ0FBQztBQUN0QyxPQUFPLEVBQUMsVUFBVSxFQUFDLE1BQU0sbUJBQW1CLENBQUM7QUFFN0M7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7R0FzQkc7QUFDSCxNQUFNLFVBQVUsUUFBUSxDQUNwQixNQUFvQixFQUFFLEtBQWdDLEVBQ3RELEtBQWdCO0lBQ2xCLGFBQWEsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN0QixJQUFJLEtBQUssSUFBSSxJQUFJLElBQUksS0FBSyxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDdkMsTUFBTSxJQUFJLEtBQUssQ0FBQyxpREFBaUQsQ0FBQyxDQUFDO0tBQ3BFO0lBQ0QsTUFBTSxhQUFhLEdBQUcsVUFBVSxDQUFDLE1BQU0sRUFBRSxLQUFLLENBQUMsQ0FBQztJQUNoRCxJQUFJLGFBQWEsQ0FBQyxNQUFNLEtBQUssQ0FBQyxJQUFJLGFBQWEsQ0FBQyxNQUFNLEtBQUssQ0FBQyxFQUFFO1FBQzVELE1BQU0sSUFBSSxLQUFL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kKCkgcmVxdWlyZXMgdmFsdWVzIHRvIGJlIG51bWJlcltdW11bXSBvciBmbGF0L1R5cGVkQXJyYXknKTtcbiAgfVxuICBpZiAoaW5mZXJyZWRTaGFwZS5sZW5ndGggPT09IDEgJiYgc2hhcGUgPT0gbnVsbCkge1xuICAgIHRocm93IG5ldyBFcnJvcihcbiAgICAgICAgJ3RlbnNvcjNkKCkgcmVxdWlyZXMgc2hhcGUgdG8gYmUgcHJvdmlkZWQgd2hlbiBgdmFsdWVzYCAnICtcbiAgICAgICAgJ2FyZSBhIGZsYXQgYXJyYXknKTtcbiAgfVxuICByZXR1cm4gbWFrZVRlbnNvcih2YWx1ZXMsIHNoYXBlLCBpbmZlcnJlZFNoYXBlLCBkdHlwZSkgYXMgVGVuc29yM0Q7XG59XG4iXX0=","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { ENGINE } from '../engine';\nimport { env } from '../environment';\nimport { FromPixels } from '../kernel_names';\nimport { getKernel } from '../kernel_registry';\nimport { Tensor } from '../tensor';\nimport { convertToTensor } from '../tensor_util_env';\nimport { cast } from './cast';\nimport { op } from './operation';\nimport { tensor3d } from './tensor3d';\nlet fromPixels2DContext;\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @returns A Tensor3D with the shape `[height, width, numChannels]`.\n *\n * Note: fromPixels can be lossy in some cases, same image may result in\n * slightly different tensor values, if rendered by different rendering\n * engines. This means that results from different browsers, or even same\n * browser with CPU and GPU rendering engines can be different. See discussion\n * in details:\n * https://github.com/tensorflow/tfjs/issues/5482\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(pixels, numChannels = 3) {\n // Sanity checks.\n if (numChannels > 4) {\n throw new Error('Cannot construct Tensor with more than 4 channels from pixels.');\n }\n if (pixels == null) {\n throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n }\n let isPixelData = false;\n let isImageData = false;\n let isVideo = false;\n let isImage = false;\n let isCanvasLike = false;\n let isImageBitmap = false;\n if (pixels.data instanceof Uint8Array) {\n isPixelData = true;\n }\n else if (typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n isImageData = true;\n }\n else if (typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement) {\n isVideo = true;\n }\n else if (typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement) {\n isImage = true;\n // tslint:disable-next-line: no-any\n }\n else if (pixels.getContext != null) {\n isCanvasLike = true;\n }\n else if (typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {\n isImageBitmap = true;\n }\n else {\n throw new Error('pixels passed to tf.browser.fromPixels() must be either an ' +\n `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n `in browser, or OffscreenCanvas, ImageData in webworker` +\n ` or {data: Uint32Array, width: number, height: number}, ` +\n `but was ${pixels.constructor.name}`);\n }\n if (isVideo) {\n const HAVE_CURRENT_DATA_READY_STATE = 2;\n if (isVideo &&\n pixels.readyState <\n HAVE_CURRENT_DATA_READY_STATE) {\n throw new Error('The video element has not loaded data yet. Please wait for ' +\n '`loadeddata` event on the