diff --git a/dist/ml5.min.js b/dist/ml5.min.js index 72adb3bc3..07bf81499 100644 --- a/dist/ml5.min.js +++ b/dist/ml5.min.js @@ -1,4 +1,4 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ml5=t():e.ml5=t()}(window,function(){return 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}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},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=682)}([function(e,t,n){"use strict";n.r(t),function(e,r,a,i){n.d(t,"setBackend",function(){return nl}),n.d(t,"getBackend",function(){return rl}),n.d(t,"disposeVariables",function(){return al}),n.d(t,"memory",function(){return il}),n.d(t,"version_core",function(){return qu}),n.d(t,"nextFrame",function(){return Vs}),n.d(t,"environment",function(){return be}),n.d(t,"io",function(){return Ru}),n.d(t,"math",function(){return ju}),n.d(t,"serialization",function(){return Fu}),n.d(t,"test_util",function(){return Wu}),n.d(t,"util",function(){return $}),n.d(t,"webgl",function(){return $u}),n.d(t,"AdadeltaOptimizer",function(){return Hu}),n.d(t,"AdagradOptimizer",function(){return Ku}),n.d(t,"AdamOptimizer",function(){return Xu}),n.d(t,"AdamaxOptimizer",function(){return Yu}),n.d(t,"MomentumOptimizer",function(){return Zu}),n.d(t,"Optimizer",function(){return Gu}),n.d(t,"RMSPropOptimizer",function(){return Qu}),n.d(t,"SGDOptimizer",function(){return Ju}),n.d(t,"Tensor",function(){return re}),n.d(t,"TensorBuffer",function(){return Q}),n.d(t,"variable",function(){return ie}),n.d(t,"Variable",function(){return ae}),n.d(t,"Rank",function(){return Et}),n.d(t,"Reduction",function(){return as}),n.d(t,"ENV",function(){return ve}),n.d(t,"Environment",function(){return ye}),n.d(t,"KernelBackend",function(){return Rt}),n.d(t,"DataStorage",function(){return Mt}),n.d(t,"image",function(){return Ls}),n.d(t,"linalg",function(){return Ts}),n.d(t,"losses",function(){return Is}),n.d(t,"spectral",function(){return gs}),n.d(t,"op",function(){return rt}),n.d(t,"batchNormalization2d",function(){return hi}),n.d(t,"batchNormalization3d",function(){return di}),n.d(t,"batchNormalization4d",function(){return mi}),n.d(t,"batchNormalization",function(){return gi}),n.d(t,"complex",function(){return ot}),n.d(t,"real",function(){return st}),n.d(t,"imag",function(){return ut}),n.d(t,"concat",function(){return zr}),n.d(t,"concat1d",function(){return Fr}),n.d(t,"concat2d",function(){return Vr}),n.d(t,"concat3d",function(){return Ur}),n.d(t,"concat4d",function(){return Wr}),n.d(t,"split",function(){return qr}),n.d(t,"conv1d",function(){return Ci}),n.d(t,"conv2d",function(){return Pi}),n.d(t,"conv2dDerFilter",function(){return Ai}),n.d(t,"depthwiseConv2d",function(){return Ti}),n.d(t,"separableConv2d",function(){return Mi}),n.d(t,"conv2dTranspose",function(){return Ri}),n.d(t,"matMul",function(){return Ni}),n.d(t,"dot",function(){return Si}),n.d(t,"outerProduct",function(){return Oi}),n.d(t,"reverse",function(){return Di}),n.d(t,"reverse1d",function(){return ji}),n.d(t,"reverse2d",function(){return Li}),n.d(t,"reverse3d",function(){return Bi}),n.d(t,"reverse4d",function(){return zi}),n.d(t,"maxPool",function(){return Ui}),n.d(t,"avgPool",function(){return Wi}),n.d(t,"pool",function(){return qi}),n.d(t,"slice",function(){return $i}),n.d(t,"slice1d",function(){return Gi}),n.d(t,"slice2d",function(){return Hi}),n.d(t,"slice3d",function(){return Ki}),n.d(t,"slice4d",function(){return Xi}),n.d(t,"abs",function(){return Ra}),n.d(t,"acos",function(){return Da}),n.d(t,"acosh",function(){return ja}),n.d(t,"asin",function(){return La}),n.d(t,"asinh",function(){return Ba}),n.d(t,"atan",function(){return za}),n.d(t,"atanh",function(){return Fa}),n.d(t,"ceil",function(){return Va}),n.d(t,"clipByValue",function(){return Ua}),n.d(t,"cos",function(){return Wa}),n.d(t,"cosh",function(){return qa}),n.d(t,"erf",function(){return $a}),n.d(t,"exp",function(){return Ga}),n.d(t,"expm1",function(){return Ha}),n.d(t,"floor",function(){return Ka}),n.d(t,"log",function(){return Xa}),n.d(t,"log1p",function(){return Ya}),n.d(t,"logSigmoid",function(){return Ja}),n.d(t,"neg",function(){return Za}),n.d(t,"reciprocal",function(){return Qa}),n.d(t,"round",function(){return ei}),n.d(t,"rsqrt",function(){return ti}),n.d(t,"sigmoid",function(){return ni}),n.d(t,"sign",function(){return ri}),n.d(t,"sin",function(){return ai}),n.d(t,"sinh",function(){return ii}),n.d(t,"softplus",function(){return oi}),n.d(t,"sqrt",function(){return si}),n.d(t,"square",function(){return ui}),n.d(t,"step",function(){return li}),n.d(t,"tan",function(){return ci}),n.d(t,"tanh",function(){return fi}),n.d(t,"all",function(){return Ji}),n.d(t,"any",function(){return Zi}),n.d(t,"argMax",function(){return Qi}),n.d(t,"argMin",function(){return eo}),n.d(t,"logSumExp",function(){return to}),n.d(t,"max",function(){return no}),n.d(t,"mean",function(){return ro}),n.d(t,"min",function(){return ao}),n.d(t,"moments",function(){return io}),n.d(t,"sum",function(){return oo}),n.d(t,"prod",function(){return so}),n.d(t,"equal",function(){return uo}),n.d(t,"equalStrict",function(){return lo}),n.d(t,"greater",function(){return co}),n.d(t,"greaterEqual",function(){return fo}),n.d(t,"greaterEqualStrict",function(){return po}),n.d(t,"greaterStrict",function(){return ho}),n.d(t,"less",function(){return mo}),n.d(t,"lessEqual",function(){return go}),n.d(t,"lessEqualStrict",function(){return yo}),n.d(t,"lessStrict",function(){return vo}),n.d(t,"notEqual",function(){return bo}),n.d(t,"notEqualStrict",function(){return wo}),n.d(t,"add",function(){return xo}),n.d(t,"addN",function(){return _o}),n.d(t,"addStrict",function(){return Eo}),n.d(t,"atan2",function(){return No}),n.d(t,"div",function(){return So}),n.d(t,"divStrict",function(){return Oo}),n.d(t,"floorDiv",function(){return ko}),n.d(t,"maximum",function(){return Io}),n.d(t,"maximumStrict",function(){return Co}),n.d(t,"minimum",function(){return Po}),n.d(t,"minimumStrict",function(){return Ao}),n.d(t,"mod",function(){return To}),n.d(t,"modStrict",function(){return Mo}),n.d(t,"mul",function(){return Ro}),n.d(t,"mulStrict",function(){return Do}),n.d(t,"pow",function(){return jo}),n.d(t,"powStrict",function(){return Lo}),n.d(t,"squaredDifference",function(){return Bo}),n.d(t,"squaredDifferenceStrict",function(){return zo}),n.d(t,"sub",function(){return Fo}),n.d(t,"subStrict",function(){return Vo}),n.d(t,"elu",function(){return Ko}),n.d(t,"leakyRelu",function(){return Xo}),n.d(t,"prelu",function(){return Yo}),n.d(t,"relu",function(){return Jo}),n.d(t,"selu",function(){return Zo}),n.d(t,"logicalAnd",function(){return Uo}),n.d(t,"logicalNot",function(){return Wo}),n.d(t,"logicalOr",function(){return qo}),n.d(t,"logicalXor",function(){return $o}),n.d(t,"where",function(){return Go}),n.d(t,"whereAsync",function(){return Ho}),n.d(t,"buffer",function(){return na}),n.d(t,"toPixels",function(){return ta}),n.d(t,"print",function(){return ra}),n.d(t,"batchToSpaceND",function(){return aa}),n.d(t,"cast",function(){return ia}),n.d(t,"clone",function(){return oa}),n.d(t,"cumsum",function(){return sa}),n.d(t,"depthToSpace",function(){return ua}),n.d(t,"expandDims",function(){return la}),n.d(t,"eye",function(){return ca}),n.d(t,"fromPixels",function(){return fa}),n.d(t,"multinomial",function(){return pa}),n.d(t,"oneHot",function(){return ha}),n.d(t,"pad",function(){return da}),n.d(t,"pad1d",function(){return ma}),n.d(t,"pad2d",function(){return ga}),n.d(t,"pad3d",function(){return ya}),n.d(t,"pad4d",function(){return va}),n.d(t,"rand",function(){return ba}),n.d(t,"randomNormal",function(){return wa}),n.d(t,"randomUniform",function(){return xa}),n.d(t,"reshape",function(){return _a}),n.d(t,"spaceToBatchND",function(){return Ea}),n.d(t,"squeeze",function(){return Na}),n.d(t,"stack",function(){return Sa}),n.d(t,"tile",function(){return Oa}),n.d(t,"truncatedNormal",function(){return ka}),n.d(t,"unstack",function(){return Ia}),n.d(t,"setdiff1dAsync",function(){return Ca}),n.d(t,"fill",function(){return bt}),n.d(t,"linspace",function(){return wt}),n.d(t,"ones",function(){return yt}),n.d(t,"range",function(){return xt}),n.d(t,"scalar",function(){return ct}),n.d(t,"tensor",function(){return lt}),n.d(t,"tensor1d",function(){return ft}),n.d(t,"tensor2d",function(){return pt}),n.d(t,"tensor3d",function(){return ht}),n.d(t,"tensor4d",function(){return dt}),n.d(t,"tensor5d",function(){return mt}),n.d(t,"tensor6d",function(){return gt}),n.d(t,"zeros",function(){return vt}),n.d(t,"onesLike",function(){return It}),n.d(t,"zerosLike",function(){return Ct}),n.d(t,"transpose",function(){return Qo}),n.d(t,"softmax",function(){return at}),n.d(t,"logSoftmax",function(){return it}),n.d(t,"localResponseNormalization",function(){return es}),n.d(t,"norm",function(){return ts}),n.d(t,"gather",function(){return is}),n.d(t,"unsortedSegmentSum",function(){return os}),n.d(t,"basicLSTMCell",function(){return ss}),n.d(t,"multiRNNCell",function(){return us}),n.d(t,"movingAverage",function(){return ls}),n.d(t,"stridedSlice",function(){return cs}),n.d(t,"topk",function(){return fs}),n.d(t,"scatterND",function(){return ps}),n.d(t,"fft",function(){return hs}),n.d(t,"ifft",function(){return ds}),n.d(t,"rfft",function(){return ms}),n.d(t,"sparseToDense",function(){return ys}),n.d(t,"gatherND",function(){return vs}),n.d(t,"train",function(){return tl}),n.d(t,"tidy",function(){return ke}),n.d(t,"keep",function(){return Ie}),n.d(t,"dispose",function(){return Ce}),n.d(t,"time",function(){return Pe}),n.d(t,"profile",function(){return Ae}),n.d(t,"customGrad",function(){return Se}),n.d(t,"grad",function(){return we}),n.d(t,"grads",function(){return xe}),n.d(t,"valueAndGrad",function(){return _e}),n.d(t,"valueAndGrads",function(){return Ee}),n.d(t,"variableGrads",function(){return Ne}); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ml5=t():e.ml5=t()}(window,function(){return 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}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},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=682)}([function(e,t,n){"use strict";(function(e,r,a,i){n.d(t,"Fc",function(){return vu}),n.d(t,"Ya",function(){return bu}),n.d(t,"Ga",function(){return wu}),n.d(t,"Gb",function(){return xu}),n.d(t,"Dd",function(){return ou}),n.d(t,"Tb",function(){return is}),n.d(t,"La",function(){return ge}),n.d(t,"hb",function(){return Zs}),n.d(t,"Ec",function(){return nu}),n.d(t,"nd",function(){return iu}),n.d(t,"yd",function(){return V}),n.d(t,"Ed",function(){return su}),n.d(t,"a",function(){return lu}),n.d(t,"b",function(){return cu}),n.d(t,"c",function(){return fu}),n.d(t,"d",function(){return pu}),n.d(t,"g",function(){return du}),n.d(t,"h",function(){return uu}),n.d(t,"i",function(){return mu}),n.d(t,"l",function(){return hu}),n.d(t,"m",function(){return Q}),n.d(t,"n",function(){return X}),n.d(t,"Bd",function(){return te}),n.d(t,"o",function(){return ee}),n.d(t,"j",function(){return gt}),n.d(t,"k",function(){return Co}),n.d(t,"e",function(){return me}),n.d(t,"f",function(){return de}),n.d(t,"gb",function(){return ts}),n.d(t,"ob",function(){return Yo}),n.d(t,"zb",function(){return Go}),n.d(t,"ac",function(){return Je}),n.d(t,"H",function(){return qa}),n.d(t,"I",function(){return $a}),n.d(t,"J",function(){return Ga}),n.d(t,"G",function(){return Ha}),n.d(t,"Q",function(){return Qe}),n.d(t,"qc",function(){return et}),n.d(t,"fb",function(){return tt}),n.d(t,"R",function(){return vr}),n.d(t,"S",function(){return br}),n.d(t,"T",function(){return wr}),n.d(t,"U",function(){return xr}),n.d(t,"V",function(){return _r}),n.d(t,"Sc",function(){return Sr}),n.d(t,"W",function(){return ii}),n.d(t,"X",function(){return oi}),n.d(t,"Ea",function(){return si}),n.d(t,"Dc",function(){return ui}),n.d(t,"Y",function(){return li}),n.d(t,"Ab",function(){return Qa}),n.d(t,"Ja",function(){return ei}),n.d(t,"bc",function(){return ti}),n.d(t,"uc",function(){return ci}),n.d(t,"vc",function(){return fi}),n.d(t,"wc",function(){return pi}),n.d(t,"xc",function(){return hi}),n.d(t,"yc",function(){return di}),n.d(t,"Cb",function(){return mi}),n.d(t,"E",function(){return gi}),n.d(t,"Kc",function(){return yi}),n.d(t,"Lc",function(){return vi}),n.d(t,"Mc",function(){return bi}),n.d(t,"Nc",function(){return wi}),n.d(t,"Oc",function(){return xi}),n.d(t,"p",function(){return fa}),n.d(t,"q",function(){return pa}),n.d(t,"r",function(){return ha}),n.d(t,"z",function(){return da}),n.d(t,"A",function(){return ma}),n.d(t,"B",function(){return ga}),n.d(t,"D",function(){return ya}),n.d(t,"N",function(){return va}),n.d(t,"O",function(){return ba}),n.d(t,"Z",function(){return wa}),n.d(t,"Aa",function(){return xa}),n.d(t,"Oa",function(){return _a}),n.d(t,"Pa",function(){return Sa}),n.d(t,"Ra",function(){return Ea}),n.d(t,"Ua",function(){return Na}),n.d(t,"rb",function(){return Oa}),n.d(t,"sb",function(){return ka}),n.d(t,"tb",function(){return Ia}),n.d(t,"Sb",function(){return Ca}),n.d(t,"rc",function(){return Aa}),n.d(t,"zc",function(){return Pa}),n.d(t,"Ac",function(){return Ta}),n.d(t,"Gc",function(){return Ma}),n.d(t,"Hc",function(){return Ra}),n.d(t,"Ic",function(){return Da}),n.d(t,"Jc",function(){return ja}),n.d(t,"Qc",function(){return La}),n.d(t,"Tc",function(){return za}),n.d(t,"Uc",function(){return Ba}),n.d(t,"Zc",function(){return Fa}),n.d(t,"ed",function(){return Va}),n.d(t,"fd",function(){return Ua}),n.d(t,"v",function(){return Si}),n.d(t,"w",function(){return Ei}),n.d(t,"x",function(){return Ni}),n.d(t,"y",function(){return Oi}),n.d(t,"ub",function(){return ki}),n.d(t,"Bb",function(){return Ii}),n.d(t,"Fb",function(){return Ci}),n.d(t,"Hb",function(){return Ai}),n.d(t,"Mb",function(){return Pi}),n.d(t,"dd",function(){return Ti}),n.d(t,"Ma",function(){return Mi}),n.d(t,"Na",function(){return Ri}),n.d(t,"bb",function(){return Di}),n.d(t,"cb",function(){return ji}),n.d(t,"db",function(){return Li}),n.d(t,"eb",function(){return zi}),n.d(t,"kb",function(){return Bi}),n.d(t,"lb",function(){return Fi}),n.d(t,"mb",function(){return Vi}),n.d(t,"nb",function(){return Ui}),n.d(t,"Vb",function(){return Wi}),n.d(t,"Wb",function(){return qi}),n.d(t,"s",function(){return $i}),n.d(t,"t",function(){return Gi}),n.d(t,"u",function(){return Hi}),n.d(t,"C",function(){return Ki}),n.d(t,"Ha",function(){return Xi}),n.d(t,"Ia",function(){return Yi}),n.d(t,"Va",function(){return Ji}),n.d(t,"Db",function(){return Zi}),n.d(t,"Eb",function(){return Qi}),n.d(t,"Ib",function(){return eo}),n.d(t,"Jb",function(){return to}),n.d(t,"Kb",function(){return no}),n.d(t,"Lb",function(){return ro}),n.d(t,"Ob",function(){return ao}),n.d(t,"Pb",function(){return io}),n.d(t,"hc",function(){return oo}),n.d(t,"ic",function(){return so}),n.d(t,"Vc",function(){return uo}),n.d(t,"Wc",function(){return lo}),n.d(t,"bd",function(){return co}),n.d(t,"cd",function(){return fo}),n.d(t,"Ka",function(){return bo}),n.d(t,"jb",function(){return wo}),n.d(t,"jc",function(){return xo}),n.d(t,"sc",function(){return _o}),n.d(t,"Cc",function(){return So}),n.d(t,"vb",function(){return po}),n.d(t,"wb",function(){return ho}),n.d(t,"xb",function(){return mo}),n.d(t,"yb",function(){return go}),n.d(t,"Fd",function(){return yo}),n.d(t,"Gd",function(){return vo}),n.d(t,"L",function(){return Dr}),n.d(t,"rd",function(){return Rr}),n.d(t,"kc",function(){return jr}),n.d(t,"K",function(){return Lr}),n.d(t,"M",function(){return zr}),n.d(t,"P",function(){return Br}),n.d(t,"Ba",function(){return Fr}),n.d(t,"Da",function(){return Vr}),n.d(t,"Qa",function(){return Ur}),n.d(t,"Sa",function(){return Wr}),n.d(t,"Wa",function(){return qr}),n.d(t,"Rb",function(){return $r}),n.d(t,"Xb",function(){return Gr}),n.d(t,"cc",function(){return Hr}),n.d(t,"dc",function(){return Kr}),n.d(t,"ec",function(){return Xr}),n.d(t,"fc",function(){return Yr}),n.d(t,"gc",function(){return Jr}),n.d(t,"mc",function(){return Zr}),n.d(t,"nc",function(){return Qr}),n.d(t,"oc",function(){return ea}),n.d(t,"tc",function(){return ta}),n.d(t,"Rc",function(){return na}),n.d(t,"Xc",function(){return ra}),n.d(t,"Yc",function(){return aa}),n.d(t,"pd",function(){return ia}),n.d(t,"vd",function(){return oa}),n.d(t,"xd",function(){return sa}),n.d(t,"Ta",function(){return pt}),n.d(t,"pb",function(){return ht}),n.d(t,"Yb",function(){return ct}),n.d(t,"pc",function(){return dt}),n.d(t,"Bc",function(){return rt}),n.d(t,"gd",function(){return nt}),n.d(t,"hd",function(){return at}),n.d(t,"id",function(){return it}),n.d(t,"jd",function(){return ot}),n.d(t,"kd",function(){return st}),n.d(t,"ld",function(){return ut}),n.d(t,"md",function(){return lt}),n.d(t,"Hd",function(){return ft}),n.d(t,"Zb",function(){return xt}),n.d(t,"Id",function(){return _t}),n.d(t,"ud",function(){return Eo}),n.d(t,"Pc",function(){return Ze}),n.d(t,"qb",function(){return No}),n.d(t,"Ub",function(){return Oo}),n.d(t,"Xa",function(){return Ao}),n.d(t,"wd",function(){return Po}),n.d(t,"F",function(){return To}),n.d(t,"Qb",function(){return Mo}),n.d(t,"Nb",function(){return Ro}),n.d(t,"ad",function(){return Do}),n.d(t,"sd",function(){return jo}),n.d(t,"td",function(){return yu}),n.d(t,"od",function(){return Ee}),n.d(t,"ib",function(){return Ne}),n.d(t,"Fa",function(){return Oe}),n.d(t,"qd",function(){return ke}),n.d(t,"lc",function(){return Ie}),n.d(t,"Ca",function(){return _e}),n.d(t,"Za",function(){return ye}),n.d(t,"ab",function(){return ve}),n.d(t,"zd",function(){return be}),n.d(t,"Ad",function(){return we}),n.d(t,"Cd",function(){return xe}); /** * @license * Copyright 2018 Google LLC. All Rights Reserved. @@ -15,7 +15,7 @@ * limitations under the License. * ============================================================================= */ -var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function s(e,t){function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var u=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function m(e,t,n){return Math.max(e,Math.min(t,n))}function g(e){return e%2==0?e:e+1}function y(e){for(var t=0,n=0;n1;--t)if(e%t==0)return[t,e/t];return[1,e]}function I(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function C(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise(function(r,a){var i=0,o=function(){if(e())r();else{var s=t(++i);null!=n&&i>=n?a():setTimeout(o,s)}};o()})}function P(e,t){for(var n=1,r=-1,a=0;a=0)n*=e[a];else if(-1===e[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-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);var i=e.slice();return i[r]=t/n,i}function A(e,t){for(var n=[],r=[],a=0,i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),t[a]<=i&&a++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function T(e,t){var 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 M(e,t,n){if("float32"===t)for(var r=0;r=0;--r)n[r]=n[r+1]*e[r+1];return n}function V(e,t,n){return function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t)?e:(Array.isArray(e)&&(e=_(e)),function(e,t,n){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return n&&R(e,t),new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),a=0;a1)for(var l=0;lK){var c=X*s,f=Array.from(t.subarray(0,c)),p=Array.from(t.subarray(u-X*s,u));return"complex64"===r&&(f=Z(f),p=Z(p)),["["+f.map(function(e,t){return J(e,i[t])}).join(", ")+", ..., "+p.map(function(e,t){return J(e,i[u-X+t])}).join(", ")+"]"]}return["["+("complex64"===r?Z(t):Array.from(t)).map(function(e,t){return J(e,i[t])}).join(", ")+"]"]}var h=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>K){for(var y=0;y {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),a=se(e);a.forEach(function(e){return r.add(e.id)});for(var i=0;i0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var i=e();b(i instanceof re,"The result y returned by f() must be a tensor.");var o=function(e,t,n){for(var r={},a={},i=0;i=0;i--)for(o=(d=e[i]).inputs,c=0;c0)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.");var s={};return s[i.id]=null==n?function(e){var t=U(E(e),"float32");return re.make(e,{values:t})}(i.shape):n,function(e,t){for(var n=function(n){var r=t[n],a=[];if(r.outputs.forEach(function(t){var n=e[t.id];if(null!=n)a.push(n);else{var r=re.make(t.shape,{values:W(t.size,t.dtype)},t.dtype);a.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var i=r.gradient(1===r.outputs.length?a[0]:a);for(var o in r.inputs){if(!(o in i))throw new Error("Cannot backprop through input "+o+". Available gradients found: "+Object.keys(i)+".");var s=i[o](),u=r.inputs[o];if(!N(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+o+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}},r=t.length-1;r>=0;r--)n(r)}(s,o),{value:i,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return b(B(e),"The f passed in customGrad(f) must be a function."),function(){for(var n,r,a=[],i=0;i {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e},e.nextTensorId=0,e.nextVariableId=0,e}();!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(ue||(ue={}));var ce,fe=[{name:"DEBUG",type:ue.BOOLEAN},{name:"IS_BROWSER",type:ue.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:ue.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:ue.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:ue.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:ue.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:ue.NUMBER},{name:"WEBGL_PAGING_ENABLED",type:ue.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:ue.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:ue.BOOLEAN},{name:"WEBGL_VERSION",type:ue.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:ue.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:ue.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:ue.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:ue.NUMBER},{name:"BACKEND",type:ue.STRING},{name:"EPSILON",type:ue.NUMBER},{name:"PROD",type:ue.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:ue.BOOLEAN}];function pe(e){try{if(null!=h(e))return!0}catch(e){return!1}return!1}var he="tfjsflags";function de(){var e={};if("undefined"==typeof window||void 0===window.location||void 0===window.location.search)return e;var t=function(e){var t={};return window.location.search.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r0&&!function(){var e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return pe(2)?2:pe(1)?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(e){if(0===e)return!1;var t=h(e);if(1===e){if(!me(t,"OES_texture_float"))return!1}else if(!me(t,"EXT_color_buffer_float"))return!1;return ge(t,e)}(this.get("WEBGL_VERSION"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(e){if(0===e)return!1;var t=h(e);if(1===e){if(!me(t,"OES_texture_float"))return!1;if(!me(t,"WEBGL_color_buffer_float"))return!1}else if(!me(t,"EXT_color_buffer_float"))return!1;return ge(t,e)}(this.get("WEBGL_VERSION"));if("WEBGL_FENCE_API_ENABLED"===t)return function(e){return 2===e&&null!=h(e).fenceSync}(this.get("WEBGL_VERSION"));if("WEBGL_SIZE_UPLOAD_UNIFORM"===t)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?4:0;if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:.001;if("PROD"===t)return!1;if("TENSORLIKE_CHECK_SHAPE_CONSISTENCY"===t)return!this.get("PROD");throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(e){this.features=Object.assign({},e)},t.prototype.reset=function(){this.features=de(),null!=this.globalEngine&&(this.globalEngine=null)},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},t.prototype.registerBackend=function(e,t,n,r){var a=this;if(void 0===n&&(n=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=r&&r(function(){return a.engine}),!1;try{var i=t();return i.setDataMover({moveData:function(e){return a.engine.moveData(e)}}),this.registry[e]={backend:i,priority:n},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},t.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initEngine(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initEngine=function(){var e=this;if(null==this.globalEngine){this.backendName=this.get("BACKEND");var t=this.findBackend(this.backendName);this.globalEngine=new le(t,!1,function(){return e.get("DEBUG")})}},t}(),ve=function(){var t=function(){var t;if("undefined"!=typeof window)t=window;else{if(void 0===e)throw new Error("Could not find a global object");t=e}return t}();return null==t.ENV&&(t.ENV=new ye(de()),ne(function(){return t.ENV.engine})),t.ENV}(),be=Object.freeze({Environment:ye,ENV:ve});function we(e){return b(B(e),"The f passed in grad(f) must be a function"),function(t,n){return b(t instanceof re,"The x passed in grad(f)(x) must be a tensor"),b(null==n||n instanceof re,"The dy passed in grad(f)(x, dy) must be a tensor"),ve.engine.tidy(function(){var r=ve.engine.gradients(function(){return e(t)},[t],n),a=r.value,i=r.grads;return null!=n&&w(a.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Oe(i),i[0]})}}function xe(e){return b(B(e),"The f passed in grads(f) must be a function"),function(t,n){return b(Array.isArray(t)&&t.every(function(e){return e instanceof re}),"The args passed in grads(f)(args) must be an array of tensors"),b(null==n||n instanceof re,"The dy passed in grads(f)(args, dy) must be a tensor"),ve.engine.tidy(function(){var r=ve.engine.gradients(function(){return e.apply(void 0,t)},t,n),a=r.value,i=r.grads;return null!=n&&w(a.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Oe(i),i})}}function _e(e){return b(B(e),"The f passed in valueAndGrad(f) must be a function"),function(t,n){b(t instanceof re,"The x passed in valueAndGrad(f)(x) must be a tensor"),b(null==n||n instanceof re,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var r=ve.engine.gradients(function(){return e(t)},[t],n),a=r.grads,i=r.value;return Oe(a),{grad:a[0],value:i}}}function Ee(e){return b(B(e),"The f passed in valueAndGrads(f) must be a function"),function(t,n){b(Array.isArray(t)&&t.every(function(e){return e instanceof re}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),b(null==n||n instanceof re,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var r=ve.engine.gradients(function(){return e.apply(void 0,t)},t,n);return null!=n&&w(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Oe(r.grads),r}}function Ne(e,t){if(b(B(e),"The f passed in variableGrads(f) must be a function"),b(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof ae}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var n in t=[],ve.engine.registeredVariables)t.push(ve.engine.registeredVariables[n]);var r=t.length;b((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable.");var a=ve.engine.gradients(e,t,null,!0),i=a.value,o=a.grads;b(o.some(function(e){return 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()."),b(0===i.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+i.rank+" tensor");var s={};return t.forEach(function(e,t){null!=o[t]&&(s[e.name]=o[t])}),{value:i,grads:s}}function Se(e){return ve.engine.customGrad(e)}function Oe(e){if(e.filter(function(e){return 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.")}var ke=ye.tidy,Ie=ye.keep,Ce=ye.dispose,Pe=ye.time,Ae=ye.profile;function Te(){for(var e=[],t=0;t=2*t+1||a%2==1?o.push(a):i.push(a);r.push.apply(r,i),r.push(0),r.push.apply(r,o)}return r}function De(e,t,n,r){void 0===r&&(r=!0);var a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(var i=1;i=-n&&ee.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+e.rank);if(0===e.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+e.shape+".");for(var n=t.shape,r=n[n.length-1],a=1,i=0;i1?t.shape[t.rank-1]:1,a=n.length,i=1,o=r;o0?a>=c[t]:a<=c[t]);a+=r[t])n+=1;return n}),[l,h,f]}function Ze(e,t,n,r,a){var i=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),m(0,i,o-1)}function Qe(e,t,n,r,a){var i=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),n[a]>0?m(0,i,o):m(-1,i,o-1)}function et(e){var t=e;if(j(e))return[e.length];if(!Array.isArray(e))return[];for(var n=[];t instanceof Array;)n.push(t.length),t=t[0];return e instanceof Array&&ve.get("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function e(t,n,r){if(r=r||[],t instanceof Array){b(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"}),b(t.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+t.length+" elements"});for(var a=n.slice(1),i=0;i1)return vt([0],r);var a=W(Math.abs(Math.ceil((t-e)/n)),r);ta}).sort(function(e,t){return t.score-e.score}),o=[],s=0;s=0;--p)if(Ut(e,c,o[p])>=r){f=!0;break}if(!f&&(o.push(c),o.length>=n))break}return ft(o,"int32")}function Ut(e,t,n){var r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),f=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(s-i)*(u-o),d=(f-l)*(p-c);if(h<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),y=Math.min(s,f),v=Math.min(u,p),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(h+d-b)}function Wt(e,t,n){var r=Array(e.rank).fill(0),a=e.shape.slice();return t.map(function(t){a[n]=t;var i=e.slice(r,a);return r[n]+=t,i})}function qt(e,t,n,r,a){for(var i=t[t.length-1],o=[e.length/i,i],s=o[0],u=o[1],l=T(n,s*r),c=T("int32",s*r),f=0;f1&&1===o&&r.unshift(i)}return r}function Gt(e,t){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Ht(e,t){for(var n=[],r=Math.max(e.length,t.length),a=0;a1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});i=i.join("\n");var o,s,u=e.map(function(e){return function(e,t,n){var r=function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1)+"Flat",r=E(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform)return 1===r?"float "+n+"(int index) {return "+t+";}":"\n float "+n+"(int index) {\n for (int i = 0; i < "+r+"; i++) {\n if (i == index) {\n return "+t+"[i];\n }\n }\n }\n ";var a=e.shapeInfo.texShape,i=a[0],o=a[1];return 1===o&&1===i?"\n float "+n+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ":1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+i+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index) + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = UVfrom1D("+i+", "+o+", index);\n return sampleTexture("+t+", uv);\n }\n "}(e);return e.shapeInfo.isPacked?r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=e.shapeInfo.texShape,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+a[0]+", "+a[1]+", index);\n return texture2D("+t+", uv);\n }\n "}(t);case 2:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,i=a[0],o=a[1];if(null!=a&&N(t,a))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o+".0, "+i+".0);\n\n return texture2D("+n+", uv);\n }\n ";var s=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(t[1]/2)+", "+s[0]+", "+s[1]+", row, col);\n return texture2D("+n+", uv);\n }\n "}(t);case 3:return function(t){var n=t.shapeInfo.logicalShape,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(1===n[0])return"\n "+e(fn(t,n.slice(1)))+"\n vec4 "+a+"(int b, int row, int col) {\n return "+a+"("+pn(["b","row","col"],[1,2])+");\n }\n ";var s=o[0],u=o[1],l=Math.ceil(n[2]/2);return"\n vec4 "+a+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+s+", "+u+", "+l*Math.ceil(n[1]/2)+", "+l+", b, row, col);\n return texture2D("+r+", uv);\n }\n "}(t);case 4:return function(e){var t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],o=i[0],s=i[1],u=Math.ceil(t[3]/2),l=u*Math.ceil(t[2]/2);return"\n vec4 "+r+"(int b2, int b, int row, int col) {\n vec2 uv = packedUVfrom4D(\n "+o+", "+s+", "+l*t[1]+",\n "+l+", "+u+", b2, b, row, col);\n return texture2D("+n+", uv);\n }\n "}(t);default:throw new Error("Packed "+n.length+"-D input sampling is not yet supported")}}(e):r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+n+"() {return "+t+";}":"\n float "+n+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}(t);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+n+"(int index) {\n return "+n+"Flat(index);\n }\n "}(t);case 2:return function(t){var n=t.shapeInfo.logicalShape,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape;if(null!=i&&N(n,i)){var o=i[0];return"\n float "+a+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var s=A(n),u=s.newShape,l=s.keptDims,c=u;if(c.lengths||o.length>0),c=function(e){for(var t=0;t=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+n+"("+(i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}(e,t,a,i);var p=E(e.shapeInfo.logicalShape),h="";l&&c&&(h="\n int mainPart = index / "+p+";\n index -= mainPart * "+p+";\n ");var d=t.texShape;if(f)return 1===p?"float "+i+"() {return "+r+";}":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return N(m,d)?"\n float "+i+"() {\n return sampleTexture("+r+", resultUV);\n }\n ":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+r+", uv);\n }\n "}(e,t,n)),r}(e,t,r)}).join("\n"),l=t.texShape,c=un;return t.isPacked?(o=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===t[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return resTexRC.x * "+n[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(N(e,t))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(e[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(e,t);case 3:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec3(b, r, c);\n }\n "}(e,t);case 4:return function(e,t){var n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[3]/2),a=r*Math.ceil(e[2]/2),i=a*e[1];return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n int b2 = index / "+i+";\n index -= b2 * "+i+";\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec4(b2, b, r, c);\n }\n "}(e,t);default:throw new Error(e.length+"-D packed output coordinate fetching is not yet supported")}}(t.logicalShape,l),s=sn):(o=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){return N(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}(e,t);case 3:return function(e,t){var n=tn(["r","c","d"],e);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n "+n+"\n return ivec3(r, c, d);\n }\n "}(e,t);case 4:return function(e,t){var n=tn(["r","c","d","d2"],e);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(e,t);case 5:return function(e,t){var n=tn(["r","c","d","d2","d3"],e);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(e,t);case 6:return function(e,t){var n=tn(["r","c","d","d2","d3","d4"],e);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}(t.logicalShape,l),s=on),a&&(c+=ln),[c,an,s,i,o,u,n].join("\n")}var an="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",on="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",sn="\n void setOutput(vec4 val) {\n gl_FragColor = val;\n }\n",un="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\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 bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\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 \nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom4D(int texNumR, int texNumC, int texelsInBatch2,\n int texelsInBatch, int texelsInLogicalRow, int b2, int b,\n int row, int col) {\n int index = b2 * texelsInBatch2 + b * texelsInBatch +\n (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n",ln="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function cn(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function fn(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function pn(e,t){return t.map(function(t){return e[t]}).join(", ")}function hn(e,t){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 sum for rank "+e+" is not yet supported")}var dn,mn,gn=function(){function e(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 "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}(),yn=function(e,t,n){this.variableNames=["real","imag"];var r=t[1];this.outputShape=t;var a=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,i=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+a+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+e+"\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 "};function vn(e,t){return[t,e]}function bn(e,t){return e*t}function wn(e,t,n){var r=function(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t}(e.length,n);if(t.length= "+r);for(var a=0,i=0;in||t>n)throw r="["+e+"x"+t+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function Fn(e){return Yn(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Vn(e,t,n,r,a,i,o){var s=e.getAttribLocation(t,n);return-1!==s&&(En(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),En(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,i,o)}),En(e,function(){return e.enableVertexAttribArray(s)}),!0)}function Un(e,t,n){Jn(e,n),En(e,function(){return e.activeTexture(e.TEXTURE0+n)}),En(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function Wn(e,t,n){return Yn(e,function(){return e.getUniformLocation(t,n)},'uniform "'+n+'" not present in program.')}function qn(e,t,n){return e.getUniformLocation(t,n)}function $n(e,t,n,r,a){En(e,function(){return Un(e,n,a)}),En(e,function(){return e.uniform1i(r,a)})}function Gn(e,t,n){En(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)}),En(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function Hn(e,t){En(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),En(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function Kn(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Xn(e,t))}function Xn(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Yn(e,t,n){var r=En(e,function(){return t()});if(null==r)throw new Error(n);return r}function Jn(e,t){var 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 Zn(e,t){void 0===t&&(t=!1);var n=ve.get("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,e=e.map(function(t,n){return n>=e.length-2?g(e[n]):e[n]})),2!==e.length){var r=A(e);e=r.newShape}var a=E(e);return e.length<=1&&a<=n?[a,1]:2===e.length&&e[0]<=n&&e[1]<=n?e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n?[e[0],e[1]*e[2]*e[3]]:k(a)}function Qn(e){return e%2==0}function er(e,t){if(N(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){if(N(A(e).newShape,A(t).newShape))return!0}else if(Qn(e[0])&&Qn(t[0])){if(Qn(e[1])&&Qn(t[1]))return!0;if(e[1]===t[1])return!0}return!1}var tr=Object.freeze({callAndCheck:En,enableDebugWebGLErrorChecking:Sn,checkWebGLError:On,getWebGLErrorMessage:kn,getExtensionOrThrow:In,createVertexShader:Cn,createFragmentShader:Pn,createProgram:Tn,linkProgram:Mn,validateProgram:Rn,createStaticVertexBuffer:Dn,createStaticIndexBuffer:jn,getNumChannels:Ln,createTexture:Bn,validateTextureSize:zn,createFramebuffer:Fn,bindVertexBufferToProgramAttribute:Vn,bindTextureUnit:Un,unbindTextureUnit:function(e,t){Jn(e,t),En(e,function(){return e.activeTexture(e.TEXTURE0+t)}),En(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:Wn,getProgramUniformLocation:qn,bindTextureToProgramUniformSampler:$n,bindCanvasToFramebuffer:function(e){En(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),En(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),En(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})},bindColorTextureToFramebuffer:Gn,unbindColorTextureFromFramebuffer:Hn,validateFramebuffer:Kn,getFramebufferErrorMessage:Xn,getTextureShapeFromLogicalShape:Zn,isReshapeFree:er});function nr(e){return Cn(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function rr(e){return Dn(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ar(e){return jn(e,new Uint16Array([0,1,2,2,1,3]))}function ir(e,t){var n,r,a,i,o,s,u,l=e;return 2===ve.get("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,a=l.RGBA32F,i=l.RED,o=4,s=1,u=l.HALF_FLOAT):(n=e.RGBA,r=e.RGBA,a=l.RGBA,i=e.RGBA,o=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:o,defaultNumChannels:s,textureTypeHalfFloat:u}}function or(e,t,n,r,a,i){zn(t,n);var o=Bn(e),s=e.TEXTURE_2D;return En(e,function(){return e.bindTexture(s,o)}),En(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),En(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),En(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),En(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),En(e,function(){return e.texImage2D(s,0,r,t,n,0,a,i,null)}),En(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),o}function sr(e,t,n,r){var a=vn(t,n);return or(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,e.FLOAT)}function ur(e,t,n,r){var a=vn(t,n);return or(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function lr(e,t,n,r){var a=vn(t,n);return or(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function cr(e,t,n,r){var a=xn(t,n);return or(e,a[0],a[1],r.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function fr(e,t,n,r){var a=xn(t,n);return or(e,a[0],a[1],r.internalFormatHalfFloat,e.RGBA,r.textureTypeHalfFloat)}function pr(e,t,n){return En(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),Vn(e,t,"clipSpacePos",n,3,20,0)&&Vn(e,t,"uv",n,2,20,12)}function hr(e,t,n){En(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),En(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}),En(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function dr(e,t,n,r,a,i){zn(n,r),En(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),En(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,i,e.FLOAT,a)}),En(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function mr(e,t,n,r,a,i,o){var s,u=vn(n,r),l=u[0],c=u[1];1===o.defaultNumChannels?s=a:function(e,t,n){var r=bn(e.length,n);if(t.length= "+r);for(var a=0,i=0;i=\n "+i);for(var o=r%2==1,s=n%2==1,u=Math.floor(r/2),l=Math.floor(n/2),c=Math.ceil(r/2),f=c*Math.ceil(n/2),p=g(n)*g(r),h=0;h= "+i);for(var o=r%2==1,s=n%2==1,u=Math.floor(r/2),l=Math.floor(n/2),c=Math.ceil(r/2),f=c*Math.ceil(n/2),p=g(n)*g(r),h=0;h0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n,r,a,i){var o=this;return this.downloadMatrixDriver(e,function(){return xr(o.gl,t,n,r,a,i,o.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=Pn(t,e),r=nr(t),a=Tn(t);return En(t,function(){return t.attachShader(a,r)}),En(t,function(){return t.attachShader(a,n)}),Mn(t,a),this.autoDebugValidate&&Rn(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=pr(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&En(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&Rn(this.gl,this.program),En(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?Wn(this.gl,e,t):qn(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),En(this.gl,function(){return n.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),$n(this.gl,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=xn(t,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(e,a,i)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&Rn(this.gl,this.program),Kn(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),En(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),En(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=In(this.gl,2===ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return l(this,void 0,void 0,function(){var t=this;return c(this,function(n){switch(n.label){case 0:return[4,C(function(){return t.disposed||t.isQueryAvailable(e,ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(e,ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise(function(n){t.addItemToPoll(function(){return e.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0,n=e.length-1,r=-1;t<=n;){var a=t+n>>1;e[a]()?(r=a,t=a+1):n=a-1}return r}(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||C(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),Gn(this.gl,e,this.framebuffer),this.autoDebugValidate&&Kn(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Gn(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Kn(this.gl)):Hn(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;Gn(r,e,this.framebuffer),this.autoDebugValidate&&Kn(r),this.outputTexture=e,En(r,function(){return r.viewport(0,0,t,n)}),En(r,function(){return r.scissor(0,0,t,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var a=this;this.throwIfDisposed(),En(this.gl,function(){return a.gl.scissor(e,t,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function Nr(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(function(e,n){var r=e.logicalShape,a=t[n],i=a.shape;if(!N(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var o=e.texShape,s=a.isUniform?null:a.texData.texShape;if(!N(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var Sr=function(e,t,n,r,a){void 0===r&&(r=!1),void 0===a&&(a=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=n;var i=r?e[0]:e[1],o=Math.ceil(i/2),s=r?"i * 2, rc.x":"rc.x, i * 2",u=a?"rc.y, i * 2":"i * 2, rc.y",l=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],c=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];this.userCode="\n const float sharedDimension = "+o+".0;\n\n vec4 dot2x2ARowBCol(ivec2 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+o+"; i++) {\n vec4 a = getMatrixA("+s+");\n vec4 b = getMatrixB("+u+");\n\n result += ("+l[0]+" * "+c[0]+") + ("+l[1]+" * "+c[1]+");\n }\n return result;\n }\n\n void main() {\n ivec2 rc = getOutputCoords();\n setOutput(dot2x2ARowBCol(rc));\n }\n "},Or=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\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 "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e)}},e}();function kr(e,t){return 1===t?[e]:function(e,t){return["x","y","z","w","u","v"].slice(0,t).map(function(t){return e+"."+t})}(e,t)}var Ir=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterWidth,a=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,s=e.dilationWidth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=e.padInfo.top,f=e.padInfo.left;this.outputShape=e.outShape;var p="avg"===t,h="0.0";if(p||(h="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+a+", "+i+");\n const ivec2 pads = ivec2("+c+", "+f+");\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 < "+u+";\n wR += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(d="avgValue / count");var m=4*Math.floor(r/4),g=r%4,y="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+a+", "+i+");\n const ivec2 pads = ivec2("+c+", "+f+");\n const float initializationValue = "+h+";\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("+h+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+y+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+y+"\n }\n }\n setOutput("+d+");\n }\n "}},Cr=function(e,t,n,r,a,i,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=cn(a.length),u=cn(i.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",f="";1===r?f="i":2===r&&(f="i, coords[1]");var p="getUpdates("+f+")",h=t>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+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("+c+");\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 "},Pr=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=cn(this.rank),n=function(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){if(null!=t.startLoc||(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null!=t.startLoc))if(1===t.rank)n.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)n.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)n.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");n.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}(),Ar=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t,n){var r,a=Tr(t,n),i=Mr(e,a,n);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var o=this.freeTextures[i].shift();return this.usedTextures[i].push(o),o}return this.numUsedTextures++,this.log(),a===mn.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===mn.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===mn.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===mn.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===mn.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(r),r},e.prototype.releaseTexture=function(e,t,n,r){if(null!=this.freeTextures){var a=Mr(t,Tr(n,r),r);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(e),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],o=i.indexOf(e);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(o,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function Tr(e,t){if(t)return ve.get("WEBGL_RENDER_FLOAT32_ENABLED")?mn.PACKED_2X2_FLOAT32:mn.PACKED_2X2_FLOAT16;if(e===dn.DOWNLOAD||e===dn.PIXELS)return mn.PACKED_4X1_UNSIGNED_BYTE;if(e===dn.UPLOAD)return mn.UNPACKED_FLOAT32;if(e===dn.RENDER)return ve.get("WEBGL_RENDER_FLOAT32_ENABLED")?mn.UNPACKED_FLOAT32:mn.UNPACKED_FLOAT16;throw new Error("Unknown logical texture type "+e)}function Mr(e,t,n){return e[0]+"_"+e[1]+"_"+t+"_"+n}var Rr=1.7580993408473768,Dr=1.0507009873554805,jr=function(){function e(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float NAN;\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 "}return e.prototype.getCustomSetupFunc=function(){var e=this;return function(t,n){null==e.startLoc&&(e.startLoc=t.getUniformLocationNoThrow(n,"NAN"),null==e.startLoc)||t.gl.uniform1f(e.startLoc,NaN)}},e}(),Lr="if (isNaN(x)) return x;",Br=function(e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=e;var t=e.length,n=kr("rc",t),r=cn(t),a=function(e,t){if(1===e)return"rc";for(var n="",r=0;r=1,"Pass at least one tensor to concat");var n=nt(e,"tensors","concat");t=Ve(t,n[0].shape)[0];var r=Ge(n.map(function(e){return e.shape}),t);if(0===E(r))return lt([],r);if(1===(n=n.filter(function(e){return e.size>0})).length)return n[0];var a=n.map(function(e){return e.shape});!function(e,t){var n=e[0].length;e.forEach(function(e,t){b(e.length===n,"Error in concat"+n+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+n+")")}),b(t>=0&&t>>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}(e),a=t&&t.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),Hr=$r(function(e){!function(e,t,n){function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),Kr=$r(function(e){!function(e,t,n){function r(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 a(e,t){var n=new function(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()}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),Xr=$r(function(e){!function(e,t,n){function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new function(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)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),Yr=$r(function(e){!function(e,t,n){function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new function(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,o,s=[],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&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;e.w=o,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),Jr=$r(function(e){!function(e,t,n){function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),Zr=$r(function(e){!function(t,r){var a,i=this,o=256,s=6,u="random",l=r.pow(o,s),c=r.pow(2,52),f=2*c,p=o-1;function h(e,n,h){var y=[],v=m(function e(t,n){var r,a=[],i=typeof t;if(n&&"object"==i)for(r in t)try{a.push(e(t[r],n-1))}catch(e){}return a.length?a:"string"==i?t:t+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[e,g(t)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(o):(e=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(e)),g(e)}catch(e){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(t)]}}():e,3),y),b=new function(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a=f;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,m(g(b.S),t),(n.pass||h||function(e,t,n,a){return a&&(a.S&&d(a,b),e.state=function(){return d(b,{})}),n?(r[u]=e,t):e})(w,v,"global"in n?n.global:this==r,n.state)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function m(e,t){for(var n,r=e+"",a=0;a=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}();function ta(e,t){return l(this,void 0,void 0,function(){var n,r,a,i,o,s,u,l,f,p,h,d,m,g,y,v,b,w,x,_;return c(this,function(c){switch(c.label){case 0:if(2!==(n=tt(e,"img","toPixels","int32")).rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(o=2===n.rank?1:n.shape[2])>4||2===o)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+o);return s=n.min(),u=n.max(),[4,s.data()];case 1:return l=c.sent()[0],[4,u.data()];case 2:if(f=c.sent()[0],s.dispose(),u.dispose(),"float32"===n.dtype){if(l<0||f>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+f+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(l<0||f>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+f+"].")}return[4,n.data()];case 3:for(p=c.sent(),h="float32"===n.dtype?255:1,d=new Uint8ClampedArray(i*a*4),m=0;m=1+t.length,"input rank is "+r.rank+" but should be > than blockShape.length "+t.length),b(n.length===t.length,"crops.length is "+n.length+" but should be equal to blockShape.length "+t.length),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),ve.engine.runKernel(function(e){return e.batchToSpaceND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}})}}),ia=rt({cast_:function(e,t){var n=tt(e,"x","cast");return ve.engine.runKernel(function(e){return e.cast(n,t)},{$x:n},function(e){return{$x:function(){return e.clone()}}})}}),oa=rt({clone_:function(e){var t=tt(e,"x","clone");return ve.engine.runKernel(function(e){return re.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),sa=rt({cumsum_:function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=tt(e,"x","cumsum"),i=We([t|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=$e(1,a.rank)[0],u=ve.engine.runKernel(function(e){return e.cumsum(o,s,n,r)},{permutedX:o},function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),ua=rt({depthToSpace_:function(e,t,n){void 0===n&&(n="NHWC");var r=tt(e,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return b(a*t>=0,"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+r.shape),b(i*t>=0,"Negative dimension size caused by overflow when multiplying\n "+i+" and "+t+" for depthToSpace with input shape\n "+r.shape),b(o%(t*t)==0,"Dimension size must be evenly divisible by "+t*t+" but is "+o+" for depthToSpace with input shape "+r.shape),ve.engine.runKernel(function(e){return e.depthToSpace(r,t,n)},{$x:r})}}),la=rt({expandDims_:function(e,t){void 0===t&&(t=0);var n=tt(e,"x","expandDims");b(t<=n.rank,"Axis must be <= rank of the tensor");var r=n.shape.slice();return t<0&&(b(-(n.rank+1)<=t,"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"),t=n.rank+t+1),r.splice(t,0,1),_a(n,r)}}),ca=rt({eye_:function(e,t,n,r){void 0===r&&(r="float32"),null==t&&(t=e);for(var a=na([e,t],r),i=e<=t?e:t,o=0;o4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return ve.engine.fromPixels(e,t)}}),pa=rt({multinomial_:function(e,t,n,r){void 0===r&&(r=!1);var a=tt(e,"logits","multinomial"),i=a.size,o=a.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?a.as2D(1,-1):a,u=ve.engine.runKernel(function(e){return e.multinomial(s,r,t,n)},{logits2D:s});return 1===o?u.as1D():u}}),ha=rt({oneHot_:function(e,t,n,r){void 0===n&&(n=1),void 0===r&&(r=0);var a=tt(e,"indices","oneHot","int32");if(b("int32"===a.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return ve.engine.runKernel(function(e){return e.oneHot(a,t,n,r)},{$indices:a},function(e){return{$indices:function(){return Ct(a)}}})}}),da=rt({pad_:function(e,t,n){void 0===n&&(n=0);var r=tt(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a=t.map(function(e){return e[0]});return ve.engine.runKernel(function(e){return e.pad(r,t,n)},{$x:r},function(e){return{$x:function(){return e.slice(a,r.shape)}}})}}),ma=rt({pad1d_:function(e,t,n){return void 0===n&&(n=0),b(2===t.length,"Invalid number of paddings. Must be length of 2."),da(e,[t],n)}}),ga=rt({pad2d_:function(e,t,n){return void 0===n&&(n=0),b(2===t.length&&2===t[0].length&&2===t[1].length,"Invalid number of paddings. Must be length of 2 each."),da(e,t,n)}}),ya=rt({pad3d_:function(e,t,n){return void 0===n&&(n=0),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."),da(e,t,n)}}),va=rt({pad4d_:function(e,t,n){return void 0===n&&(n=0),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."),da(e,t,n)}}),ba=rt({rand_:function(e,t,n){var r=E(e),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(var i=0;i=1+t.length,"input rank "+r.rank+" should be > than [blockShape] "+t.length),b(n.length===t.length,"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+t.length),b(r.shape.reduce(function(e,r,a){return 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()),ve.engine.runKernel(function(e){return e.spaceToBatchND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}})}}),Na=rt({squeeze_:function(e,t){var n=tt(e,"x","squeeze");return _a(n,A(n.shape,t).newShape)}}),Sa=rt({stack_:function(e,t){void 0===t&&(t=0);var n=nt(e,"tensors","stack");if(b(n.length>=1,"Pass at least one tensor to tf.stack"),1===n.length)return n[0].expandDims(t);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;b(t<=r,"Axis must be <= rank of the tensor"),n.forEach(function(e){w(a,e.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(e){b(i===e.dtype,"All tensors passed to stack must have matching dtypes")});var o=n.map(function(e){return e.expandDims(t)});return zr(o,t)}}),Oa=rt({tile_:function(e,t){var n=tt(e,"x","tile");return b(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of reps "+t+"."),ve.engine.runKernel(function(e){return e.tile(n,t)},{$x:n},function(e){return{$x:function(){var r=Ct(n);if(1===n.rank)for(var a=0;a1?n[n.length-2]:1,u=n[n.length-1];return this.gpgpu.downloadMatrixFromPackedTexture(a,o,s,u,i[0],i[1])}return this.gpgpu.downloadFloat32MatrixFromOutputTexture(a,i[0],i[1])}var l=this.makeTensorHandle(n,"float32");l.size=E(n),this.texData.get(l.dataId).usage=dn.DOWNLOAD;var c=new function(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\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\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "}(n);this.compileAndRun(c,[{shape:n,dtype:r,dataId:e}],l,null,!1);var f=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(f.texture,f.texShape[0],f.texShape[1]);return this.disposeData(l.dataId),p},e.prototype.time=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),a=_(this.activeTimers.map(function(e){return e.query})).filter(function(e){return null!=e}),i=_(this.activeTimers.map(function(e){return e.name})).filter(function(e){return null!=e}),this.activeTimers=t,r&&(this.programTimersStack=null),[4,Promise.all(a)];case 1:return o=u.sent(),s={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:y(o),getExtraProfileInfo:function(){return o.map(function(e,t){return{name:i[t],ms:e}}).map(function(e){return e.name+": "+e.ms}).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,s]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return l(this,void 0,void 0,function(){var t;return c(this,function(n){return ve.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),n=t.texture,r=t.texShape,a=t.usage,i=t.complexTensors,o=t.isPacked;null!=n&&this.releaseTexture(e,n,r,a,o),null!=i&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getCPUBackend=function(){return ve.get("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=ve.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(e,t){var n=this;return void 0===t&&(t=10),null!=this.getCPUBackend()&&e.every(function(e){return null==n.texData.get(e.dataId).texture&&e.size4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=e,1!==n){var r=e.map(function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),a=cn(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "}(e.shape,t);return this.compileAndRun(n,[e])},e.prototype.concat2Tensors=function(e,t,n){var r=Ge([e.shape,t.shape],n),a=e.as2D(-1,E(e.shape.slice(n))),i=t.as2D(-1,E(t.shape.slice(n))),o=new function(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=Ge([e,t],1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "}(a.shape,i.shape);return this.compileAndRun(o,[a,i]).reshape(r)},e.prototype.concat=function(e,t){if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(1===e.length)return e[0];for(var n=e[0],r=1;r1e3){n&&(e=e.transpose([0,2,1])),r&&(t=t.transpose([0,2,1]));var u=1===i?e:e.as3D(s,o,1),l=1===i?2:1,c=1===i?t.as3D(s,1,o):t;return this.multiply(u,c).sum(l,!0)}if(1===s){var f=e.as2D(e.shape[1],e.shape[2]),p=t.as2D(t.shape[1],t.shape[2]),h=new Sr(f.shape,p.shape,[a,i],n,r),d=this.compileAndRun(h,[f,p],this.makePackedTensor(h.outputShape));return!1===ve.get("WEBGL_LAZILY_UNPACK")&&(d=this.unpackTensor(d)),d.reshape([1,d.shape[0],d.shape[1]])}return this.compileAndRun(new function(e,t,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1),this.variableNames=["matrixA","matrixB"];var a=e[0],i=n?e[2]:e[1],o=r?t[1]:t[2],s=n?e[1]:e[2];this.outputShape=[a,i,o];var u=function(e,t){return n?"batch, "+t+" + "+e+", aRow":"batch, aRow, "+t+" + "+e},l=function(e,t){return r?"batch, bCol, "+t+" + "+e:"batch, "+t+" + "+e+", bCol"},c=4*Math.floor(s/4),f=s%4;this.userCode=" float dotARowBCol(int batch, int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+c+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+u(0,"i")+"),\n getMatrixA("+u(1,"i")+"),\n getMatrixA("+u(2,"i")+"),\n getMatrixA("+u(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+l(0,"i")+"),\n getMatrixB("+l(1,"i")+"),\n getMatrixB("+l(2,"i")+"),\n getMatrixB("+l(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1===f)+") {\n result += getMatrixA("+u(0,c)+") *\n getMatrixB("+l(0,c)+");\n } else if ("+(2===f)+") {\n vec2 a = vec2(\n getMatrixA("+u(0,c)+"),\n getMatrixA("+u(1,c)+")\n );\n vec2 b = vec2(\n getMatrixB("+l(0,c)+"),\n getMatrixB("+l(1,c)+")\n );\n result += dot(a, b);\n } else if ("+(3===f)+") {\n vec3 a = vec3(\n getMatrixA("+u(0,c)+"),\n getMatrixA("+u(1,c)+"),\n getMatrixA("+u(2,c)+")\n );\n vec3 b = vec3(\n getMatrixB("+l(0,c)+"),\n getMatrixB("+l(1,c)+"),\n getMatrixB("+l(2,c)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec3 resBRC = getOutputCoords();\n setOutput(dotARowBCol(resBRC.x, resBRC.y, resBRC.z));\n }\n "}(e.shape,t.shape,n,r),[e,t])},e.prototype.multiply=function(e,t){if("complex64"===e.dtype){var n=this.texData.get(e.dataId),r=this.texData.get(t.dataId),a=new Jt("return areal * breal - aimag * bimag;",e.shape,t.shape),i=new Jt("return areal * bimag + aimag * breal;",e.shape,t.shape),o=[this.makeComplexComponentTensorHandle(e,n.complexTensors.real),this.makeComplexComponentTensorHandle(e,n.complexTensors.imag),this.makeComplexComponentTensorHandle(t,r.complexTensors.real),this.makeComplexComponentTensorHandle(t,r.complexTensors.imag)],s=this.compileAndRun(a,o),u=this.compileAndRun(i,o),l=this.complex(s,u);return s.dispose(),u.dispose(),l}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);var c=new en("return a * b;",e.shape,t.shape),f=this.makeOutputArray(c.outputShape,e.dtype);return this.compileAndRun(c,[e,t],f)},e.prototype.batchNormalization=function(e,t,n,r,a,i){var o=[e,t,n],s=null;null!=i&&(s=i.shape,o.push(i));var u=null;null!=a&&(u=a.shape,o.push(a));var l=null,c=Kt;ve.get("WEBGL_PACK_BATCHNORMALIZATION")&&(l=this.makePackedTensor(e.shape),c=Xt);var f=new c(e.shape,t.shape,n.shape,s,u,r);return this.compileAndRun(f,o,l)},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){var i=new function(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];var i,o=t,s=e[3]-1;this.outputShape=e;var u="float("+n+") + float("+r+") * sum";i=.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 = -"+o+"; j <= "+o+"; 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 * "+i+";\n setOutput(val);\n }\n "}(e.shape,t,n,r,a);return this.compileAndRun(i,[e])},e.prototype.LRNGrad=function(e,t,n,r,a,i,o){var s=new function(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 "}(t.shape,r,a,i,o);return this.compileAndRun(s,[t,n,e])},e.prototype.tile=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.transpose=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r6)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),a=0;a4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=Me(e.shape,t,r),i=Re(a.length,t.length),o=De(e.shape,t,r),s=je(n,t.length),u=Le(o,n,t.length);return e.reshape(a).transpose(i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(e,t,n){b(e.rank<=4,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=[[0,0]];a.push.apply(a,n);for(var i=1+t.length;i= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(o="0.0",f="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var h="";a%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\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("+o+");\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 < "+l+"; 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 "+f+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+f+"\n }\n setOutput("+u+");\n }\n "}({windowSize:Xe(a),inSize:a,batchSize:r},t),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],n);return this.compileAndRun(i,[e],l),1===l.shape[1]?l:this.reduce(l,t,n)},e.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],a=e.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=new function(e,t,n){this.variableNames=["A"];var r=e.windowSize,a=e.batchSize,i=e.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===t?">":"<",u=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 = "+u+";\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 "}({windowSize:Xe(a),inSize:a,batchSize:r},t,null==n),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],"int32"),c=[e];return null!=n&&c.push(n),this.compileAndRun(i,c,l),1===l.shape[1]?l:this.argReduce(e,t,l)},e.prototype.sum=function(e,t){Ue("sum",t,e.rank);var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a),o=Tt(e.dtype);return this.reduce(i,"sum",o).reshape(r)},e.prototype.prod=function(e,t){var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a),o=Tt(e.dtype);return this.reduce(i,"prod",o).reshape(r)},e.prototype.unsortedSegmentSum=function(e,t,n){var r=0,a=We([r],e.rank),i=e;null!=a&&(i=e.transpose(a),r=$e(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],a=e.length,i=0;it||n===e){r=!0;break}n=z(e,n+1)}return n}(o,a),u=new function(e,t){this.variableNames=["x","segmentIds"];var n=e.windowSize,r=e.batchSize,a=e.inSize,i=e.numSegments,o=i*Math.ceil(a/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, filter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var f="";a%n>0&&(f="\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 "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+f+"\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 < "+s+"; 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 filter = 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 "+l+"\n }\n\n int inIdx = inOffset + "+s+";\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = 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 "+l+"\n }\n setOutput(sumValue);\n }\n "}({windowSize:s,inSize:o,batchSize:i,numSegments:a},t),l=u.outputShape,c=l[0],f=l[1],p=this.makeOutputArray([c,f],r);return this.compileAndRun(u,[e,n],p),p.shape[1]===a?p:(n=xt(0,a).tile([o/s]),this.segOpCompute(p,t,n,r,a))},e.prototype.argMin=function(e,t){var n=[t];Ue("argMin",n,e.rank);var r=ze(e.shape,n),a=r[0],i=E(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"min").reshape(a)},e.prototype.argMax=function(e,t){var n=[t];Ue("argMax",n,e.rank);var r=ze(e.shape,n),a=r[0],i=E(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"max").reshape(a)},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new function(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,a=e[e.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+cn(r)+" coords = getOutputCoords();\n int end = "+hn(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+hn(r,"coords")+" = idx;\n val += getX("+function(e,t){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 sum for rank "+e+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}(e.shape,n,r);return this.compileAndRun(a,[e])},e.prototype.equal=function(e,t){var n=new en("return float(a == b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.notEqual=function(e,t){var n=new en("return float(a != b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);var n=new en("return float(a < b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.lessEqual=function(e,t){var n=new en("return float(a <= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);var n=new en("return float(a > b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greaterEqual=function(e,t){var n=new en("return float(a >= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalNot=function(e){var t=new jr(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},e.prototype.logicalAnd=function(e,t){var n=new en("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalOr=function(e,t){var n=new en("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.select=function(e,t,n){var r=new function(e,t,n){var 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{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "}(e.rank,t.shape,t.rank),a=this.makeOutputArray(r.outputShape,At(t.dtype,n.dtype));return this.compileAndRun(r,[e,t,n],a)},e.prototype.where=function(e){Te("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return Pa(e.shape,t)},e.prototype.topk=function(e,t,n){return qt(e.dataSync(),e.shape,e.dtype,t)},e.prototype.min=function(e,t){Ue("min",t,e.rank);var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var n=new en("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.mod=function(e,t){var n=new en("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[e,t],null,r)},e.prototype.max=function(e,t){Ue("max",t,e.rank);var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var n=new en("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.all=function(e,t){Ue("all",t,e.rank);var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(e,t){Ue("any",t,e.rank);var n=ze(e.shape,t),r=n[0],a=E(n[1]),i=e.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.squaredDifference=function(e,t){var n=new en("return (a - b) * (a - b);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.realDivide=function(e,t){var n=new en("if (a == b) return 1.0;\n return a / b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e,t],r)},e.prototype.floorDiv=function(e,t){var n=new en("\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[e,t],r)},e.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,Zt);var n=new en(Zt,e.shape,t.shape),r=this.makeOutputArray(n.outputShape,At(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r)},e.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,a=this.texData.get(e.dataId),i=this.texData.get(t.dataId),o=[[a.complexTensors.real,i.complexTensors.real],[a.complexTensors.imag,i.complexTensors.imag]].map(function(a){var i=a[0],o=a[1],s=new en(n,e.shape,t.shape),u=r.makeOutputArray(s.outputShape,At(i.dtype,o.dtype)),l=r.makeComplexComponentTensorHandle(e,i),c=r.makeComplexComponentTensorHandle(t,o);return r.compileAndRun(s,[l,c],u)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},e.prototype.addN=function(e){for(var t=e[0],n=1;n 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");return this.compileAndRun(t,[e])},e.prototype.exp=function(e){var t=new jr(e.shape,"return exp(x);");return this.compileAndRun(t,[e])},e.prototype.expm1=function(e){var t=new jr(e.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[e])},e.prototype.log=function(e){var t=new jr(e.shape,"if (x < 0.0) return NAN;\n return log(x);"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.log1p=function(e){var t=new jr(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},e.prototype.sqrt=function(e){var t=new jr(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},e.prototype.rsqrt=function(e){var t=new jr(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},e.prototype.square=function(e){var t=new jr(e.shape,"return x * x;");return this.compileAndRun(t,[e])},e.prototype.reciprocal=function(e){var t=new jr(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},e.prototype.relu=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(t,[e])},e.prototype.elu=function(e){var t=new jr(e.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[e])},e.prototype.eluDer=function(e,t){var n=new en("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.selu=function(e){var t=new jr(e.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[e])},e.prototype.int=function(e){var t=new jr(e.shape,"return float(int(x));"),n=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],n)},e.prototype.clip=function(e,t,n){var r=new function(e,t,n){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, float("+t+"), float("+n+")));\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.abs=function(e){var t=new jr(e.shape,"return abs(x);");return this.compileAndRun(t,[e])},e.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),n=new function(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float real = getRealAtOutCoords();\n float imag = getImagAtOutCoords();\n vec2 v = vec2(real, imag);\n\n setOutput(sqrt(dot(v, v)));\n }\n "}(e.shape),r=[this.makeComplexComponentTensorHandle(e,t.complexTensors.real),this.makeComplexComponentTensorHandle(e,t.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(e){var t=new jr(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},e.prototype.softplus=function(e){var t=new jr(e.shape,"\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");return this.compileAndRun(t,[e])},e.prototype.sin=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n return sin(x);\n");return this.compileAndRun(t,[e])},e.prototype.cos=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n return cos(x);\n");return this.compileAndRun(t,[e])},e.prototype.tan=function(e){var t=new jr(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},e.prototype.asin=function(e){var t=new jr(e.shape,"return asin(x);");return this.compileAndRun(t,[e])},e.prototype.acos=function(e){var t=new jr(e.shape,"return acos(x);");return this.compileAndRun(t,[e])},e.prototype.atan=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e])},e.prototype.atan2=function(e,t){var n=new en("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.sinh=function(e){var t=new jr(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.cosh=function(e){var t=new jr(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.tanh=function(e){var t=new jr(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},e.prototype.asinh=function(e){var t=new jr(e.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e])},e.prototype.acosh=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.atanh=function(e){var t=new jr(e.shape,"if (isNaN(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.erf=function(e){var t=new jr(e.shape,'\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 = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(t,[e])},e.prototype.step=function(e,t){var n=new jr(e.shape,function(e){return void 0===e&&(e=0),Lr+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(n,[e])},e.prototype.conv2dWithIm2Row=function(e,t,n){var r=n.filterWidth,a=n.filterHeight,i=n.inChannels,o=n.outWidth,s=n.outHeight,u=r*a*i,l=s*o,c=[u,l],f=e.squeeze([0]),p=t.reshape([u,-1]),h=new function(e,t,n){this.variableNames=["A"],this.outputShape=e;var r=n.filterWidth,a=n.inChannels,i=n.strideWidth,o=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,f=s.left,p=s.top,h=a*r;this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n int blockIndex = rc.y + col;\n int pos = rc.x + row;\n\n if(blockIndex >= "+e[1]+" || pos >= "+e[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+o+" - "+p+";\n int d0 = offsetY + "+c+" * (pos / "+h+");\n\n if(d0 >= "+t[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+f+".);\n int d1 = offsetX + "+l+" * (int(mod(float(pos), "+h+".) / "+a+".));\n\n if(d1 >= "+t[1]+" || d1 < 0) continue;\n\n result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+a+".)));\n }\n }\n\n gl_FragColor = result;\n }\n "}(c,f.shape,n),d=this.compileAndRun(h,[f],this.makePackedTensor(c)),m=new Sr(d.shape,p.shape,[l,n.outChannels],!0,!1),g=this.compileAndRun(m,[d,p],this.makePackedTensor(m.outputShape));return!1===ve.get("WEBGL_LAZILY_UNPACK")&&(g=this.unpackTensor(g)),g.reshape([1,s,o,n.outChannels])},e.prototype.conv2d=function(e,t,n){if(ve.get("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,t,n);var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,n=e.padInfo.left,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),c=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+a+");\n const ivec2 pads = ivec2("+t+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * 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 < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\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 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 dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - 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 float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left;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 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2D=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,n=e.inWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,o=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,f=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+r+", "+a+");\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 / "+f+";\n int q = d2 - d1 * "+f+";\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 // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\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 setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[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 // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var 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 // TODO: 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.maxPool=function(e,t){var n=new Ir(t,"max",!1),r=this.makeOutputArray(n.outputShape,e.dtype);return this.compileAndRun(n,[e],r)},e.prototype.avgPool=function(e,t){var n=new Ir(t,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e],r)},e.prototype.maxPoolBackprop=function(e,t,n,r){var a=new Ir(r,"max",!0),i=this.compileAndRun(a,[t]),o=new function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,a=e.effectiveFilterHeight,i=e.effectiveFilterWidth,o=a-1-e.padInfo.top,s=i-1-e.padInfo.left,u=a*i-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\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 "}(r),s=this.makeOutputArray(o.outputShape,t.dtype),u=this.compileAndRun(o,[e,i],s);return i.dispose(),u},e.prototype.avgPoolBackprop=function(e,t,n){var r=new function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=s-1-e.padInfo.top,c=u-1-e.padInfo.left,f=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+f+");\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 < "+s+";\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+= "+o+") {\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 "}(n),a=this.makeOutputArray(r.outputShape,t.dtype);return this.compileAndRun(r,[e],a)},e.prototype.cast=function(e,t){return Dt(e,t,this)},e.prototype.reshape=function(e,t){return this.texData.get(e.dataId).isPacked&&!er(e.shape,t)?this.packedReshape(e,t):jt(e,t)},e.prototype.resizeBilinear=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\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 "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-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), "+(i-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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.resizeNearestNeighbor=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.multinomial=function(e,t,n,r){var a=t?e:at(e),i=a.shape[0],o=a.shape[1],s=new Or(i,o,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],u,l)},e.prototype.oneHot=function(e,t,n,r){var a=new function(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 "}(e.size,t,n,r);return this.compileAndRun(a,[e])},e.prototype.nonMaxSuppression=function(e,t,n,r,a){return Te("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Vt(e.dataSync(),t.dataSync(),n,r,a)},e.prototype.cropAndResize=function(e,t,n,r,a,i){var o=new function(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=e[0],o=e[1],s=e[2],u=e[3],l=t[0],c=n[0],f=n[1];this.outputShape=[l,c,f,u];var p="bilinear"===r?1:0,h=[o-1+".0",s-1+".0"],d=h[0],m=h[1],g=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],E=w[2];this.userCode="\n const float height_ratio = float("+y+");\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 = "+v+";\n float width_scale = "+_+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "}(e.shape,t.shape,r,a,i);return this.compileAndRun(o,[e,t,n])},e.prototype.depthToSpace=function(e,t,n){b(t>1,"blockSize should be > 1 for depthToSpace, but was: "+t);var r=e.shape[0],a=("NHWC"===n?e.shape[1]:e.shape[2])*t,i=("NHWC"===n?e.shape[2]:e.shape[3])*t,o=("NHWC"===n?e.shape[3]:e.shape[1])/(t*t),s=new gn("NHWC"===n?[r,a,i,o]:[r,o,a,i],t,n);return this.compileAndRun(s,[e])},e.prototype.split=function(e,t,n){return Wt(e,t,n)},e.prototype.scatterND=function(e,t,n){var r=Ye(0,e,n),a=r.sliceRank,i=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=e.reshape([i,a]),f=t.reshape([i,o]);if(0===u)return jt(lt([]),n);var p=ct(0),h=new Cr(i,a,c.rank,f.rank,s,l);return this.compileAndRun(h,[f,c,p]).reshape(n)},e.prototype.sparseToDense=function(e,t,n,r){var a=Ye(0,e,n),i=a.sliceRank,o=a.numUpdates,s=a.strides,u=a.outputSize,l=new Cr(o,i,e.rank,t.rank,s,[u,1],!1);return this.compileAndRun(l,[t,e,r]).reshape(n)},e.prototype.fft=function(e){return this.fftImpl(e,!1)},e.prototype.ifft=function(e){return this.fftImpl(e,!0)},e.prototype.fftImpl=function(e,t){var n=this.texData.get(e.dataId),r=new yn("return real * expR - imag * expI;",e.shape,t),a=new yn("return real * expI + imag * expR;",e.shape,t),i=[this.makeComplexComponentTensorHandle(e,n.complexTensors.real),this.makeComplexComponentTensorHandle(e,n.complexTensors.imag)],o=this.compileAndRun(r,i),s=this.compileAndRun(a,i),u=this.complex(o,s).as2D(e.shape[0],e.shape[1]);return o.dispose(),s.dispose(),u},e.prototype.gatherND=function(e,t){var n=t.shape,r=n[n.length-1],a=He(e,t),i=a[0],o=a[1],s=a[2],u=a[3],l=t.reshape([o,r]),c=e.reshape([e.size/s,s]),f=new function(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;var r=cn(t.length),a=cn(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 "}(r,u,[o,s]);return this.compileAndRun(f,[c,l]).reshape(i)},e.prototype.makeOutputArray=function(e,t){return re.make(e,{},t)},e.prototype.makePackedTensor=function(e){var t=re.make(e,{});return this.texData.get(t.dataId).isPacked=!0,t},e.prototype.unpackTensor=function(e){var t=new Br(e.shape);return this.compileAndRun(t,[e])},e.prototype.getBatchDim=function(e,t){return void 0===t&&(t=2),E(e.slice(0,e.length-t))},e.prototype.getRowsCols=function(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]]},e.prototype.packedReshape=function(e,t){var n=e.reshape([this.getBatchDim(e.shape)].concat(this.getRowsCols(e.shape))),r=[this.getBatchDim(t)].concat(this.getRowsCols(t)),a=new function(e,t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=e;for(var n="",r=0;r<4;r++){var a="thisRC = rc;";r%2==1&&(a+="thisRC.z += 1;"),r>1&&(a+="thisRC.y += 1;"),n+="\n "+a+"\n "+(r>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["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+tn(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n \n "+function(e){return"\n int getFlatIndex(ivec3 coords) {\n return round("+function(e,t){if(e.length!==t.length)throw new Error("Vectors to be dotted must be of the same length -got "+e.length+" and "+t.length);for(var n=[],r=Math.floor(e.length/4),a=e.length%4,i=0;i "+t[0];for(var r="",a=e-2;a= "+t[a],a= "+t+";\n bool rEdge = rp1 >= "+n+";\n "}(t,e[e.length-1],e[e.length-2],n),o=function(e,t){var n=e.length,r=function(e,t){for(var n=[],r=0;r<=1;r++)for(var a=0;a<=1;a++){for(var i=(0===r?"r":"rp1")+", "+(0===a?"c":"cp1"),o=2;o= "+e[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(e,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+a+") {\n gl_FragColor = vec4(0);\n } else {\n "+i+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}(t.shape),a=i.compileAndRun(r,[t],i.makePackedTensor(t.shape))),n=i.texData.get(a.dataId),t=a}return i.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(e,t,n){var r="";o.concat(n).forEach(function(e){r+=e.shape+"_"+(e.isUniform?"uniform":e.texData.texShape)});var a=e.userCode,i=(!0===e.supportsBroadcasting).toString();return e.constructor.name+"_"+i+"_"+r+"_"+a}(e,0,u),c=this.getAndSaveBinary(l,function(){return function(e,t,n,r){for(var a=t.userCode,i=n.map(function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked};return{name:t.variableNames[n],shapeInfo:r}}),o=i.map(function(e){return e.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked},u=rn(i,s,a,!0===t.supportsBroadcasting,t.usesPackedTextures),l=e.createProgram(u),c={},f=0;fthis.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;p>0&&this.lruDataGPU.length>0;){var h=this.lruDataGPU.shift(),d=this.texData.get(h),m=d.shape,g=d.dtype;p-=this.computeBytes(m,g),this.read(h)}return f&&(s=this.endTimer(s),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(s)})),n},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.floatPrecision=function(){var e=this;return ke(function(){return e.abs(ct(1e-8)).get()>0?32:16})},e.prototype.uploadToGPU=function(e){var t=this.texData.get(e),n=t.shape,r=t.values,a=t.texture,i=t.dtype,o=t.usage,s=t.isPacked;if(null==a){var u,l=null!=this.activeTimers;l&&(u=performance.now());var c=Zn(n,s);t.texShape=c;var f=this.acquireTexture(e,c,o,s);if(t.texture=f,null!=r){if(s){var p=E(n.slice(0,n.length-2)),h=n.length>1?n[n.length-2]:1,d=n[n.length-1];this.gpgpu.uploadMatrixToPackedTexture(f,p,h,d,Ma(r,i))}else this.gpgpu.uploadMatrixToTexture(f,c[0],c[1],Ma(r,i));t.values=null,l&&(this.uploadWaitMs+=performance.now()-u)}}else ve.get("WEBGL_PAGING_ENABLED")&&this.lruDataGPU.indexOf(e)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),this.lruDataGPU.push(e))},e.prototype.convertAndCacheOnCPU=function(e,t){var n=this.delayedStorage,r=this.texData.get(e),a=r.texture,i=r.texShape,o=r.dtype,s=r.usage,u=r.isPacked;return n&&null!=a&&(this.releaseTexture(e,a,i,s,u),r.texture=null,r.texShape=null),r.usage=dn.UPLOAD,null!=t&&(r.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r=0&&this.lruDataGPU.splice(u,1)}this.numBytesInGPU-=this.computeBytes(o,s),this.textureManager.releaseTexture(t,n,r,a)},e.prototype.acquireTexture=function(e,t,n,r){var a=this.texData.get(e),i=a.shape,o=a.dtype;return ve.get("WEBGL_PAGING_ENABLED")&&this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(i,o),this.textureManager.acquireTexture(t,n,r)},e.prototype.computeBytes=function(e,t){return E(e)*L(t)},e}();function Ma(e,t){return e instanceof Float32Array?e:new Float32Array(e)}ve.get("IS_BROWSER")&&ve.registerBackend("webgl",function(){return new Ta},2,ne);var Ra=rt({abs_:function(e){var t=tt(e,"x","abs");return"complex64"===t.dtype?ve.engine.runKernel(function(e){return e.complexAbs(t)},{$x:t}):ve.engine.runKernel(function(e){return e.abs(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().step(-1))}}})}}),Da=rt({acos_:function(e){var t=tt(e,"x","acos");return ve.engine.runKernel(function(e){return e.acos(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(ct(1).sub(t.toFloat().square()).sqrt()).neg()}}})}}),ja=rt({acosh_:function(e){var t=tt(e,"x","acosh");return ve.engine.runKernel(function(e){return e.acosh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().square().sub(ct(1)).sqrt())}}})}}),La=rt({asin_:function(e){var t=tt(e,"x","asin");return ve.engine.runKernel(function(e){return e.asin(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(ct(1).sub(t.toFloat().square()).sqrt())}}})}}),Ba=rt({asinh_:function(e){var t=tt(e,"x","asinh");return ve.engine.runKernel(function(e){return e.asinh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(ct(1).add(t.toFloat().square()).sqrt())}}})}}),za=rt({atan_:function(e){var t=tt(e,"x","atan");return ve.engine.runKernel(function(e){return e.atan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(ct(1).add(t.toFloat().square()))}}})}}),Fa=rt({atanh_:function(e){var t=tt(e,"x","atanh");return ve.engine.runKernel(function(e){return e.atanh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(ct(1).sub(t.toFloat().square()))}}})}}),Va=rt({ceil_:function(e){var t=tt(e,"x","ceil");return ve.engine.runKernel(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return Ct(e)}}})}}),Ua=rt({clipByValue_:function(e,t,n){var r=tt(e,"x","clipByValue");return b(t<=n,"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."),ve.engine.runKernel(function(e){return e.clip(r,t,n)},{$x:r},function(e){return{$x:function(){return e.where(r.greaterEqual(ct(t)).logicalAnd(r.lessEqual(ct(n))),Ct(e))}}})}}),Wa=rt({cos_:function(e){var t=tt(e,"x","cos");return ve.engine.runKernel(function(e){return e.cos(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sin().neg().mulStrict(e)}}})}}),qa=rt({cosh_:function(e){var t=tt(e,"x","cosh");return ve.engine.runKernel(function(e){return e.cosh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sinh().mulStrict(e)}}})}}),$a=rt({erf_:function(e){var t=tt(e,"x","erf");return b("int32"===t.dtype||"float32"===t.dtype,"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=t.toFloat()),ve.engine.runKernel(function(e){return e.erf(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(ct(2/Math.sqrt(Math.PI)).mul(t.square().neg().exp()))}}})}}),Ga=rt({exp_:function(e){var t=tt(e,"x","exp");return ve.engine.runKernel(function(e,n){return n(e.exp(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n)}}})}}),Ha=rt({expm1_:function(e){var t=tt(e,"x","expm1");return ve.engine.runKernel(function(e){return e.expm1(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.exp())}}})}}),Ka=rt({floor_:function(e){var t=tt(e,"x","floor");return ve.engine.runKernel(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return Ct(e)}}})}}),Xa=rt({log_:function(e){var t=tt(e,"x","log");return ve.engine.runKernel(function(e){return e.log(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat())}}})}}),Ya=rt({log1p_:function(e){var t=tt(e,"x","log1p");return ve.engine.runKernel(function(e){return e.log1p(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.add(ct(1)))}}})}}),Ja=rt({logSigmoid_:function(e){var t=tt(e,"x","logSigmoid");return ve.engine.runKernel(function(e){return e.softplus(t.neg()).neg()},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.neg().sigmoid())}}})}}),Za=rt({neg_:function(e){var t=tt(e,"x","neg");return ve.engine.runKernel(function(e){return e.neg(t)},{$x:t},function(e){return{$x:function(){return e.neg()}}})}}),Qa=rt({reciprocal_:function(e){var t=tt(e,"x","reciprocal");return ve.engine.runKernel(function(e){return e.reciprocal(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.square().neg())}}})}}),ei=rt({round_:function(e){var t=tt(e,"x","round");return ve.engine.runKernel(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return Ct(e)}}})}}),ti=rt({rsqrt_:function(e){var t=tt(e,"x","rsqrt");return ve.engine.runKernel(function(e){return e.rsqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.pow(ct(1.5)).mul(ct(2))).neg()}}})}}),ni=rt({sigmoid_:function(e){var t=tt(e,"x","sigmoid");return ve.engine.runKernel(function(e,n){return n(e.sigmoid(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n.mul(ct(1).sub(n)))}}})}}),ri=rt({sign_:function(e){var t=tt(e,"x","sign");return ve.engine.runKernel(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return Ct(e)}}})}}),ai=rt({sin_:function(e){var t=tt(e,"x","sin");return ve.engine.runKernel(function(e){return e.sin(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cos().mulStrict(e)}}})}}),ii=rt({sinh_:function(e){var t=tt(e,"x","sinh");return ve.engine.runKernel(function(e){return e.sinh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cosh().mulStrict(e)}}})}}),oi=rt({softplus_:function(e){var t=tt(e,"x","softplus");return ve.engine.runKernel(function(e){return e.softplus(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.sigmoid())}}})}}),si=rt({sqrt_:function(e){var t=tt(e,"x","sqrt");return ve.engine.runKernel(function(e){return e.sqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().sqrt().mul(ct(2)))}}})}}),ui=rt({square_:function(e){var t=tt(e,"x","square");return ve.engine.runKernel(function(e){return e.square(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().mul(ct(2)))}}})}}),li=rt({step_:function(e,t){void 0===t&&(t=0);var n=tt(e,"x","step");return ve.engine.runKernel(function(e){return e.step(n,t)},{$x:n},function(e){return{$x:function(){return Ct(e)}}})}}),ci=rt({tan_:function(e){var t=tt(e,"x","tan");return ve.engine.runKernel(function(e){return e.tan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.cos().square())}}})}}),fi=rt({tanh_:function(e){var t=tt(e,"x","tanh");return ve.engine.runKernel(function(e,n){return n(e.tanh(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return ct(1).sub(n.square()).mulStrict(e)}}})}});function pi(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}var hi=rt({batchNormalization2d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=tt(e,"x","batchNormalization"),l=tt(t,"mean","batchNormalization"),c=tt(n,"variance","batchNormalization");return null!=a&&(o=tt(a,"scale","batchNormalization")),null!=i&&(s=tt(i,"offset","batchNormalization")),b(2===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),b(2===l.rank||1===l.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."),b(2===c.rank||1===c.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."),null!=o&&b(2===o.rank||1===o.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."),null!=s&&b(2===s.rank||1===s.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."),gi(u,l,c,r,o,s)}}),di=rt({batchNormalization3d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=tt(e,"x","batchNormalization"),l=tt(t,"mean","batchNormalization"),c=tt(n,"variance","batchNormalization");return null!=a&&(o=tt(a,"scale","batchNormalization")),null!=i&&(s=tt(i,"offset","batchNormalization")),b(3===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),b(3===l.rank||1===l.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."),b(3===c.rank||1===c.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."),null!=o&&b(3===o.rank||1===o.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."),null!=s&&b(3===s.rank||1===s.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."),gi(u,l,c,r,o,s)}}),mi=rt({batchNormalization4d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=tt(e,"x","batchNormalization"),l=tt(t,"mean","batchNormalization"),c=tt(n,"variance","batchNormalization");return null!=a&&(o=tt(a,"scale","batchNormalization")),null!=i&&(s=tt(i,"offset","batchNormalization")),b(4===u.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+u.rank+"."),b(4===l.rank||1===l.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."),b(4===c.rank||1===c.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."),null!=o&&b(4===o.rank||1===o.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."),null!=s&&b(4===s.rank||1===s.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."),gi(u,l,c,r,o,s)}}),gi=rt({batchNormalization_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u,l=tt(e,"x","batchNormalization"),c=tt(t,"mean","batchNormalization"),f=tt(n,"variance","batchNormalization");return null!=a&&(o=tt(a,"scale","batchNormalization")),null!=i&&(s=tt(i,"offset","batchNormalization")),b(c.rank===f.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),b(null==s||c.rank===s.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),b(null==o||c.rank===o.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,ve.engine.runKernel(function(e){return e.batchNormalization(u,pi(c),pi(f),r,pi(o),pi(s))},{$x:l,$mean:c,$variance:f,$scale:o,$offset:s},function(e){var t=null==o?ct(1):o,n=Gt(c.shape,u.shape),a=[];if(1===c.rank){for(var i=0;i=2&&i.rank>=2&&a.rank===i.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."),b(N(c,f),"Error in matMul: outer dimensions ("+c+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."),b(o===s,"Error in matMul: inner shapes ("+o+") and ("+s+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match.");var d=a.shape.slice(0,-2).concat([u,l]),m=n?a.as3D(p,o,u):a.as3D(p,u,o),g=r?i.as3D(h,l,s):i.as3D(h,s,l);return ve.engine.runKernel(function(e){return e.batchMatMul(m,g,n,r)},{$a:m,$b:g},function(e){return n||r?!n&&r?{$a:function(){return e.matMul(g.toFloat(),!1,!1)},$b:function(){return e.matMul(m.toFloat(),!0,!1)}}:n&&!r?{$a:function(){return g.toFloat().matMul(e,!1,!0)},$b:function(){return m.toFloat().matMul(e,!1,!1)}}:{$a:function(){return g.toFloat().matMul(e,!0,!0)},$b:function(){return e.matMul(m.toFloat(),!0,!0)}}:{$a:function(){return e.matMul(g.toFloat(),!1,!0)},$b:function(){return m.toFloat().matMul(e,!0,!1)}}}).reshape(d)}}),Si=rt({dot_:function(e,t){var n=tt(e,"t1","dot"),r=tt(t,"t2","dot");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+".");var a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return b(a===i,"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+i+"."),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Oi=rt({outerProduct_:function(e,t){var n=tt(e,"v1","outerProduct"),r=tt(t,"v2","outerProduct");return b(1===n.rank&&1===r.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."),n.as2D(-1,1).matMul(r.as2D(1,-1))}});function ki(e,t,n,r,a,i){b(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var o=e,s=t,u=!1;3===t.rank&&(u=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),o=[1,e[0],e[1],e[2]]);var l=o[3],c=s.shape[3];b(4===o.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+o.length+"."),b(4===s.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank),b(4===n.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank),b(l===n.shape[2],"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."),b(c===n.shape[3],"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[3]+"."),null!=i&&b(S(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var f=vi(o,n.shape,r,1,a,i),p=ve.engine.runKernel(function(e){return e.conv2dDerInput(s,n,f)},{dy4D:s,filter:n},function(e){return{dy4D:function(){return Pi(e,n,r,a,"NHWC",1,i)},filter:function(){return Ai(e,s,n.shape,r,a,i)}}});return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function Ii(e,t,n,r,a,i){var o=e;3===e.rank&&(o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t;3===s.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),b(4===o.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+o.shape+"."),b(4===s.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."),b(4===n.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."),b(o.shape[3]===n[2],"Error in conv2dDerFilter: depth of input "+o.shape[3]+") must match input depth in filter ("+n[2]+"."),b(s.shape[3]===n[3],"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+n[3]+")."),null!=i&&b(S(a),"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var u=vi(o.shape,n,r,1,a,i);return ve.engine.runKernel(function(e){return e.conv2dDerFilter(o,s,u)},{x4D:o,dy4D:s})}var Ci=rt({conv1d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NWC"),void 0===i&&(i=1);var s=tt(e,"x","conv1d"),u=tt(t,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),b(3===l.rank,"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."),b(3===u.rank,"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."),null!=o&&b(S(r),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),b(l.shape[2]===u.shape[1],"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."),b(Ei(n,i),"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"),b("NWC"===a,"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported.");var f=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),p=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),h=Pi(p,f,[1,n],r,"NHWC",[1,i],o);return c?h.as2D(h.shape[2],h.shape[3]):h.as3D(h.shape[0],h.shape[2],h.shape[3])}}),Pi=rt({conv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=tt(e,"x","conv2d"),u=tt(t,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===l.rank,"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."),b(4===u.rank,"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."),null!=o&&b(S(r),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),b(l.shape[3]===u.shape[2],"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+"."),b(Ei(n,i),"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),b("NHWC"===a,"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported.");var f,p=vi(l.shape,u.shape,n,i,r,o);if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)f=ve.engine.runKernel(function(e){return e.conv2d(l,u,p)},{x:l,$filter:u},function(e){return b(_i(i),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+i+"'"),{x:function(){return ki(l.shape,e,u,n,r)},$filter:function(){return Ii(l,e,u.shape,n,r)}}});else{var h=l.reshape([-1,p.inChannels]),d=u.reshape([p.inChannels,p.outChannels]);f=Ni(h,d).reshape(p.outShape)}return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),Ai=rt({conv2dDerFilter_:Ii}),Ti=rt({depthwiseConv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=tt(e,"x","depthwiseConv2d"),u=tt(t,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===l.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."),b(4===u.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),b(l.shape[3]===u.shape[2],"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."),null==i&&(i=[1,1]),b(Ei(n,i),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),null!=o&&b(S(r),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+".");var f=vi(l.shape,u.shape,n,i,r,o,!0),p=ve.engine.runKernel(function(e){return e.depthwiseConv2D(l,u,f)},{x:l,$filter:u},function(e){return b(_i(i),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"),{x:function(){return function(e,t,n,r){var a=t,i=!1;3===t.rank&&(i=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=ve.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,n,r)},{dy4D:a});return i?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}(l.shape,e,u,f)},$filter:function(){return function(e,t,n,r){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=t;return 3===i.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),ve.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,i,r)},{x4D:a,dy4D:i})}(l,e,u.shape,f)}}});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),Mi=rt({separableConv2d_:function(e,t,n,r,a,i,o){void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC");var s=tt(e,"x","separableConv2d"),u=tt(t,"depthwiseFilter","separableConv2d"),l=tt(n,"pointwiseFilter","separableConv2d"),c=s,f=!1;if(3===s.rank&&(f=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");b(4===c.rank,"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."),b(4===u.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."),b(4===l.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."),b(1===l.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."),b(1===l.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+".");var p=u.shape[2],h=u.shape[3];b(l.shape[2]===p*h,"Error in separableConv2d: the third dimension of pointwise filter must be "+p*h+", but got "+l.shape[2]+".");var d=Ti(c,u,r,a,o,i),m=Pi(d,l,1,"valid",o);return f?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Ri=rt({conv2dTranspose_:function(e,t,n,r,a,i){return ki(n,tt(e,"x","conv2dTranspose"),tt(t,"filter","conv2dTranspose"),r,a,i)}}),Di=rt({reverse_:function(e,t){var n=tt(e,"x","reverse");if(0===n.rank)return n.clone();var r=Ve(t,n.shape);return ve.engine.runKernel(function(e){return e.reverse(n,r)},{$x:n},function(e){return{$x:function(){return e.reverse(r)}}}).reshapeAs(n)}}),ji=rt({reverse1d_:function(e){var t=tt(e,"x","reverse");return b(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),Di(t,0)}}),Li=rt({reverse2d_:function(e,t){var n=tt(e,"x","reverse");return b(2===n.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+n.rank+"."),Di(n,t)}}),Bi=rt({reverse3d_:function(e,t){var n=tt(e,"x","reverse");return b(3===n.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+n.rank+"."),Di(n,t)}}),zi=rt({reverse4d_:function(e,t){var n=tt(e,"x","reverse");return b(4===n.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+n.rank+"."),Di(n,t)}});function Fi(e,t,n,r,a,i){var o=tt(e,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),null==r&&(r=[1,1]),b(4===s.rank,"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."),b(Ei(n,r),"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"),null!=i&&b(S(a),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var l=yi(s.shape,t,n,r,a,i),c=ve.engine.runKernel(function(e,t){return t(e.maxPool(s,l))},{x:s},function(e,i){var o=i[0];return{x:function(){return function(e,t,n,r,a,i,o,s){var u=tt(e,"dy","maxPoolBackprop"),l=tt(t,"input","maxPoolBackprop"),c=tt(n,"output","maxPoolBackprop");b(l.rank===u.rank,"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"),null==i&&(i=[1,1]),b(Ei(a,i),"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"),b(4===u.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),b(4===l.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+".");var f=yi(l.shape,r,a,i,o,s);return ve.engine.runKernel(function(e){return e.maxPoolBackprop(u,l,c,f)},{$dy:u,$input:l})}(e,s,o,t,n,r,a)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function Vi(e,t,n,r,a,i){var o=tt(e,"x","avgPool");b("float32"===o.dtype,"The input dtype to avgPool must be float32"),null==r&&(r=[1,1]),b(Ei(n,r),"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'");var s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),b(4===s.rank,"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."),null!=i&&b(S(a),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var l=yi(s.shape,t,n,r,a),c=ve.engine.runKernel(function(e){return e.avgPool(s,l)},{x:s},function(e){return{x:function(){return function(e,t,n,r,a,i){var o=tt(e,"dy","avgPoolBackprop"),s=tt(t,"input","avgPoolBackprop");b(s.rank===o.rank,"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"),null==a&&(a=[1,1]),b(Ei(r,a),"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'");var u=s,l=o,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),b(4===l.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."),b(4===u.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+".");var f=yi(u.shape,n,r,a,i),p=ve.engine.runKernel(function(e){return e.avgPoolBackprop(l,u,f)},{dy4D:l,input4D:u});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(e,s,t,n,r,a)}}});return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Ui=rt({maxPool_:function(e,t,n,r,a){return Fi(e,t,n,1,r,a)}}),Wi=rt({avgPool_:function(e,t,n,r,a){return Vi(e,t,n,1,r,a)}}),qi=rt({pool_:function(e,t,n,r,a,i){null==a&&(a=[1,1]),null==i&&(i=1),0===r&&(r="valid");var o=tt(e,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),b(Ei(i,a),"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'");var l,c=yi(s.shape,t,i,a,r),f=[c.dilationHeight,c.dilationWidth];l="same"===r?function(e,t){var n=e.map(function(e,n){return e+(e-1)*(t[n]-1)}).map(function(e){return e-1}),r=n.map(function(e){return Math.floor(e/2)}),a=n.map(function(e,t){return e-r[t]});return n.map(function(e,t){return[r[t],a[t]]})}([c.filterHeight,c.filterWidth],f):[[0,0],[0,0]];var p=1===f[0]&&1===f[1],h=function(e,t,n){var r=n.map(function(e){return e[0]}),a=n.map(function(e){return e[1]}),i=e.concat(r,a),o=t.map(function(e,t){return(e-i[t]%e)%e}),s=a.map(function(e,t){return e+o[t]});return[t.map(function(e,t){return[r[t],s[t]]}),t.map(function(e,t){return[0,o[t]]})]}([c.inHeight,c.inWidth],f,l),d=h[0],m=h[1],g=p?r:"valid",y=p?s:Ea(s,f,d),v=("avg"===n?function(){return Vi(y,t,i,1,g)}:function(){return Fi(y,t,i,1,g)})(),w=p?v:aa(v,f,m);return u?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}}),$i=rt({slice_:function(e,t,n){var r,a,i=tt(e,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof t?[t].concat(new Array(i.rank-1).fill(0)):t.length=0?e:(b(-1===e,"Bad value in size"),i.shape[t]-r[t])}),function(e,t,n){b(e.rank===t.length,"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."),b(e.rank===n.length,"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+").");for(var r=0;r0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Gt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)}}})}}),_o=rt({addN_:function(e){b(Array.isArray(e),function(){return"The argument passed to tf.addN() must be a list of tensors"}),b(e.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length});var t=e.map(function(e,t){return tt(e,"tensors"+t,"addN")}),n=t[0];t.forEach(function(e){if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(e){if(!N(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=t;return ve.engine.runKernel(function(e){return e.addN(t)},r,function(e){var n={};return t.forEach(function(t,r){n[r]=function(){return e.clone()}}),n})}}),Eo=rt({addStrict_:function(e,t){return w(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),No=rt({atan2_:function(e,t){var n=tt(e,"a","atan2"),r=tt(t,"b","atan2");oe(n,r);var a=Ht(n.shape,r.shape);return ve.engine.runKernel(function(e){return e.atan2(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=xo(n.square(),r.square()),i=e.mul(r.div(t)),o=Gt(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=xo(n.square(),r.square()),i=Za(e.mul(n.div(t))),o=Gt(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),So=rt({div_:function(e,t){var n,r=tt(e,"a","div"),a=tt(t,"b","div");if(oe(r,a),"int32"===r.dtype&&"int32"===a.dtype)return ko(r,a);n=function(e){return e.realDivide(r,a)};var i=Ht(r.shape,a.shape);return ve.engine.runKernel(n,{$a:r,$b:a},function(e){return{$a:function(){var t=e.div(a.toFloat()),n=Gt(r.shape,i);return n.length>0?t.sum(n).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),n=Gt(a.shape,i);n.length>0&&(t=t.sum(n).reshape(a.shape));var o=a.square();return t.div(o.toFloat()).neg()}}})}}),Oo=rt({divStrict_:function(e,t){return w(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),ko=rt({floorDiv_:function(e,t){var n=tt(e,"a","floorDiv"),r=tt(t,"b","floorDiv");oe(n,r);var a=Ht(n.shape,r.shape);return ve.engine.runKernel(function(e){return e.floorDiv(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.div(r.toFloat()),i=Gt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Gt(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}})}}),Io=rt({maximum_:function(e,t){var n=tt(e,"a","maximum"),r=tt(t,"b","maximum");return oe(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Ht(n.shape,r.shape),ve.engine.runKernel(function(e){return e.maximum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.greaterEqual(r).toFloat())},$b:function(){return e.mul(n.less(r).toFloat())}}})}}),Co=rt({maximumStrict_:function(e,t){return w(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),Po=rt({minimum_:function(e,t){var n=tt(e,"a","minimum"),r=tt(t,"b","minimum");return oe(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Ht(n.shape,r.shape),ve.engine.runKernel(function(e){return e.minimum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.lessEqual(r).toFloat())},$b:function(){return e.mul(n.greater(r).toFloat())}}})}}),Ao=rt({minimumStrict_:function(e,t){return w(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),To=rt({mod_:function(e,t){var n=tt(e,"a","mod"),r=tt(t,"b","mod");oe(n,r);var a=Ht(n.shape,r.shape);return ve.engine.runKernel(function(e){return e.mod(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=Gt(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=Gt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),Mo=rt({modStrict_:function(e,t){return w(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),Ro=rt({mul_:function(e,t){var n=tt(e,"a","mul"),r=tt(t,"b","mul");oe(n,r);var a=Ht(n.shape,r.shape);return ve.engine.runKernel(function(e){return e.multiply(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.mul(r.toFloat()),i=Gt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Gt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),Do=rt({mulStrict_:function(e,t){return w(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),jo=rt({pow_:function(e,t){var n=tt(e,"base","pow"),r=tt(t,"exp","pow"),a=Ht(n.shape,r.shape);return e=n.cast(At(n.dtype,r.dtype)),t=r.cast(At(n.dtype,r.dtype)),ve.engine.runKernel(function(e,t){return t(e.pow(n,r))},{$base:n,$exp:r},function(e,t){var i=t[0];return{$base:function(){var t=r.toFloat(),i=e.mul(t.mul(n.pow(t.sub(ct(1))))),o=Gt(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$exp:function(){var t=e.mul(i.mul(n.log()).toFloat()),o=Gt(r.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(r.shape)}}})}}),Lo=rt({powStrict_:function(e,t){return w(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),Bo=rt({squaredDifference_:function(e,t){var n=tt(e,"a","squaredDifference"),r=tt(t,"b","squaredDifference");return oe(n,r),Ht(n.shape,r.shape),ve.engine.runKernel(function(e){return e.squaredDifference(n,r)},{$a:n,$b:r},function(e){var t=ct(2);return{$a:function(){return e.mul(n.sub(r).mul(t))},$b:function(){return e.mul(r.sub(n).mul(t))}}})}}),zo=rt({squaredDifferenceStrict_:function(e,t){return w(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),Fo=rt({sub_:function(e,t){var n=tt(e,"a","sub"),r=tt(t,"b","sub");oe(n,r);var a=Ht(n.shape,r.shape);return ve.engine.runKernel(function(e){return e.subtract(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e,r=Gt(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Gt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(r.shape)}}})}}),Vo=rt({subStrict_:function(e,t){return w(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),Uo=rt({logicalAnd_:function(e,t){var n=tt(e,"a","logicalAnd","bool"),r=tt(t,"b","logicalAnd","bool");return b("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Ht(n.shape,r.shape),ve.engine.runKernel(function(e){return e.logicalAnd(n,r)},{$a:n,$b:r})}}),Wo=rt({logicalNot_:function(e){var t=tt(e,"x","logicalNot","bool");return b("bool"===t.dtype,"Error Array must be of type bool."),ve.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})}}),qo=rt({logicalOr_:function(e,t){var n=tt(e,"a","logicalOr","bool"),r=tt(t,"b","logicalOr","bool");return b("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Ht(n.shape,r.shape),ve.engine.runKernel(function(e){return e.logicalOr(n,r)},{$a:n,$b:r})}}),$o=rt({logicalXor_:function(e,t){var n=tt(e,"a","logicalXor","bool"),r=tt(t,"b","logicalXor","bool");return b("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Ht(n.shape,r.shape),qo(e,t).logicalAnd(Uo(e,t).logicalNot())}}),Go=rt({where_:function(e,t,n){var r=tt(t,"a","where"),a=tt(n,"b","where"),i=tt(e,"condition","where","bool");return b("bool"===i.dtype,"Error Condition must be of type bool."),w(r.shape,a.shape,"Error in where: "),1===i.rank?b(i.shape[0]===r.shape[0],"The first dimension of `a` must match the size of `condition`."):w(i.shape,a.shape,"Error in where: "),ve.engine.runKernel(function(e){return e.select(i,r,a)},{$condition:i,$a:r,$b:a},function(e){return{$condition:function(){return Ct(i)},$a:function(){return e.mul(i.cast(r.dtype))},$b:function(){return e.mul(i.logicalNot().cast(a.dtype))}}})}}),Ho=function(e){return l(this,void 0,void 0,function(){var t,n,r;return c(this,function(a){switch(a.label){case 0:return b("bool"===(t=tt(e,"condition","where","bool")).dtype,"Condition must be of type bool."),[4,t.data()];case 1:return n=a.sent(),r=Pa(t.shape,n),e!==t&&t.dispose(),[2,r]}})})},Ko=rt({elu_:function(e){var t=tt(e,"x","elu");return ve.engine.runKernel(function(e,n){return n(e.elu(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return ve.engine.runKernel(function(t){return t.eluDer(e,n)},{dy:e,y:n})}}})}}),Xo=rt({leakyRelu_:function(e,t){void 0===t&&(t=.2);var n=tt(e,"x","leakyRelu");return Io(ct(t).mul(n),n)}}),Yo=rt({prelu_:function(e,t){var n=tt(e,"x","prelu"),r=tt(t,"alpha","prelu"),a=ct(0);return Io(a,n).add(r.mul(Po(a,n)))}}),Jo=rt({relu_:function(e){var t=tt(e,"x","relu");return"bool"===t.dtype?t.toInt():ve.engine.runKernel(function(e){return e.relu(t)},{$x:t},function(e){var n=t.step();return{$x:function(){return e.mulStrict(n.toFloat())}}})}}),Zo=rt({selu_:function(e){var t=tt(e,"x","selu");return ve.engine.runKernel(function(e){return e.selu(t)},{$x:t},function(e){return{$x:function(){var n=t.greater(ct(0)),r=ct(Rr),a=ct(Dr),i=e.mul(a),o=e.mul(r).mul(t.toFloat().exp());return Go(n,i,o)}}})}}),Qo=rt({transpose_:function(e,t){var n=tt(e,"x","transpose");return null==t&&(t=n.shape.map(function(e,t){return t}).reverse()),b(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of perm "+t+"."),t.forEach(function(e){b(e>=0&&ea)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+t);var i=ve.engine.runKernel(function(e){return e.topk(r,t,n)},{$x:r});return{values:i[0],indices:i[1]}}}),ps=rt({scatterND_:function(e,t,n){var r=tt(e,"indices","scatterND","int32"),a=tt(t,"updates","scatterND");return function(e,t,n){if(t.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==t.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===t.size)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(0===e.size)throw new Error("Updates specified for empty output. updates shape: "+e.shape)}!function(e,t,n){var 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.rank2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+e.shape+".");var 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+".");var o=t.size;if(0!==t.rank&&(1!==t.rank||o!==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,o),ve.engine.runKernel(function(e){return e.sparseToDense(a,i,n,o)},{$sparseIndices:a,$sparseValues:i,$defaultValue:o})}}),vs=rt({gatherND_:function(e,t){var n=tt(t,"indices","gatherND","int32"),r=tt(e,"x","gatherND");return ve.engine.runKernel(function(e){return e.gatherND(r,n)},{$x:r,$indices:n})}});!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"}(as||(as={}));var bs=rt({absoluteDifference_:function(e,t,n,r){void 0===r&&(r=as.SUM_BY_NONZERO_WEIGHTS);var a=tt(e,"labels","absoluteDifference"),i=tt(t,"predictions","absoluteDifference"),o=null;null!=n&&(o=tt(n,"weights","absoluteDifference")),w(a.shape,i.shape,"Error in absoluteDifference: ");var s=a.sub(i).abs();return ws(s,o,r)}}),ws=rt({computeWeightedLoss_:function(e,t,n){void 0===n&&(n=as.SUM_BY_NONZERO_WEIGHTS);var r=tt(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=tt(t,"weights","computeWeightedLoss"));var i=null==a?r:r.mul(a);if(n===as.NONE)return i;if(n===as.SUM)return i.sum();if(n===as.MEAN){if(null==a)return i.mean();var o=E(r.shape)/E(a.shape),s=i.sum().div(a.sum());return o>1?s.div(ct(o)):s}if(n===as.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(ct(r.size));var u=a.mul(yt(r.shape)).notEqual(ct(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),xs=rt({cosineDistance_:function(e,t,n,r,a){void 0===a&&(a=as.SUM_BY_NONZERO_WEIGHTS);var i=tt(e,"labels","cosineDistance"),o=tt(t,"predictions","cosineDistance"),s=null;null!=r&&(s=tt(r,"weights","cosineDistance")),w(i.shape,o.shape,"Error in cosineDistance: ");var u=ct(1).sub(i.mul(o).sum(n,!0));return ws(u,s,a)}}),_s=rt({hingeLoss_:function(e,t,n,r){void 0===r&&(r=as.SUM_BY_NONZERO_WEIGHTS);var a=tt(e,"labels","hingeLoss"),i=tt(t,"predictions","hingeLoss"),o=null;null!=n&&(o=tt(n,"weights","hingeLoss")),w(a.shape,i.shape,"Error in hingeLoss: ");var s=ct(1);a=ct(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return ws(u,o,r)}}),Es=rt({huberLoss_:function(e,t,n,r,a){void 0===r&&(r=1),void 0===a&&(a=as.SUM_BY_NONZERO_WEIGHTS);var i=tt(e,"labels","huberLoss"),o=tt(t,"predictions","huberLoss"),s=null;null!=n&&(s=tt(n,"weights","huberLoss")),w(i.shape,o.shape,"Error in huberLoss: ");var u=ct(r),l=o.sub(i).abs(),c=Po(l,u),f=l.sub(c),p=ct(.5).mul(c.square()).add(u.mul(f));return ws(p,s,a)}}),Ns=rt({logLoss_:function(e,t,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=as.SUM_BY_NONZERO_WEIGHTS);var i=tt(e,"labels","logLoss"),o=tt(t,"predictions","logLoss"),s=null;null!=n&&(s=tt(n,"weights","logLoss")),w(i.shape,o.shape,"Error in logLoss: ");var u=ct(1),l=ct(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return ws(c,s,a)}}),Ss=rt({meanSquaredError_:function(e,t,n,r){void 0===r&&(r=as.SUM_BY_NONZERO_WEIGHTS);var a=tt(e,"labels","meanSquaredError"),i=tt(t,"predictions","meanSquaredError"),o=null;null!=n&&(o=tt(n,"weights","meanSquaredError")),w(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return ws(s,o,r)}}),Os=rt({sigmoidCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=as.SUM_BY_NONZERO_WEIGHTS);var i=tt(e,"multiClassLabels","sigmoidCrossEntropy"),o=tt(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=tt(n,"weights","sigmoidCrossEntropy")),w(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=ct(r),l=ct(1),c=ct(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var f=function(e,t){var n=tt(e,"labels","sigmoidCrossEntropyWithLogits"),r=tt(t,"logits","sigmoidCrossEntropyWithLogits");w(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),i=r.mul(n),o=r.abs().neg().exp().log1p();return a.sub(i).add(o)}(i,o);return ws(f,s,a)}}),ks=rt({softmaxCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=as.SUM_BY_NONZERO_WEIGHTS);var i=tt(e,"onehotLabels","softmaxCrossEntropy"),o=tt(t,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=tt(n,"weights","softmaxCrossEntropy")),w(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=ct(r),l=ct(1),c=ct(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var f=function(e,t,n){if(void 0===n&&(n=-1),-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);return Se(function(e,t){var r=t.logSumExp([n],!0),a=t.toFloat().sub(r);return{value:a.mul(e).neg().sum([n]),gradFunc:function(t){var r=Fe(t.shape,[n]);return[t.reshape(r).mul(e.toFloat().sub(a.exp())),t.reshape(r).mul(a.exp().sub(e.toFloat()))]}}})(e,t)}(i,o);return ws(f,s,a)}}),Is=Object.freeze({get Reduction(){return as},absoluteDifference:bs,computeWeightedLoss:ws,cosineDistance:xs,hingeLoss:_s,huberLoss:Es,logLoss:Ns,meanSquaredError:Ss,sigmoidCrossEntropy:Os,softmaxCrossEntropy:ks});function Cs(e,t){return void 0===t&&(t=!1),ve.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var n=e.shape[0],r=e.shape[1],a=ca(n),i=e.clone(),o=pt([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(e){var t,u=i,l=s,c=a;t=ve.engine.tidy(function(){var t=i.slice([e,e],[n-e,1]),u=t.norm(),l=i.slice([e,e],[1,1]),c=l.sign().neg(),f=l.sub(c.mul(u)),p=t.div(f);s=1===p.shape[0]?o.clone():o.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var h=c.matMul(f).div(u).neg(),d=i.slice([e,0],[n-e,r]),m=h.mul(s);i=0===e?d.sub(m.matMul(s.transpose().matMul(d))):i.slice([0,0],[e,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=a.slice([0,e],[n,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[n,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,i,a]}),s=t[0],i=t[1],a=t[2],Ce([u,l,c])},c=0;cr&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]})}var Ps=rt({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,b(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var n=e[0].shape[0],r=1;r0)for(var n=0;n= 2, but got rank "+e.rank);if(2===e.rank)return Cs(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),r=[],a=[];return Ia(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var n=Cs(e,t),i=n[0],o=n[1];r.push(i),a.push(o)}),[Sa(r,0).reshape(e.shape),Sa(a,0).reshape(e.shape)]}}),Ts=Object.freeze({gramSchmidt:Ps,qr:As});function Ms(e,t,n,r,a){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY);var i=e.shape[0];return n=Math.min(n,i),b(0<=r&&r<=1,"iouThreshold must be in [0, 1], but was '"+r+"'"),b(2===e.rank,"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"),b(4===e.shape[1],"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),b(1===t.rank,"scores must be a 1D tensor"),b(t.shape[0]===i,"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a}}var Rs=rt({resizeBilinear_:function(e,t,n){void 0===n&&(n=!1);var r=tt(e,"images","resizeBilinear");b(3===r.rank||4===r.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."),b(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=ve.engine.runKernel(function(e,t){return e.resizeBilinear(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return ve.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ds=rt({resizeNearestNeighbor_:function(e,t,n){void 0===n&&(n=!1);var r=tt(e,"images","resizeNearestNeighbor");b(3===r.rank||4===r.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."),b(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),b("float32"===r.dtype||"int32"===r.dtype,"`images` must have `int32` or `float32` as dtype");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=ve.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return ve.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),js=rt({nonMaxSuppression_:function(e,t,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=tt(e,"boxes","nonMaxSuppression"),o=tt(t,"scores","nonMaxSuppression"),s=Ms(i,o,n,r,a);return n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,ve.engine.runKernel(function(e){return e.nonMaxSuppression(i,o,n,r,a)},{$boxes:i})}}),Ls=Object.freeze({resizeBilinear:Rs,resizeNearestNeighbor:Ds,nonMaxSuppression:js,nonMaxSuppressionAsync:function(e,t,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),l(this,void 0,void 0,function(){var i,o,s,u,l,f;return c(this,function(c){switch(c.label){case 0:return i=tt(e,"boxes","nonMaxSuppressionAsync"),o=tt(t,"scores","nonMaxSuppressionAsync"),s=Ms(i,o,n,r,a),n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,[4,i.data()];case 1:return u=c.sent(),[4,o.data()];case 2:return l=c.sent(),f=Vt(u,l,n,r,a),i!==e&&i.dispose(),o!==t&&o.dispose(),[2,f]}})})},cropAndResize:function(e,t,n,r,a,i){var o=tt(e,"image","cropAndResize","float32"),s=tt(t,"boxes","cropAndResize","float32"),u=tt(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return b(4===o.rank,"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."),b(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."),b(1===u.rank&&u.shape[0]===l,"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."),b("int32"===u.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+u.dtype+"."),b(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),b(r[0]>=1&&r[1]>=1,"cropSize must be atleast [1,1], but was "+r),b("bilinear"===a||"nearest"===a,"method must be bilinear or nearest, but was "+a),ve.engine.runKernel(function(e,t){return e.cropAndResize(o,s,u,r,a,i)},{$image:o,$boxes:s})}}),Bs=Object.freeze({image:Ls,linalg:Ts,losses:Is,spectral:gs,op:rt,batchNormalization2d:hi,batchNormalization3d:di,batchNormalization4d:mi,batchNormalization:gi,complex:ot,real:st,imag:ut,concat:zr,concat1d:Fr,concat2d:Vr,concat3d:Ur,concat4d:Wr,split:qr,conv1d:Ci,conv2d:Pi,conv2dDerFilter:Ai,depthwiseConv2d:Ti,separableConv2d:Mi,conv2dTranspose:Ri,matMul:Ni,dot:Si,outerProduct:Oi,reverse:Di,reverse1d:ji,reverse2d:Li,reverse3d:Bi,reverse4d:zi,maxPool:Ui,avgPool:Wi,pool:qi,slice:$i,slice1d:Gi,slice2d:Hi,slice3d:Ki,slice4d:Xi,abs:Ra,acos:Da,acosh:ja,asin:La,asinh:Ba,atan:za,atanh:Fa,ceil:Va,clipByValue:Ua,cos:Wa,cosh:qa,erf:$a,exp:Ga,expm1:Ha,floor:Ka,log:Xa,log1p:Ya,logSigmoid:Ja,neg:Za,reciprocal:Qa,round:ei,rsqrt:ti,sigmoid:ni,sign:ri,sin:ai,sinh:ii,softplus:oi,sqrt:si,square:ui,step:li,tan:ci,tanh:fi,all:Ji,any:Zi,argMax:Qi,argMin:eo,logSumExp:to,max:no,mean:ro,min:ao,moments:io,sum:oo,prod:so,equal:uo,equalStrict:lo,greater:co,greaterEqual:fo,greaterEqualStrict:po,greaterStrict:ho,less:mo,lessEqual:go,lessEqualStrict:yo,lessStrict:vo,notEqual:bo,notEqualStrict:wo,add:xo,addN:_o,addStrict:Eo,atan2:No,div:So,divStrict:Oo,floorDiv:ko,maximum:Io,maximumStrict:Co,minimum:Po,minimumStrict:Ao,mod:To,modStrict:Mo,mul:Ro,mulStrict:Do,pow:jo,powStrict:Lo,squaredDifference:Bo,squaredDifferenceStrict:zo,sub:Fo,subStrict:Vo,elu:Ko,leakyRelu:Xo,prelu:Yo,relu:Jo,selu:Zo,logicalAnd:Uo,logicalNot:Wo,logicalOr:qo,logicalXor:$o,where:Go,whereAsync:Ho,buffer:na,toPixels:ta,print:ra,batchToSpaceND:aa,cast:ia,clone:oa,cumsum:sa,depthToSpace:ua,expandDims:la,eye:ca,fromPixels:fa,multinomial:pa,oneHot:ha,pad:da,pad1d:ma,pad2d:ga,pad3d:ya,pad4d:va,rand:ba,randomNormal:wa,randomUniform:xa,reshape:_a,spaceToBatchND:Ea,squeeze:Na,stack:Sa,tile:Oa,truncatedNormal:ka,unstack:Ia,setdiff1dAsync:Ca,fill:bt,linspace:wt,ones:yt,range:xt,scalar:ct,tensor:lt,tensor1d:ft,tensor2d:pt,tensor3d:ht,tensor4d:dt,tensor5d:mt,tensor6d:gt,zeros:vt,onesLike:It,zerosLike:Ct,transpose:Qo,softmax:at,logSoftmax:it,localResponseNormalization:es,norm:ts,gather:is,unsortedSegmentSum:os,basicLSTMCell:ss,multiRNNCell:us,movingAverage:ls,stridedSlice:cs,topk:fs,scatterND:ps,fft:hs,ifft:ds,rfft:ms,sparseToDense:ys,gatherND:vs}),zs=function(){function e(){this.blockSize=48,this.firstUse=!0,ve.get("IS_BROWSER")&&(this.fromPixels2DContext=document.createElement("canvas").getContext("2d"))}return e.prototype.setDataMover=function(e){this.data=new Mt(e)},e.prototype.register=function(e,t,n){if(this.firstUse&&(this.firstUse=!1,ve.get("IS_NODE")&&Te("\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============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:n})},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(e).values=t},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var n,r;if(ve.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else if(e instanceof ImageData)n=e.data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=e.width,this.fromPixels2DContext.canvas.height=e.height,this.fromPixels2DContext.drawImage(e,0,0,e.width,e.height),n=this.fromPixels2DContext.getImageData(0,0,e.width,e.height).data}if(4===t)r=new Int32Array(n);else{var a=e.width*e.height;r=new Int32Array(a*t);for(var i=0;ip&&(p=m,h=d)}u[c]=h}return o},e.prototype.cumsum=function(e,t,n,r){if(this.assertNotComplex(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=At(e.dtype,"int32"),i=vt(e.shape,a),o=i.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=r?function(e,t){return e+u-t-1}:function(e,t){return e+t},c=0;ct?1:0})},e.prototype.greaterEqual=function(e,t){return this.assertNotComplex([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){this.assertNotComplex(e,"logicalNot");for(var t=e.dataSync(),n=new Int32Array(t.length),r=0;r1||1===t.rank?1:t.shape[1],c=0;c=0&&t>=0?n:(n+t)%t})},e.prototype.max=function(e,t){this.assertNotComplex(e,"max"),Ue("max",t,e.rank);for(var n=ze(e.shape,t),r=n[0],a=n[1],i=vt(r,e.dtype),o=E(a),s=i.dataSync(),u=e.dataSync(),l=0;lf&&(f=h)}s[l]=f}return i},e.prototype.maximum=function(e,t){return this.assertNotComplex([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){this.assertNotComplex(e,"all"),Ue("all",t,e.rank);for(var n=ze(e.shape,t),r=n[0],a=n[1],i=vt(r,e.dtype),o=E(a),s=i.dataSync(),u=e.dataSync(),l=0;l0?n[r]=1:n[r]=0;return re.make(e.shape,{values:n})},e.prototype.round=function(e){this.assertNotComplex(e,"round");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r.5?n[r]=Math.ceil(t[r]):n[r]=a%2==0?a:a+1}return re.make(e.shape,{values:n})},e.prototype.exp=function(e){this.assertNotComplex(e,"exp");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r=0?a:Math.exp(a)-1}return re.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){this.assertNotComplex([e,t],"eluDer");for(var n=new Float32Array(t.size),r=t.dataSync(),a=e.dataSync(),i=0;i=1?a[i]:a[i]*(o+1)}return re.make(t.shape,{values:n})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return re.make(e.shape,{values:t})},e.prototype.clip=function(e,t,n){this.assertNotComplex(e,"clip");for(var r=new Float32Array(e.size),a=e.dataSync(),i=0;in?n:o-t,s=r[a]0?1:t}return re.make(e.shape,{values:n})},e.prototype.conv2d=function(e,t,n){this.assertNotComplex([e,t],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=na(n.outShape,e.dtype),c=e.dataSync(),f=t.dataSync(),p=l.values,h=0;h=n.inHeight))for(var x=b*t.strides[0],_=d+w*e.strides[1],E=0;E=n.inWidth))for(var I=x+O*t.strides[1],C=_+k*n.inChannels,P=I,A=0;A=n.inHeight))for(var _=w*t.strides[0],E=m+x*e.strides[1],N=0;N=n.inWidth))for(var C=_+k*t.strides[1],P=E+I*n.inChannels,A=S,T=C,M=0;MA?A=L:"avg"===n&&(T+=L,M++)}if(isNaN(A))break}d[O+k*y+x]="avg"===n?T/M:A}return h.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var n=na(t.outShape,"int32"),r=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=t.padInfo.top,c=t.padInfo.left,f=0;fx&&(x=k,_=N*u+O)}n.set(_,f,h,y,p)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(e,t,n,r){this.assertNotComplex([t,n],"maxPoolBackprop");for(var a=this.maxPoolPositions(t,r),i=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,f=c-1-r.padInfo.left,p=l-1-r.padInfo.top,h=na(t.shape,"float32"),d=0;d=r.outHeight||Math.floor(_)!==_))for(var E=0;E=r.outWidth||Math.floor(N)!==N)){var S=l*c-1-a.get(d,_,N,m)===x*c+E?1:0;0!==S&&(w+=e.get(d,_,N,m)*S)}}}h.set(w,d,g,y,m)}return h.toTensor()},e.prototype.avgPoolBackprop=function(e,t,n){this.assertNotComplex([e,t],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,f=c-1-n.padInfo.left,p=l-1-n.padInfo.top,h=na(t.shape,"float32"),d=1/(i*o),m=0;m=n.outHeight||Math.floor(E)!==E))for(var N=0;N=n.outWidth||Math.floor(S)!==S||(x+=e.get(m,E,S,g))}}h.set(x*d,m,y,v,g)}return h.toTensor()},e.prototype.cast=function(e,t){return Dt(e,t,this)},e.prototype.reshape=function(e,t){return jt(e,t)},e.prototype.avgPool=function(e,t){return this.assertNotComplex(e,"avgPool"),this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,n,r){this.assertNotComplex(e,"resizeBilinear");for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=e.dataSync(),c=new Float32Array(E([i,t,n,u])),f=[r&&t>1?o-1:o,r&&n>1?s-1:s],p=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=0,d=f[0]/p[0],m=f[1]/p[1],g=0;g1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/h[0],m=p[1]/h[1],g=e.dataSync(),y=0,v=0;v1?o-1:o,r&&n>1?s-1:s],p=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=f[0]/p[0],d=f[1]/p[1],m=0,g=0;g1?i-1:i,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=h[0]/d[0],g=h[1]/d[1],y=1/m,v=1/g,b=2*Math.ceil(y)+2,w=2*Math.ceil(v)+2,x=0;x=l)){var D=_+R*e.strides[1],j=R*m;if(E===Math.min(i-1,n?Math.round(j):Math.floor(j)))for(var L=0;L=c)){var z=D+B*e.strides[2],F=B*g;k===Math.min(o-1,n?Math.round(F):Math.floor(F))&&(T+=p[z+A])}}}}f[I+A]=T}return dt(f,t.shape,t.dtype)},e.prototype.batchNormalization=function(e,t,n,r,a,i){this.assertNotComplex([e,t,n,a,i],"batchNormalization");for(var o=e.dataSync(),s=t.dataSync(),u=n.dataSync(),l=a?a.dataSync():new Float32Array([1]),c=i?i.dataSync():new Float32Array([0]),f=new Float32Array(o.length),p=c.length,h=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w=p&&(g=0),y>=m&&(y=0),v>=h&&(v=0),b>=d&&(b=0);return dt(f,e.shape)},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){this.assertNotComplex(e,"localResponseNormalization4D");var i=e.shape[3],o=i-1,s=e.dataSync(),u=E(e.shape),l=new Float32Array(u);function c(e){for(var n=e%i,r=e-n+Math.max(0,n-t),a=e-n+Math.min(n+t,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var f=0;f=0&&e.get(i)1,"blockSize should be > 1 for depthToSpace, but was: "+t);for(var r=e.shape[0],a=e.shape[1],i=e.shape[2],o=e.shape[3],s=a*t,u=i*t,l=o/(t*t),c=e.dataSync(),f=new Float32Array(r*s*u*l),p=0,h=0;h=s))for(var k=p>1?(N-_)*(u-1)/(p-1):0,I=h>1?(S-E)*(l-1)/(h-1):0,C=0;C1?_*(u-1)+C*k:.5*(_+N)*(u-1);if(P<0||P>u-1)for(var A=0;A1?E*(l-1)+A*I:.5*(E+S)*(l-1))<0||$>l-1)for(T=0;T1?E*(l-1)+A*I:.5*(E+S)*(l-1))<0||$>l-1)for(T=0;T=e.size/s)throw new Error("Invalid indices: "+h+" does not index into "+e.shape);for(var y=0;y=r/a)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b0,"scheme must not be an empty string.");var r=e.getInstance();b(null==r.managers[t],"A model store manager is already registered for scheme '"+t+"'."),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function Zs(e){if(-1===e.indexOf(Ys))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Js.getSchemes().join(","));return{scheme:e.split(Ys)[0],path:e.split(Ys)[1]}}function Qs(e,t,n){return void 0===n&&(n=!1),l(this,void 0,void 0,function(){var r,a,i,o,s,u,l,f,p;return c(this,function(c){switch(c.label){case 0:return b(e!==t,"Old path and new path are the same: '"+e+"'"),b((r=Xs.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),b(r.length<2,"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."),a=r[0],b((i=Xs.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),b(i.length<2,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."),o=i[0],s=Zs(e).scheme,u=Zs(e).path,l=s===Zs(e).scheme,[4,a.load()];case 1:return f=c.sent(),n&&l?[4,Js.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,o.save(f)];case 4:return p=c.sent(),!n||l?[3,6]:[4,Js.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var eu="models_store",tu="model_info_store";function nu(){if(!ve.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=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 ru(e){var t=e.result;t.createObjectStore(eu,{keyPath:"modelPath"}),t.createObjectStore(tu,{keyPath:"modelPath"})}var au=function(){function e(e){if(this.indexedDB=nu(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,this.databaseAction(this.modelPath)]})})},e.prototype.databaseAction=function(e,t){var n=this;return new Promise(function(e,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return ru(a)},a.onsuccess=function(){var i=a.result;if(null==t){var o=i.transaction(eu,"readonly"),s=o.objectStore(eu).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=Ks(t),c=i.transaction(tu,"readwrite"),f=c.objectStore(tu),p=f.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var a=(u=i.transaction(eu,"readwrite")).objectStore(eu).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});a.onsuccess=function(){return e({modelArtifactsInfo:l})},a.onerror=function(e){var t=(f=c.objectStore(tu)).delete(n.modelPath);t.onsuccess=function(){return i.close(),r(a.error)},t.onerror=function(e){return i.close(),r(a.error)}}},p.onerror=function(e){return i.close(),r(p.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(e){return r(a.error)}})},e.URL_SCHEME="indexeddb://",e}(),iu=function(e){return ve.get("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(au.URL_SCHEME)?function(e){return new au(e)}(e.slice(au.URL_SCHEME.length)):null};Xs.registerSaveRouter(iu),Xs.registerLoadRouter(iu);var ou=function(){function e(){this.indexedDB=nu()}return e.prototype.listModels=function(){return l(this,void 0,void 0,function(){var e=this;return c(this,function(t){return[2,new Promise(function(t,n){var r=e.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return ru(r)},r.onsuccess=function(){var e=r.result,a=e.transaction(tu,"readonly"),i=a.objectStore(tu).getAll();i.onsuccess=function(){for(var e={},n=0,r=i.result;n0,"URL path for browserHTTPRequest must not be null, undefined or empty."),Array.isArray(e)&&b(2===e.length,"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+e.length+")."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest: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"),[4,fetch(this.path,t)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:Ks(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,Array.isArray(this.path)?this.loadBinaryModel():this.loadJSONModel()]})})},e.prototype.loadBinaryTopology=function(){return l(this,void 0,void 0,function(){var e,t;return c(this,function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,fetch(this.path[0],this.requestInit)];case 1:if(!(e=n.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+e.statusText);return[4,e.arrayBuffer()];case 2:return[2,n.sent()];case 3:throw t=n.sent(),new Error(this.path[0]+" not found. "+t);case 4:return[2]}})})},e.prototype.loadBinaryModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return e=this.loadBinaryTopology(),[4,fetch(this.path[1],this.requestInit)];case 1:if(!(t=u.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+t.statusText);return[4,Promise.all([e,t])];case 2:return n=u.sent(),r=n[0],[4,n[1].json()];case 3:return null==(a=u.sent())?[3,5]:[4,this.loadWeights(a)];case 4:s=u.sent(),i=s[0],o=s[1],u.label=5;case 5:return[2,{modelTopology:r,weightSpecs:i,weightData:o}]}})})},e.prototype.loadJSONModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:if(!(e=u.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+e.statusText);return[4,e.json()];case 2:if(t=u.sent(),n=t.modelTopology,r=t.weightsManifest,null==n&&null==r)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==r?[3,4]:(o=t.weightsManifest,[4,this.loadWeights(o)]);case 3:s=u.sent(),a=s[0],i=s[1],u.label=4;case 4:return[2,{modelTopology:n,weightSpecs:a,weightData:i}]}})})},e.prototype.loadWeights=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o,s,u,l,f,p,h;return c(this,function(c){switch(c.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=function(e){var t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),r=n[0],a=n[1],i=this.weightPathPrefix||r,o=[],s=0,u=e;s0&&(e=u({weightSpecs:this.weightSpecs},e)),null!=this.weightData&&this.weightData.byteLength>0&&(e=u({weightData:this.weightData},e)),[2,e]})})},e}(),Cu=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){return[2,this.saveHandler(e)]})})},e}(),Pu=Xs.registerSaveRouter,Au=Xs.registerLoadRouter,Tu=Xs.getSaveHandlers,Mu=Xs.getLoadHandlers,Ru=Object.freeze({browserFiles:function(e){return new _u(e)},browserHTTPRequest:ku,concatenateArrayBuffers:Gs,decodeWeights:Ws,encodeWeights:function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:for(r in t=[],n=[],e){if("float32"!==(a=e[r]).dtype&&"int32"!==a.dtype&&"bool"!==a.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+a.dtype);t.push({name:r,shape:a.shape,dtype:a.dtype}),n.push(a.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0,n=[];e.forEach(function(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)});var r=new Uint8Array(t),a=0;return n.forEach(function(e){r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}(i.sent()),specs:t}]}})})},fromMemory:function(e,t,n){return new Iu(e,t,n)},getLoadHandlers:Mu,getModelArtifactsInfoForJSON:Ks,getSaveHandlers:Tu,loadWeights:function(e,t,n,r){return void 0===t&&(t=""),l(this,void 0,void 0,function(){var a,i,o,s,u,l,f,p,h,d;return c(this,function(c){switch(c.label){case 0:if(a=e.map(function(){return!1}),i={},o=null!=n?n.map(function(){return!1}):[],s=[],e.forEach(function(e,t){var r=0;e.weights.forEach(function(e){var u="quantization"in e?e.quantization.dtype:e.dtype,l=Us[u]*E(e.shape),c=function(){a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:r,sizeBytes:l})};null!=n?n.forEach(function(t,n){t===e.name&&(c(),o[n]=!0)}):c(),s.push(e.name),r+=l})}),!o.every(function(e){return e}))throw u=n.filter(function(e,t){return!o[t]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=a.reduce(function(e,t,n){return t&&e.push(n),e},[]),f=[],l.forEach(function(n){e[n].paths.forEach(function(e){var n=t+(t.endsWith("/")?"":"/")+e;f.push(n)})}),[4,Eu(f,r)];case 1:return p=c.sent(),h={},d=0,l.forEach(function(t){for(var n=e[t].paths.length,r=0,a=0;a0&&Number.isInteger(n),"If provided, numClasses must be a positive integer, but got "+n),b(1===r.rank,"Expected the rank of labels to be 1, but got "+r.rank),b(1===a.rank,"Expected the rank of predictions to be 1, but got "+a.rank),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."),b(n>0&&Number.isInteger(n),"numClasses is required to be a positive integer, but got "+n);var i=ha(r.asType("int32"),n),o=ha(a.asType("int32"),n);return i.transpose().matMul(o).asType("int32")}}),ju=Object.freeze({confusionMatrix:Du}),Lu=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(e,t){return new e(t)},e}(),Bu=function(){function e(){this.classNameMap={}}return e.getMap=function(){return null==e.instance&&(e.instance=new e),e.instance},e.register=function(t){e.getMap().classNameMap[t.className]=[t,t.fromConfig]},e}();function zu(e){b(null!=e.className,"Class being registered does not have the static className property defined."),b("string"==typeof e.className,"className is required to be a string, but got type "+typeof e.className),b(e.className.length>0,"Class being registered has an empty-string as its className, which is disallowed."),Bu.register(e)}var Fu=Object.freeze({Serializable:Lu,SerializationMap:Bu,registerClass:zu});function Vu(e,t,n){if(null==n&&(n=ve.get("TEST_EPSILON")),e instanceof re||t instanceof re){if(e instanceof re&&t instanceof re){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!N(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".")}}else{var r=e.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+a)}var i,o;if(i=e instanceof re?e.dataSync():e,o=t instanceof re?t.dataSync():t,i.length!==o.length)throw new Error("Arrays have different lengths actual: "+i.length+" vs expected: "+o.length+".\nActual: "+i+".\nExpected: "+o+".");for(var s=0;sn)}var Wu=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},BROWSER_CPU_ENVS:{BACKEND:"test-cpu"},ALL_ENVS:{},expectArraysClose:Vu,expectPromiseToFail:function(e,t){e().then(function(){return t.fail()},function(){return t()})},expectArraysEqual:function(e,t){return Vu(e,t,0)},expectNumbersClose:function(e,t,n){if(null==n&&(n=ve.get("TEST_EPSILON")),!Uu(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t)},expectValuesInRange:function(e,t,n){var r;r=e instanceof re?e.dataSync():e;for(var a=0;an)throw new Error("Value out of range:"+r[a]+" low: "+t+", high: "+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),qu="0.13.11",$u=Object.freeze({gpgpu_util:_r,webgl_util:tr,MathBackendWebGL:Ta,GPGPUContext:Er}),Gu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),a=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(e){return i[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return Ne(e,t)},t}(Lu),Hu=function(e){function t(t,n,r){void 0===r&&(r=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=n,a.epsilon=r,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=Ie(ct(-t)),a.rhoScalar=Ie(ct(n)),a.oneMinusRho=Ie(ct(1-n)),null===r&&(r=ve.get("EPSILON")),a.epsilonScalar=Ie(ct(r)),a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=ve.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&ke(function(){t.accumulatedGrads[n]=Ct(a).variable(!1)}),null==r.accumulatedUpdates[n]&&ke(function(){t.accumulatedUpdates[n]=Ct(a).variable(!1)});var i=e[n],o=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];ke(function(){var e=t.rhoScalar.mul(o).add(t.oneMinusRho.mul(i.square())),r=s.add(t.epsilonScalar).sqrt().div(o.add(t.epsilonScalar).sqrt()).mul(i),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(r.square()));t.accumulatedGrads[n].assign(e),t.accumulatedUpdates[n].assign(u);var l=t.c.mul(r).add(a);a.assign(l)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(Gu);zu(Hu);var Ku=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Ie(ct(-t)),r.epsilon=Ie(ct(ve.get("EPSILON"))),r}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=ve.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&ke(function(){t.accumulatedGrads[n]=bt(a.shape,t.initialAccumulatorValue).variable(!1)});var i=e[n],o=r.accumulatedGrads[n];ke(function(){var e=o.add(i.square());t.accumulatedGrads[n].assign(e);var r=t.c.mul(i.div(e.add(t.epsilon).sqrt())).add(a);a.assign(r)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(Gu);zu(Ku);var Xu=function(e){function t(t,n,r,a){void 0===a&&(a=null);var i=e.call(this)||this;return i.learningRate=t,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment={},i.accumulatedSecondMoment={},i.c=Ie(ct(-t)),i.beta1Scalar=Ie(ct(n)),i.beta2Scalar=Ie(ct(r)),ke(function(){i.accBeta1=ct(n).variable(),i.accBeta2=ct(r).variable()}),i.oneMinusBeta1=Ie(ct(1-n)),i.oneMinusBeta2=Ie(ct(1-r)),i.one=Ie(ct(1)),null===a&&(a=ve.get("EPSILON")),i.epsScalar=Ie(ct(a)),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;ke(function(){var n=t.one.sub(t.accBeta1),r=t.one.sub(t.accBeta2);for(var a in e){var i=ve.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=Ct(i).variable(o)}null==t.accumulatedSecondMoment[a]&&(o=!1,t.accumulatedSecondMoment[a]=Ct(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),p=c.div(n),h=f.div(r);t.accumulatedFirstMoment[a].assign(c),t.accumulatedSecondMoment[a].assign(f);var d=t.c.mul(p.div(t.epsScalar.add(h.sqrt()))).add(i);i.assign(d)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(Gu);zu(Xu);var Yu=function(e){function t(t,n,r,a,i){void 0===a&&(a=null),void 0===i&&(i=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment={},o.accumulatedWeightedInfNorm={},o.c=Ie(ct(-t)),o.beta1Scalar=Ie(ct(n)),o.beta2Scalar=Ie(ct(r)),o.decayScalar=Ie(ct(i)),ke(function(){o.iteration=ct(0).variable(),o.accBeta1=ct(n).variable()}),o.oneMinusBeta1=Ie(ct(1-n)),o.one=Ie(ct(1)),null===a&&(a=ve.get("EPSILON")),o.epsScalar=Ie(ct(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this;ke(function(){var n=t.one.sub(t.accBeta1),r=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var i=ve.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=Ct(i).variable(o)}null==t.accumulatedWeightedInfNorm[a]&&(o=!1,t.accumulatedWeightedInfNorm[a]=Ct(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l),p=s.abs(),h=f.maximum(p);t.accumulatedFirstMoment[a].assign(c),t.accumulatedWeightedInfNorm[a].assign(h);var d=r.div(n).mul(c.div(t.epsScalar.add(h))).add(i);i.assign(d)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(Gu);zu(Yu);var Ju=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(n){var r=e[n],a=ve.engine.registeredVariables[n];ke(function(){var e=t.c.mul(r).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Ie(ct(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(Gu);zu(Ju);var Zu=function(e){function t(t,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=n,a.useNesterov=r,a.m=ct(a.momentum),a.accumulations={},a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=ve.engine.registeredVariables[n];null==r.accumulations[n]&&ke(function(){t.accumulations[n]=Ct(a).variable(!1)});var i=r.accumulations[n],o=e[n];ke(function(){var e,r=t.m.mul(i).add(o);e=t.useNesterov?t.c.mul(o.add(r.mul(t.m))).add(a):t.c.mul(r).add(a),t.accumulations[n].assign(r),a.assign(e)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(Ju);zu(Zu);var Qu=function(e){function t(t,n,r,a,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=null),void 0===i&&(i=!1);var o=e.call(this)||this;return o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares={},o.accumulatedMeanGrads={},o.accumulatedMoments={},o.c=Ie(ct(t)),o.decayScalar=Ie(ct(n)),o.momentumScalar=Ie(ct(r)),o.oneMinusDecay=Ie(ct(1-n)),o.centered=i,null===a&&(a=ve.get("EPSILON")),o.epsilonScalar=Ie(ct(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=ve.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&ke(function(){t.accumulatedMeanSquares[n]=Ct(a).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&ke(function(){t.accumulatedMeanGrads[n]=Ct(a).variable(!1)}),null==r.accumulatedMoments[n]&&ke(function(){t.accumulatedMoments[n]=Ct(a).variable(!1)});var i=r.accumulatedMeanSquares[n],o=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=e[n];ke(function(){var e=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var r=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(r.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[n].assign(e),t.accumulatedMeanGrads[n].assign(r),t.accumulatedMoments[n].assign(l);var c=a.sub(l);a.assign(c)}else{var f=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(f.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[n].assign(f),t.accumulatedMoments[n].assign(l),c=a.sub(l),a.assign(c)}})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(Gu);zu(Qu);var el=function(){function e(){}return e.sgd=function(e){return new Ju(e)},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new Zu(e,t,n)},e.rmsprop=function(e,t,n,r,a){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new Qu(e,t,n,r,a)},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new Xu(e,t,n,r)},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=null),new Hu(e,t,n)},e.adamax=function(e,t,n,r,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new Yu(e,t,n,r,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new Ku(e,t)},e}(),tl={sgd:el.sgd,momentum:el.momentum,adadelta:el.adadelta,adagrad:el.adagrad,rmsprop:el.rmsprop,adamax:el.adamax,adam:el.adam},nl=ye.setBackend,rl=ye.getBackend,al=ye.disposeVariables,il=ye.memory;te=Bs}.call(this,n(46),n(26),n(162).setImmediate,n(16).Buffer)},function(e,t,n){"use strict";(function(e,r,a,i){n.d(t,"Fc",function(){return vu}),n.d(t,"Ya",function(){return bu}),n.d(t,"Ga",function(){return wu}),n.d(t,"Gb",function(){return xu}),n.d(t,"Dd",function(){return ou}),n.d(t,"Tb",function(){return is}),n.d(t,"La",function(){return ge}),n.d(t,"hb",function(){return Zs}),n.d(t,"Ec",function(){return nu}),n.d(t,"nd",function(){return iu}),n.d(t,"yd",function(){return V}),n.d(t,"Ed",function(){return su}),n.d(t,"a",function(){return lu}),n.d(t,"b",function(){return cu}),n.d(t,"c",function(){return fu}),n.d(t,"d",function(){return pu}),n.d(t,"g",function(){return du}),n.d(t,"h",function(){return uu}),n.d(t,"i",function(){return mu}),n.d(t,"l",function(){return hu}),n.d(t,"m",function(){return Q}),n.d(t,"n",function(){return X}),n.d(t,"Bd",function(){return te}),n.d(t,"o",function(){return ee}),n.d(t,"j",function(){return gt}),n.d(t,"k",function(){return Co}),n.d(t,"e",function(){return me}),n.d(t,"f",function(){return de}),n.d(t,"gb",function(){return ts}),n.d(t,"ob",function(){return Yo}),n.d(t,"zb",function(){return Go}),n.d(t,"ac",function(){return Je}),n.d(t,"H",function(){return qa}),n.d(t,"I",function(){return $a}),n.d(t,"J",function(){return Ga}),n.d(t,"G",function(){return Ha}),n.d(t,"Q",function(){return Qe}),n.d(t,"qc",function(){return et}),n.d(t,"fb",function(){return tt}),n.d(t,"R",function(){return vr}),n.d(t,"S",function(){return br}),n.d(t,"T",function(){return wr}),n.d(t,"U",function(){return xr}),n.d(t,"V",function(){return _r}),n.d(t,"Sc",function(){return Er}),n.d(t,"W",function(){return ii}),n.d(t,"X",function(){return oi}),n.d(t,"Ea",function(){return si}),n.d(t,"Dc",function(){return ui}),n.d(t,"Y",function(){return li}),n.d(t,"Ab",function(){return Qa}),n.d(t,"Ja",function(){return ei}),n.d(t,"bc",function(){return ti}),n.d(t,"uc",function(){return ci}),n.d(t,"vc",function(){return fi}),n.d(t,"wc",function(){return pi}),n.d(t,"xc",function(){return hi}),n.d(t,"yc",function(){return di}),n.d(t,"Cb",function(){return mi}),n.d(t,"E",function(){return gi}),n.d(t,"Kc",function(){return yi}),n.d(t,"Lc",function(){return vi}),n.d(t,"Mc",function(){return bi}),n.d(t,"Nc",function(){return wi}),n.d(t,"Oc",function(){return xi}),n.d(t,"p",function(){return fa}),n.d(t,"q",function(){return pa}),n.d(t,"r",function(){return ha}),n.d(t,"z",function(){return da}),n.d(t,"A",function(){return ma}),n.d(t,"B",function(){return ga}),n.d(t,"D",function(){return ya}),n.d(t,"N",function(){return va}),n.d(t,"O",function(){return ba}),n.d(t,"Z",function(){return wa}),n.d(t,"Aa",function(){return xa}),n.d(t,"Oa",function(){return _a}),n.d(t,"Pa",function(){return Ea}),n.d(t,"Ra",function(){return Na}),n.d(t,"Ua",function(){return Sa}),n.d(t,"rb",function(){return Oa}),n.d(t,"sb",function(){return ka}),n.d(t,"tb",function(){return Ia}),n.d(t,"Sb",function(){return Ca}),n.d(t,"rc",function(){return Pa}),n.d(t,"zc",function(){return Aa}),n.d(t,"Ac",function(){return Ta}),n.d(t,"Gc",function(){return Ma}),n.d(t,"Hc",function(){return Ra}),n.d(t,"Ic",function(){return Da}),n.d(t,"Jc",function(){return ja}),n.d(t,"Qc",function(){return La}),n.d(t,"Tc",function(){return Ba}),n.d(t,"Uc",function(){return za}),n.d(t,"Zc",function(){return Fa}),n.d(t,"ed",function(){return Va}),n.d(t,"fd",function(){return Ua}),n.d(t,"v",function(){return Ei}),n.d(t,"w",function(){return Ni}),n.d(t,"x",function(){return Si}),n.d(t,"y",function(){return Oi}),n.d(t,"ub",function(){return ki}),n.d(t,"Bb",function(){return Ii}),n.d(t,"Fb",function(){return Ci}),n.d(t,"Hb",function(){return Pi}),n.d(t,"Mb",function(){return Ai}),n.d(t,"dd",function(){return Ti}),n.d(t,"Ma",function(){return Mi}),n.d(t,"Na",function(){return Ri}),n.d(t,"bb",function(){return Di}),n.d(t,"cb",function(){return ji}),n.d(t,"db",function(){return Li}),n.d(t,"eb",function(){return Bi}),n.d(t,"kb",function(){return zi}),n.d(t,"lb",function(){return Fi}),n.d(t,"mb",function(){return Vi}),n.d(t,"nb",function(){return Ui}),n.d(t,"Vb",function(){return Wi}),n.d(t,"Wb",function(){return qi}),n.d(t,"s",function(){return $i}),n.d(t,"t",function(){return Gi}),n.d(t,"u",function(){return Hi}),n.d(t,"C",function(){return Ki}),n.d(t,"Ha",function(){return Xi}),n.d(t,"Ia",function(){return Yi}),n.d(t,"Va",function(){return Ji}),n.d(t,"Db",function(){return Zi}),n.d(t,"Eb",function(){return Qi}),n.d(t,"Ib",function(){return eo}),n.d(t,"Jb",function(){return to}),n.d(t,"Kb",function(){return no}),n.d(t,"Lb",function(){return ro}),n.d(t,"Ob",function(){return ao}),n.d(t,"Pb",function(){return io}),n.d(t,"hc",function(){return oo}),n.d(t,"ic",function(){return so}),n.d(t,"Vc",function(){return uo}),n.d(t,"Wc",function(){return lo}),n.d(t,"bd",function(){return co}),n.d(t,"cd",function(){return fo}),n.d(t,"Ka",function(){return bo}),n.d(t,"jb",function(){return wo}),n.d(t,"jc",function(){return xo}),n.d(t,"sc",function(){return _o}),n.d(t,"Cc",function(){return Eo}),n.d(t,"vb",function(){return po}),n.d(t,"wb",function(){return ho}),n.d(t,"xb",function(){return mo}),n.d(t,"yb",function(){return go}),n.d(t,"Fd",function(){return yo}),n.d(t,"Gd",function(){return vo}),n.d(t,"L",function(){return Dr}),n.d(t,"rd",function(){return Rr}),n.d(t,"kc",function(){return jr}),n.d(t,"K",function(){return Lr}),n.d(t,"M",function(){return Br}),n.d(t,"P",function(){return zr}),n.d(t,"Ba",function(){return Fr}),n.d(t,"Da",function(){return Vr}),n.d(t,"Qa",function(){return Ur}),n.d(t,"Sa",function(){return Wr}),n.d(t,"Wa",function(){return qr}),n.d(t,"Rb",function(){return $r}),n.d(t,"Xb",function(){return Gr}),n.d(t,"cc",function(){return Hr}),n.d(t,"dc",function(){return Kr}),n.d(t,"ec",function(){return Xr}),n.d(t,"fc",function(){return Yr}),n.d(t,"gc",function(){return Jr}),n.d(t,"mc",function(){return Zr}),n.d(t,"nc",function(){return Qr}),n.d(t,"oc",function(){return ea}),n.d(t,"tc",function(){return ta}),n.d(t,"Rc",function(){return na}),n.d(t,"Xc",function(){return ra}),n.d(t,"Yc",function(){return aa}),n.d(t,"pd",function(){return ia}),n.d(t,"vd",function(){return oa}),n.d(t,"xd",function(){return sa}),n.d(t,"Ta",function(){return pt}),n.d(t,"pb",function(){return ht}),n.d(t,"Yb",function(){return ct}),n.d(t,"pc",function(){return dt}),n.d(t,"Bc",function(){return rt}),n.d(t,"gd",function(){return nt}),n.d(t,"hd",function(){return at}),n.d(t,"id",function(){return it}),n.d(t,"jd",function(){return ot}),n.d(t,"kd",function(){return st}),n.d(t,"ld",function(){return ut}),n.d(t,"md",function(){return lt}),n.d(t,"Hd",function(){return ft}),n.d(t,"Zb",function(){return xt}),n.d(t,"Id",function(){return _t}),n.d(t,"ud",function(){return No}),n.d(t,"Pc",function(){return Ze}),n.d(t,"qb",function(){return So}),n.d(t,"Ub",function(){return Oo}),n.d(t,"Xa",function(){return Po}),n.d(t,"wd",function(){return Ao}),n.d(t,"F",function(){return To}),n.d(t,"Qb",function(){return Mo}),n.d(t,"Nb",function(){return Ro}),n.d(t,"ad",function(){return Do}),n.d(t,"sd",function(){return jo}),n.d(t,"td",function(){return yu}),n.d(t,"od",function(){return Ne}),n.d(t,"ib",function(){return Se}),n.d(t,"Fa",function(){return Oe}),n.d(t,"qd",function(){return ke}),n.d(t,"lc",function(){return Ie}),n.d(t,"Ca",function(){return _e}),n.d(t,"Za",function(){return ye}),n.d(t,"ab",function(){return ve}),n.d(t,"zd",function(){return be}),n.d(t,"Ad",function(){return we}),n.d(t,"Cd",function(){return xe}); +var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function s(e,t){function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var u=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function p(e,t,n){return Math.max(e,Math.min(t,n))}function h(e,t){var n=Math.random();return t*n+(1-n)*e}function d(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function m(e,t,n){void 0===n&&(n=""),d(w(e,t),n+" Shapes "+e+" and "+t+" must match")}function g(e){d(null!=e,"The input to the tensor constructor must be a non-null value.")}function y(e,t){if(void 0===t&&(t=[]),Array.isArray(e))for(var n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"}),d(t.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+t.length+" elements"});for(var a=n.slice(1),i=0;i1;--t)if(e%t==0)return[t,e/t];return[1,e]}function E(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function N(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise(function(r,a){var i=0,o=function(){if(e())r();else{var s=t(++i);null!=n&&i>=n?a():setTimeout(o,s)}};o()})}function O(e,t){for(var n=1,r=-1,a=0;a=0)n*=e[a];else if(-1===e[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-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);var i=e.slice();return i[r]=t/n,i}function k(e,t){for(var n=[],r=[],a=0,i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),t[a]<=i&&a++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function I(e,t){var 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 C(e,t,n){if("float32"===t)for(var r=0;r=0;--r)n[r]=n[r+1]*e[r+1];return n}function L(e,t,n){return function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t)?e:(Array.isArray(e)&&(e=y(e)),function(e,t,n){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return n&&A(e,t),new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),a=0;a1)for(var l=0;lq){var c=$*s,f=Array.from(t.subarray(0,c)),p=Array.from(t.subarray(u-$*s,u));return"complex64"===r&&(f=K(f),p=K(p)),["["+f.map(function(e,t){return H(e,i[t])}).join(", ")+", ..., "+p.map(function(e,t){return H(e,i[u-$+t])}).join(", ")+"]"]}return["["+("complex64"===r?K(t):Array.from(t)).map(function(e,t){return H(e,i[t])}).join(", ")+"]"]}var h=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>q){for(var y=0;y<$;y++){var v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,r,d,i,!1))}for(g.push("..."),y=u-$;y {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),a=re(e);a.forEach(function(e){return r.add(e.id)});for(var i=0;i0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var i=e();d(i instanceof Q,"The result y returned by f() must be a tensor.");var o=function(e,t,n){for(var r={},a={},i=0;i=0;i--)for(o=(d=e[i]).inputs,c=0;c0)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.");var s={};return s[i.id]=null==n?function(e){var t=z(b(e),"float32");return Q.make(e,{values:t})}(i.shape):n,function(e,t){for(var n=function(n){var r=t[n],a=[];if(r.outputs.forEach(function(t){var n=e[t.id];if(null!=n)a.push(n);else{var r=Q.make(t.shape,{values:B(t.size,t.dtype)},t.dtype);a.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var i=r.gradient(1===r.outputs.length?a[0]:a);for(var o in r.inputs){if(!(o in i))throw new Error("Cannot backprop through input "+o+". Available gradients found: "+Object.keys(i)+".");var s=i[o](),u=r.inputs[o];if(!w(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+o+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}},r=t.length-1;r>=0;r--)n(r)}(s,o),{value:i,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return d(R(e),"The f passed in customGrad(f) must be a function."),function(){for(var n,r,a=[],i=0;i {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e},e}();!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(ae||(ae={}));var oe=[{name:"DEBUG",type:ae.BOOLEAN},{name:"IS_BROWSER",type:ae.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:ae.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:ae.BOOLEAN},{name:"WEBGL_VERSION",type:ae.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:ae.BOOLEAN},{name:"BACKEND",type:ae.STRING},{name:"EPSILON",type:ae.NUMBER}];function se(e,t){var n;try{n=fe(e,t)}catch(e){return!1}return null!=n&&(pe(n),!0)}var ue="tfjsflags";function le(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=function(e){var t={};return window.location.search.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r0?0:function(e,t){if(0===e)return 0;var n,r=fe(e,t);return n=ce(r,"EXT_disjoint_timer_query_webgl2")&&2===e?2:ce(r,"EXT_disjoint_timer_query")?1:0,null!=r&&pe(r),n}(n,this.get("IS_BROWSER"))}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===t)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!function(){var e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return se(2,this.get("IS_BROWSER"))?2:se(1,this.get("IS_BROWSER"))?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1;if(!ce(n,"WEBGL_color_buffer_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_FENCE_API_ENABLED"===t)return function(e,t){if(2!==e)return!1;var n=fe(e,t),r=null!=n.fenceSync;return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:.001;throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(e){this.features=Object.assign({},e)},t.prototype.reset=function(){this.features=le(),null!=this.globalEngine&&(this.globalEngine=null)},t.prototype.initBackend=function(e,t){var n=this;if(void 0===t&&(t=!1),this.backendName=e,this.engines[e])this.globalEngine=this.engines[e];else{var r=this.findBackend(e);this.globalEngine=new ie(r,t,function(){return n.get("DEBUG")}),this.engines[e]=this.globalEngine}},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},t.prototype.registerBackend=function(e,t,n,r){var a=this;if(void 0===n&&(n=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=r&&r(function(){return a.engine}),!1;try{var i=t();return this.registry[e]={backend:i,priority:n},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},t.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e],e in this.engines&&delete this.engines[e]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initDefaultBackend(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(this.get("BACKEND"),!1)},t}(),me=function(){var t=function(){var t;if("undefined"!=typeof window)t=window;else{if(void 0===e)throw new Error("Could not find a global object");t=e}return t}();return null==t.ENV&&(t.ENV=new de(le()),Z(function(){return t.ENV.engine})),t.ENV}(),ge=Object.freeze({Environment:de,ENV:me});function ye(e){return d(R(e),"The f passed in grad(f) must be a function"),function(t,n){return d(t instanceof Q,"The x passed in grad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in grad(f)(x, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Se(i),i[0]})}}function ve(e){return d(R(e),"The f passed in grads(f) must be a function"),function(t,n){return d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in grads(f)(args) must be an array of tensors"),d(null==n||n instanceof Q,"The dy passed in grads(f)(args, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Se(i),i})}}function be(e){return d(R(e),"The f passed in valueAndGrad(f) must be a function"),function(t,n){d(t instanceof Q,"The x passed in valueAndGrad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.grads,i=r.value;return Se(a),{grad:a[0],value:i}}}function we(e){return d(R(e),"The f passed in valueAndGrads(f) must be a function"),function(t,n){d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),d(null==n||n instanceof Q,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n);return null!=n&&m(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Se(r.grads),r}}function xe(e,t){if(d(R(e),"The f passed in variableGrads(f) must be a function"),d(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof ee}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var n in t=[],me.engine.registeredVariables)t.push(me.engine.registeredVariables[n]);var r=t.length;d((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable.");var a=me.engine.gradients(e,t,null,!0),i=a.value,o=a.grads;d(o.some(function(e){return 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()."),d(0===i.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+i.rank+" tensor");var s={};return t.forEach(function(e,t){null!=o[t]&&(s[e.name]=o[t])}),{value:i,grads:s}}function _e(e){return me.engine.customGrad(e)}function Se(e){if(e.filter(function(e){return 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.")}var Ee=de.tidy,Ne=de.keep,Oe=de.dispose,ke=de.time,Ie=de.profile;function Ce(){for(var e=[],t=0;t=2*t+1||a%2==1?o.push(a):i.push(a);r.push.apply(r,i),r.push(0),r.push.apply(r,o)}return r}function Te(e,t,n,r){void 0===r&&(r=!0);var a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(var i=1;i=-n&&e0?a>=c[t]:a<=c[t]);a+=r[t])n+=1;return n}),[l,h,f]}function He(e,t,n,r,a){var i=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),p(0,i,o-1)}function Ke(e,t,n,r,a){var i=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),n[a]>0?p(0,i,o):p(-1,i,o-1)}function Xe(e,t,n,r){if(void 0===r&&(r="float32"),r=r||"float32",e instanceof Q)return e;if(!T(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e)throw new Error("Argument '"+t+"' passed to '"+n+"' must be a Tensor or TensorLike, but got "+e.constructor.name);var a=v(e);return T(e)||Array.isArray(e)||(e=[e]),Q.make(a,{values:L(e,r,me.get("DEBUG"))},r)}function Ye(e,t,n){if(!Array.isArray(e))throw new Error("Argument "+t+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map(function(e,r){return Xe(e,t+"["+r+"]",n)})}function Je(e){var 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.");var n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var a=function(){for(var e=[],t=0;t1)return ft([0],r);var a=B(Math.abs(Math.ceil((t-e)/n)),r);ta}).sort(function(e,t){return t.score-e.score}),o=[],s=0;s=0;--p)if(At(e,c,o[p])>=r){f=!0;break}if(!f&&(o.push(c),o.length>=n))break}return at(o,"int32")}function At(e,t,n){var r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),f=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(s-i)*(u-o),d=(f-l)*(p-c);if(h<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),y=Math.min(s,f),v=Math.min(u,p),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(h+d-b)}function Pt(e,t,n){var r=Array(e.rank).fill(0),a=e.shape.slice();return t.map(function(t){a[n]=t;var i=e.slice(r,a);return r[n]+=t,i})}function Tt(e,t,n,r,a){for(var i=t[t.length-1],o=[e.length/i,i],s=o[0],u=o[1],l=I(n,s*r),c=I("int32",s*r),f=0;f1&&1===o&&r.unshift(i)}return r}function Rt(e,t){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Dt(e,t){for(var n=[],r=Math.max(e.length,t.length),a=0;a1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});a=a.join("\n");var i,o=e.map(function(e){return function(e,t,n){var r=function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1)+"Flat",r=b(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform)return 1===r?"float "+n+"(int index) {return "+t+";}":"\n float "+n+"(int index) {\n for (int i = 0; i < "+r+"; i++) {\n if (i == index) {\n return "+t+"[i];\n }\n }\n }\n ";var a=e.shapeInfo.texShape,i=a[0],o=a[1];return 1===o&&1===i?"\n float "+n+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ":1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+i+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index) + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = UVfrom1D("+i+", "+o+", index);\n return sampleTexture("+t+", uv);\n }\n "}(e);return r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+n+"() {return "+t+";}":"\n float "+n+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}(t);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+n+"(int index) {\n return "+n+"Flat(index);\n }\n "}(t);case 2:return function(t){var n=t.shapeInfo.logicalShape,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape;if(null!=i&&w(n,i)){var o=i[0];return"\n float "+a+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var s=k(n),u=s.newShape,l=s.keptDims,c=u;if(c.lengths||o.length>0),c=function(e){for(var t=0;t=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+n+"("+(i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}(e,t,a,i);var p=b(e.shapeInfo.logicalShape),h="";l&&c&&(h="\n int mainPart = index / "+p+";\n index -= mainPart * "+p+";\n ");var d=t.texShape;if(f)return 1===p?"float "+i+"() {return "+r+";}":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return w(m,d)?"\n float "+i+"() {\n return sampleTexture("+r+", resultUV);\n }\n ":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+r+", uv);\n }\n "}(e,t,n)),r}(e,t,r)}).join("\n"),s=t.texShape;return i=t.isPacked?function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 2:return function(e,t){return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+Math.ceil(t[0]/2)+", "+Math.ceil(t[1]/2)+"));\n }\n "}(0,t);default:throw new Error(e.length+"-D output packed sampling is not yet supported")}}(t.logicalShape,s):function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){return w(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}(e,t);case 3:return function(e,t){var n=e[1]*e[2],r=e[2];return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+n+";\n index -= r * "+n+";\n int c = index / "+r+";\n int d = index - c * "+r+";\n return ivec3(r, c, d);\n }\n "}(e,t);case 4:return function(e,t){var n=e[3],r=e[2]*n,a=e[1]*r;return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+a+";\n index -= r * "+a+";\n\n int c = index / "+r+";\n index -= c * "+r+";\n\n int d = index / "+n+";\n int d2 = index - d * "+n+";\n\n return ivec4(r, c, d, d2);\n }\n "}(e,t);case 5:return function(e,t){var n=e[4],r=e[3]*n,a=e[2]*r,i=e[1]*a;return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+i+";\n index -= r * "+i+";\n\n int c = index / "+a+";\n index -= c * "+a+";\n\n int d = index / "+r+";\n index -= d * "+r+";\n\n int d2 = index / "+n+";\n int d3 = index - d2 * "+n+";\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(e,t);case 6:return function(e,t){var n=e[5],r=e[4]*n,a=e[3]*r,i=e[2]*a,o=e[1]*i;return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+o+";\n index -= r * "+o+";\n\n int c = index / "+i+";\n index -= c * "+i+";\n\n int d = index / "+a+";\n index -= d * "+a+";\n\n int d2 = index / "+r+";\n index -= d2 * "+r+";\n\n int d3 = index / "+n+";\n int d4 = index - d3 * "+n+";\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}(t.logicalShape,s),[Wt,Vt,Ut,a,i,o,n].join("\n")}var Vt="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",Ut="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",Wt="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\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 bool isNaN(float val) {\n return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\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 \nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n";function qt(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function $t(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Gt(e,t){return t.map(function(t){return e[t]}).join(", ")}function Ht(e,t){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 sum for rank "+e+" is not yet supported")}var Kt,Xt,Yt=function(){function e(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 "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}();function Jt(e,t){return[t,e]}function Zt(e,t){return e*t}function Qt(e,t,n){var r=function(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t}(e.length,n);if(t.length= "+r);for(var a=0,i=0;ir||n>r)throw a="["+t+"x"+n+"]",new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function En(e){return Rn(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Nn(e,t,n,r,a,i,o){var s=e.getAttribLocation(t,n);return-1!==s&&(on(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),on(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,i,o)}),on(e,function(){return e.enableVertexAttribArray(s)}),!0)}function On(e,t,n){Dn(e,n),on(e,function(){return e.activeTexture(e.TEXTURE0+n)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function kn(e,t,n){return Rn(e,function(){return e.getUniformLocation(t,n)},'uniform "'+n+'" not present in program.')}function In(e,t,n){return e.getUniformLocation(t,n)}function Cn(e,t,n,r,a){on(e,function(){return On(e,n,a)}),on(e,function(){return e.uniform1i(r,a)})}function An(e,t,n){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)}),on(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function Pn(e,t){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),on(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function Tn(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Mn(e,t))}function Mn(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Rn(e,t,n){var r=on(e,function(){return t()});if(null==r)throw new Error(n);return r}function Dn(e,t){var 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 jn(e,t){2!==t.length&&(t=k(t).newShape);var n=wn(e),r=b(t);return t.length<=1&&r<=n?[r,1]:2===t.length&&t[0]<=n&&t[1]<=n?t:3===t.length&&t[0]<=n&&t[1]*t[2]<=n?[t[0],t[1]*t[2]]:4===t.length&&t[0]<=n&&t[1]*t[2]*t[3]<=n?[t[0],t[1]*t[2]*t[3]]:S(r)}var Ln=Object.freeze({createWebGLRenderingContext:rn,createWebGLRenderingContextFromCanvas:an,callAndCheck:on,enableDebugWebGLErrorChecking:un,checkWebGLError:ln,getWebGLErrorMessage:cn,getExtensionOrThrow:fn,createVertexShader:pn,createFragmentShader:hn,createProgram:mn,linkProgram:gn,validateProgram:yn,createStaticVertexBuffer:vn,createStaticIndexBuffer:bn,queryMaxTextureSize:wn,getNumChannels:xn,createTexture:_n,validateTextureSize:Sn,createFramebuffer:En,bindVertexBufferToProgramAttribute:Nn,bindTextureUnit:On,unbindTextureUnit:function(e,t){Dn(e,t),on(e,function(){return e.activeTexture(e.TEXTURE0+t)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:kn,getProgramUniformLocation:In,bindTextureToProgramUniformSampler:Cn,bindCanvasToFramebuffer:function(e){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),on(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),on(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})},bindColorTextureToFramebuffer:An,unbindColorTextureFromFramebuffer:Pn,validateFramebuffer:Tn,getFramebufferErrorMessage:Mn,getTextureShapeFromLogicalShape:jn});function zn(e){var t,n={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};return on(t=null!=e?an(e,n):rn(n),function(){return t.disable(t.DEPTH_TEST)}),on(t,function(){return t.disable(t.STENCIL_TEST)}),on(t,function(){return t.disable(t.BLEND)}),on(t,function(){return t.disable(t.DITHER)}),on(t,function(){return t.disable(t.POLYGON_OFFSET_FILL)}),on(t,function(){return t.disable(t.SAMPLE_COVERAGE)}),on(t,function(){return t.enable(t.SCISSOR_TEST)}),on(t,function(){return t.enable(t.CULL_FACE)}),on(t,function(){return t.cullFace(t.BACK)}),t}function Bn(e){return pn(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Fn(e){return vn(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Vn(e){return bn(e,new Uint16Array([0,1,2,2,1,3]))}function Un(e,t){var n,r,a,i,o,s,u,l=e;return 2===me.get("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,a=l.RGBA32F,i=l.RED,o=4,s=1,u=l.HALF_FLOAT):(n=e.RGBA,r=e.RGBA,a=l.RGBA,i=e.RGBA,o=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:o,defaultNumChannels:s,textureTypeHalfFloat:u}}function Wn(e,t,n,r,a,i){Sn(e,t,n);var o=_n(e),s=e.TEXTURE_2D;return on(e,function(){return e.bindTexture(s,o)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),on(e,function(){return e.texImage2D(s,0,r,t,n,0,a,i,null)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),o}function qn(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,e.FLOAT)}function $n(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function Gn(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function Hn(e,t,n,r){var a=en(t,n);return Wn(e,a[0],a[1],r.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function Kn(e,t,n){return on(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),Nn(e,t,"clipSpacePos",n,3,20,0)&&Nn(e,t,"uv",n,2,20,12)}function Xn(e,t,n){on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),on(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Yn(e,t,n,r,a,i){Sn(e,n,r),on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),on(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,i,e.FLOAT,a)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Jn(e,t,n,r,a,i,o){var s,u=Jt(n,r),l=u[0],c=u[1];1===o.defaultNumChannels?s=a:function(e,t,n){var r=Zt(e.length,n);if(t.length= "+r);for(var a=0,i=0;i= "+a);for(var i=en(t,n),o=i[0],s=i[1],u=n%2==1,l=t%2==1,c=Math.floor(n/2),f=Math.floor(t/2),p=u?4:0,h=n,d=0,m=0;m= "+a);for(var i=n%2==1,o=t%2==1,s=Math.floor(n/2),u=Math.floor(t/2),l=en(t,n),c=l[0],f=l[1],p=i?4:0,h=n+(i?1:0),d=0,m=0,g=n,y=0;y0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,function(){return rr(r.gl,t,n,r.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=hn(t,e),r=Bn(t),a=mn(t);return on(t,function(){return t.attachShader(a,r)}),on(t,function(){return t.attachShader(a,n)}),gn(t,a),this.autoDebugValidate&&yn(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=Kn(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&on(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&yn(this.gl,this.program),on(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?kn(this.gl,e,t):In(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),on(this.gl,function(){return n.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Cn(this.gl,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=en(t,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(e,a,i)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&yn(this.gl,this.program),Tn(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),on(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),on(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=fn(this.gl,2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return l(this,void 0,void 0,function(){var t=this;return c(this,function(n){switch(n.label){case 0:return[4,N(function(){return t.isQueryAvailable(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise(function(n){t.addItemToPoll(function(){return e.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0,n=e.length-1,r=-1;t<=n;){var a=t+n>>1;e[a]()?(r=a,t=a+1):n=a-1}return r}(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||N(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),An(this.gl,e,this.framebuffer),this.autoDebugValidate&&Tn(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(An(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Tn(this.gl)):Pn(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;An(r,e,this.framebuffer),this.autoDebugValidate&&Tn(r),this.outputTexture=e,on(r,function(){return r.viewport(0,0,t,n)}),on(r,function(){return r.scissor(0,0,t,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var a=this;this.throwIfDisposed(),on(this.gl,function(){return a.gl.scissor(e,t,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function or(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(function(e,n){var r=e.logicalShape,a=t[n],i=a.shape;if(!w(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var o=e.texShape,s=a.isUniform?null:a.texData.texShape;if(!w(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var sr=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\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 "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e)}},e}(),ur=function(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n int r = rc.x;\n int c = rc.y;\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e[1]+";\n bool rEdge = rp1 >= "+e[0]+";\n\n gl_FragColor = vec4(\n getA(r, c),\n cEdge ? 0. : getA(r, cp1),\n rEdge ? 0. : getA(rp1, c),\n rEdge || cEdge ? 0. : getA(rp1, cp1)\n );\n }\n "},lr=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterHeight,a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,s=e.padInfo.top,u=e.padInfo.left;this.outputShape=e.outShape;var l="avg"===t,c="0.0";if(l||(c="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\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 < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+a+"; wC++) {\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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+a+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var p=4*Math.floor(a/4),h=a%4,d="\n if ("+l+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\n const float initializationValue = "+c+";\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("+c+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n "+d+"\n }\n\n int xC = xCCorner + "+p+";\n if ("+(1===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(2===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(3===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n "+d+"\n }\n }\n setOutput("+f+");\n }\n "}},cr=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=qt(this.rank),n=function(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){if(null!=t.startLoc||(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null!=t.startLoc))if(1===t.rank)n.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)n.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)n.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");n.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}(),fr=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t){var n,r=pr(t),a=hr(e,r);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),r===Xt.PACKED_2X2_FLOAT32?n=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===Xt.UNPACKED_FLOAT32?n=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===Xt.UNPACKED_FLOAT16?n=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===Xt.PACKED_4X1_UNSIGNED_BYTE&&(n=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(n),n},e.prototype.releaseTexture=function(e,t,n){var r=hr(t,pr(n));r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[r],i=a.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function pr(e){if(e===Kt.DOWNLOAD||e===Kt.PIXELS)return Xt.PACKED_4X1_UNSIGNED_BYTE;if(e===Kt.UPLOAD)return Xt.UNPACKED_FLOAT32;if(e===Kt.RENDER)return me.get("WEBGL_RENDER_FLOAT32_ENABLED")?Xt.UNPACKED_FLOAT32:Xt.UNPACKED_FLOAT16;if(e===Kt.PACK)return Xt.PACKED_2X2_FLOAT32;throw new Error("Unknown logical texture type "+e)}function hr(e,t){return e[0]+"_"+e[1]+"_"+t}var dr=1.7580993408473768,mr=1.0507009873554805,gr=function(){function e(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float NAN;\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 "}return e.prototype.getCustomSetupFunc=function(){var e=this;return function(t,n){null==e.startLoc&&(e.startLoc=t.getUniformLocationNoThrow(n,"NAN"),null==e.startLoc)||t.gl.uniform1f(e.startLoc,NaN)}},e}(),yr="if (isNaN(x)) return x;",vr=Je({concat_:function(e,t){void 0===t&&(t=0),d(e.length>=1,"Pass at least one tensor to concat");var n=Ye(e,"tensors","concat");t=ze(t,n[0].shape)[0];var r=We(n.map(function(e){return e.shape}),t);if(0===b(r))return nt([],r);if(1===(n=n.filter(function(e){return e.size>0})).length)return n[0];var a=n.map(function(e){return e.shape});!function(e,t){var n=e[0].length;e.forEach(function(e,t){d(e.length===n,"Error in concat"+n+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+n+")")}),d(t>=0&&t>>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}(e),a=t&&t.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),Or=Er(function(e){!function(e,t,n){function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),kr=Er(function(e){!function(e,t,n){function r(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 a(e,t){var n=new function(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()}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),Ir=Er(function(e){!function(e,t,n){function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new function(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)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),Cr=Er(function(e){!function(e,t,n){function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new function(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,o,s=[],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&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;e.w=o,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),Ar=Er(function(e){!function(e,t,n){function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),Pr=Er(function(e){!function(t,r){var a,i=this,o=256,s=6,u="random",l=r.pow(o,s),c=r.pow(2,52),f=2*c,p=o-1;function h(e,n,h){var y=[],v=m(function e(t,n){var r,a=[],i=typeof t;if(n&&"object"==i)for(r in t)try{a.push(e(t[r],n-1))}catch(e){}return a.length?a:"string"==i?t:t+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[e,g(t)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(o):(e=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(e)),g(e)}catch(e){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(t)]}}():e,3),y),b=new function(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a=f;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,m(g(b.S),t),(n.pass||h||function(e,t,n,a){return a&&(a.S&&d(a,b),e.state=function(){return d(b,{})}),n?(r[u]=e,t):e})(w,v,"global"in n?n.global:this==r,n.state)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function m(e,t){for(var n,r=e+"",a=0;a=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}();function Rr(e,t){return l(this,void 0,void 0,function(){var n,r,a,i,o,s,u,l,f,p,h,d,m,g,y,v,b,w,x,_;return c(this,function(c){switch(c.label){case 0:if(2!==(n=Xe(e,"img","toPixels","int32")).rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(o=2===n.rank?1:n.shape[2])>4||2===o)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+o);return s=n.min(),u=n.max(),[4,s.data()];case 1:return l=c.sent()[0],[4,u.data()];case 2:if(f=c.sent()[0],s.dispose(),u.dispose(),"float32"===n.dtype){if(l<0||f>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+f+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(l<0||f>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+f+"].")}return[4,n.data()];case 3:for(p=c.sent(),h="float32"===n.dtype?255:1,d=new Uint8ClampedArray(i*a*4),m=0;m=1+t.length,"input rank should be > than [blockShape] but got "+r.rank),d(n.length===t.length,"crops.shape[0] must be equal to [blockShape] but got "+n.length),d(r.shape[0]%a==0,"input tensor batch must be divisible by prod( blockShape )"),me.engine.runKernel(function(e){return e.batchToSpaceND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}})}}),zr=Je({cast_:function(e,t){var n=Xe(e,"x","cast");return me.engine.runKernel(function(e){return e.cast(n,t)},{$x:n},function(e){return{$x:function(){return e.clone()}}})}}),Br=Je({clone_:function(e){var t=Xe(e,"x","clone");return me.engine.runKernel(function(e){return Q.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),Fr=Je({cumsum_:function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=Xe(e,"x","cumsum"),i=Fe([t|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=Ue(1,a.rank)[0],u=me.engine.runKernel(function(e){return e.cumsum(o,s,n,r)},{permutedX:o},function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),Vr=Je({depthToSpace_:function(e,t,n){void 0===n&&(n="NHWC");var r=Xe(e,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return d(a*t>=0,"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(i*t>=0,"Negative dimension size caused by overflow when multiplying\n "+i+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(o%(t*t)==0,"Dimension size must be evenly divisible by "+t*t+" but is "+o+" for depthToSpace with input shape "+r.shape),me.engine.runKernel(function(e){return e.depthToSpace(r,t,n)},{$x:r})}}),Ur=Je({expandDims_:function(e,t){void 0===t&&(t=0);var n=Xe(e,"x","expandDims");d(t<=n.rank,"Axis must be <= rank of the tensor");var r=n.shape.slice();return t<0&&(d(-(n.rank+1)<=t,"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"),t=n.rank+t+1),r.splice(t,0,1),ta(n,r)}}),Wr=Je({eye_:function(e,t,n,r){void 0===r&&(r="float32"),null==t&&(t=e);for(var a=Dr([e,t],r),i=e<=t?e:t,o=0;o4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return me.engine.fromPixels(e,t)}}),$r=Je({multinomial_:function(e,t,n,r){void 0===r&&(r=!1);var a=Xe(e,"logits","multinomial"),i=a.size,o=a.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?a.as2D(1,-1):a,u=me.engine.runKernel(function(e){return e.multinomial(s,r,t,n)},{logits2D:s});return 1===o?u.as1D():u}}),Gr=Je({oneHot_:function(e,t,n,r){void 0===n&&(n=1),void 0===r&&(r=0);var a=Xe(e,"indices","oneHot","int32");if(d("int32"===a.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return me.engine.runKernel(function(e){return e.oneHot(a,t,n,r)},{$indices:a},function(e){return{$indices:function(){return _t(a)}}})}}),Hr=Je({pad_:function(e,t,n){void 0===n&&(n=0);var r=Xe(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a=t.map(function(e){return e[0]});return me.engine.runKernel(function(e){return e.pad(r,t,n)},{$x:r},function(e){return{$x:function(){return e.slice(a,r.shape)}}})}}),Kr=Je({pad1d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length,"Invalid number of paddings. Must be length of 2."),Hr(e,[t],n)}}),Xr=Je({pad2d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length&&2===t[0].length&&2===t[1].length,"Invalid number of paddings. Must be length of 2 each."),Hr(e,t,n)}}),Yr=Je({pad3d_:function(e,t,n){return void 0===n&&(n=0),d(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."),Hr(e,t,n)}}),Jr=Je({pad4d_:function(e,t,n){return void 0===n&&(n=0),d(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."),Hr(e,t,n)}}),Zr=Je({rand_:function(e,t,n){var r=b(e),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(var i=0;i=1+t.length,"input rank "+r.rank+" should be > than [blockShape] "+t.length),d(n.length===t.length,"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+t.length),d(r.shape.reduce(function(e,r,a){return 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()),me.engine.runKernel(function(e){return e.spaceToBatchND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}})}}),ra=Je({squeeze_:function(e,t){var n=Xe(e,"x","squeeze");return ta(n,k(n.shape,t).newShape)}}),aa=Je({stack_:function(e,t){void 0===t&&(t=0);var n=Ye(e,"tensors","stack");if(d(n.length>=1,"Pass at least one tensor to tf.stack"),1===n.length)return n[0].expandDims(t);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;d(t<=r,"Axis must be <= rank of the tensor"),n.forEach(function(e){m(a,e.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(e){d(i===e.dtype,"All tensors passed to stack must have matching dtypes")});var o=n.map(function(e){return e.expandDims(t)});return vr(o,t)}}),ia=Je({tile_:function(e,t){var n=Xe(e,"x","tile");return d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of reps "+t+"."),me.engine.runKernel(function(e){return e.tile(n,t)},{$x:n},function(e){return{$x:function(){var r=_t(n);if(1===n.rank)for(var a=0;a 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\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "}(a);this.compileAndRun(s,[o],i,null,!1);var u=this.texData.get(i.dataId),l=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture,u.texShape[0],u.texShape[1]);return o.dispose(),i.dispose(),l},e.prototype.time=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),a=y(this.activeTimers),this.activeTimers=t,r&&(this.programTimersStack=null),[4,Promise.all(a).then(function(e){var t=0;return e.forEach(function(e){return t+=e}),t})];case 1:return i=s.sent(),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:i,wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return l(this,void 0,void 0,function(){var t;return c(this,function(n){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),n=t.texture,r=t.texShape,a=t.usage,i=t.complexTensors;null!=n&&this.releaseTexture(e,n,r,a),null!=i&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.getCanvas=function(){return this.canvas},e.prototype.complex=function(e,t){var n=Q.make(e.shape,{},"complex64");return this.texData.get(n.dataId).complexTensors={real:me.engine.keep(e.clone()),imag:me.engine.keep(t.clone())},n},e.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},e.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},e.prototype.slice=function(e,t,n){var r=new cr(n),a=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,a)},e.prototype.stridedSlice=function(e,t,n,r,a,i,o,s,u){var l=Ge(e.shape,t,n,r,a,i,o,s,u),c=l[0],f=l[1],p=l[2],h=f.filter(function(e,t){return-1===p.indexOf(t)});if(h.some(function(e){return 0===e}))return nt([],h);var d=new function(e,t,n,r){this.variableNames=["x"];var a=n.filter(function(e,t){return-1===r.indexOf(t)});this.outputShape=a;var i=n.length,o=qt(n.length),s=qt(a.length),u="";if(1===i)u="coords * strides + begin";else{var l=0;u=n.map(function(e,t){return-1===r.indexOf(t)?(l++,1===a.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(l-1)+"] * strides["+t+"] + begin["+t+"]"):"begin["+t+"]"}).join(",")}this.userCode="\n "+o+" begin = "+o+"("+e+");\n "+o+" strides = "+o+"("+t+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "}(c,r,f,p);return this.compileAndRun(d,[e])},e.prototype.reverse=function(e,t){var n=new function(e,t){this.variableNames=["x"];var 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){var r=e.map(function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),a=qt(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "}(e.shape,t);return this.compileAndRun(n,[e])},e.prototype.concat2Tensors=function(e,t,n){var r=We([e.shape,t.shape],n),a=e.as2D(-1,b(e.shape.slice(n))),i=t.as2D(-1,b(t.shape.slice(n))),o=new function(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=We([e,t],1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "}(a.shape,i.shape);return this.compileAndRun(o,[a,i]).reshape(r)},e.prototype.concat=function(e,t){if(1===e.length)return e[0];for(var n=e[0],r=1;r= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "}(e.shape,t,n,r,a);return this.compileAndRun(i,[e])},e.prototype.LRNGrad=function(e,t,n,r,a,i,o){var s=new function(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 "}(t.shape,r,a,i,o);return this.compileAndRun(s,[t,n,e])},e.prototype.tile=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.transpose=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r6)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),a=0;a4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=Ae(e.shape,t,r),i=Pe(a.length,t.length),o=Te(e.shape,t,r),s=Me(n,t.length),u=Re(o,n,t.length);return e.reshape(a).transpose(i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(e,t,n){d(e.rank<=4,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=[[0,0]];a.push.apply(a,n);for(var i=1+t.length;i= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(o="0.0",f="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var h="";a%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\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("+o+");\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; 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 "+f+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+f+"\n }\n setOutput("+u+");\n }\n "}({windowSize:$e(a),inSize:a,batchSize:r},t),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],n);return this.compileAndRun(i,[e],l),1===l.shape[1]?l:this.reduce(l,t,n)},e.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],a=e.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=new function(e,t,n){this.variableNames=["A"];var r=e.windowSize,a=e.batchSize,i=e.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===t?">":"<",u=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 = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\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 "}({windowSize:$e(a),inSize:a,batchSize:r},t,null==n),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],"int32"),c=[e];return null!=n&&c.push(n),this.compileAndRun(i,c,l),1===l.shape[1]?l:this.argReduce(e,t,l)},e.prototype.sum=function(e,t){Be("sum",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a),o=Nt(e.dtype);return this.reduce(i,"sum",o).reshape(r)},e.prototype.unsortedSegmentSum=function(e,t,n){var r=0,a=Fe([r],e.rank),i=e;null!=a&&(i=e.transpose(a),r=Ue(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],a=e.length,i=0;it||n===e){r=!0;break}n=D(e,n+1)}return n}(o,a),u=new function(e,t){this.variableNames=["x","segmentIds"];var n=e.windowSize,r=e.batchSize,a=e.inSize,i=e.numSegments,o=i*Math.ceil(a/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, filter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var f="";a%n>0&&(f="\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 "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+f+"\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 < "+s+"; 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 filter = 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 "+l+"\n }\n\n int inIdx = inOffset + "+s+";\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = 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 "+l+"\n }\n setOutput(sumValue);\n }\n "}({windowSize:s,inSize:o,batchSize:i,numSegments:a},t),l=u.outputShape,c=l[0],f=l[1],p=this.makeOutputArray([c,f],r);return this.compileAndRun(u,[e,n],p),p.shape[1]===a?p:(n=dt(0,a).tile([o/s]),this.segOpCompute(p,t,n,r,a))},e.prototype.argMin=function(e,t){var n=[t];Be("argMin",n,e.rank);var r=je(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"min").reshape(a)},e.prototype.argMax=function(e,t){var n=[t];Be("argMax",n,e.rank);var r=je(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"max").reshape(a)},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new function(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,a=e[e.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+qt(r)+" coords = getOutputCoords();\n int end = "+Ht(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+Ht(r,"coords")+" = idx;\n val += getX("+function(e,t){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 sum for rank "+e+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}(e.shape,n,r);return this.compileAndRun(a,[e])},e.prototype.equal=function(e,t){var n=new Bt("return float(a == b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.notEqual=function(e,t){var n=new Bt("return float(a != b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.less=function(e,t){var n=new Bt("return float(a < b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.lessEqual=function(e,t){var n=new Bt("return float(a <= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greater=function(e,t){var n=new Bt("return float(a > b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greaterEqual=function(e,t){var n=new Bt("return float(a >= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalNot=function(e){var t=new gr(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},e.prototype.logicalAnd=function(e,t){var n=new Bt("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalOr=function(e,t){var n=new Bt("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.select=function(e,t,n){var r=new function(e,t,n){var 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{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "}(e.rank,t.shape,t.rank),a=this.makeOutputArray(r.outputShape,Et(t.dtype,n.dtype));return this.compileAndRun(r,[e,t,n],a)},e.prototype.where=function(e){Ce("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return ua(e.shape,t)},e.prototype.topk=function(e,t,n){return Tt(e.dataSync(),e.shape,e.dtype,t)},e.prototype.min=function(e,t){Be("min",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(e,t){var n=new Bt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.mod=function(e,t){var n=new Bt("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[e,t],null,r)},e.prototype.max=function(e,t){Be("max",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(e,t){var n=new Bt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.all=function(e,t){Be("all",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(e,t){Be("any",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.squaredDifference=function(e,t){var n=new Bt("return (a - b) * (a - b);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.realDivide=function(e,t){var n=new Bt("if (a == b) return 1.0;\n return a / b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e,t],r)},e.prototype.floorDiv=function(e,t){var n=new Bt("\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[e,t],r)},e.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,Lt);var n=new Bt(Lt,e.shape,t.shape),r=this.makeOutputArray(n.outputShape,Et(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r)},e.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,a=this.texData.get(e.dataId),i=this.texData.get(t.dataId),o=[[a.complexTensors.real,i.complexTensors.real],[a.complexTensors.imag,i.complexTensors.imag]].map(function(a){var i=a[0],o=a[1],s=new Bt(n,e.shape,t.shape),u=r.makeOutputArray(s.outputShape,Et(i.dtype,o.dtype)),l=r.makeComplexComponentTensorHandle(e,i),c=r.makeComplexComponentTensorHandle(t,o);return r.compileAndRun(s,[l,c],u)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},e.prototype.addN=function(e){for(var t=e[0],n=1;n 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");return this.compileAndRun(t,[e])},e.prototype.exp=function(e){var t=new gr(e.shape,"return exp(x);");return this.compileAndRun(t,[e])},e.prototype.expm1=function(e){var t=new gr(e.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[e])},e.prototype.log=function(e){var t=new gr(e.shape,"if (x < 0.0) return NAN;\n return log(x);"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.log1p=function(e){var t=new gr(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},e.prototype.sqrt=function(e){var t=new gr(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},e.prototype.rsqrt=function(e){var t=new gr(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},e.prototype.square=function(e){var t=new gr(e.shape,"return x * x;");return this.compileAndRun(t,[e])},e.prototype.reciprocal=function(e){var t=new gr(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},e.prototype.relu=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(t,[e])},e.prototype.elu=function(e){var t=new gr(e.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[e])},e.prototype.eluDer=function(e,t){var n=new Bt("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.selu=function(e){var t=new gr(e.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[e])},e.prototype.int=function(e){var t=new gr(e.shape,"return float(int(x));"),n=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],n)},e.prototype.clip=function(e,t,n){var r=new function(e,t,n){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, float("+t+"), float("+n+")));\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.abs=function(e){var t=new gr(e.shape,"return abs(x);");return this.compileAndRun(t,[e])},e.prototype.sigmoid=function(e){var t=new gr(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},e.prototype.softplus=function(e){var t=new gr(e.shape,"\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");return this.compileAndRun(t,[e])},e.prototype.sin=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return sin(x);\n");return this.compileAndRun(t,[e])},e.prototype.cos=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return cos(x);\n");return this.compileAndRun(t,[e])},e.prototype.tan=function(e){var t=new gr(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},e.prototype.asin=function(e){var t=new gr(e.shape,"return asin(x);");return this.compileAndRun(t,[e])},e.prototype.acos=function(e){var t=new gr(e.shape,"return acos(x);");return this.compileAndRun(t,[e])},e.prototype.atan=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e])},e.prototype.atan2=function(e,t){var n=new Bt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.sinh=function(e){var t=new gr(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.cosh=function(e){var t=new gr(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.tanh=function(e){var t=new gr(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},e.prototype.asinh=function(e){var t=new gr(e.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e])},e.prototype.acosh=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.atanh=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.erf=function(e){var t=new gr(e.shape,'\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 = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(t,[e])},e.prototype.step=function(e,t){var n=new gr(e.shape,function(e){return void 0===e&&(e=0),yr+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(n,[e])},e.prototype.conv2d=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,n=e.padInfo.left,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),c=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+a+");\n const ivec2 pads = ivec2("+t+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * 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 < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\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 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 dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - 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 float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left;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 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2D=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,n=e.inWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,o=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,f=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+r+", "+a+");\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 / "+f+";\n int q = d2 - d1 * "+f+";\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 // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\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 setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[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 // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var 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 // TODO: 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.maxPool=function(e,t){var n=new lr(t,"max",!1),r=this.makeOutputArray(n.outputShape,e.dtype);return this.compileAndRun(n,[e],r)},e.prototype.avgPool=function(e,t){var n=new lr(t,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e],r)},e.prototype.maxPoolBackprop=function(e,t,n,r){var a=new lr(r,"max",!0),i=this.compileAndRun(a,[t]),o=new function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=t*n-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+s+" - 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 * "+n+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}(r),s=this.makeOutputArray(o.outputShape,t.dtype),u=this.compileAndRun(o,[e,i],s);return i.dispose(),u},e.prototype.avgPoolBackprop=function(e,t,n){var r=new function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n const float avgMultiplier = float("+s+");\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 < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}(n),a=this.makeOutputArray(r.outputShape,t.dtype);return this.compileAndRun(r,[e],a)},e.prototype.cast=function(e,t){return Ot(e,t,this)},e.prototype.reshape=function(e,t){return kt(e,t)},e.prototype.resizeBilinear=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\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 "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-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), "+(i-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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.resizeNearestNeighbor=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.multinomial=function(e,t,n,r){var a=t?e:Ze(e),i=a.shape[0],o=a.shape[1],s=new sr(i,o,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],u,l)},e.prototype.oneHot=function(e,t,n,r){var a=new function(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 "}(e.size,t,n,r);return this.compileAndRun(a,[e])},e.prototype.nonMaxSuppression=function(e,t,n,r,a){return Ce("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Ct(e.dataSync(),t.dataSync(),n,r,a)},e.prototype.cropAndResize=function(e,t,n,r,a,i){var o=new function(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=e[0],o=e[1],s=e[2],u=e[3],l=t[0],c=n[0],f=n[1];this.outputShape=[l,c,f,u];var p="bilinear"===r?1:0,h=[o-1+".0",s-1+".0"],d=h[0],m=h[1],g=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],S=w[2];this.userCode="\n const float height_ratio = float("+y+");\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 = "+v+";\n float width_scale = "+_+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "}(e.shape,t.shape,r,a,i);return this.compileAndRun(o,[e,t,n])},e.prototype.depthToSpace=function(e,t,n){d(t>1,"blockSize should be > 1 for depthToSpace, but was: "+t);var r=e.shape[0],a=("NHWC"===n?e.shape[1]:e.shape[2])*t,i=("NHWC"===n?e.shape[2]:e.shape[3])*t,o=("NHWC"===n?e.shape[3]:e.shape[1])/(t*t),s=new Yt("NHWC"===n?[r,a,i,o]:[r,o,a,i],t,n);return this.compileAndRun(s,[e])},e.prototype.split=function(e,t,n){return Pt(e,t,n)},e.prototype.makeOutputArray=function(e,t){return Q.make(e,{},t)},e.prototype.compileAndRun=function(e,t,n,r,a){var i=this;if(void 0===a&&(a=!0),null==n&&(n=this.makeOutputArray(e.outputShape,t[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=I(n.dtype,0),n;var o=t.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var t=i.texData.get(e.dataId);return null==t.texture&&b(e.shape)<=32?{shape:e.shape,texData:null,isUniform:!0,uniformValues:i.readSync(e.dataId)}:(i.uploadToGPU(e.dataId),{shape:e.shape,texData:t,isUniform:!1})});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(e,t,n){var r="";o.concat(n).forEach(function(e){r+=e.shape+"_"+(e.isUniform?"uniform":e.texData.texShape)});var a=e.userCode,i=(!0===e.supportsBroadcasting).toString();return e.constructor.name+"_"+i+"_"+r+"_"+a}(e,0,u),c=this.getAndSaveBinary(l,function(){return function(e,t,n,r){for(var a=t.userCode,i=n.map(function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.usage===Kt.PACK};return{name:t.variableNames[n],shapeInfo:r}}),o=i.map(function(e){return e.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.usage===Kt.PACK},u=Ft(i,s,a,!0===t.supportsBroadcasting),l=e.createProgram(u),c={},f=0;fthis.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;p>0&&this.lruDataGPU.length>0;){var h=this.lruDataGPU.shift(),d=this.texData.get(h),m=d.shape,g=d.dtype;p-=this.computeBytes(m,g),this.read(h)}return f&&(s=this.endTimer(s),this.activeTimers.push(this.getQueryTime(s))),n},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixelsCanvas&&this.fromPixelsCanvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.floatPrecision=function(){var e=this;return Ee(function(){return e.abs(rt(1e-8)).get()>0?32:16})},e.prototype.throwIfNoData=function(e){if(!this.texData.has(e))throw new Error("WebGL backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends")},e.prototype.uploadToGPU=function(e){this.throwIfNoData(e);var t=this.texData.get(e),n=t.shape,r=t.values,a=t.texture,i=(t.dtype,t.usage);if(null==a){var o,s=null!=this.activeTimers;s&&(o=performance.now());var u=jn(this.gpgpu.gl,n);t.texShape=u;var l=this.acquireTexture(e,u,i);t.texture=l,null!=r&&(this.gpgpu.uploadMatrixToTexture(l,u[0],u[1],r instanceof Float32Array?r:new Float32Array(r)),t.values=null,s&&(this.uploadWaitMs+=performance.now()-o))}else this.lruDataGPU.indexOf(e)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),this.lruDataGPU.push(e))},e.prototype.cacheOnCPU=function(e,t){var n=this.delayedStorage,r=this.texData.get(e),a=r.texture,i=r.texShape,o=r.dtype,s=r.usage;n&&null!=a&&(this.releaseTexture(e,a,i,s),r.texture=null,r.texShape=null),r.usage=Kt.UPLOAD,null!=t&&(r.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r=0&&this.lruDataGPU.splice(s,1),this.numBytesInGPU-=this.computeBytes(i,o),this.textureManager.releaseTexture(t,n,r)},e.prototype.acquireTexture=function(e,t,n){var r=this.texData.get(e),a=r.shape,i=r.dtype;return this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(a,i),this.textureManager.acquireTexture(t,n)},e.prototype.computeBytes=function(e,t){return b(e)*M(t)},e}();me.get("IS_BROWSER")&&me.registerBackend("webgl",function(){return new ca},2,Z);var fa=Je({abs_:function(e){var t=Xe(e,"x","abs");return me.engine.runKernel(function(e){return e.abs(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().step(-1))}}})}}),pa=Je({acos_:function(e){var t=Xe(e,"x","acos");return me.engine.runKernel(function(e){return e.acos(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()).sqrt()).neg()}}})}}),ha=Je({acosh_:function(e){var t=Xe(e,"x","acosh");return me.engine.runKernel(function(e){return e.acosh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().square().sub(rt(1)).sqrt())}}})}}),da=Je({asin_:function(e){var t=Xe(e,"x","asin");return me.engine.runKernel(function(e){return e.asin(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()).sqrt())}}})}}),ma=Je({asinh_:function(e){var t=Xe(e,"x","asinh");return me.engine.runKernel(function(e){return e.asinh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).add(t.toFloat().square()).sqrt())}}})}}),ga=Je({atan_:function(e){var t=Xe(e,"x","atan");return me.engine.runKernel(function(e){return e.atan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).add(t.toFloat().square()))}}})}}),ya=Je({atanh_:function(e){var t=Xe(e,"x","atanh");return me.engine.runKernel(function(e){return e.atanh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()))}}})}}),va=Je({ceil_:function(e){var t=Xe(e,"x","ceil");return me.engine.runKernel(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),ba=Je({clipByValue_:function(e,t,n){var r=Xe(e,"x","clipByValue");return d(t<=n,"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."),me.engine.runKernel(function(e){return e.clip(r,t,n)},{$x:r},function(e){return{$x:function(){return e.where(r.greaterEqual(rt(t)).logicalAnd(r.lessEqual(rt(n))),_t(e))}}})}}),wa=Je({cos_:function(e){var t=Xe(e,"x","cos");return me.engine.runKernel(function(e){return e.cos(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sin().neg().mulStrict(e)}}})}}),xa=Je({cosh_:function(e){var t=Xe(e,"x","cosh");return me.engine.runKernel(function(e){return e.cosh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sinh().mulStrict(e)}}})}}),_a=Je({erf_:function(e){var t=Xe(e,"x","erf");return d("int32"===t.dtype||"float32"===t.dtype,"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=t.toFloat()),me.engine.runKernel(function(e){return e.erf(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(rt(2/Math.sqrt(Math.PI)).mul(t.square().neg().exp()))}}})}}),Sa=Je({exp_:function(e){var t=Xe(e,"x","exp");return me.engine.runKernel(function(e,n){return n(e.exp(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n)}}})}}),Ea=Je({expm1_:function(e){var t=Xe(e,"x","expm1");return me.engine.runKernel(function(e){return e.expm1(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.exp())}}})}}),Na=Je({floor_:function(e){var t=Xe(e,"x","floor");return me.engine.runKernel(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Oa=Je({log_:function(e){var t=Xe(e,"x","log");return me.engine.runKernel(function(e){return e.log(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat())}}})}}),ka=Je({log1p_:function(e){var t=Xe(e,"x","log1p");return me.engine.runKernel(function(e){return e.log1p(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.add(rt(1)))}}})}}),Ia=Je({logSigmoid_:function(e){var t=Xe(e,"x","logSigmoid");return me.engine.runKernel(function(e){return e.softplus(t.neg()).neg()},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.neg().sigmoid())}}})}}),Ca=Je({neg_:function(e){var t=Xe(e,"x","neg");return me.engine.runKernel(function(e){return e.neg(t)},{$x:t},function(e){return{$x:function(){return e.neg()}}})}}),Aa=Je({reciprocal_:function(e){var t=Xe(e,"x","reciprocal");return me.engine.runKernel(function(e){return e.reciprocal(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.square().neg())}}})}}),Pa=Je({round_:function(e){var t=Xe(e,"x","round");return me.engine.runKernel(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Ta=Je({rsqrt_:function(e){var t=Xe(e,"x","rsqrt");return me.engine.runKernel(function(e){return e.rsqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.pow(rt(1.5)).mul(rt(2))).neg()}}})}}),Ma=Je({sigmoid_:function(e){var t=Xe(e,"x","sigmoid");return me.engine.runKernel(function(e,n){return n(e.sigmoid(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n.mul(rt(1).sub(n)))}}})}}),Ra=Je({sign_:function(e){var t=Xe(e,"x","sign");return me.engine.runKernel(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Da=Je({sin_:function(e){var t=Xe(e,"x","sin");return me.engine.runKernel(function(e){return e.sin(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cos().mulStrict(e)}}})}}),ja=Je({sinh_:function(e){var t=Xe(e,"x","sinh");return me.engine.runKernel(function(e){return e.sinh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cosh().mulStrict(e)}}})}}),La=Je({softplus_:function(e){var t=Xe(e,"x","softplus");return me.engine.runKernel(function(e){return e.softplus(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.sigmoid())}}})}}),za=Je({sqrt_:function(e){var t=Xe(e,"x","sqrt");return me.engine.runKernel(function(e){return e.sqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().sqrt().mul(rt(2)))}}})}}),Ba=Je({square_:function(e){var t=Xe(e,"x","square");return me.engine.runKernel(function(e){return e.square(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().mul(rt(2)))}}})}}),Fa=Je({step_:function(e,t){void 0===t&&(t=0);var n=Xe(e,"x","step");return me.engine.runKernel(function(e){return e.step(n,t)},{$x:n},function(e){return{$x:function(){return _t(e)}}})}}),Va=Je({tan_:function(e){var t=Xe(e,"x","tan");return me.engine.runKernel(function(e){return e.tan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.cos().square())}}})}}),Ua=Je({tanh_:function(e){var t=Xe(e,"x","tanh");return me.engine.runKernel(function(e,n){return n(e.tanh(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return rt(1).sub(n.square()).mulStrict(e)}}})}});function Wa(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}var qa=Je({batchNormalization2d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(2===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(2===l.rank||1===l.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."),d(2===c.rank||1===c.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."),null!=o&&d(2===o.rank||1===o.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."),null!=s&&d(2===s.rank||1===s.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),$a=Je({batchNormalization3d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(3===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(3===l.rank||1===l.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."),d(3===c.rank||1===c.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."),null!=o&&d(3===o.rank||1===o.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."),null!=s&&d(3===s.rank||1===s.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),Ga=Je({batchNormalization4d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(4===u.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+u.rank+"."),d(4===l.rank||1===l.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."),d(4===c.rank||1===c.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."),null!=o&&d(4===o.rank||1===o.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."),null!=s&&d(4===s.rank||1===s.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),Ha=Je({batchNormalization_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u,l=Xe(e,"x","batchNormalization"),c=Xe(t,"mean","batchNormalization"),f=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(c.rank===f.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),d(null==s||c.rank===s.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),d(null==o||c.rank===o.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,me.engine.runKernel(function(e){return e.batchNormalization(u,Wa(c),Wa(f),r,Wa(o),Wa(s))},{$x:l,$mean:c,$variance:f,$scale:o,$offset:s},function(e){var t=null==o?rt(1):o,n=Rt(c.shape,u.shape),a=[];if(1===c.rank){for(var i=0;i=2&&i.rank>=2&&a.rank===i.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."),d(w(c,f),"Error in matMul: outer dimensions ("+c+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."),d(o===s,"Error in matMul: inner shapes ("+o+") and ("+s+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match.");var m=a.shape.slice(0,-2).concat([u,l]),g=n?a.as3D(p,o,u):a.as3D(p,u,o),y=r?i.as3D(h,l,s):i.as3D(h,s,l);return me.engine.runKernel(function(e){return e.batchMatMul(g,y,n,r)},{$a:g,$b:y},function(e){return n||r?!n&&r?{$a:function(){return e.matMul(y.toFloat(),!1,!1)},$b:function(){return e.matMul(g.toFloat(),!0,!1)}}:n&&!r?{$a:function(){return y.toFloat().matMul(e,!1,!0)},$b:function(){return g.toFloat().matMul(e,!1,!1)}}:{$a:function(){return y.toFloat().matMul(e,!0,!0)},$b:function(){return e.matMul(g.toFloat(),!0,!0)}}:{$a:function(){return e.matMul(y.toFloat(),!1,!0)},$b:function(){return g.toFloat().matMul(e,!0,!1)}}}).reshape(m)}}),ei=Je({dot_:function(e,t){var n=Xe(e,"t1","dot"),r=Xe(t,"t2","dot");d(!(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+".");var a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return d(a===i,"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+i+"."),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),ti=Je({outerProduct_:function(e,t){var n=Xe(e,"v1","outerProduct"),r=Xe(t,"v2","outerProduct");return d(1===n.rank&&1===r.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."),n.as2D(-1,1).matMul(r.as2D(1,-1))}});function ni(e,t,n,r,a,i){d(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var o=e,s=t,u=!1;3===t.rank&&(u=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),o=[1,e[0],e[1],e[2]]);var l=o[3],c=s.shape[3];d(4===o.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+o.length+"."),d(4===s.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank),d(4===n.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank),d(l===n.shape[2],"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."),d(c===n.shape[3],"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[3]+"."),null!=i&&d(x(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var f=Xa(o,n.shape,r,1,a,i),p=me.engine.runKernel(function(e){return e.conv2dDerInput(s,n,f)},{dy4D:s});return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function ri(e){var t=function(e){return"number"==typeof e?[e,e]:e}(e),n=t[0],r=t[1];return 1===n&&1===r}function ai(e,t){return ri(e)||ri(t)}var ii=Je({conv1d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NWC"),void 0===i&&(i=1);var s=Xe(e,"x","conv1d"),u=Xe(t,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),d(3===l.rank,"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."),d(3===u.rank,"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."),null!=o&&d(x(r),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),d(l.shape[2]===u.shape[1],"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."),d(ai(n,i),"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"),d("NWC"===a,"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported.");var f=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),p=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),h=oi(p,f,[1,n],r,"NHWC",[1,i],o);return c?h.as2D(h.shape[2],h.shape[3]):h.as3D(h.shape[0],h.shape[2],h.shape[3])}}),oi=Je({conv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=Xe(e,"x","conv2d"),u=Xe(t,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."),d(4===u.rank,"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."),null!=o&&d(x(r),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),d(l.shape[3]===u.shape[2],"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+"."),d(ai(n,i),"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),d("NHWC"===a,"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported.");var f,p=Xa(l.shape,u.shape,n,i,r,o);if(1===p.filterHeight&&1===p.filterWidth&&1===p.dilationHeight&&1===p.dilationWidth&&1===p.strideHeight&&1===p.strideWidth&&"SAME"===p.padInfo.type){var h=l.reshape([-1,p.inChannels]),m=u.reshape([p.inChannels,p.outChannels]);f=Qa(h,m).reshape(p.outShape)}else f=me.engine.runKernel(function(e){return e.conv2d(l,u,p)},{x:l,$filter:u},function(e){return d(ri(i),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+i+"'"),{x:function(){return ni(l.shape,e,u,n,r)},$filter:function(){return function(e,t,n,r,a,i){var o=e;3===e.rank&&(o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t;3===s.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),d(4===o.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+o.shape+"."),d(4===s.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."),d(4===n.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."),d(o.shape[3]===n[2],"Error in conv2dDerFilter: depth of input "+o.shape[3]+") must match input depth in filter ("+n[2]+"."),d(s.shape[3]===n[3],"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+n[3]+").");var u=Xa(o.shape,n,r,1,a,i);return me.engine.runKernel(function(e){return e.conv2dDerFilter(o,s,u)},{x4D:o,dy4D:s})}(l,e,u.shape,n,r)}}});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),si=Je({depthwiseConv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=Xe(e,"x","depthwiseConv2d"),u=Xe(t,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."),d(4===u.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),d(l.shape[3]===u.shape[2],"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."),null==i&&(i=[1,1]),d(ai(n,i),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),null!=o&&d(x(r),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+".");var f=Xa(l.shape,u.shape,n,i,r,o,!0),p=me.engine.runKernel(function(e){return e.depthwiseConv2D(l,u,f)},{x:l,$filter:u},function(e){return d(ri(i),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"),{x:function(){return function(e,t,n,r){var a=t,i=!1;3===t.rank&&(i=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=me.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,n,r)},{dy4D:a});return i?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}(l.shape,e,u,f)},$filter:function(){return function(e,t,n,r){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=t;return 3===i.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),me.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,i,r)},{x4D:a,dy4D:i})}(l,e,u.shape,f)}}});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),ui=Je({separableConv2d_:function(e,t,n,r,a,i,o){void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC");var s=Xe(e,"x","separableConv2d"),u=Xe(t,"depthwiseFilter","separableConv2d"),l=Xe(n,"pointwiseFilter","separableConv2d"),c=s,f=!1;if(3===s.rank&&(f=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");d(4===c.rank,"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."),d(4===u.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."),d(4===l.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."),d(1===l.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."),d(1===l.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+".");var p=u.shape[2],h=u.shape[3];d(l.shape[2]===p*h,"Error in separableConv2d: the third dimension of pointwise filter must be "+p*h+", but got "+l.shape[2]+".");var m=si(c,u,r,a,o,i),g=oi(m,l,1,"valid",o);return f?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),li=Je({conv2dTranspose_:function(e,t,n,r,a,i){return ni(n,Xe(e,"x","conv2dTranspose"),Xe(t,"filter","conv2dTranspose"),r,a,i)}}),ci=Je({reverse_:function(e,t){var n=Xe(e,"x","reverse");if(0===n.rank)return n.clone();var r=ze(t,n.shape);return me.engine.runKernel(function(e){return e.reverse(n,r)},{$x:n},function(e){return{$x:function(){return e.reverse(r)}}}).reshapeAs(n)}}),fi=Je({reverse1d_:function(e){var t=Xe(e,"x","reverse");return d(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),ci(t,0)}}),pi=Je({reverse2d_:function(e,t){var n=Xe(e,"x","reverse");return d(2===n.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+n.rank+"."),ci(n,t)}}),hi=Je({reverse3d_:function(e,t){var n=Xe(e,"x","reverse");return d(3===n.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+n.rank+"."),ci(n,t)}}),di=Je({reverse4d_:function(e,t){var n=Xe(e,"x","reverse");return d(4===n.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+n.rank+"."),ci(n,t)}}),mi=Je({maxPool_:function(e,t,n,r,a){var i=Xe(e,"x","maxPool"),o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ka(o.shape,t,n,r,a),l=me.engine.runKernel(function(e,t){return t(e.maxPool(o,u))},{x:o},function(e,a){var i=a[0];return{x:function(){return function(e,t,n,r,a,i,o){var s=Xe(e,"dy","maxPoolBackprop"),u=Xe(t,"input","maxPoolBackprop"),l=Xe(n,"output","maxPoolBackprop");d(u.rank===s.rank,"Rank of input ("+u.rank+") does not match rank of dy ("+s.rank+")"),d(4===s.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+s.rank+"."),d(4===u.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+".");var c=Ka(u.shape,r,a,i,o);return me.engine.runKernel(function(e){return e.maxPoolBackprop(s,u,l,c)},{$dy:s,$input:u})}(e,o,i,t,n,r)}}});return s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),gi=Je({avgPool_:function(e,t,n,r,a){var i=Xe(e,"x","avgPool");d("float32"===i.dtype,"The input dtype to avgPool must be float32");var o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in avgPool: x must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ka(o.shape,t,n,r),l=me.engine.runKernel(function(e){return e.avgPool(o,u)},{x:o},function(e){return{x:function(){return function(e,t,n,r,a){var i=Xe(e,"dy","avgPoolBackprop"),o=Xe(t,"input","avgPoolBackprop");d(o.rank===i.rank,"Rank of input ("+o.rank+") does not match rank of dy ("+i.rank+")");var s=o,u=i,l=!1;3===o.rank&&(l=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]),u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===u.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),d(4===s.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+".");var c=Ka(s.shape,n,r,a),f=me.engine.runKernel(function(e){return e.avgPoolBackprop(u,s,c)},{dy4D:u,input4D:s});return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(e,o,t,n,r)}}});return l=l.cast(i.dtype),s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),yi=Je({slice_:function(e,t,n){var r,a,i=Xe(e,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof t?[t].concat(new Array(i.rank-1).fill(0)):t.length=0?e:(d(-1===e,"Bad value in size"),i.shape[t]-r[t])}),function(e,t,n){d(e.rank===t.length,"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."),d(e.rank===n.length,"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+").");for(var r=0;r0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Rt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)}}})}}),Gi=Je({addN_:function(e){d(Array.isArray(e),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(e.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length});var t=e.map(function(e,t){return Xe(e,"tensors"+t,"addN")}),n=t[0];t.forEach(function(e){if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(e){if(!w(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=t;return me.engine.runKernel(function(e){return e.addN(t)},r,function(e){var n={};return t.forEach(function(t,r){n[r]=function(){return e.clone()}}),n})}}),Hi=Je({addStrict_:function(e,t){return m(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),Ki=Je({atan2_:function(e,t){var n=Xe(e,"a","atan2"),r=Xe(t,"b","atan2");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.atan2(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=$i(n.square(),r.square()),i=e.mul(r.div(t)),o=Rt(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=$i(n.square(),r.square()),i=Ca(e.mul(n.div(t))),o=Rt(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Xi=Je({div_:function(e,t){var n,r=Xe(e,"a","div"),a=Xe(t,"b","div");if(ne(r,a),"int32"===r.dtype&&"int32"===a.dtype)return Ji(r,a);n=function(e){return e.realDivide(r,a)};var i=Dt(r.shape,a.shape);return me.engine.runKernel(n,{$a:r,$b:a},function(e){return{$a:function(){var t=e.div(a.toFloat()),n=Rt(r.shape,i);return n.length>0?t.sum(n).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),n=Rt(a.shape,i);n.length>0&&(t=t.sum(n).reshape(a.shape));var o=a.square();return t.div(o.toFloat()).neg()}}})}}),Yi=Je({divStrict_:function(e,t){return m(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),Ji=Je({floorDiv_:function(e,t){var n=Xe(e,"a","floorDiv"),r=Xe(t,"b","floorDiv");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.floorDiv(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.div(r.toFloat()),i=Rt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Rt(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}})}}),Zi=Je({maximum_:function(e,t){var n=Xe(e,"a","maximum"),r=Xe(t,"b","maximum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.maximum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.greaterEqual(r).toFloat())},$b:function(){return e.mul(n.less(r).toFloat())}}})}}),Qi=Je({maximumStrict_:function(e,t){return m(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),eo=Je({minimum_:function(e,t){var n=Xe(e,"a","minimum"),r=Xe(t,"b","minimum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.minimum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.lessEqual(r).toFloat())},$b:function(){return e.mul(n.greater(r).toFloat())}}})}}),to=Je({minimumStrict_:function(e,t){return m(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),no=Je({mod_:function(e,t){var n=Xe(e,"a","mod"),r=Xe(t,"b","mod");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.mod(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=Rt(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=Rt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),ro=Je({modStrict_:function(e,t){return m(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),ao=Je({mul_:function(e,t){var n=Xe(e,"a","mul"),r=Xe(t,"b","mul");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.multiply(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.mul(r.toFloat()),i=Rt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Rt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),io=Je({mulStrict_:function(e,t){return m(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),oo=Je({pow_:function(e,t){var n=Xe(e,"base","pow"),r=Xe(t,"exp","pow"),a=Dt(n.shape,r.shape);return e=n.cast(Et(n.dtype,r.dtype)),t=r.cast(Et(n.dtype,r.dtype)),me.engine.runKernel(function(e,t){return t(e.pow(n,r))},{$base:n,$exp:r},function(e,t){var i=t[0];return{$base:function(){var t=e.mul(r.toFloat().mul(i.div(n))),o=Rt(n.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(n.shape)},$exp:function(){var t=e.mul(i.mul(n.log()).toFloat()),o=Rt(r.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(r.shape)}}})}}),so=Je({powStrict_:function(e,t){return m(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),uo=Je({squaredDifference_:function(e,t){var n=Xe(e,"a","squaredDifference"),r=Xe(t,"b","squaredDifference");return ne(n,r),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.squaredDifference(n,r)},{$a:n,$b:r},function(e){var t=rt(2);return{$a:function(){return e.mul(n.sub(r).mul(t))},$b:function(){return e.mul(r.sub(n).mul(t))}}})}}),lo=Je({squaredDifferenceStrict_:function(e,t){return m(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),co=Je({sub_:function(e,t){var n=Xe(e,"a","sub"),r=Xe(t,"b","sub");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.subtract(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e,r=Rt(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Rt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(r.shape)}}})}}),fo=Je({subStrict_:function(e,t){return m(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),po=Je({logicalAnd_:function(e,t){var n=Xe(e,"a","logicalAnd","bool"),r=Xe(t,"b","logicalAnd","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalAnd(n,r)},{$a:n,$b:r})}}),ho=Je({logicalNot_:function(e){var t=Xe(e,"x","logicalNot","bool");return d("bool"===t.dtype,"Error Array must be of type bool."),me.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})}}),mo=Je({logicalOr_:function(e,t){var n=Xe(e,"a","logicalOr","bool"),r=Xe(t,"b","logicalOr","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalOr(n,r)},{$a:n,$b:r})}}),go=Je({logicalXor_:function(e,t){var n=Xe(e,"a","logicalXor","bool"),r=Xe(t,"b","logicalXor","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),mo(e,t).logicalAnd(po(e,t).logicalNot())}}),yo=Je({where_:function(e,t,n){var r=Xe(t,"a","where"),a=Xe(n,"b","where"),i=Xe(e,"condition","where","bool");return d("bool"===i.dtype,"Error Condition must be of type bool."),m(r.shape,a.shape,"Error in where: "),1===i.rank?d(i.shape[0]===r.shape[0],"The first dimension of `a` must match the size of `condition`."):m(i.shape,a.shape,"Error in where: "),me.engine.runKernel(function(e){return e.select(i,r,a)},{$condition:i,$a:r,$b:a},function(e){return{$condition:function(){return _t(i)},$a:function(){return e.mul(i.cast(r.dtype))},$b:function(){return e.mul(i.logicalNot().cast(a.dtype))}}})}}),vo=function(e){return l(this,void 0,void 0,function(){var t,n,r;return c(this,function(a){switch(a.label){case 0:return d("bool"===(t=Xe(e,"condition","where","bool")).dtype,"Condition must be of type bool."),[4,t.data()];case 1:return n=a.sent(),r=ua(t.shape,n),e!==t&&t.dispose(),[2,r]}})})},bo=Je({elu_:function(e){var t=Xe(e,"x","elu");return me.engine.runKernel(function(e,n){return n(e.elu(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return me.engine.runKernel(function(t){return t.eluDer(e,n)},{dy:e,y:n})}}})}}),wo=Je({leakyRelu_:function(e,t){void 0===t&&(t=.2);var n=Xe(e,"x","leakyRelu");return Zi(rt(t).mul(n),n)}}),xo=Je({prelu_:function(e,t){var n=Xe(e,"x","prelu"),r=Xe(t,"alpha","prelu"),a=rt(0);return Zi(a,n).add(r.mul(eo(a,n)))}}),_o=Je({relu_:function(e){var t=Xe(e,"x","relu");return"bool"===t.dtype?t.toInt():me.engine.runKernel(function(e){return e.relu(t)},{$x:t},function(e){var n=t.step();return{$x:function(){return e.mulStrict(n.toFloat())}}})}}),So=Je({selu_:function(e){var t=Xe(e,"x","selu");return me.engine.runKernel(function(e){return e.selu(t)},{$x:t},function(e){return{$x:function(){var n=t.greater(rt(0)),r=rt(dr),a=rt(mr),i=e.mul(a),o=e.mul(r).mul(t.toFloat().exp());return yo(n,i,o)}}})}}),Eo=Je({transpose_:function(e,t){var n=Xe(e,"x","transpose");return null==t&&(t=n.shape.map(function(e,t){return t}).reverse()),d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of perm "+t+"."),t.forEach(function(e){d(e>=0&&ea)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+t);var i=me.engine.runKernel(function(e){return e.topk(r,t,n)},{$x:r});return{values:i[0],indices:i[1]}}});!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"}(Co||(Co={}));var Lo=Je({absoluteDifference_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","absoluteDifference"),i=Xe(t,"predictions","absoluteDifference"),o=null;null!=n&&(o=Xe(n,"weights","absoluteDifference")),m(a.shape,i.shape,"Error in absoluteDifference: ");var s=a.sub(i).abs();return zo(s,o,r)}}),zo=Je({computeWeightedLoss_:function(e,t,n){void 0===n&&(n=Co.SUM_BY_NONZERO_WEIGHTS);var r=Xe(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=Xe(t,"weights","computeWeightedLoss"));var i=null==a?r:r.mul(a);if(n===Co.NONE)return i;if(n===Co.SUM)return i.sum();if(n===Co.MEAN){if(null==a)return i.mean();var o=b(r.shape)/b(a.shape),s=i.sum().div(a.sum());return o>1?s.div(rt(o)):s}if(n===Co.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(rt(r.size));var u=a.mul(ct(r.shape)).notEqual(rt(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),Bo=Je({cosineDistance_:function(e,t,n,r,a){void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","cosineDistance"),o=Xe(t,"predictions","cosineDistance"),s=null;null!=r&&(s=Xe(r,"weights","cosineDistance")),m(i.shape,o.shape,"Error in cosineDistance: ");var u=rt(1).sub(i.mul(o).sum(n,!0));return zo(u,s,a)}}),Fo=Je({hingeLoss_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","hingeLoss"),i=Xe(t,"predictions","hingeLoss"),o=null;null!=n&&(o=Xe(n,"weights","hingeLoss")),m(a.shape,i.shape,"Error in hingeLoss: ");var s=rt(1);a=rt(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return zo(u,o,r)}}),Vo=Je({huberLoss_:function(e,t,n,r,a){void 0===r&&(r=1),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","huberLoss"),o=Xe(t,"predictions","huberLoss"),s=null;null!=n&&(s=Xe(n,"weights","huberLoss")),m(i.shape,o.shape,"Error in huberLoss: ");var u=rt(r),l=o.sub(i).abs(),c=eo(l,u),f=l.sub(c),p=rt(.5).mul(c.square()).add(u.mul(f));return zo(p,s,a)}}),Uo=Je({logLoss_:function(e,t,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","logLoss"),o=Xe(t,"predictions","logLoss"),s=null;null!=n&&(s=Xe(n,"weights","logLoss")),m(i.shape,o.shape,"Error in logLoss: ");var u=rt(1),l=rt(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return zo(c,s,a)}}),Wo=Je({meanSquaredError_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","meanSquaredError"),i=Xe(t,"predictions","meanSquaredError"),o=null;null!=n&&(o=Xe(n,"weights","meanSquaredError")),m(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return zo(s,o,r)}}),qo=Je({sigmoidCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"multiClassLabels","sigmoidCrossEntropy"),o=Xe(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Xe(n,"weights","sigmoidCrossEntropy")),m(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=rt(r),l=rt(1),c=rt(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var f=function(e,t){var n=Xe(e,"labels","sigmoidCrossEntropyWithLogits"),r=Xe(t,"logits","sigmoidCrossEntropyWithLogits");m(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),i=r.mul(n),o=r.abs().neg().exp().log1p();return a.sub(i).add(o)}(i,o);return zo(f,s,a)}}),$o=Je({softmaxCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"onehotLabels","softmaxCrossEntropy"),o=Xe(t,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Xe(n,"weights","softmaxCrossEntropy")),m(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=rt(r),l=rt(1),c=rt(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var f=function(e,t,n){if(void 0===n&&(n=-1),-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);return _e(function(e,t){var r=t.logSumExp([n],!0),a=t.toFloat().sub(r);return{value:a.mul(e).neg().sum([n]),gradFunc:function(t){var r=Le(t.shape,[n]);return[t.reshape(r).mul(e.toFloat().sub(a.exp())),t.reshape(r).mul(a.exp().sub(e.toFloat()))]}}})(e,t)}(i,o);return zo(f,s,a)}}),Go=Object.freeze({get Reduction(){return Co},absoluteDifference:Lo,computeWeightedLoss:zo,cosineDistance:Bo,hingeLoss:Fo,huberLoss:Vo,logLoss:Uo,meanSquaredError:Wo,sigmoidCrossEntropy:qo,softmaxCrossEntropy:$o});function Ho(e,t){return void 0===t&&(t=!1),me.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var n=e.shape[0],r=e.shape[1],a=Wr(n),i=e.clone(),o=it([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(e){var t,u=i,l=s,c=a;t=me.engine.tidy(function(){var t=i.slice([e,e],[n-e,1]),u=t.norm(),l=i.slice([e,e],[1,1]),c=l.sign().neg(),f=l.sub(c.mul(u)),p=t.div(f);s=1===p.shape[0]?o.clone():o.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var h=c.matMul(f).div(u).neg(),d=i.slice([e,0],[n-e,r]),m=h.mul(s);i=0===e?d.sub(m.matMul(s.transpose().matMul(d))):i.slice([0,0],[e,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=a.slice([0,e],[n,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[n,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,i,a]}),s=t[0],i=t[1],a=t[2],Oe([u,l,c])},c=0;cr&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]})}var Ko=Je({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,d(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var n=e[0].shape[0],r=1;r0)for(var n=0;n= 2, but got rank "+e.rank);if(2===e.rank)return Ho(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),r=[],a=[];return sa(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var n=Ho(e,t),i=n[0],o=n[1];r.push(i),a.push(o)}),[aa(r,0).reshape(e.shape),aa(a,0).reshape(e.shape)]}}),Yo=Object.freeze({gramSchmidt:Ko,qr:Xo});function Jo(e,t,n,r,a){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY);var i=e.shape[0];return n=Math.min(n,i),d(0<=r&&r<=1,"iouThreshold must be in [0, 1], but was '"+r+"'"),d(2===e.rank,"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"),d(4===e.shape[1],"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),d(1===t.rank,"scores must be a 1D tensor"),d(t.shape[0]===i,"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a}}var Zo=Je({resizeBilinear_:function(e,t,n){void 0===n&&(n=!1);var r=Xe(e,"images","resizeBilinear");d(3===r.rank||4===r.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeBilinear(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Qo=Je({resizeNearestNeighbor_:function(e,t,n){void 0===n&&(n=!1);var r=Xe(e,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),d("float32"===r.dtype||"int32"===r.dtype,"`images` must have `int32` or `float32` as dtype");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),es=Je({nonMaxSuppression_:function(e,t,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=Xe(e,"boxes","nonMaxSuppression"),o=Xe(t,"scores","nonMaxSuppression"),s=Jo(i,o,n,r,a);return n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,me.engine.runKernel(function(e){return e.nonMaxSuppression(i,o,n,r,a)},{$boxes:i})}}),ts=Object.freeze({resizeBilinear:Zo,resizeNearestNeighbor:Qo,nonMaxSuppression:es,nonMaxSuppressionAsync:function(e,t,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),l(this,void 0,void 0,function(){var i,o,s,u,l,f;return c(this,function(c){switch(c.label){case 0:return i=Xe(e,"boxes","nonMaxSuppressionAsync"),o=Xe(t,"scores","nonMaxSuppressionAsync"),s=Jo(i,o,n,r,a),n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,[4,i.data()];case 1:return u=c.sent(),[4,o.data()];case 2:return l=c.sent(),f=Ct(u,l,n,r,a),i!==e&&i.dispose(),o!==t&&o.dispose(),[2,f]}})})},cropAndResize:function(e,t,n,r,a,i){var o=Xe(e,"image","cropAndResize","float32"),s=Xe(t,"boxes","cropAndResize","float32"),u=Xe(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return d(4===o.rank,"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."),d(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."),d(1===u.rank&&u.shape[0]===l,"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."),d("int32"===u.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+u.dtype+"."),d(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),d(r[0]>=1&&r[1]>=1,"cropSize must be atleast [1,1], but was "+r),d("bilinear"===a||"nearest"===a,"method must be bilinear or nearest, but was "+a),me.engine.runKernel(function(e,t){return e.cropAndResize(o,s,u,r,a,i)},{$image:o,$boxes:s})}}),ns=Object.freeze({image:ts,linalg:Yo,losses:Go,op:Je,batchNormalization2d:qa,batchNormalization3d:$a,batchNormalization4d:Ga,batchNormalization:Ha,complex:Qe,real:et,imag:tt,concat:vr,concat1d:br,concat2d:wr,concat3d:xr,concat4d:_r,split:Sr,conv1d:ii,conv2d:oi,depthwiseConv2d:si,separableConv2d:ui,conv2dTranspose:li,matMul:Qa,dot:ei,outerProduct:ti,reverse:ci,reverse1d:fi,reverse2d:pi,reverse3d:hi,reverse4d:di,maxPool:mi,avgPool:gi,slice:yi,slice1d:vi,slice2d:bi,slice3d:wi,slice4d:xi,abs:fa,acos:pa,acosh:ha,asin:da,asinh:ma,atan:ga,atanh:ya,ceil:va,clipByValue:ba,cos:wa,cosh:xa,erf:_a,exp:Sa,expm1:Ea,floor:Na,log:Oa,log1p:ka,logSigmoid:Ia,neg:Ca,reciprocal:Aa,round:Pa,rsqrt:Ta,sigmoid:Ma,sign:Ra,sin:Da,sinh:ja,softplus:La,sqrt:za,square:Ba,step:Fa,tan:Va,tanh:Ua,all:Si,any:Ei,argMax:Ni,argMin:Oi,logSumExp:ki,max:Ii,mean:Ci,min:Ai,moments:Pi,sum:Ti,equal:Mi,equalStrict:Ri,greater:Di,greaterEqual:ji,greaterEqualStrict:Li,greaterStrict:zi,less:Bi,lessEqual:Fi,lessEqualStrict:Vi,lessStrict:Ui,notEqual:Wi,notEqualStrict:qi,add:$i,addN:Gi,addStrict:Hi,atan2:Ki,div:Xi,divStrict:Yi,floorDiv:Ji,maximum:Zi,maximumStrict:Qi,minimum:eo,minimumStrict:to,mod:no,modStrict:ro,mul:ao,mulStrict:io,pow:oo,powStrict:so,squaredDifference:uo,squaredDifferenceStrict:lo,sub:co,subStrict:fo,elu:bo,leakyRelu:wo,prelu:xo,relu:_o,selu:So,logicalAnd:po,logicalNot:ho,logicalOr:mo,logicalXor:go,where:yo,whereAsync:vo,buffer:Dr,toPixels:Rr,print:jr,batchToSpaceND:Lr,cast:zr,clone:Br,cumsum:Fr,depthToSpace:Vr,expandDims:Ur,eye:Wr,fromPixels:qr,multinomial:$r,oneHot:Gr,pad:Hr,pad1d:Kr,pad2d:Xr,pad3d:Yr,pad4d:Jr,rand:Zr,randomNormal:Qr,randomUniform:ea,reshape:ta,spaceToBatchND:na,squeeze:ra,stack:aa,tile:ia,truncatedNormal:oa,unstack:sa,fill:pt,linspace:ht,ones:ct,range:dt,scalar:rt,tensor:nt,tensor1d:at,tensor2d:it,tensor3d:ot,tensor4d:st,tensor5d:ut,tensor6d:lt,zeros:ft,onesLike:xt,zerosLike:_t,transpose:Eo,softmax:Ze,localResponseNormalization:No,norm:Oo,gather:Ao,unsortedSegmentSum:Po,basicLSTMCell:To,multiRNNCell:Mo,movingAverage:Ro,stridedSlice:Do,topk:jo}),rs=function(){function e(){this.blockSize=48,this.data=new WeakMap,this.firstUse=!0,me.get("IS_BROWSER")&&(this.canvas=document.createElement("canvas"))}return e.prototype.register=function(e,t,n){if(this.firstUse&&(this.firstUse=!1,me.get("IS_NODE")&&Ce("\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============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:n})},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.throwIfNoData(e),this.data.get(e).values=t},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var n,r;if(me.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else if(e instanceof ImageData)n=e.data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(null==this.canvas)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.canvas.width=e.width,this.canvas.height=e.height,this.canvas.getContext("2d").drawImage(e,0,0,e.width,e.height),n=this.canvas.getContext("2d").getImageData(0,0,e.width,e.height).data}if(4===t)r=new Int32Array(n);else{var a=e.width*e.height;r=new Int32Array(a*t);for(var i=0;ip&&(p=m,h=d)}u[c]=h}return o},e.prototype.cumsum=function(e,t,n,r){if(this.assertNotComplex(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=Et(e.dtype,"int32"),i=ft(e.shape,a),o=i.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=r?function(e,t){return e+u-t-1}:function(e,t){return e+t},c=0;ct?1:0})},e.prototype.greaterEqual=function(e,t){return this.assertNotComplex([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){this.assertNotComplex(e,"logicalNot");for(var t=e.dataSync(),n=new Int32Array(t.length),r=0;r1||1===t.rank?1:t.shape[1],c=0;c=0&&t>=0?n:(n+t)%t})},e.prototype.max=function(e,t){this.assertNotComplex(e,"max"),Be("max",t,e.rank);for(var n=je(e.shape,t),r=n[0],a=n[1],i=ft(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;lf&&(f=h)}s[l]=f}return i},e.prototype.maximum=function(e,t){return this.assertNotComplex([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){this.assertNotComplex(e,"all"),Be("all",t,e.rank);for(var n=je(e.shape,t),r=n[0],a=n[1],i=ft(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;l0?n[r]=1:n[r]=0;return Q.make(e.shape,{values:n})},e.prototype.round=function(e){this.assertNotComplex(e,"round");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r.5?n[r]=Math.ceil(t[r]):n[r]=a%2==0?a:a+1}return Q.make(e.shape,{values:n})},e.prototype.exp=function(e){this.assertNotComplex(e,"exp");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r=0?a:Math.exp(a)-1}return Q.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){this.assertNotComplex([e,t],"eluDer");for(var n=new Float32Array(t.size),r=t.dataSync(),a=e.dataSync(),i=0;i=1?a[i]:a[i]*(o+1)}return Q.make(t.shape,{values:n})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return Q.make(e.shape,{values:t})},e.prototype.clip=function(e,t,n){this.assertNotComplex(e,"clip");for(var r=new Float32Array(e.size),a=e.dataSync(),i=0;in?n:o-t,s=r[a]0?1:t}return Q.make(e.shape,{values:n})},e.prototype.conv2d=function(e,t,n){this.assertNotComplex([e,t],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Dr(n.outShape,e.dtype),c=e.dataSync(),f=t.dataSync(),p=l.values,h=0;h=n.inHeight))for(var x=b*t.strides[0],_=d+w*e.strides[1],S=0;S=n.inWidth))for(var I=x+O*t.strides[1],C=_+k*n.inChannels,A=I,P=0;P=n.inHeight))for(var _=w*t.strides[0],S=m+x*e.strides[1],E=0;E=n.inWidth))for(var C=_+k*t.strides[1],A=S+I*n.inChannels,P=N,T=C,M=0;Mx?x=O:"avg"===n&&(_+=O,S++)}if(isNaN(x))break}s.set("avg"===n?_/S:x,f,h,y,p)}return s.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var n=Dr(t.outShape,"int32"),r=t.strideHeight,a=t.strideWidth,i=t.filterHeight,o=t.filterWidth,s=t.padInfo.top,u=t.padInfo.left,l=0;lb&&(b=N,w=_*o+E)}n.set(w,l,f,m,c)}return n.toTensor()},e.prototype.maxPoolBackprop=function(e,t,n,r){this.assertNotComplex([t,n],"maxPoolBackprop");for(var a=this.maxPoolPositions(t,r),i=r.strideHeight,o=r.strideWidth,s=r.filterHeight,u=r.filterWidth,l=u-1-r.padInfo.left,c=s-1-r.padInfo.top,f=Dr(t.shape,"float32"),p=0;p=r.outHeight||Math.floor(w)!==w))for(var x=0;x=r.outWidth||Math.floor(_)!==_)){var S=s*u-1-a.get(p,w,_,h)===b*u+x?1:0;0!==S&&(v+=e.get(p,w,_,h)*S)}}}f.set(v,p,d,m,h)}return f.toTensor()},e.prototype.avgPoolBackprop=function(e,t,n){this.assertNotComplex([e,t],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=o-1-n.padInfo.left,u=i-1-n.padInfo.top,l=Dr(t.shape,"float32"),c=1/(i*o),f=0;f=n.outHeight||Math.floor(b)!==b))for(var w=0;w=n.outWidth||Math.floor(x)!==x||(y+=e.get(f,b,x,p))}}l.set(y*c,f,h,d,p)}return l.toTensor()},e.prototype.cast=function(e,t){return Ot(e,t,this)},e.prototype.reshape=function(e,t){return kt(e,t)},e.prototype.avgPool=function(e,t){return this.assertNotComplex(e,"avgPool"),this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,n,r){this.assertNotComplex(e,"resizeBilinear");for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=Dr([i,t,n,u],e.dtype),c=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/h[0],m=p[1]/h[1],g=0;g1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=1/(p[0]/h[0]),m=1/(p[1]/h[1]),g=2*Math.ceil(d)+2,y=2*Math.ceil(m)+2,v=0;v=l))for(var C=0;C=c)){var P=p[0]*(I/h[0]),T=p[1]*(A/h[1]),M=Math.min(i-1,n?Math.round(P):Math.floor(P)),R=Math.min(o-1,n?Math.round(T):Math.floor(T));b===M&&w===R&&(O+=e.get(v,I,A,N))}}}f.set(O,v,b,w,N)}return f.toTensor()},e.prototype.batchNormalization=function(e,t,n,r,a,i){this.assertNotComplex([e,t,n,a,i],"batchNormalization");for(var o=e.dataSync(),s=t.dataSync(),u=n.dataSync(),l=a?a.dataSync():new Float32Array([1]),c=i?i.dataSync():new Float32Array([0]),f=new Float32Array(o.length),p=c.length,h=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w=p&&(g=0),y>=m&&(y=0),v>=h&&(v=0),b>=d&&(b=0);return st(f,e.shape)},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){this.assertNotComplex(e,"localResponseNormalization4D");var i=e.shape[3],o=i-1,s=e.dataSync(),u=b(e.shape),l=new Float32Array(u);function c(e){for(var n=e%i,r=e-n+Math.max(0,n-t),a=e-n+Math.min(n+t,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var f=0;f=0&&e.get(i)1,"blockSize should be > 1 for depthToSpace, but was: "+t);for(var r=e.shape[0],a=e.shape[1],i=e.shape[2],o=e.shape[3],s=a*t,u=i*t,l=o/(t*t),c=e.dataSync(),f=new Float32Array(r*s*u*l),p=0,h=0;h=s))for(var k=p>1?(E-_)*(u-1)/(p-1):0,I=h>1?(N-S)*(l-1)/(h-1):0,C=0;C1?_*(u-1)+C*k:.5*(_+E)*(u-1);if(A<0||A>u-1)for(var P=0;P1?S*(l-1)+P*I:.5*(S+N)*(l-1))<0||$>l-1)for(T=0;T1?S*(l-1)+P*I:.5*(S+N)*(l-1))<0||$>l-1)for(T=0;T0,"scheme must not be an empty string.");var r=e.getInstance();d(null==r.managers[t],"A model store manager is already registered for scheme '"+t+"'."),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function gs(e){if(-1===e.indexOf(ds))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ms.getSchemes().join(","));return{scheme:e.split(ds)[0],path:e.split(ds)[1]}}function ys(e,t,n){return void 0===n&&(n=!1),l(this,void 0,void 0,function(){var r,a,i,o,s,u,l,f,p;return c(this,function(c){switch(c.label){case 0:return d(e!==t,"Old path and new path are the same: '"+e+"'"),d((r=hs.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),d(r.length<2,"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."),a=r[0],d((i=hs.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),d(i.length<2,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."),o=i[0],s=gs(e).scheme,u=gs(e).path,l=s===gs(e).scheme,[4,a.load()];case 1:return f=c.sent(),n&&l?[4,ms.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,o.save(f)];case 4:return p=c.sent(),!n||l?[3,6]:[4,ms.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var vs="models_store",bs="model_info_store";function ws(){if(!me.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=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 xs(e){var t=e.result;t.createObjectStore(vs,{keyPath:"modelPath"}),t.createObjectStore(bs,{keyPath:"modelPath"})}var _s=function(){function e(e){if(this.indexedDB=ws(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,this.databaseAction(this.modelPath)]})})},e.prototype.databaseAction=function(e,t){var n=this;return new Promise(function(e,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return xs(a)},a.onsuccess=function(){var i=a.result;if(null==t){var o=i.transaction(vs,"readonly"),s=o.objectStore(vs).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=ps(t),c=i.transaction(bs,"readwrite"),f=c.objectStore(bs),p=f.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var a=(u=i.transaction(vs,"readwrite")).objectStore(vs).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});a.onsuccess=function(){return e({modelArtifactsInfo:l})},a.onerror=function(e){var t=(f=c.objectStore(bs)).delete(n.modelPath);t.onsuccess=function(){return i.close(),r(a.error)},t.onerror=function(e){return i.close(),r(a.error)}}},p.onerror=function(e){return i.close(),r(p.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(e){return r(a.error)}})},e.URL_SCHEME="indexeddb://",e}(),Ss=function(e){return me.get("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(_s.URL_SCHEME)?function(e){return new _s(e)}(e.slice(_s.URL_SCHEME.length)):null};hs.registerSaveRouter(Ss),hs.registerLoadRouter(Ss);var Es=function(){function e(){this.indexedDB=ws()}return e.prototype.listModels=function(){return l(this,void 0,void 0,function(){var e=this;return c(this,function(t){return[2,new Promise(function(t,n){var r=e.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return xs(r)},r.onsuccess=function(){var e=r.result,a=e.transaction(bs,"readonly"),i=a.objectStore(bs).getAll();i.onsuccess=function(){for(var e={},n=0,r=i.result;n0,"URL path for browserHTTPRequest must not be null, undefined or empty."),Array.isArray(e)&&d(2===e.length,"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+e.length+")."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest: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"),[4,fetch(this.path,t)];case 1:if(200===(a=i.sent()).status)return[2,{modelArtifactsInfo:ps(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,Array.isArray(this.path)?this.loadBinaryModel():this.loadJSONModel()]})})},e.prototype.loadBinaryTopology=function(){return l(this,void 0,void 0,function(){var e;return c(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch(this.path[0],this.requestInit)];case 1:return[4,t.sent().arrayBuffer()];case 2:return[2,t.sent()];case 3:throw e=t.sent(),new Error(this.path[0]+" not found. "+e);case 4:return[2]}})})},e.prototype.loadBinaryModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return e=this.loadBinaryTopology(),[4,fetch(this.path[1],this.requestInit)];case 1:return t=u.sent(),[4,Promise.all([e,t])];case 2:return n=u.sent(),r=n[0],[4,n[1].json()];case 3:return null==(a=u.sent())?[3,5]:[4,this.loadWeights(a)];case 4:s=u.sent(),i=s[0],o=s[1],u.label=5;case 5:return[2,{modelTopology:r,weightSpecs:i,weightData:o}]}})})},e.prototype.loadJSONModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:return[4,s.sent().json()];case 2:if(e=s.sent(),t=e.modelTopology,n=e.weightsManifest,null==t&&null==n)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==n?[3,4]:(i=e.weightsManifest,[4,this.loadWeights(i)]);case 3:o=s.sent(),r=o[0],a=o[1],s.label=4;case 4:return[2,{modelTopology:t,weightSpecs:r,weightData:a}]}})})},e.prototype.loadWeights=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o,s,u,l;return c(this,function(c){switch(c.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=[],r=0,a=e;r0&&(e=u({weightSpecs:this.weightSpecs},e)),null!=this.weightData&&this.weightData.byteLength>0&&(e=u({weightData:this.weightData},e)),[2,e]})})},e}(),Hs=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){return[2,this.saveHandler(e)]})})},e}(),Ks=hs.registerSaveRouter,Xs=hs.registerLoadRouter,Ys=hs.getSaveHandlers,Js=hs.getLoadHandlers,Zs=Object.freeze({browserFiles:function(e){return new Fs(e)},browserHTTPRequest:$s,concatenateArrayBuffers:cs,decodeWeights:ss,encodeWeights:function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:for(r in t=[],n=[],e){if("float32"!==(a=e[r]).dtype&&"int32"!==a.dtype&&"bool"!==a.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+a.dtype);t.push({name:r,shape:a.shape,dtype:a.dtype}),n.push(a.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0,n=[];e.forEach(function(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)});var r=new Uint8Array(t),a=0;return n.forEach(function(e){r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}(i.sent()),specs:t}]}})})},fromMemory:function(e,t,n){return new Gs(e,t,n)},getLoadHandlers:Js,getModelArtifactsInfoForJSON:ps,getSaveHandlers:Ys,loadWeights:function(e,t,n,r){return void 0===t&&(t=""),l(this,void 0,void 0,function(){var a,i,o,s,u,l,f,p,h,d;return c(this,function(c){switch(c.label){case 0:if(a=e.map(function(){return!1}),i={},o=null!=n?n.map(function(){return!1}):[],s=[],e.forEach(function(e,t){var r=0;e.weights.forEach(function(e){var u="quantization"in e?e.quantization.dtype:e.dtype,l=os[u]*b(e.shape),c=function(){a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:r,sizeBytes:l})};null!=n?n.forEach(function(t,n){t===e.name&&(c(),o[n]=!0)}):c(),s.push(e.name),r+=l})}),!o.every(function(e){return e}))throw u=n.filter(function(e,t){return!o[t]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=a.reduce(function(e,t,n){return t&&e.push(n),e},[]),f=[],l.forEach(function(n){e[n].paths.forEach(function(e){var n=t+(t.endsWith("/")?"":"/")+e;f.push(n)})}),[4,Vs(f,r)];case 1:return p=c.sent(),h={},d=0,l.forEach(function(t){for(var n=e[t].paths.length,r=0,a=0;a0,"Class being registered has an empty-string as its className, which is disallowed."),eu.register(e)}var nu=Object.freeze({Serializable:Qs,SerializationMap:eu,registerClass:tu});function ru(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),e instanceof Q||t instanceof Q){if(e instanceof Q&&t instanceof Q){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!w(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".")}}else{var r=e.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+a)}var i,o;if(i=e instanceof Q?e.dataSync():e,o=t instanceof Q?t.dataSync():t,i.length!==o.length)throw new Error("Arrays have different lengths actual: "+i.length+" vs expected: "+o.length+".\nActual: "+i+".\nExpected: "+o+".");for(var s=0;sn)}var iu=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},ALL_ENVS:{},expectArraysClose:ru,expectPromiseToFail:function(e,t){e().then(function(){return t.fail()},function(){return t()})},expectArraysEqual:function(e,t){return ru(e,t,0)},expectNumbersClose:function(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),!au(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t)},expectValuesInRange:function(e,t,n){var r;r=e instanceof Q?e.dataSync():e;for(var a=0;an)throw new Error("Value out of range:"+r[a]+" low: "+t+", high: "+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),ou="0.13.0",su=Object.freeze({gpgpu_util:ar,webgl_util:Ln,MathBackendWebGL:ca,GPGPUContext:ir}),uu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),a=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(e){return i[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return xe(e,t)},t}(Qs),lu=function(e){function t(t,n,r){void 0===r&&(r=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=n,a.epsilon=r,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=Ne(rt(-t)),a.rhoScalar=Ne(rt(n)),a.oneMinusRho=Ne(rt(1-n)),null===r&&(r=me.get("EPSILON")),a.epsilonScalar=Ne(rt(r)),a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ee(function(){t.accumulatedGrads[n]=_t(a).variable(!1)}),null==r.accumulatedUpdates[n]&&Ee(function(){t.accumulatedUpdates[n]=_t(a).variable(!1)});var i=e[n],o=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];Ee(function(){var e=t.rhoScalar.mul(o).add(t.oneMinusRho.mul(i.square())),r=s.add(t.epsilonScalar).sqrt().div(o.add(t.epsilonScalar).sqrt()).mul(i),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(r.square()));t.accumulatedGrads[n].assign(e),t.accumulatedUpdates[n].assign(u);var l=t.c.mul(r).add(a);a.assign(l)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(uu);tu(lu);var cu=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Ne(rt(-t)),r.epsilon=Ne(rt(me.get("EPSILON"))),r}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ee(function(){t.accumulatedGrads[n]=pt(a.shape,t.initialAccumulatorValue).variable(!1)});var i=e[n],o=r.accumulatedGrads[n];Ee(function(){var e=o.add(i.square());t.accumulatedGrads[n].assign(e);var r=t.c.mul(i.div(e.add(t.epsilon).sqrt())).add(a);a.assign(r)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(uu);tu(cu);var fu=function(e){function t(t,n,r,a){void 0===a&&(a=null);var i=e.call(this)||this;return i.learningRate=t,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment={},i.accumulatedSecondMoment={},i.c=Ne(rt(-t)),i.beta1Scalar=Ne(rt(n)),i.beta2Scalar=Ne(rt(r)),Ee(function(){i.accBeta1=rt(n).variable(),i.accBeta2=rt(r).variable()}),i.oneMinusBeta1=Ne(rt(1-n)),i.oneMinusBeta2=Ne(rt(1-r)),i.one=Ne(rt(1)),null===a&&(a=me.get("EPSILON")),i.epsScalar=Ne(rt(a)),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ee(function(){var n=t.one.sub(t.accBeta1),r=t.one.sub(t.accBeta2);for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=_t(i).variable(o)}null==t.accumulatedSecondMoment[a]&&(o=!1,t.accumulatedSecondMoment[a]=_t(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),p=c.div(n),h=f.div(r);t.accumulatedFirstMoment[a].assign(c),t.accumulatedSecondMoment[a].assign(f);var d=t.c.mul(p.div(t.epsScalar.add(h.sqrt()))).add(i);i.assign(d)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(uu);tu(fu);var pu=function(e){function t(t,n,r,a,i){void 0===a&&(a=null),void 0===i&&(i=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment={},o.accumulatedWeightedInfNorm={},o.c=Ne(rt(-t)),o.beta1Scalar=Ne(rt(n)),o.beta2Scalar=Ne(rt(r)),o.decayScalar=Ne(rt(i)),Ee(function(){o.iteration=rt(0).variable(),o.accBeta1=rt(n).variable()}),o.oneMinusBeta1=Ne(rt(1-n)),o.one=Ne(rt(1)),null===a&&(a=me.get("EPSILON")),o.epsScalar=Ne(rt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ee(function(){var n=t.one.sub(t.accBeta1),r=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=_t(i).variable(o)}null==t.accumulatedWeightedInfNorm[a]&&(o=!1,t.accumulatedWeightedInfNorm[a]=_t(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l),p=s.abs(),h=f.maximum(p);t.accumulatedFirstMoment[a].assign(c),t.accumulatedWeightedInfNorm[a].assign(h);var d=r.div(n).mul(c.div(t.epsScalar.add(h))).add(i);i.assign(d)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(uu);tu(pu);var hu=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(n){var r=e[n],a=me.engine.registeredVariables[n];Ee(function(){var e=t.c.mul(r).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Ne(rt(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(uu);tu(hu);var du=function(e){function t(t,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=n,a.useNesterov=r,a.m=rt(a.momentum),a.accumulations={},a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulations[n]&&Ee(function(){t.accumulations[n]=_t(a).variable(!1)});var i=r.accumulations[n],o=e[n];Ee(function(){var e,r=t.m.mul(i).add(o);e=t.useNesterov?t.c.mul(o.add(r.mul(t.m))).add(a):t.c.mul(r).add(a),t.accumulations[n].assign(r),a.assign(e)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(hu);tu(du);var mu=function(e){function t(t,n,r,a,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=null),void 0===i&&(i=!1);var o=e.call(this)||this;return o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares={},o.accumulatedMeanGrads={},o.accumulatedMoments={},o.c=Ne(rt(t)),o.decayScalar=Ne(rt(n)),o.momentumScalar=Ne(rt(r)),o.oneMinusDecay=Ne(rt(1-n)),o.centered=i,null===a&&(a=me.get("EPSILON")),o.epsilonScalar=Ne(rt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&Ee(function(){t.accumulatedMeanSquares[n]=_t(a).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&Ee(function(){t.accumulatedMeanGrads[n]=_t(a).variable(!1)}),null==r.accumulatedMoments[n]&&Ee(function(){t.accumulatedMoments[n]=_t(a).variable(!1)});var i=r.accumulatedMeanSquares[n],o=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=e[n];Ee(function(){var e=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var r=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(r.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[n].assign(e),t.accumulatedMeanGrads[n].assign(r),t.accumulatedMoments[n].assign(l);var c=a.sub(l);a.assign(c)}else{var f=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(f.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[n].assign(f),t.accumulatedMoments[n].assign(l),c=a.sub(l),a.assign(c)}})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(uu);tu(mu);var gu=function(){function e(){}return e.sgd=function(e){return new hu(e)},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new du(e,t,n)},e.rmsprop=function(e,t,n,r,a){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new mu(e,t,n,r,a)},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new fu(e,t,n,r)},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=null),new lu(e,t,n)},e.adamax=function(e,t,n,r,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new pu(e,t,n,r,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new cu(e,t)},e}(),yu={sgd:gu.sgd,momentum:gu.momentum,adadelta:gu.adadelta,adagrad:gu.adagrad,rmsprop:gu.rmsprop,adamax:gu.adamax,adam:gu.adam},vu=de.setBackend,bu=de.getBackend,wu=de.disposeVariables,xu=de.memory;J=ns}).call(this,n(46),n(26),n(162).setImmediate,n(16).Buffer)},function(e,t,n){"use strict";n.r(t),function(e,r,a,i){n.d(t,"setBackend",function(){return mu}),n.d(t,"getBackend",function(){return gu}),n.d(t,"disposeVariables",function(){return yu}),n.d(t,"memory",function(){return vu}),n.d(t,"version_core",function(){return ru}),n.d(t,"nextFrame",function(){return ns}),n.d(t,"environment",function(){return ge}),n.d(t,"io",function(){return Xs}),n.d(t,"serialization",function(){return Qs}),n.d(t,"test_util",function(){return nu}),n.d(t,"util",function(){return V}),n.d(t,"webgl",function(){return au}),n.d(t,"AdadeltaOptimizer",function(){return ou}),n.d(t,"AdagradOptimizer",function(){return su}),n.d(t,"AdamOptimizer",function(){return uu}),n.d(t,"AdamaxOptimizer",function(){return lu}),n.d(t,"MomentumOptimizer",function(){return fu}),n.d(t,"Optimizer",function(){return iu}),n.d(t,"RMSPropOptimizer",function(){return pu}),n.d(t,"SGDOptimizer",function(){return cu}),n.d(t,"Tensor",function(){return Q}),n.d(t,"TensorBuffer",function(){return X}),n.d(t,"variable",function(){return te}),n.d(t,"Variable",function(){return ee}),n.d(t,"Rank",function(){return mt}),n.d(t,"Reduction",function(){return Oo}),n.d(t,"ENV",function(){return me}),n.d(t,"Environment",function(){return de}),n.d(t,"image",function(){return Zo}),n.d(t,"linalg",function(){return Ho}),n.d(t,"losses",function(){return Wo}),n.d(t,"op",function(){return Ye}),n.d(t,"batchNormalization2d",function(){return Ua}),n.d(t,"batchNormalization3d",function(){return Wa}),n.d(t,"batchNormalization4d",function(){return qa}),n.d(t,"batchNormalization",function(){return $a}),n.d(t,"complex",function(){return Ze}),n.d(t,"real",function(){return Qe}),n.d(t,"imag",function(){return et}),n.d(t,"concat",function(){return gr}),n.d(t,"concat1d",function(){return yr}),n.d(t,"concat2d",function(){return vr}),n.d(t,"concat3d",function(){return br}),n.d(t,"concat4d",function(){return wr}),n.d(t,"split",function(){return xr}),n.d(t,"conv1d",function(){return ei}),n.d(t,"conv2d",function(){return ti}),n.d(t,"depthwiseConv2d",function(){return ni}),n.d(t,"separableConv2d",function(){return ri}),n.d(t,"conv2dTranspose",function(){return ai}),n.d(t,"matMul",function(){return ii}),n.d(t,"dot",function(){return oi}),n.d(t,"outerProduct",function(){return si}),n.d(t,"reverse",function(){return ui}),n.d(t,"reverse1d",function(){return li}),n.d(t,"reverse2d",function(){return ci}),n.d(t,"reverse3d",function(){return fi}),n.d(t,"reverse4d",function(){return pi}),n.d(t,"maxPool",function(){return hi}),n.d(t,"avgPool",function(){return di}),n.d(t,"slice",function(){return mi}),n.d(t,"slice1d",function(){return gi}),n.d(t,"slice2d",function(){return yi}),n.d(t,"slice3d",function(){return vi}),n.d(t,"slice4d",function(){return bi}),n.d(t,"abs",function(){return la}),n.d(t,"acos",function(){return ca}),n.d(t,"acosh",function(){return fa}),n.d(t,"asin",function(){return pa}),n.d(t,"asinh",function(){return ha}),n.d(t,"atan",function(){return da}),n.d(t,"atanh",function(){return ma}),n.d(t,"ceil",function(){return ga}),n.d(t,"clipByValue",function(){return ya}),n.d(t,"cos",function(){return va}),n.d(t,"cosh",function(){return ba}),n.d(t,"erf",function(){return wa}),n.d(t,"exp",function(){return xa}),n.d(t,"expm1",function(){return _a}),n.d(t,"floor",function(){return Sa}),n.d(t,"log",function(){return Ea}),n.d(t,"log1p",function(){return Na}),n.d(t,"logSigmoid",function(){return Oa}),n.d(t,"neg",function(){return ka}),n.d(t,"reciprocal",function(){return Ia}),n.d(t,"round",function(){return Ca}),n.d(t,"rsqrt",function(){return Aa}),n.d(t,"sigmoid",function(){return Pa}),n.d(t,"sign",function(){return Ta}),n.d(t,"sin",function(){return Ma}),n.d(t,"sinh",function(){return Ra}),n.d(t,"softplus",function(){return Da}),n.d(t,"sqrt",function(){return ja}),n.d(t,"square",function(){return La}),n.d(t,"step",function(){return za}),n.d(t,"tan",function(){return Ba}),n.d(t,"tanh",function(){return Fa}),n.d(t,"all",function(){return wi}),n.d(t,"any",function(){return xi}),n.d(t,"argMax",function(){return _i}),n.d(t,"argMin",function(){return Si}),n.d(t,"logSumExp",function(){return Ei}),n.d(t,"max",function(){return Ni}),n.d(t,"mean",function(){return Oi}),n.d(t,"min",function(){return ki}),n.d(t,"moments",function(){return Ii}),n.d(t,"sum",function(){return Ci}),n.d(t,"equal",function(){return Ai}),n.d(t,"equalStrict",function(){return Pi}),n.d(t,"greater",function(){return Ti}),n.d(t,"greaterEqual",function(){return Mi}),n.d(t,"greaterEqualStrict",function(){return Ri}),n.d(t,"greaterStrict",function(){return Di}),n.d(t,"less",function(){return ji}),n.d(t,"lessEqual",function(){return Li}),n.d(t,"lessEqualStrict",function(){return zi}),n.d(t,"lessStrict",function(){return Bi}),n.d(t,"notEqual",function(){return Fi}),n.d(t,"notEqualStrict",function(){return Vi}),n.d(t,"add",function(){return Ui}),n.d(t,"addN",function(){return Wi}),n.d(t,"addStrict",function(){return qi}),n.d(t,"atan2",function(){return $i}),n.d(t,"div",function(){return Gi}),n.d(t,"divStrict",function(){return Hi}),n.d(t,"floorDiv",function(){return Ki}),n.d(t,"maximum",function(){return Xi}),n.d(t,"maximumStrict",function(){return Yi}),n.d(t,"minimum",function(){return Ji}),n.d(t,"minimumStrict",function(){return Zi}),n.d(t,"mod",function(){return Qi}),n.d(t,"modStrict",function(){return eo}),n.d(t,"mul",function(){return to}),n.d(t,"mulStrict",function(){return no}),n.d(t,"pow",function(){return ro}),n.d(t,"powStrict",function(){return ao}),n.d(t,"squaredDifference",function(){return io}),n.d(t,"squaredDifferenceStrict",function(){return oo}),n.d(t,"sub",function(){return so}),n.d(t,"subStrict",function(){return uo}),n.d(t,"elu",function(){return go}),n.d(t,"leakyRelu",function(){return yo}),n.d(t,"prelu",function(){return vo}),n.d(t,"relu",function(){return bo}),n.d(t,"selu",function(){return wo}),n.d(t,"logicalAnd",function(){return lo}),n.d(t,"logicalNot",function(){return co}),n.d(t,"logicalOr",function(){return fo}),n.d(t,"logicalXor",function(){return po}),n.d(t,"where",function(){return ho}),n.d(t,"whereAsync",function(){return mo}),n.d(t,"buffer",function(){return Mr}),n.d(t,"toPixels",function(){return Tr}),n.d(t,"print",function(){return Rr}),n.d(t,"batchToSpaceND",function(){return Dr}),n.d(t,"cast",function(){return jr}),n.d(t,"clone",function(){return Lr}),n.d(t,"cumsum",function(){return zr}),n.d(t,"depthToSpace",function(){return Br}),n.d(t,"expandDims",function(){return Fr}),n.d(t,"eye",function(){return Vr}),n.d(t,"fromPixels",function(){return Ur}),n.d(t,"multinomial",function(){return Wr}),n.d(t,"oneHot",function(){return qr}),n.d(t,"pad",function(){return $r}),n.d(t,"pad1d",function(){return Gr}),n.d(t,"pad2d",function(){return Hr}),n.d(t,"pad3d",function(){return Kr}),n.d(t,"pad4d",function(){return Xr}),n.d(t,"rand",function(){return Yr}),n.d(t,"randomNormal",function(){return Jr}),n.d(t,"randomUniform",function(){return Zr}),n.d(t,"reshape",function(){return Qr}),n.d(t,"spaceToBatchND",function(){return ea}),n.d(t,"squeeze",function(){return ta}),n.d(t,"stack",function(){return na}),n.d(t,"tile",function(){return ra}),n.d(t,"truncatedNormal",function(){return aa}),n.d(t,"unstack",function(){return ia}),n.d(t,"fill",function(){return ft}),n.d(t,"linspace",function(){return pt}),n.d(t,"ones",function(){return lt}),n.d(t,"range",function(){return ht}),n.d(t,"scalar",function(){return nt}),n.d(t,"tensor",function(){return tt}),n.d(t,"tensor1d",function(){return rt}),n.d(t,"tensor2d",function(){return at}),n.d(t,"tensor3d",function(){return it}),n.d(t,"tensor4d",function(){return ot}),n.d(t,"tensor5d",function(){return st}),n.d(t,"tensor6d",function(){return ut}),n.d(t,"zeros",function(){return ct}),n.d(t,"onesLike",function(){return wt}),n.d(t,"zerosLike",function(){return xt}),n.d(t,"transpose",function(){return xo}),n.d(t,"softmax",function(){return Je}),n.d(t,"localResponseNormalization",function(){return _o}),n.d(t,"norm",function(){return So}),n.d(t,"gather",function(){return ko}),n.d(t,"unsortedSegmentSum",function(){return Io}),n.d(t,"basicLSTMCell",function(){return Co}),n.d(t,"multiRNNCell",function(){return Ao}),n.d(t,"movingAverage",function(){return Po}),n.d(t,"stridedSlice",function(){return To}),n.d(t,"topk",function(){return Mo}),n.d(t,"train",function(){return du}),n.d(t,"tidy",function(){return Ee}),n.d(t,"keep",function(){return Ne}),n.d(t,"dispose",function(){return Oe}),n.d(t,"time",function(){return ke}),n.d(t,"customGrad",function(){return _e}),n.d(t,"grad",function(){return ye}),n.d(t,"grads",function(){return ve}),n.d(t,"valueAndGrad",function(){return be}),n.d(t,"valueAndGrads",function(){return we}),n.d(t,"variableGrads",function(){return xe}); /** * @license * Copyright 2018 Google LLC. All Rights Reserved. @@ -32,7 +32,7 @@ var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__p * limitations under the License. * ============================================================================= */ -var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function s(e,t){function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var u=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function p(e,t,n){return Math.max(e,Math.min(t,n))}function h(e,t){var n=Math.random();return t*n+(1-n)*e}function d(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function m(e,t,n){void 0===n&&(n=""),d(w(e,t),n+" Shapes "+e+" and "+t+" must match")}function g(e){d(null!=e,"The input to the tensor constructor must be a non-null value.")}function y(e,t){if(void 0===t&&(t=[]),Array.isArray(e))for(var n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"}),d(t.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+t.length+" elements"});for(var a=n.slice(1),i=0;i1;--t)if(e%t==0)return[t,e/t];return[1,e]}function N(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function S(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise(function(r,a){var i=0,o=function(){if(e())r();else{var s=t(++i);null!=n&&i>=n?a():setTimeout(o,s)}};o()})}function O(e,t){for(var n=1,r=-1,a=0;a=0)n*=e[a];else if(-1===e[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-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);var i=e.slice();return i[r]=t/n,i}function k(e,t){for(var n=[],r=[],a=0,i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),t[a]<=i&&a++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function I(e,t){var 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 C(e,t,n){if("float32"===t)for(var r=0;r=0;--r)n[r]=n[r+1]*e[r+1];return n}function L(e,t,n){return function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t)?e:(Array.isArray(e)&&(e=y(e)),function(e,t,n){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return n&&P(e,t),new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),a=0;a1)for(var l=0;lq){var c=$*s,f=Array.from(t.subarray(0,c)),p=Array.from(t.subarray(u-$*s,u));return"complex64"===r&&(f=K(f),p=K(p)),["["+f.map(function(e,t){return H(e,i[t])}).join(", ")+", ..., "+p.map(function(e,t){return H(e,i[u-$+t])}).join(", ")+"]"]}return["["+("complex64"===r?K(t):Array.from(t)).map(function(e,t){return H(e,i[t])}).join(", ")+"]"]}var h=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>q){for(var y=0;y<$;y++){var v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,r,d,i,!1))}for(g.push("..."),y=u-$;y {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),a=re(e);a.forEach(function(e){return r.add(e.id)});for(var i=0;i0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var i=e();d(i instanceof Q,"The result y returned by f() must be a tensor.");var o=function(e,t,n){for(var r={},a={},i=0;i=0;i--)for(o=(d=e[i]).inputs,c=0;c0)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.");var s={};return s[i.id]=null==n?function(e){var t=B(b(e),"float32");return Q.make(e,{values:t})}(i.shape):n,function(e,t){for(var n=function(n){var r=t[n],a=[];if(r.outputs.forEach(function(t){var n=e[t.id];if(null!=n)a.push(n);else{var r=Q.make(t.shape,{values:z(t.size,t.dtype)},t.dtype);a.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var i=r.gradient(1===r.outputs.length?a[0]:a);for(var o in r.inputs){if(!(o in i))throw new Error("Cannot backprop through input "+o+". Available gradients found: "+Object.keys(i)+".");var s=i[o](),u=r.inputs[o];if(!w(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+o+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}},r=t.length-1;r>=0;r--)n(r)}(s,o),{value:i,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return d(R(e),"The f passed in customGrad(f) must be a function."),function(){for(var n,r,a=[],i=0;i {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e},e}();!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(ae||(ae={}));var oe=[{name:"DEBUG",type:ae.BOOLEAN},{name:"IS_BROWSER",type:ae.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:ae.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:ae.BOOLEAN},{name:"WEBGL_VERSION",type:ae.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:ae.BOOLEAN},{name:"BACKEND",type:ae.STRING},{name:"EPSILON",type:ae.NUMBER}];function se(e,t){var n;try{n=fe(e,t)}catch(e){return!1}return null!=n&&(pe(n),!0)}var ue="tfjsflags";function le(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=function(e){var t={};return window.location.search.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r0?0:function(e,t){if(0===e)return 0;var n,r=fe(e,t);return n=ce(r,"EXT_disjoint_timer_query_webgl2")&&2===e?2:ce(r,"EXT_disjoint_timer_query")?1:0,null!=r&&pe(r),n}(n,this.get("IS_BROWSER"))}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===t)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!function(){var e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return se(2,this.get("IS_BROWSER"))?2:se(1,this.get("IS_BROWSER"))?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1;if(!ce(n,"WEBGL_color_buffer_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_FENCE_API_ENABLED"===t)return function(e,t){if(2!==e)return!1;var n=fe(e,t),r=null!=n.fenceSync;return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:.001;throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(e){this.features=Object.assign({},e)},t.prototype.reset=function(){this.features=le(),null!=this.globalEngine&&(this.globalEngine=null)},t.prototype.initBackend=function(e,t){var n=this;if(void 0===t&&(t=!1),this.backendName=e,this.engines[e])this.globalEngine=this.engines[e];else{var r=this.findBackend(e);this.globalEngine=new ie(r,t,function(){return n.get("DEBUG")}),this.engines[e]=this.globalEngine}},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},t.prototype.registerBackend=function(e,t,n,r){var a=this;if(void 0===n&&(n=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=r&&r(function(){return a.engine}),!1;try{var i=t();return this.registry[e]={backend:i,priority:n},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},t.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e],e in this.engines&&delete this.engines[e]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initDefaultBackend(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(this.get("BACKEND"),!1)},t}(),me=function(){var t=function(){var t;if("undefined"!=typeof window)t=window;else{if(void 0===e)throw new Error("Could not find a global object");t=e}return t}();return null==t.ENV&&(t.ENV=new de(le()),Z(function(){return t.ENV.engine})),t.ENV}(),ge=Object.freeze({Environment:de,ENV:me});function ye(e){return d(R(e),"The f passed in grad(f) must be a function"),function(t,n){return d(t instanceof Q,"The x passed in grad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in grad(f)(x, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ee(i),i[0]})}}function ve(e){return d(R(e),"The f passed in grads(f) must be a function"),function(t,n){return d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in grads(f)(args) must be an array of tensors"),d(null==n||n instanceof Q,"The dy passed in grads(f)(args, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ee(i),i})}}function be(e){return d(R(e),"The f passed in valueAndGrad(f) must be a function"),function(t,n){d(t instanceof Q,"The x passed in valueAndGrad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.grads,i=r.value;return Ee(a),{grad:a[0],value:i}}}function we(e){return d(R(e),"The f passed in valueAndGrads(f) must be a function"),function(t,n){d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),d(null==n||n instanceof Q,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n);return null!=n&&m(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ee(r.grads),r}}function xe(e,t){if(d(R(e),"The f passed in variableGrads(f) must be a function"),d(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof ee}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var n in t=[],me.engine.registeredVariables)t.push(me.engine.registeredVariables[n]);var r=t.length;d((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable.");var a=me.engine.gradients(e,t,null,!0),i=a.value,o=a.grads;d(o.some(function(e){return 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()."),d(0===i.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+i.rank+" tensor");var s={};return t.forEach(function(e,t){null!=o[t]&&(s[e.name]=o[t])}),{value:i,grads:s}}function _e(e){return me.engine.customGrad(e)}function Ee(e){if(e.filter(function(e){return 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.")}var Ne=de.tidy,Se=de.keep,Oe=de.dispose,ke=de.time,Ie=de.profile;function Ce(){for(var e=[],t=0;t=2*t+1||a%2==1?o.push(a):i.push(a);r.push.apply(r,i),r.push(0),r.push.apply(r,o)}return r}function Te(e,t,n,r){void 0===r&&(r=!0);var a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(var i=1;i=-n&&e0?a>=c[t]:a<=c[t]);a+=r[t])n+=1;return n}),[l,h,f]}function He(e,t,n,r,a){var i=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),p(0,i,o-1)}function Ke(e,t,n,r,a){var i=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),n[a]>0?p(0,i,o):p(-1,i,o-1)}function Xe(e,t,n,r){if(void 0===r&&(r="float32"),r=r||"float32",e instanceof Q)return e;if(!T(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e)throw new Error("Argument '"+t+"' passed to '"+n+"' must be a Tensor or TensorLike, but got "+e.constructor.name);var a=v(e);return T(e)||Array.isArray(e)||(e=[e]),Q.make(a,{values:L(e,r,me.get("DEBUG"))},r)}function Ye(e,t,n){if(!Array.isArray(e))throw new Error("Argument "+t+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map(function(e,r){return Xe(e,t+"["+r+"]",n)})}function Je(e){var 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.");var n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var a=function(){for(var e=[],t=0;t1)return ft([0],r);var a=z(Math.abs(Math.ceil((t-e)/n)),r);ta}).sort(function(e,t){return t.score-e.score}),o=[],s=0;s=0;--p)if(Pt(e,c,o[p])>=r){f=!0;break}if(!f&&(o.push(c),o.length>=n))break}return at(o,"int32")}function Pt(e,t,n){var r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),f=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(s-i)*(u-o),d=(f-l)*(p-c);if(h<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),y=Math.min(s,f),v=Math.min(u,p),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(h+d-b)}function At(e,t,n){var r=Array(e.rank).fill(0),a=e.shape.slice();return t.map(function(t){a[n]=t;var i=e.slice(r,a);return r[n]+=t,i})}function Tt(e,t,n,r,a){for(var i=t[t.length-1],o=[e.length/i,i],s=o[0],u=o[1],l=I(n,s*r),c=I("int32",s*r),f=0;f1&&1===o&&r.unshift(i)}return r}function Rt(e,t){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Dt(e,t){for(var n=[],r=Math.max(e.length,t.length),a=0;a1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});a=a.join("\n");var i,o=e.map(function(e){return function(e,t,n){var r=function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1)+"Flat",r=b(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform)return 1===r?"float "+n+"(int index) {return "+t+";}":"\n float "+n+"(int index) {\n for (int i = 0; i < "+r+"; i++) {\n if (i == index) {\n return "+t+"[i];\n }\n }\n }\n ";var a=e.shapeInfo.texShape,i=a[0],o=a[1];return 1===o&&1===i?"\n float "+n+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ":1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+i+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index) + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = UVfrom1D("+i+", "+o+", index);\n return sampleTexture("+t+", uv);\n }\n "}(e);return r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+n+"() {return "+t+";}":"\n float "+n+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}(t);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+n+"(int index) {\n return "+n+"Flat(index);\n }\n "}(t);case 2:return function(t){var n=t.shapeInfo.logicalShape,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape;if(null!=i&&w(n,i)){var o=i[0];return"\n float "+a+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var s=k(n),u=s.newShape,l=s.keptDims,c=u;if(c.lengths||o.length>0),c=function(e){for(var t=0;t=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+n+"("+(i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}(e,t,a,i);var p=b(e.shapeInfo.logicalShape),h="";l&&c&&(h="\n int mainPart = index / "+p+";\n index -= mainPart * "+p+";\n ");var d=t.texShape;if(f)return 1===p?"float "+i+"() {return "+r+";}":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return w(m,d)?"\n float "+i+"() {\n return sampleTexture("+r+", resultUV);\n }\n ":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+r+", uv);\n }\n "}(e,t,n)),r}(e,t,r)}).join("\n"),s=t.texShape;return i=t.isPacked?function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 2:return function(e,t){return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+Math.ceil(t[0]/2)+", "+Math.ceil(t[1]/2)+"));\n }\n "}(0,t);default:throw new Error(e.length+"-D output packed sampling is not yet supported")}}(t.logicalShape,s):function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){return w(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}(e,t);case 3:return function(e,t){var n=e[1]*e[2],r=e[2];return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+n+";\n index -= r * "+n+";\n int c = index / "+r+";\n int d = index - c * "+r+";\n return ivec3(r, c, d);\n }\n "}(e,t);case 4:return function(e,t){var n=e[3],r=e[2]*n,a=e[1]*r;return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+a+";\n index -= r * "+a+";\n\n int c = index / "+r+";\n index -= c * "+r+";\n\n int d = index / "+n+";\n int d2 = index - d * "+n+";\n\n return ivec4(r, c, d, d2);\n }\n "}(e,t);case 5:return function(e,t){var n=e[4],r=e[3]*n,a=e[2]*r,i=e[1]*a;return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+i+";\n index -= r * "+i+";\n\n int c = index / "+a+";\n index -= c * "+a+";\n\n int d = index / "+r+";\n index -= d * "+r+";\n\n int d2 = index / "+n+";\n int d3 = index - d2 * "+n+";\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(e,t);case 6:return function(e,t){var n=e[5],r=e[4]*n,a=e[3]*r,i=e[2]*a,o=e[1]*i;return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+o+";\n index -= r * "+o+";\n\n int c = index / "+i+";\n index -= c * "+i+";\n\n int d = index / "+a+";\n index -= d * "+a+";\n\n int d2 = index / "+r+";\n index -= d2 * "+r+";\n\n int d3 = index / "+n+";\n int d4 = index - d3 * "+n+";\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}(t.logicalShape,s),[Wt,Vt,Ut,a,i,o,n].join("\n")}var Vt="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",Ut="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",Wt="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\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 bool isNaN(float val) {\n return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\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 \nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n";function qt(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function $t(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Gt(e,t){return t.map(function(t){return e[t]}).join(", ")}function Ht(e,t){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 sum for rank "+e+" is not yet supported")}var Kt,Xt,Yt=function(){function e(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 "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}();function Jt(e,t){return[t,e]}function Zt(e,t){return e*t}function Qt(e,t,n){var r=function(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t}(e.length,n);if(t.length= "+r);for(var a=0,i=0;ir||n>r)throw a="["+t+"x"+n+"]",new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function Nn(e){return Rn(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Sn(e,t,n,r,a,i,o){var s=e.getAttribLocation(t,n);return-1!==s&&(on(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),on(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,i,o)}),on(e,function(){return e.enableVertexAttribArray(s)}),!0)}function On(e,t,n){Dn(e,n),on(e,function(){return e.activeTexture(e.TEXTURE0+n)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function kn(e,t,n){return Rn(e,function(){return e.getUniformLocation(t,n)},'uniform "'+n+'" not present in program.')}function In(e,t,n){return e.getUniformLocation(t,n)}function Cn(e,t,n,r,a){on(e,function(){return On(e,n,a)}),on(e,function(){return e.uniform1i(r,a)})}function Pn(e,t,n){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)}),on(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function An(e,t){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),on(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function Tn(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Mn(e,t))}function Mn(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Rn(e,t,n){var r=on(e,function(){return t()});if(null==r)throw new Error(n);return r}function Dn(e,t){var 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 jn(e,t){2!==t.length&&(t=k(t).newShape);var n=wn(e),r=b(t);return t.length<=1&&r<=n?[r,1]:2===t.length&&t[0]<=n&&t[1]<=n?t:3===t.length&&t[0]<=n&&t[1]*t[2]<=n?[t[0],t[1]*t[2]]:4===t.length&&t[0]<=n&&t[1]*t[2]*t[3]<=n?[t[0],t[1]*t[2]*t[3]]:E(r)}var Ln=Object.freeze({createWebGLRenderingContext:rn,createWebGLRenderingContextFromCanvas:an,callAndCheck:on,enableDebugWebGLErrorChecking:un,checkWebGLError:ln,getWebGLErrorMessage:cn,getExtensionOrThrow:fn,createVertexShader:pn,createFragmentShader:hn,createProgram:mn,linkProgram:gn,validateProgram:yn,createStaticVertexBuffer:vn,createStaticIndexBuffer:bn,queryMaxTextureSize:wn,getNumChannels:xn,createTexture:_n,validateTextureSize:En,createFramebuffer:Nn,bindVertexBufferToProgramAttribute:Sn,bindTextureUnit:On,unbindTextureUnit:function(e,t){Dn(e,t),on(e,function(){return e.activeTexture(e.TEXTURE0+t)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:kn,getProgramUniformLocation:In,bindTextureToProgramUniformSampler:Cn,bindCanvasToFramebuffer:function(e){on(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),on(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),on(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})},bindColorTextureToFramebuffer:Pn,unbindColorTextureFromFramebuffer:An,validateFramebuffer:Tn,getFramebufferErrorMessage:Mn,getTextureShapeFromLogicalShape:jn});function Bn(e){var t,n={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};return on(t=null!=e?an(e,n):rn(n),function(){return t.disable(t.DEPTH_TEST)}),on(t,function(){return t.disable(t.STENCIL_TEST)}),on(t,function(){return t.disable(t.BLEND)}),on(t,function(){return t.disable(t.DITHER)}),on(t,function(){return t.disable(t.POLYGON_OFFSET_FILL)}),on(t,function(){return t.disable(t.SAMPLE_COVERAGE)}),on(t,function(){return t.enable(t.SCISSOR_TEST)}),on(t,function(){return t.enable(t.CULL_FACE)}),on(t,function(){return t.cullFace(t.BACK)}),t}function zn(e){return pn(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Fn(e){return vn(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Vn(e){return bn(e,new Uint16Array([0,1,2,2,1,3]))}function Un(e,t){var n,r,a,i,o,s,u,l=e;return 2===me.get("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,a=l.RGBA32F,i=l.RED,o=4,s=1,u=l.HALF_FLOAT):(n=e.RGBA,r=e.RGBA,a=l.RGBA,i=e.RGBA,o=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:o,defaultNumChannels:s,textureTypeHalfFloat:u}}function Wn(e,t,n,r,a,i){En(e,t,n);var o=_n(e),s=e.TEXTURE_2D;return on(e,function(){return e.bindTexture(s,o)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),on(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),on(e,function(){return e.texImage2D(s,0,r,t,n,0,a,i,null)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),o}function qn(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,e.FLOAT)}function $n(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function Gn(e,t,n,r){var a=Jt(t,n);return Wn(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function Hn(e,t,n,r){var a=en(t,n);return Wn(e,a[0],a[1],r.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function Kn(e,t,n){return on(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),Sn(e,t,"clipSpacePos",n,3,20,0)&&Sn(e,t,"uv",n,2,20,12)}function Xn(e,t,n){on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),on(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Yn(e,t,n,r,a,i){En(e,n,r),on(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),on(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,i,e.FLOAT,a)}),on(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Jn(e,t,n,r,a,i,o){var s,u=Jt(n,r),l=u[0],c=u[1];1===o.defaultNumChannels?s=a:function(e,t,n){var r=Zt(e.length,n);if(t.length= "+r);for(var a=0,i=0;i= "+a);for(var i=en(t,n),o=i[0],s=i[1],u=n%2==1,l=t%2==1,c=Math.floor(n/2),f=Math.floor(t/2),p=u?4:0,h=n,d=0,m=0;m= "+a);for(var i=n%2==1,o=t%2==1,s=Math.floor(n/2),u=Math.floor(t/2),l=en(t,n),c=l[0],f=l[1],p=i?4:0,h=n+(i?1:0),d=0,m=0,g=n,y=0;y0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,function(){return rr(r.gl,t,n,r.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=hn(t,e),r=zn(t),a=mn(t);return on(t,function(){return t.attachShader(a,r)}),on(t,function(){return t.attachShader(a,n)}),gn(t,a),this.autoDebugValidate&&yn(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=Kn(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&on(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&yn(this.gl,this.program),on(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?kn(this.gl,e,t):In(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),on(this.gl,function(){return n.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Cn(this.gl,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=en(t,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(e,a,i)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&yn(this.gl,this.program),Tn(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),on(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),on(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=fn(this.gl,2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return l(this,void 0,void 0,function(){var t=this;return c(this,function(n){switch(n.label){case 0:return[4,S(function(){return t.isQueryAvailable(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise(function(n){t.addItemToPoll(function(){return e.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0,n=e.length-1,r=-1;t<=n;){var a=t+n>>1;e[a]()?(r=a,t=a+1):n=a-1}return r}(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||S(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),Pn(this.gl,e,this.framebuffer),this.autoDebugValidate&&Tn(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Pn(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Tn(this.gl)):An(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;Pn(r,e,this.framebuffer),this.autoDebugValidate&&Tn(r),this.outputTexture=e,on(r,function(){return r.viewport(0,0,t,n)}),on(r,function(){return r.scissor(0,0,t,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var a=this;this.throwIfDisposed(),on(this.gl,function(){return a.gl.scissor(e,t,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function or(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(function(e,n){var r=e.logicalShape,a=t[n],i=a.shape;if(!w(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var o=e.texShape,s=a.isUniform?null:a.texData.texShape;if(!w(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var sr=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\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 "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e)}},e}(),ur=function(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n int r = rc.x;\n int c = rc.y;\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e[1]+";\n bool rEdge = rp1 >= "+e[0]+";\n\n gl_FragColor = vec4(\n getA(r, c),\n cEdge ? 0. : getA(r, cp1),\n rEdge ? 0. : getA(rp1, c),\n rEdge || cEdge ? 0. : getA(rp1, cp1)\n );\n }\n "},lr=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterHeight,a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,s=e.padInfo.top,u=e.padInfo.left;this.outputShape=e.outShape;var l="avg"===t,c="0.0";if(l||(c="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\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 < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+a+"; wC++) {\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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+a+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var p=4*Math.floor(a/4),h=a%4,d="\n if ("+l+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\n const float initializationValue = "+c+";\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("+c+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n "+d+"\n }\n\n int xC = xCCorner + "+p+";\n if ("+(1===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(2===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(3===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n "+d+"\n }\n }\n setOutput("+f+");\n }\n "}},cr=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=qt(this.rank),n=function(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){if(null!=t.startLoc||(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null!=t.startLoc))if(1===t.rank)n.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)n.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)n.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");n.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}(),fr=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t){var n,r=pr(t),a=hr(e,r);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),r===Xt.PACKED_2X2_FLOAT32?n=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===Xt.UNPACKED_FLOAT32?n=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===Xt.UNPACKED_FLOAT16?n=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===Xt.PACKED_4X1_UNSIGNED_BYTE&&(n=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(n),n},e.prototype.releaseTexture=function(e,t,n){var r=hr(t,pr(n));r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[r],i=a.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function pr(e){if(e===Kt.DOWNLOAD||e===Kt.PIXELS)return Xt.PACKED_4X1_UNSIGNED_BYTE;if(e===Kt.UPLOAD)return Xt.UNPACKED_FLOAT32;if(e===Kt.RENDER)return me.get("WEBGL_RENDER_FLOAT32_ENABLED")?Xt.UNPACKED_FLOAT32:Xt.UNPACKED_FLOAT16;if(e===Kt.PACK)return Xt.PACKED_2X2_FLOAT32;throw new Error("Unknown logical texture type "+e)}function hr(e,t){return e[0]+"_"+e[1]+"_"+t}var dr=1.7580993408473768,mr=1.0507009873554805,gr=function(){function e(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float NAN;\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 "}return e.prototype.getCustomSetupFunc=function(){var e=this;return function(t,n){null==e.startLoc&&(e.startLoc=t.getUniformLocationNoThrow(n,"NAN"),null==e.startLoc)||t.gl.uniform1f(e.startLoc,NaN)}},e}(),yr="if (isNaN(x)) return x;",vr=Je({concat_:function(e,t){void 0===t&&(t=0),d(e.length>=1,"Pass at least one tensor to concat");var n=Ye(e,"tensors","concat");t=Be(t,n[0].shape)[0];var r=We(n.map(function(e){return e.shape}),t);if(0===b(r))return nt([],r);if(1===(n=n.filter(function(e){return e.size>0})).length)return n[0];var a=n.map(function(e){return e.shape});!function(e,t){var n=e[0].length;e.forEach(function(e,t){d(e.length===n,"Error in concat"+n+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+n+")")}),d(t>=0&&t>>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}(e),a=t&&t.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),Or=Nr(function(e){!function(e,t,n){function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),kr=Nr(function(e){!function(e,t,n){function r(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 a(e,t){var n=new function(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()}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),Ir=Nr(function(e){!function(e,t,n){function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new function(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)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),Cr=Nr(function(e){!function(e,t,n){function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new function(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,o,s=[],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&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;e.w=o,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),Pr=Nr(function(e){!function(e,t,n){function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),Ar=Nr(function(e){!function(t,r){var a,i=this,o=256,s=6,u="random",l=r.pow(o,s),c=r.pow(2,52),f=2*c,p=o-1;function h(e,n,h){var y=[],v=m(function e(t,n){var r,a=[],i=typeof t;if(n&&"object"==i)for(r in t)try{a.push(e(t[r],n-1))}catch(e){}return a.length?a:"string"==i?t:t+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[e,g(t)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(o):(e=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(e)),g(e)}catch(e){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(t)]}}():e,3),y),b=new function(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a=f;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,m(g(b.S),t),(n.pass||h||function(e,t,n,a){return a&&(a.S&&d(a,b),e.state=function(){return d(b,{})}),n?(r[u]=e,t):e})(w,v,"global"in n?n.global:this==r,n.state)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function m(e,t){for(var n,r=e+"",a=0;a=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}();function Rr(e,t){return l(this,void 0,void 0,function(){var n,r,a,i,o,s,u,l,f,p,h,d,m,g,y,v,b,w,x,_;return c(this,function(c){switch(c.label){case 0:if(2!==(n=Xe(e,"img","toPixels","int32")).rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(o=2===n.rank?1:n.shape[2])>4||2===o)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+o);return s=n.min(),u=n.max(),[4,s.data()];case 1:return l=c.sent()[0],[4,u.data()];case 2:if(f=c.sent()[0],s.dispose(),u.dispose(),"float32"===n.dtype){if(l<0||f>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+f+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(l<0||f>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+f+"].")}return[4,n.data()];case 3:for(p=c.sent(),h="float32"===n.dtype?255:1,d=new Uint8ClampedArray(i*a*4),m=0;m=1+t.length,"input rank should be > than [blockShape] but got "+r.rank),d(n.length===t.length,"crops.shape[0] must be equal to [blockShape] but got "+n.length),d(r.shape[0]%a==0,"input tensor batch must be divisible by prod( blockShape )"),me.engine.runKernel(function(e){return e.batchToSpaceND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}})}}),Br=Je({cast_:function(e,t){var n=Xe(e,"x","cast");return me.engine.runKernel(function(e){return e.cast(n,t)},{$x:n},function(e){return{$x:function(){return e.clone()}}})}}),zr=Je({clone_:function(e){var t=Xe(e,"x","clone");return me.engine.runKernel(function(e){return Q.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),Fr=Je({cumsum_:function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=Xe(e,"x","cumsum"),i=Fe([t|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=Ue(1,a.rank)[0],u=me.engine.runKernel(function(e){return e.cumsum(o,s,n,r)},{permutedX:o},function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),Vr=Je({depthToSpace_:function(e,t,n){void 0===n&&(n="NHWC");var r=Xe(e,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return d(a*t>=0,"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(i*t>=0,"Negative dimension size caused by overflow when multiplying\n "+i+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(o%(t*t)==0,"Dimension size must be evenly divisible by "+t*t+" but is "+o+" for depthToSpace with input shape "+r.shape),me.engine.runKernel(function(e){return e.depthToSpace(r,t,n)},{$x:r})}}),Ur=Je({expandDims_:function(e,t){void 0===t&&(t=0);var n=Xe(e,"x","expandDims");d(t<=n.rank,"Axis must be <= rank of the tensor");var r=n.shape.slice();return t<0&&(d(-(n.rank+1)<=t,"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"),t=n.rank+t+1),r.splice(t,0,1),ta(n,r)}}),Wr=Je({eye_:function(e,t,n,r){void 0===r&&(r="float32"),null==t&&(t=e);for(var a=Dr([e,t],r),i=e<=t?e:t,o=0;o4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return me.engine.fromPixels(e,t)}}),$r=Je({multinomial_:function(e,t,n,r){void 0===r&&(r=!1);var a=Xe(e,"logits","multinomial"),i=a.size,o=a.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?a.as2D(1,-1):a,u=me.engine.runKernel(function(e){return e.multinomial(s,r,t,n)},{logits2D:s});return 1===o?u.as1D():u}}),Gr=Je({oneHot_:function(e,t,n,r){void 0===n&&(n=1),void 0===r&&(r=0);var a=Xe(e,"indices","oneHot","int32");if(d("int32"===a.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return me.engine.runKernel(function(e){return e.oneHot(a,t,n,r)},{$indices:a},function(e){return{$indices:function(){return _t(a)}}})}}),Hr=Je({pad_:function(e,t,n){void 0===n&&(n=0);var r=Xe(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a=t.map(function(e){return e[0]});return me.engine.runKernel(function(e){return e.pad(r,t,n)},{$x:r},function(e){return{$x:function(){return e.slice(a,r.shape)}}})}}),Kr=Je({pad1d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length,"Invalid number of paddings. Must be length of 2."),Hr(e,[t],n)}}),Xr=Je({pad2d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length&&2===t[0].length&&2===t[1].length,"Invalid number of paddings. Must be length of 2 each."),Hr(e,t,n)}}),Yr=Je({pad3d_:function(e,t,n){return void 0===n&&(n=0),d(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."),Hr(e,t,n)}}),Jr=Je({pad4d_:function(e,t,n){return void 0===n&&(n=0),d(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."),Hr(e,t,n)}}),Zr=Je({rand_:function(e,t,n){var r=b(e),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(var i=0;i=1+t.length,"input rank "+r.rank+" should be > than [blockShape] "+t.length),d(n.length===t.length,"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+t.length),d(r.shape.reduce(function(e,r,a){return 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()),me.engine.runKernel(function(e){return e.spaceToBatchND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}})}}),ra=Je({squeeze_:function(e,t){var n=Xe(e,"x","squeeze");return ta(n,k(n.shape,t).newShape)}}),aa=Je({stack_:function(e,t){void 0===t&&(t=0);var n=Ye(e,"tensors","stack");if(d(n.length>=1,"Pass at least one tensor to tf.stack"),1===n.length)return n[0].expandDims(t);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;d(t<=r,"Axis must be <= rank of the tensor"),n.forEach(function(e){m(a,e.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(e){d(i===e.dtype,"All tensors passed to stack must have matching dtypes")});var o=n.map(function(e){return e.expandDims(t)});return vr(o,t)}}),ia=Je({tile_:function(e,t){var n=Xe(e,"x","tile");return d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of reps "+t+"."),me.engine.runKernel(function(e){return e.tile(n,t)},{$x:n},function(e){return{$x:function(){var r=_t(n);if(1===n.rank)for(var a=0;a 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\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "}(a);this.compileAndRun(s,[o],i,null,!1);var u=this.texData.get(i.dataId),l=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture,u.texShape[0],u.texShape[1]);return o.dispose(),i.dispose(),l},e.prototype.time=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),a=y(this.activeTimers),this.activeTimers=t,r&&(this.programTimersStack=null),[4,Promise.all(a).then(function(e){var t=0;return e.forEach(function(e){return t+=e}),t})];case 1:return i=s.sent(),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:i,wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return l(this,void 0,void 0,function(){var t;return c(this,function(n){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),n=t.texture,r=t.texShape,a=t.usage,i=t.complexTensors;null!=n&&this.releaseTexture(e,n,r,a),null!=i&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.getCanvas=function(){return this.canvas},e.prototype.complex=function(e,t){var n=Q.make(e.shape,{},"complex64");return this.texData.get(n.dataId).complexTensors={real:me.engine.keep(e.clone()),imag:me.engine.keep(t.clone())},n},e.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},e.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},e.prototype.slice=function(e,t,n){var r=new cr(n),a=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,a)},e.prototype.stridedSlice=function(e,t,n,r,a,i,o,s,u){var l=Ge(e.shape,t,n,r,a,i,o,s,u),c=l[0],f=l[1],p=l[2],h=f.filter(function(e,t){return-1===p.indexOf(t)});if(h.some(function(e){return 0===e}))return nt([],h);var d=new function(e,t,n,r){this.variableNames=["x"];var a=n.filter(function(e,t){return-1===r.indexOf(t)});this.outputShape=a;var i=n.length,o=qt(n.length),s=qt(a.length),u="";if(1===i)u="coords * strides + begin";else{var l=0;u=n.map(function(e,t){return-1===r.indexOf(t)?(l++,1===a.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(l-1)+"] * strides["+t+"] + begin["+t+"]"):"begin["+t+"]"}).join(",")}this.userCode="\n "+o+" begin = "+o+"("+e+");\n "+o+" strides = "+o+"("+t+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "}(c,r,f,p);return this.compileAndRun(d,[e])},e.prototype.reverse=function(e,t){var n=new function(e,t){this.variableNames=["x"];var 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){var r=e.map(function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),a=qt(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "}(e.shape,t);return this.compileAndRun(n,[e])},e.prototype.concat2Tensors=function(e,t,n){var r=We([e.shape,t.shape],n),a=e.as2D(-1,b(e.shape.slice(n))),i=t.as2D(-1,b(t.shape.slice(n))),o=new function(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=We([e,t],1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "}(a.shape,i.shape);return this.compileAndRun(o,[a,i]).reshape(r)},e.prototype.concat=function(e,t){if(1===e.length)return e[0];for(var n=e[0],r=1;r= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "}(e.shape,t,n,r,a);return this.compileAndRun(i,[e])},e.prototype.LRNGrad=function(e,t,n,r,a,i,o){var s=new function(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 "}(t.shape,r,a,i,o);return this.compileAndRun(s,[t,n,e])},e.prototype.tile=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.transpose=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r6)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),a=0;a4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=Pe(e.shape,t,r),i=Ae(a.length,t.length),o=Te(e.shape,t,r),s=Me(n,t.length),u=Re(o,n,t.length);return e.reshape(a).transpose(i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(e,t,n){d(e.rank<=4,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=[[0,0]];a.push.apply(a,n);for(var i=1+t.length;i= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(o="0.0",f="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var h="";a%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\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("+o+");\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; 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 "+f+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+f+"\n }\n setOutput("+u+");\n }\n "}({windowSize:$e(a),inSize:a,batchSize:r},t),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],n);return this.compileAndRun(i,[e],l),1===l.shape[1]?l:this.reduce(l,t,n)},e.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],a=e.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=new function(e,t,n){this.variableNames=["A"];var r=e.windowSize,a=e.batchSize,i=e.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===t?">":"<",u=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 = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\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 "}({windowSize:$e(a),inSize:a,batchSize:r},t,null==n),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],"int32"),c=[e];return null!=n&&c.push(n),this.compileAndRun(i,c,l),1===l.shape[1]?l:this.argReduce(e,t,l)},e.prototype.sum=function(e,t){ze("sum",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a),o=St(e.dtype);return this.reduce(i,"sum",o).reshape(r)},e.prototype.unsortedSegmentSum=function(e,t,n){var r=0,a=Fe([r],e.rank),i=e;null!=a&&(i=e.transpose(a),r=Ue(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],a=e.length,i=0;it||n===e){r=!0;break}n=D(e,n+1)}return n}(o,a),u=new function(e,t){this.variableNames=["x","segmentIds"];var n=e.windowSize,r=e.batchSize,a=e.inSize,i=e.numSegments,o=i*Math.ceil(a/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, filter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var f="";a%n>0&&(f="\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 "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+f+"\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 < "+s+"; 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 filter = 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 "+l+"\n }\n\n int inIdx = inOffset + "+s+";\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = 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 "+l+"\n }\n setOutput(sumValue);\n }\n "}({windowSize:s,inSize:o,batchSize:i,numSegments:a},t),l=u.outputShape,c=l[0],f=l[1],p=this.makeOutputArray([c,f],r);return this.compileAndRun(u,[e,n],p),p.shape[1]===a?p:(n=dt(0,a).tile([o/s]),this.segOpCompute(p,t,n,r,a))},e.prototype.argMin=function(e,t){var n=[t];ze("argMin",n,e.rank);var r=je(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"min").reshape(a)},e.prototype.argMax=function(e,t){var n=[t];ze("argMax",n,e.rank);var r=je(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"max").reshape(a)},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new function(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,a=e[e.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+qt(r)+" coords = getOutputCoords();\n int end = "+Ht(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+Ht(r,"coords")+" = idx;\n val += getX("+function(e,t){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 sum for rank "+e+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}(e.shape,n,r);return this.compileAndRun(a,[e])},e.prototype.equal=function(e,t){var n=new zt("return float(a == b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.notEqual=function(e,t){var n=new zt("return float(a != b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.less=function(e,t){var n=new zt("return float(a < b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.lessEqual=function(e,t){var n=new zt("return float(a <= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greater=function(e,t){var n=new zt("return float(a > b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greaterEqual=function(e,t){var n=new zt("return float(a >= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalNot=function(e){var t=new gr(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},e.prototype.logicalAnd=function(e,t){var n=new zt("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalOr=function(e,t){var n=new zt("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.select=function(e,t,n){var r=new function(e,t,n){var 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{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "}(e.rank,t.shape,t.rank),a=this.makeOutputArray(r.outputShape,Nt(t.dtype,n.dtype));return this.compileAndRun(r,[e,t,n],a)},e.prototype.where=function(e){Ce("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return ua(e.shape,t)},e.prototype.topk=function(e,t,n){return Tt(e.dataSync(),e.shape,e.dtype,t)},e.prototype.min=function(e,t){ze("min",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.mod=function(e,t){var n=new zt("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[e,t],null,r)},e.prototype.max=function(e,t){ze("max",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.all=function(e,t){ze("all",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(e,t){ze("any",t,e.rank);var n=je(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.squaredDifference=function(e,t){var n=new zt("return (a - b) * (a - b);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.realDivide=function(e,t){var n=new zt("if (a == b) return 1.0;\n return a / b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e,t],r)},e.prototype.floorDiv=function(e,t){var n=new zt("\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[e,t],r)},e.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,Lt);var n=new zt(Lt,e.shape,t.shape),r=this.makeOutputArray(n.outputShape,Nt(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r)},e.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,a=this.texData.get(e.dataId),i=this.texData.get(t.dataId),o=[[a.complexTensors.real,i.complexTensors.real],[a.complexTensors.imag,i.complexTensors.imag]].map(function(a){var i=a[0],o=a[1],s=new zt(n,e.shape,t.shape),u=r.makeOutputArray(s.outputShape,Nt(i.dtype,o.dtype)),l=r.makeComplexComponentTensorHandle(e,i),c=r.makeComplexComponentTensorHandle(t,o);return r.compileAndRun(s,[l,c],u)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},e.prototype.addN=function(e){for(var t=e[0],n=1;n 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");return this.compileAndRun(t,[e])},e.prototype.exp=function(e){var t=new gr(e.shape,"return exp(x);");return this.compileAndRun(t,[e])},e.prototype.expm1=function(e){var t=new gr(e.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[e])},e.prototype.log=function(e){var t=new gr(e.shape,"if (x < 0.0) return NAN;\n return log(x);"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.log1p=function(e){var t=new gr(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},e.prototype.sqrt=function(e){var t=new gr(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},e.prototype.rsqrt=function(e){var t=new gr(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},e.prototype.square=function(e){var t=new gr(e.shape,"return x * x;");return this.compileAndRun(t,[e])},e.prototype.reciprocal=function(e){var t=new gr(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},e.prototype.relu=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(t,[e])},e.prototype.elu=function(e){var t=new gr(e.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[e])},e.prototype.eluDer=function(e,t){var n=new zt("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.selu=function(e){var t=new gr(e.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[e])},e.prototype.int=function(e){var t=new gr(e.shape,"return float(int(x));"),n=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],n)},e.prototype.clip=function(e,t,n){var r=new function(e,t,n){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, float("+t+"), float("+n+")));\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.abs=function(e){var t=new gr(e.shape,"return abs(x);");return this.compileAndRun(t,[e])},e.prototype.sigmoid=function(e){var t=new gr(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},e.prototype.softplus=function(e){var t=new gr(e.shape,"\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");return this.compileAndRun(t,[e])},e.prototype.sin=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return sin(x);\n");return this.compileAndRun(t,[e])},e.prototype.cos=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return cos(x);\n");return this.compileAndRun(t,[e])},e.prototype.tan=function(e){var t=new gr(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},e.prototype.asin=function(e){var t=new gr(e.shape,"return asin(x);");return this.compileAndRun(t,[e])},e.prototype.acos=function(e){var t=new gr(e.shape,"return acos(x);");return this.compileAndRun(t,[e])},e.prototype.atan=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e])},e.prototype.atan2=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.sinh=function(e){var t=new gr(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.cosh=function(e){var t=new gr(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.tanh=function(e){var t=new gr(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},e.prototype.asinh=function(e){var t=new gr(e.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e])},e.prototype.acosh=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.atanh=function(e){var t=new gr(e.shape,"if (isNaN(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.erf=function(e){var t=new gr(e.shape,'\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 = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(t,[e])},e.prototype.step=function(e,t){var n=new gr(e.shape,function(e){return void 0===e&&(e=0),yr+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(n,[e])},e.prototype.conv2d=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,n=e.padInfo.left,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),c=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+a+");\n const ivec2 pads = ivec2("+t+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * 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 < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\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 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 dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - 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 float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left;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 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2D=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,n=e.inWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,o=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,f=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+r+", "+a+");\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 / "+f+";\n int q = d2 - d1 * "+f+";\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 // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\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 setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[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 // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var 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 // TODO: 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.maxPool=function(e,t){var n=new lr(t,"max",!1),r=this.makeOutputArray(n.outputShape,e.dtype);return this.compileAndRun(n,[e],r)},e.prototype.avgPool=function(e,t){var n=new lr(t,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e],r)},e.prototype.maxPoolBackprop=function(e,t,n,r){var a=new lr(r,"max",!0),i=this.compileAndRun(a,[t]),o=new function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=t*n-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+s+" - 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 * "+n+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}(r),s=this.makeOutputArray(o.outputShape,t.dtype),u=this.compileAndRun(o,[e,i],s);return i.dispose(),u},e.prototype.avgPoolBackprop=function(e,t,n){var r=new function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n const float avgMultiplier = float("+s+");\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 < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}(n),a=this.makeOutputArray(r.outputShape,t.dtype);return this.compileAndRun(r,[e],a)},e.prototype.cast=function(e,t){return Ot(e,t,this)},e.prototype.reshape=function(e,t){return kt(e,t)},e.prototype.resizeBilinear=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\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 "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-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), "+(i-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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.resizeNearestNeighbor=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.multinomial=function(e,t,n,r){var a=t?e:Ze(e),i=a.shape[0],o=a.shape[1],s=new sr(i,o,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],u,l)},e.prototype.oneHot=function(e,t,n,r){var a=new function(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 "}(e.size,t,n,r);return this.compileAndRun(a,[e])},e.prototype.nonMaxSuppression=function(e,t,n,r,a){return Ce("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Ct(e.dataSync(),t.dataSync(),n,r,a)},e.prototype.cropAndResize=function(e,t,n,r,a,i){var o=new function(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=e[0],o=e[1],s=e[2],u=e[3],l=t[0],c=n[0],f=n[1];this.outputShape=[l,c,f,u];var p="bilinear"===r?1:0,h=[o-1+".0",s-1+".0"],d=h[0],m=h[1],g=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],E=w[2];this.userCode="\n const float height_ratio = float("+y+");\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 = "+v+";\n float width_scale = "+_+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "}(e.shape,t.shape,r,a,i);return this.compileAndRun(o,[e,t,n])},e.prototype.depthToSpace=function(e,t,n){d(t>1,"blockSize should be > 1 for depthToSpace, but was: "+t);var r=e.shape[0],a=("NHWC"===n?e.shape[1]:e.shape[2])*t,i=("NHWC"===n?e.shape[2]:e.shape[3])*t,o=("NHWC"===n?e.shape[3]:e.shape[1])/(t*t),s=new Yt("NHWC"===n?[r,a,i,o]:[r,o,a,i],t,n);return this.compileAndRun(s,[e])},e.prototype.split=function(e,t,n){return At(e,t,n)},e.prototype.makeOutputArray=function(e,t){return Q.make(e,{},t)},e.prototype.compileAndRun=function(e,t,n,r,a){var i=this;if(void 0===a&&(a=!0),null==n&&(n=this.makeOutputArray(e.outputShape,t[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=I(n.dtype,0),n;var o=t.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var t=i.texData.get(e.dataId);return null==t.texture&&b(e.shape)<=32?{shape:e.shape,texData:null,isUniform:!0,uniformValues:i.readSync(e.dataId)}:(i.uploadToGPU(e.dataId),{shape:e.shape,texData:t,isUniform:!1})});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(e,t,n){var r="";o.concat(n).forEach(function(e){r+=e.shape+"_"+(e.isUniform?"uniform":e.texData.texShape)});var a=e.userCode,i=(!0===e.supportsBroadcasting).toString();return e.constructor.name+"_"+i+"_"+r+"_"+a}(e,0,u),c=this.getAndSaveBinary(l,function(){return function(e,t,n,r){for(var a=t.userCode,i=n.map(function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.usage===Kt.PACK};return{name:t.variableNames[n],shapeInfo:r}}),o=i.map(function(e){return e.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.usage===Kt.PACK},u=Ft(i,s,a,!0===t.supportsBroadcasting),l=e.createProgram(u),c={},f=0;fthis.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;p>0&&this.lruDataGPU.length>0;){var h=this.lruDataGPU.shift(),d=this.texData.get(h),m=d.shape,g=d.dtype;p-=this.computeBytes(m,g),this.read(h)}return f&&(s=this.endTimer(s),this.activeTimers.push(this.getQueryTime(s))),n},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixelsCanvas&&this.fromPixelsCanvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.floatPrecision=function(){var e=this;return Ne(function(){return e.abs(rt(1e-8)).get()>0?32:16})},e.prototype.throwIfNoData=function(e){if(!this.texData.has(e))throw new Error("WebGL backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends")},e.prototype.uploadToGPU=function(e){this.throwIfNoData(e);var t=this.texData.get(e),n=t.shape,r=t.values,a=t.texture,i=(t.dtype,t.usage);if(null==a){var o,s=null!=this.activeTimers;s&&(o=performance.now());var u=jn(this.gpgpu.gl,n);t.texShape=u;var l=this.acquireTexture(e,u,i);t.texture=l,null!=r&&(this.gpgpu.uploadMatrixToTexture(l,u[0],u[1],r instanceof Float32Array?r:new Float32Array(r)),t.values=null,s&&(this.uploadWaitMs+=performance.now()-o))}else this.lruDataGPU.indexOf(e)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),this.lruDataGPU.push(e))},e.prototype.cacheOnCPU=function(e,t){var n=this.delayedStorage,r=this.texData.get(e),a=r.texture,i=r.texShape,o=r.dtype,s=r.usage;n&&null!=a&&(this.releaseTexture(e,a,i,s),r.texture=null,r.texShape=null),r.usage=Kt.UPLOAD,null!=t&&(r.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r=0&&this.lruDataGPU.splice(s,1),this.numBytesInGPU-=this.computeBytes(i,o),this.textureManager.releaseTexture(t,n,r)},e.prototype.acquireTexture=function(e,t,n){var r=this.texData.get(e),a=r.shape,i=r.dtype;return this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(a,i),this.textureManager.acquireTexture(t,n)},e.prototype.computeBytes=function(e,t){return b(e)*M(t)},e}();me.get("IS_BROWSER")&&me.registerBackend("webgl",function(){return new ca},2,Z);var fa=Je({abs_:function(e){var t=Xe(e,"x","abs");return me.engine.runKernel(function(e){return e.abs(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().step(-1))}}})}}),pa=Je({acos_:function(e){var t=Xe(e,"x","acos");return me.engine.runKernel(function(e){return e.acos(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()).sqrt()).neg()}}})}}),ha=Je({acosh_:function(e){var t=Xe(e,"x","acosh");return me.engine.runKernel(function(e){return e.acosh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().square().sub(rt(1)).sqrt())}}})}}),da=Je({asin_:function(e){var t=Xe(e,"x","asin");return me.engine.runKernel(function(e){return e.asin(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()).sqrt())}}})}}),ma=Je({asinh_:function(e){var t=Xe(e,"x","asinh");return me.engine.runKernel(function(e){return e.asinh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).add(t.toFloat().square()).sqrt())}}})}}),ga=Je({atan_:function(e){var t=Xe(e,"x","atan");return me.engine.runKernel(function(e){return e.atan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).add(t.toFloat().square()))}}})}}),ya=Je({atanh_:function(e){var t=Xe(e,"x","atanh");return me.engine.runKernel(function(e){return e.atanh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(rt(1).sub(t.toFloat().square()))}}})}}),va=Je({ceil_:function(e){var t=Xe(e,"x","ceil");return me.engine.runKernel(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),ba=Je({clipByValue_:function(e,t,n){var r=Xe(e,"x","clipByValue");return d(t<=n,"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."),me.engine.runKernel(function(e){return e.clip(r,t,n)},{$x:r},function(e){return{$x:function(){return e.where(r.greaterEqual(rt(t)).logicalAnd(r.lessEqual(rt(n))),_t(e))}}})}}),wa=Je({cos_:function(e){var t=Xe(e,"x","cos");return me.engine.runKernel(function(e){return e.cos(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sin().neg().mulStrict(e)}}})}}),xa=Je({cosh_:function(e){var t=Xe(e,"x","cosh");return me.engine.runKernel(function(e){return e.cosh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sinh().mulStrict(e)}}})}}),_a=Je({erf_:function(e){var t=Xe(e,"x","erf");return d("int32"===t.dtype||"float32"===t.dtype,"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=t.toFloat()),me.engine.runKernel(function(e){return e.erf(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(rt(2/Math.sqrt(Math.PI)).mul(t.square().neg().exp()))}}})}}),Ea=Je({exp_:function(e){var t=Xe(e,"x","exp");return me.engine.runKernel(function(e,n){return n(e.exp(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n)}}})}}),Na=Je({expm1_:function(e){var t=Xe(e,"x","expm1");return me.engine.runKernel(function(e){return e.expm1(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.exp())}}})}}),Sa=Je({floor_:function(e){var t=Xe(e,"x","floor");return me.engine.runKernel(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Oa=Je({log_:function(e){var t=Xe(e,"x","log");return me.engine.runKernel(function(e){return e.log(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat())}}})}}),ka=Je({log1p_:function(e){var t=Xe(e,"x","log1p");return me.engine.runKernel(function(e){return e.log1p(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.add(rt(1)))}}})}}),Ia=Je({logSigmoid_:function(e){var t=Xe(e,"x","logSigmoid");return me.engine.runKernel(function(e){return e.softplus(t.neg()).neg()},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.neg().sigmoid())}}})}}),Ca=Je({neg_:function(e){var t=Xe(e,"x","neg");return me.engine.runKernel(function(e){return e.neg(t)},{$x:t},function(e){return{$x:function(){return e.neg()}}})}}),Pa=Je({reciprocal_:function(e){var t=Xe(e,"x","reciprocal");return me.engine.runKernel(function(e){return e.reciprocal(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.square().neg())}}})}}),Aa=Je({round_:function(e){var t=Xe(e,"x","round");return me.engine.runKernel(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Ta=Je({rsqrt_:function(e){var t=Xe(e,"x","rsqrt");return me.engine.runKernel(function(e){return e.rsqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.pow(rt(1.5)).mul(rt(2))).neg()}}})}}),Ma=Je({sigmoid_:function(e){var t=Xe(e,"x","sigmoid");return me.engine.runKernel(function(e,n){return n(e.sigmoid(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n.mul(rt(1).sub(n)))}}})}}),Ra=Je({sign_:function(e){var t=Xe(e,"x","sign");return me.engine.runKernel(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return _t(e)}}})}}),Da=Je({sin_:function(e){var t=Xe(e,"x","sin");return me.engine.runKernel(function(e){return e.sin(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cos().mulStrict(e)}}})}}),ja=Je({sinh_:function(e){var t=Xe(e,"x","sinh");return me.engine.runKernel(function(e){return e.sinh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cosh().mulStrict(e)}}})}}),La=Je({softplus_:function(e){var t=Xe(e,"x","softplus");return me.engine.runKernel(function(e){return e.softplus(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.sigmoid())}}})}}),Ba=Je({sqrt_:function(e){var t=Xe(e,"x","sqrt");return me.engine.runKernel(function(e){return e.sqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().sqrt().mul(rt(2)))}}})}}),za=Je({square_:function(e){var t=Xe(e,"x","square");return me.engine.runKernel(function(e){return e.square(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().mul(rt(2)))}}})}}),Fa=Je({step_:function(e,t){void 0===t&&(t=0);var n=Xe(e,"x","step");return me.engine.runKernel(function(e){return e.step(n,t)},{$x:n},function(e){return{$x:function(){return _t(e)}}})}}),Va=Je({tan_:function(e){var t=Xe(e,"x","tan");return me.engine.runKernel(function(e){return e.tan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.cos().square())}}})}}),Ua=Je({tanh_:function(e){var t=Xe(e,"x","tanh");return me.engine.runKernel(function(e,n){return n(e.tanh(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return rt(1).sub(n.square()).mulStrict(e)}}})}});function Wa(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}var qa=Je({batchNormalization2d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(2===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(2===l.rank||1===l.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."),d(2===c.rank||1===c.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."),null!=o&&d(2===o.rank||1===o.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."),null!=s&&d(2===s.rank||1===s.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),$a=Je({batchNormalization3d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(3===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(3===l.rank||1===l.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."),d(3===c.rank||1===c.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."),null!=o&&d(3===o.rank||1===o.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."),null!=s&&d(3===s.rank||1===s.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),Ga=Je({batchNormalization4d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Xe(e,"x","batchNormalization"),l=Xe(t,"mean","batchNormalization"),c=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(4===u.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+u.rank+"."),d(4===l.rank||1===l.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."),d(4===c.rank||1===c.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."),null!=o&&d(4===o.rank||1===o.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."),null!=s&&d(4===s.rank||1===s.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."),Ha(u,l,c,r,o,s)}}),Ha=Je({batchNormalization_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u,l=Xe(e,"x","batchNormalization"),c=Xe(t,"mean","batchNormalization"),f=Xe(n,"variance","batchNormalization");return null!=a&&(o=Xe(a,"scale","batchNormalization")),null!=i&&(s=Xe(i,"offset","batchNormalization")),d(c.rank===f.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),d(null==s||c.rank===s.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),d(null==o||c.rank===o.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,me.engine.runKernel(function(e){return e.batchNormalization(u,Wa(c),Wa(f),r,Wa(o),Wa(s))},{$x:l,$mean:c,$variance:f,$scale:o,$offset:s},function(e){var t=null==o?rt(1):o,n=Rt(c.shape,u.shape),a=[];if(1===c.rank){for(var i=0;i=2&&i.rank>=2&&a.rank===i.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."),d(w(c,f),"Error in matMul: outer dimensions ("+c+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."),d(o===s,"Error in matMul: inner shapes ("+o+") and ("+s+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match.");var m=a.shape.slice(0,-2).concat([u,l]),g=n?a.as3D(p,o,u):a.as3D(p,u,o),y=r?i.as3D(h,l,s):i.as3D(h,s,l);return me.engine.runKernel(function(e){return e.batchMatMul(g,y,n,r)},{$a:g,$b:y},function(e){return n||r?!n&&r?{$a:function(){return e.matMul(y.toFloat(),!1,!1)},$b:function(){return e.matMul(g.toFloat(),!0,!1)}}:n&&!r?{$a:function(){return y.toFloat().matMul(e,!1,!0)},$b:function(){return g.toFloat().matMul(e,!1,!1)}}:{$a:function(){return y.toFloat().matMul(e,!0,!0)},$b:function(){return e.matMul(g.toFloat(),!0,!0)}}:{$a:function(){return e.matMul(y.toFloat(),!1,!0)},$b:function(){return g.toFloat().matMul(e,!0,!1)}}}).reshape(m)}}),ei=Je({dot_:function(e,t){var n=Xe(e,"t1","dot"),r=Xe(t,"t2","dot");d(!(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+".");var a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return d(a===i,"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+i+"."),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),ti=Je({outerProduct_:function(e,t){var n=Xe(e,"v1","outerProduct"),r=Xe(t,"v2","outerProduct");return d(1===n.rank&&1===r.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."),n.as2D(-1,1).matMul(r.as2D(1,-1))}});function ni(e,t,n,r,a,i){d(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var o=e,s=t,u=!1;3===t.rank&&(u=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),o=[1,e[0],e[1],e[2]]);var l=o[3],c=s.shape[3];d(4===o.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+o.length+"."),d(4===s.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank),d(4===n.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank),d(l===n.shape[2],"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."),d(c===n.shape[3],"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[3]+"."),null!=i&&d(x(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+".");var f=Xa(o,n.shape,r,1,a,i),p=me.engine.runKernel(function(e){return e.conv2dDerInput(s,n,f)},{dy4D:s});return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function ri(e){var t=function(e){return"number"==typeof e?[e,e]:e}(e),n=t[0],r=t[1];return 1===n&&1===r}function ai(e,t){return ri(e)||ri(t)}var ii=Je({conv1d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NWC"),void 0===i&&(i=1);var s=Xe(e,"x","conv1d"),u=Xe(t,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),d(3===l.rank,"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."),d(3===u.rank,"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."),null!=o&&d(x(r),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),d(l.shape[2]===u.shape[1],"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."),d(ai(n,i),"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"),d("NWC"===a,"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported.");var f=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),p=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),h=oi(p,f,[1,n],r,"NHWC",[1,i],o);return c?h.as2D(h.shape[2],h.shape[3]):h.as3D(h.shape[0],h.shape[2],h.shape[3])}}),oi=Je({conv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=Xe(e,"x","conv2d"),u=Xe(t,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."),d(4===u.rank,"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."),null!=o&&d(x(r),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."),d(l.shape[3]===u.shape[2],"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+"."),d(ai(n,i),"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),d("NHWC"===a,"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported.");var f,p=Xa(l.shape,u.shape,n,i,r,o);if(1===p.filterHeight&&1===p.filterWidth&&1===p.dilationHeight&&1===p.dilationWidth&&1===p.strideHeight&&1===p.strideWidth&&"SAME"===p.padInfo.type){var h=l.reshape([-1,p.inChannels]),m=u.reshape([p.inChannels,p.outChannels]);f=Qa(h,m).reshape(p.outShape)}else f=me.engine.runKernel(function(e){return e.conv2d(l,u,p)},{x:l,$filter:u},function(e){return d(ri(i),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+i+"'"),{x:function(){return ni(l.shape,e,u,n,r)},$filter:function(){return function(e,t,n,r,a,i){var o=e;3===e.rank&&(o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t;3===s.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),d(4===o.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+o.shape+"."),d(4===s.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."),d(4===n.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."),d(o.shape[3]===n[2],"Error in conv2dDerFilter: depth of input "+o.shape[3]+") must match input depth in filter ("+n[2]+"."),d(s.shape[3]===n[3],"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+n[3]+").");var u=Xa(o.shape,n,r,1,a,i);return me.engine.runKernel(function(e){return e.conv2dDerFilter(o,s,u)},{x4D:o,dy4D:s})}(l,e,u.shape,n,r)}}});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),si=Je({depthwiseConv2d_:function(e,t,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=Xe(e,"x","depthwiseConv2d"),u=Xe(t,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."),d(4===u.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),d(l.shape[3]===u.shape[2],"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."),null==i&&(i=[1,1]),d(ai(n,i),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"),null!=o&&d(x(r),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+".");var f=Xa(l.shape,u.shape,n,i,r,o,!0),p=me.engine.runKernel(function(e){return e.depthwiseConv2D(l,u,f)},{x:l,$filter:u},function(e){return d(ri(i),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"),{x:function(){return function(e,t,n,r){var a=t,i=!1;3===t.rank&&(i=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=me.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,n,r)},{dy4D:a});return i?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}(l.shape,e,u,f)},$filter:function(){return function(e,t,n,r){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=t;return 3===i.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),me.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,i,r)},{x4D:a,dy4D:i})}(l,e,u.shape,f)}}});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}}),ui=Je({separableConv2d_:function(e,t,n,r,a,i,o){void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC");var s=Xe(e,"x","separableConv2d"),u=Xe(t,"depthwiseFilter","separableConv2d"),l=Xe(n,"pointwiseFilter","separableConv2d"),c=s,f=!1;if(3===s.rank&&(f=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");d(4===c.rank,"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."),d(4===u.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."),d(4===l.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."),d(1===l.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."),d(1===l.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+".");var p=u.shape[2],h=u.shape[3];d(l.shape[2]===p*h,"Error in separableConv2d: the third dimension of pointwise filter must be "+p*h+", but got "+l.shape[2]+".");var m=si(c,u,r,a,o,i),g=oi(m,l,1,"valid",o);return f?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),li=Je({conv2dTranspose_:function(e,t,n,r,a,i){return ni(n,Xe(e,"x","conv2dTranspose"),Xe(t,"filter","conv2dTranspose"),r,a,i)}}),ci=Je({reverse_:function(e,t){var n=Xe(e,"x","reverse");if(0===n.rank)return n.clone();var r=Be(t,n.shape);return me.engine.runKernel(function(e){return e.reverse(n,r)},{$x:n},function(e){return{$x:function(){return e.reverse(r)}}}).reshapeAs(n)}}),fi=Je({reverse1d_:function(e){var t=Xe(e,"x","reverse");return d(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),ci(t,0)}}),pi=Je({reverse2d_:function(e,t){var n=Xe(e,"x","reverse");return d(2===n.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+n.rank+"."),ci(n,t)}}),hi=Je({reverse3d_:function(e,t){var n=Xe(e,"x","reverse");return d(3===n.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+n.rank+"."),ci(n,t)}}),di=Je({reverse4d_:function(e,t){var n=Xe(e,"x","reverse");return d(4===n.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+n.rank+"."),ci(n,t)}}),mi=Je({maxPool_:function(e,t,n,r,a){var i=Xe(e,"x","maxPool"),o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ka(o.shape,t,n,r,a),l=me.engine.runKernel(function(e,t){return t(e.maxPool(o,u))},{x:o},function(e,a){var i=a[0];return{x:function(){return function(e,t,n,r,a,i,o){var s=Xe(e,"dy","maxPoolBackprop"),u=Xe(t,"input","maxPoolBackprop"),l=Xe(n,"output","maxPoolBackprop");d(u.rank===s.rank,"Rank of input ("+u.rank+") does not match rank of dy ("+s.rank+")"),d(4===s.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+s.rank+"."),d(4===u.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+".");var c=Ka(u.shape,r,a,i,o);return me.engine.runKernel(function(e){return e.maxPoolBackprop(s,u,l,c)},{$dy:s,$input:u})}(e,o,i,t,n,r)}}});return s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),gi=Je({avgPool_:function(e,t,n,r,a){var i=Xe(e,"x","avgPool");d("float32"===i.dtype,"The input dtype to avgPool must be float32");var o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in avgPool: x must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ka(o.shape,t,n,r),l=me.engine.runKernel(function(e){return e.avgPool(o,u)},{x:o},function(e){return{x:function(){return function(e,t,n,r,a){var i=Xe(e,"dy","avgPoolBackprop"),o=Xe(t,"input","avgPoolBackprop");d(o.rank===i.rank,"Rank of input ("+o.rank+") does not match rank of dy ("+i.rank+")");var s=o,u=i,l=!1;3===o.rank&&(l=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]),u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===u.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),d(4===s.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+".");var c=Ka(s.shape,n,r,a),f=me.engine.runKernel(function(e){return e.avgPoolBackprop(u,s,c)},{dy4D:u,input4D:s});return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(e,o,t,n,r)}}});return l=l.cast(i.dtype),s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),yi=Je({slice_:function(e,t,n){var r,a,i=Xe(e,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof t?[t].concat(new Array(i.rank-1).fill(0)):t.length=0?e:(d(-1===e,"Bad value in size"),i.shape[t]-r[t])}),function(e,t,n){d(e.rank===t.length,"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."),d(e.rank===n.length,"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+").");for(var r=0;r0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Rt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)}}})}}),Gi=Je({addN_:function(e){d(Array.isArray(e),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(e.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length});var t=e.map(function(e,t){return Xe(e,"tensors"+t,"addN")}),n=t[0];t.forEach(function(e){if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(e){if(!w(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=t;return me.engine.runKernel(function(e){return e.addN(t)},r,function(e){var n={};return t.forEach(function(t,r){n[r]=function(){return e.clone()}}),n})}}),Hi=Je({addStrict_:function(e,t){return m(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),Ki=Je({atan2_:function(e,t){var n=Xe(e,"a","atan2"),r=Xe(t,"b","atan2");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.atan2(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=$i(n.square(),r.square()),i=e.mul(r.div(t)),o=Rt(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=$i(n.square(),r.square()),i=Ca(e.mul(n.div(t))),o=Rt(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Xi=Je({div_:function(e,t){var n,r=Xe(e,"a","div"),a=Xe(t,"b","div");if(ne(r,a),"int32"===r.dtype&&"int32"===a.dtype)return Ji(r,a);n=function(e){return e.realDivide(r,a)};var i=Dt(r.shape,a.shape);return me.engine.runKernel(n,{$a:r,$b:a},function(e){return{$a:function(){var t=e.div(a.toFloat()),n=Rt(r.shape,i);return n.length>0?t.sum(n).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),n=Rt(a.shape,i);n.length>0&&(t=t.sum(n).reshape(a.shape));var o=a.square();return t.div(o.toFloat()).neg()}}})}}),Yi=Je({divStrict_:function(e,t){return m(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),Ji=Je({floorDiv_:function(e,t){var n=Xe(e,"a","floorDiv"),r=Xe(t,"b","floorDiv");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.floorDiv(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.div(r.toFloat()),i=Rt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Rt(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}})}}),Zi=Je({maximum_:function(e,t){var n=Xe(e,"a","maximum"),r=Xe(t,"b","maximum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.maximum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.greaterEqual(r).toFloat())},$b:function(){return e.mul(n.less(r).toFloat())}}})}}),Qi=Je({maximumStrict_:function(e,t){return m(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),eo=Je({minimum_:function(e,t){var n=Xe(e,"a","minimum"),r=Xe(t,"b","minimum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.minimum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.lessEqual(r).toFloat())},$b:function(){return e.mul(n.greater(r).toFloat())}}})}}),to=Je({minimumStrict_:function(e,t){return m(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),no=Je({mod_:function(e,t){var n=Xe(e,"a","mod"),r=Xe(t,"b","mod");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.mod(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=Rt(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=Rt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),ro=Je({modStrict_:function(e,t){return m(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),ao=Je({mul_:function(e,t){var n=Xe(e,"a","mul"),r=Xe(t,"b","mul");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.multiply(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.mul(r.toFloat()),i=Rt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Rt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),io=Je({mulStrict_:function(e,t){return m(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),oo=Je({pow_:function(e,t){var n=Xe(e,"base","pow"),r=Xe(t,"exp","pow"),a=Dt(n.shape,r.shape);return e=n.cast(Nt(n.dtype,r.dtype)),t=r.cast(Nt(n.dtype,r.dtype)),me.engine.runKernel(function(e,t){return t(e.pow(n,r))},{$base:n,$exp:r},function(e,t){var i=t[0];return{$base:function(){var t=e.mul(r.toFloat().mul(i.div(n))),o=Rt(n.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(n.shape)},$exp:function(){var t=e.mul(i.mul(n.log()).toFloat()),o=Rt(r.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(r.shape)}}})}}),so=Je({powStrict_:function(e,t){return m(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),uo=Je({squaredDifference_:function(e,t){var n=Xe(e,"a","squaredDifference"),r=Xe(t,"b","squaredDifference");return ne(n,r),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.squaredDifference(n,r)},{$a:n,$b:r},function(e){var t=rt(2);return{$a:function(){return e.mul(n.sub(r).mul(t))},$b:function(){return e.mul(r.sub(n).mul(t))}}})}}),lo=Je({squaredDifferenceStrict_:function(e,t){return m(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),co=Je({sub_:function(e,t){var n=Xe(e,"a","sub"),r=Xe(t,"b","sub");ne(n,r);var a=Dt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.subtract(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e,r=Rt(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Rt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(r.shape)}}})}}),fo=Je({subStrict_:function(e,t){return m(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),po=Je({logicalAnd_:function(e,t){var n=Xe(e,"a","logicalAnd","bool"),r=Xe(t,"b","logicalAnd","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalAnd(n,r)},{$a:n,$b:r})}}),ho=Je({logicalNot_:function(e){var t=Xe(e,"x","logicalNot","bool");return d("bool"===t.dtype,"Error Array must be of type bool."),me.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})}}),mo=Je({logicalOr_:function(e,t){var n=Xe(e,"a","logicalOr","bool"),r=Xe(t,"b","logicalOr","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalOr(n,r)},{$a:n,$b:r})}}),go=Je({logicalXor_:function(e,t){var n=Xe(e,"a","logicalXor","bool"),r=Xe(t,"b","logicalXor","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Dt(n.shape,r.shape),mo(e,t).logicalAnd(po(e,t).logicalNot())}}),yo=Je({where_:function(e,t,n){var r=Xe(t,"a","where"),a=Xe(n,"b","where"),i=Xe(e,"condition","where","bool");return d("bool"===i.dtype,"Error Condition must be of type bool."),m(r.shape,a.shape,"Error in where: "),1===i.rank?d(i.shape[0]===r.shape[0],"The first dimension of `a` must match the size of `condition`."):m(i.shape,a.shape,"Error in where: "),me.engine.runKernel(function(e){return e.select(i,r,a)},{$condition:i,$a:r,$b:a},function(e){return{$condition:function(){return _t(i)},$a:function(){return e.mul(i.cast(r.dtype))},$b:function(){return e.mul(i.logicalNot().cast(a.dtype))}}})}}),vo=function(e){return l(this,void 0,void 0,function(){var t,n,r;return c(this,function(a){switch(a.label){case 0:return d("bool"===(t=Xe(e,"condition","where","bool")).dtype,"Condition must be of type bool."),[4,t.data()];case 1:return n=a.sent(),r=ua(t.shape,n),e!==t&&t.dispose(),[2,r]}})})},bo=Je({elu_:function(e){var t=Xe(e,"x","elu");return me.engine.runKernel(function(e,n){return n(e.elu(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return me.engine.runKernel(function(t){return t.eluDer(e,n)},{dy:e,y:n})}}})}}),wo=Je({leakyRelu_:function(e,t){void 0===t&&(t=.2);var n=Xe(e,"x","leakyRelu");return Zi(rt(t).mul(n),n)}}),xo=Je({prelu_:function(e,t){var n=Xe(e,"x","prelu"),r=Xe(t,"alpha","prelu"),a=rt(0);return Zi(a,n).add(r.mul(eo(a,n)))}}),_o=Je({relu_:function(e){var t=Xe(e,"x","relu");return"bool"===t.dtype?t.toInt():me.engine.runKernel(function(e){return e.relu(t)},{$x:t},function(e){var n=t.step();return{$x:function(){return e.mulStrict(n.toFloat())}}})}}),Eo=Je({selu_:function(e){var t=Xe(e,"x","selu");return me.engine.runKernel(function(e){return e.selu(t)},{$x:t},function(e){return{$x:function(){var n=t.greater(rt(0)),r=rt(dr),a=rt(mr),i=e.mul(a),o=e.mul(r).mul(t.toFloat().exp());return yo(n,i,o)}}})}}),No=Je({transpose_:function(e,t){var n=Xe(e,"x","transpose");return null==t&&(t=n.shape.map(function(e,t){return t}).reverse()),d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of perm "+t+"."),t.forEach(function(e){d(e>=0&&ea)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+t);var i=me.engine.runKernel(function(e){return e.topk(r,t,n)},{$x:r});return{values:i[0],indices:i[1]}}});!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"}(Co||(Co={}));var Lo=Je({absoluteDifference_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","absoluteDifference"),i=Xe(t,"predictions","absoluteDifference"),o=null;null!=n&&(o=Xe(n,"weights","absoluteDifference")),m(a.shape,i.shape,"Error in absoluteDifference: ");var s=a.sub(i).abs();return Bo(s,o,r)}}),Bo=Je({computeWeightedLoss_:function(e,t,n){void 0===n&&(n=Co.SUM_BY_NONZERO_WEIGHTS);var r=Xe(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=Xe(t,"weights","computeWeightedLoss"));var i=null==a?r:r.mul(a);if(n===Co.NONE)return i;if(n===Co.SUM)return i.sum();if(n===Co.MEAN){if(null==a)return i.mean();var o=b(r.shape)/b(a.shape),s=i.sum().div(a.sum());return o>1?s.div(rt(o)):s}if(n===Co.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(rt(r.size));var u=a.mul(ct(r.shape)).notEqual(rt(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),zo=Je({cosineDistance_:function(e,t,n,r,a){void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","cosineDistance"),o=Xe(t,"predictions","cosineDistance"),s=null;null!=r&&(s=Xe(r,"weights","cosineDistance")),m(i.shape,o.shape,"Error in cosineDistance: ");var u=rt(1).sub(i.mul(o).sum(n,!0));return Bo(u,s,a)}}),Fo=Je({hingeLoss_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","hingeLoss"),i=Xe(t,"predictions","hingeLoss"),o=null;null!=n&&(o=Xe(n,"weights","hingeLoss")),m(a.shape,i.shape,"Error in hingeLoss: ");var s=rt(1);a=rt(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return Bo(u,o,r)}}),Vo=Je({huberLoss_:function(e,t,n,r,a){void 0===r&&(r=1),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","huberLoss"),o=Xe(t,"predictions","huberLoss"),s=null;null!=n&&(s=Xe(n,"weights","huberLoss")),m(i.shape,o.shape,"Error in huberLoss: ");var u=rt(r),l=o.sub(i).abs(),c=eo(l,u),f=l.sub(c),p=rt(.5).mul(c.square()).add(u.mul(f));return Bo(p,s,a)}}),Uo=Je({logLoss_:function(e,t,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"labels","logLoss"),o=Xe(t,"predictions","logLoss"),s=null;null!=n&&(s=Xe(n,"weights","logLoss")),m(i.shape,o.shape,"Error in logLoss: ");var u=rt(1),l=rt(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return Bo(c,s,a)}}),Wo=Je({meanSquaredError_:function(e,t,n,r){void 0===r&&(r=Co.SUM_BY_NONZERO_WEIGHTS);var a=Xe(e,"labels","meanSquaredError"),i=Xe(t,"predictions","meanSquaredError"),o=null;null!=n&&(o=Xe(n,"weights","meanSquaredError")),m(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return Bo(s,o,r)}}),qo=Je({sigmoidCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"multiClassLabels","sigmoidCrossEntropy"),o=Xe(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Xe(n,"weights","sigmoidCrossEntropy")),m(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=rt(r),l=rt(1),c=rt(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var f=function(e,t){var n=Xe(e,"labels","sigmoidCrossEntropyWithLogits"),r=Xe(t,"logits","sigmoidCrossEntropyWithLogits");m(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),i=r.mul(n),o=r.abs().neg().exp().log1p();return a.sub(i).add(o)}(i,o);return Bo(f,s,a)}}),$o=Je({softmaxCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Co.SUM_BY_NONZERO_WEIGHTS);var i=Xe(e,"onehotLabels","softmaxCrossEntropy"),o=Xe(t,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Xe(n,"weights","softmaxCrossEntropy")),m(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=rt(r),l=rt(1),c=rt(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var f=function(e,t,n){if(void 0===n&&(n=-1),-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);return _e(function(e,t){var r=t.logSumExp([n],!0),a=t.toFloat().sub(r);return{value:a.mul(e).neg().sum([n]),gradFunc:function(t){var r=Le(t.shape,[n]);return[t.reshape(r).mul(e.toFloat().sub(a.exp())),t.reshape(r).mul(a.exp().sub(e.toFloat()))]}}})(e,t)}(i,o);return Bo(f,s,a)}}),Go=Object.freeze({get Reduction(){return Co},absoluteDifference:Lo,computeWeightedLoss:Bo,cosineDistance:zo,hingeLoss:Fo,huberLoss:Vo,logLoss:Uo,meanSquaredError:Wo,sigmoidCrossEntropy:qo,softmaxCrossEntropy:$o});function Ho(e,t){return void 0===t&&(t=!1),me.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var n=e.shape[0],r=e.shape[1],a=Wr(n),i=e.clone(),o=it([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(e){var t,u=i,l=s,c=a;t=me.engine.tidy(function(){var t=i.slice([e,e],[n-e,1]),u=t.norm(),l=i.slice([e,e],[1,1]),c=l.sign().neg(),f=l.sub(c.mul(u)),p=t.div(f);s=1===p.shape[0]?o.clone():o.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var h=c.matMul(f).div(u).neg(),d=i.slice([e,0],[n-e,r]),m=h.mul(s);i=0===e?d.sub(m.matMul(s.transpose().matMul(d))):i.slice([0,0],[e,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=a.slice([0,e],[n,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[n,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,i,a]}),s=t[0],i=t[1],a=t[2],Oe([u,l,c])},c=0;cr&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]})}var Ko=Je({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,d(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var n=e[0].shape[0],r=1;r0)for(var n=0;n= 2, but got rank "+e.rank);if(2===e.rank)return Ho(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),r=[],a=[];return sa(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var n=Ho(e,t),i=n[0],o=n[1];r.push(i),a.push(o)}),[aa(r,0).reshape(e.shape),aa(a,0).reshape(e.shape)]}}),Yo=Object.freeze({gramSchmidt:Ko,qr:Xo});function Jo(e,t,n,r,a){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY);var i=e.shape[0];return n=Math.min(n,i),d(0<=r&&r<=1,"iouThreshold must be in [0, 1], but was '"+r+"'"),d(2===e.rank,"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"),d(4===e.shape[1],"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),d(1===t.rank,"scores must be a 1D tensor"),d(t.shape[0]===i,"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a}}var Zo=Je({resizeBilinear_:function(e,t,n){void 0===n&&(n=!1);var r=Xe(e,"images","resizeBilinear");d(3===r.rank||4===r.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeBilinear(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Qo=Je({resizeNearestNeighbor_:function(e,t,n){void 0===n&&(n=!1);var r=Xe(e,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),d("float32"===r.dtype||"int32"===r.dtype,"`images` must have `int32` or `float32` as dtype");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),es=Je({nonMaxSuppression_:function(e,t,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=Xe(e,"boxes","nonMaxSuppression"),o=Xe(t,"scores","nonMaxSuppression"),s=Jo(i,o,n,r,a);return n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,me.engine.runKernel(function(e){return e.nonMaxSuppression(i,o,n,r,a)},{$boxes:i})}}),ts=Object.freeze({resizeBilinear:Zo,resizeNearestNeighbor:Qo,nonMaxSuppression:es,nonMaxSuppressionAsync:function(e,t,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),l(this,void 0,void 0,function(){var i,o,s,u,l,f;return c(this,function(c){switch(c.label){case 0:return i=Xe(e,"boxes","nonMaxSuppressionAsync"),o=Xe(t,"scores","nonMaxSuppressionAsync"),s=Jo(i,o,n,r,a),n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,[4,i.data()];case 1:return u=c.sent(),[4,o.data()];case 2:return l=c.sent(),f=Ct(u,l,n,r,a),i!==e&&i.dispose(),o!==t&&o.dispose(),[2,f]}})})},cropAndResize:function(e,t,n,r,a,i){var o=Xe(e,"image","cropAndResize","float32"),s=Xe(t,"boxes","cropAndResize","float32"),u=Xe(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return d(4===o.rank,"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."),d(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."),d(1===u.rank&&u.shape[0]===l,"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."),d("int32"===u.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+u.dtype+"."),d(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),d(r[0]>=1&&r[1]>=1,"cropSize must be atleast [1,1], but was "+r),d("bilinear"===a||"nearest"===a,"method must be bilinear or nearest, but was "+a),me.engine.runKernel(function(e,t){return e.cropAndResize(o,s,u,r,a,i)},{$image:o,$boxes:s})}}),ns=Object.freeze({image:ts,linalg:Yo,losses:Go,op:Je,batchNormalization2d:qa,batchNormalization3d:$a,batchNormalization4d:Ga,batchNormalization:Ha,complex:Qe,real:et,imag:tt,concat:vr,concat1d:br,concat2d:wr,concat3d:xr,concat4d:_r,split:Er,conv1d:ii,conv2d:oi,depthwiseConv2d:si,separableConv2d:ui,conv2dTranspose:li,matMul:Qa,dot:ei,outerProduct:ti,reverse:ci,reverse1d:fi,reverse2d:pi,reverse3d:hi,reverse4d:di,maxPool:mi,avgPool:gi,slice:yi,slice1d:vi,slice2d:bi,slice3d:wi,slice4d:xi,abs:fa,acos:pa,acosh:ha,asin:da,asinh:ma,atan:ga,atanh:ya,ceil:va,clipByValue:ba,cos:wa,cosh:xa,erf:_a,exp:Ea,expm1:Na,floor:Sa,log:Oa,log1p:ka,logSigmoid:Ia,neg:Ca,reciprocal:Pa,round:Aa,rsqrt:Ta,sigmoid:Ma,sign:Ra,sin:Da,sinh:ja,softplus:La,sqrt:Ba,square:za,step:Fa,tan:Va,tanh:Ua,all:Ei,any:Ni,argMax:Si,argMin:Oi,logSumExp:ki,max:Ii,mean:Ci,min:Pi,moments:Ai,sum:Ti,equal:Mi,equalStrict:Ri,greater:Di,greaterEqual:ji,greaterEqualStrict:Li,greaterStrict:Bi,less:zi,lessEqual:Fi,lessEqualStrict:Vi,lessStrict:Ui,notEqual:Wi,notEqualStrict:qi,add:$i,addN:Gi,addStrict:Hi,atan2:Ki,div:Xi,divStrict:Yi,floorDiv:Ji,maximum:Zi,maximumStrict:Qi,minimum:eo,minimumStrict:to,mod:no,modStrict:ro,mul:ao,mulStrict:io,pow:oo,powStrict:so,squaredDifference:uo,squaredDifferenceStrict:lo,sub:co,subStrict:fo,elu:bo,leakyRelu:wo,prelu:xo,relu:_o,selu:Eo,logicalAnd:po,logicalNot:ho,logicalOr:mo,logicalXor:go,where:yo,whereAsync:vo,buffer:Dr,toPixels:Rr,print:jr,batchToSpaceND:Lr,cast:Br,clone:zr,cumsum:Fr,depthToSpace:Vr,expandDims:Ur,eye:Wr,fromPixels:qr,multinomial:$r,oneHot:Gr,pad:Hr,pad1d:Kr,pad2d:Xr,pad3d:Yr,pad4d:Jr,rand:Zr,randomNormal:Qr,randomUniform:ea,reshape:ta,spaceToBatchND:na,squeeze:ra,stack:aa,tile:ia,truncatedNormal:oa,unstack:sa,fill:pt,linspace:ht,ones:ct,range:dt,scalar:rt,tensor:nt,tensor1d:at,tensor2d:it,tensor3d:ot,tensor4d:st,tensor5d:ut,tensor6d:lt,zeros:ft,onesLike:xt,zerosLike:_t,transpose:No,softmax:Ze,localResponseNormalization:So,norm:Oo,gather:Po,unsortedSegmentSum:Ao,basicLSTMCell:To,multiRNNCell:Mo,movingAverage:Ro,stridedSlice:Do,topk:jo}),rs=function(){function e(){this.blockSize=48,this.data=new WeakMap,this.firstUse=!0,me.get("IS_BROWSER")&&(this.canvas=document.createElement("canvas"))}return e.prototype.register=function(e,t,n){if(this.firstUse&&(this.firstUse=!1,me.get("IS_NODE")&&Ce("\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============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:n})},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.throwIfNoData(e),this.data.get(e).values=t},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var n,r;if(me.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else if(e instanceof ImageData)n=e.data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(null==this.canvas)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.canvas.width=e.width,this.canvas.height=e.height,this.canvas.getContext("2d").drawImage(e,0,0,e.width,e.height),n=this.canvas.getContext("2d").getImageData(0,0,e.width,e.height).data}if(4===t)r=new Int32Array(n);else{var a=e.width*e.height;r=new Int32Array(a*t);for(var i=0;ip&&(p=m,h=d)}u[c]=h}return o},e.prototype.cumsum=function(e,t,n,r){if(this.assertNotComplex(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=Nt(e.dtype,"int32"),i=ft(e.shape,a),o=i.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=r?function(e,t){return e+u-t-1}:function(e,t){return e+t},c=0;ct?1:0})},e.prototype.greaterEqual=function(e,t){return this.assertNotComplex([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){this.assertNotComplex(e,"logicalNot");for(var t=e.dataSync(),n=new Int32Array(t.length),r=0;r1||1===t.rank?1:t.shape[1],c=0;c=0&&t>=0?n:(n+t)%t})},e.prototype.max=function(e,t){this.assertNotComplex(e,"max"),ze("max",t,e.rank);for(var n=je(e.shape,t),r=n[0],a=n[1],i=ft(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;lf&&(f=h)}s[l]=f}return i},e.prototype.maximum=function(e,t){return this.assertNotComplex([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){this.assertNotComplex(e,"all"),ze("all",t,e.rank);for(var n=je(e.shape,t),r=n[0],a=n[1],i=ft(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;l0?n[r]=1:n[r]=0;return Q.make(e.shape,{values:n})},e.prototype.round=function(e){this.assertNotComplex(e,"round");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r.5?n[r]=Math.ceil(t[r]):n[r]=a%2==0?a:a+1}return Q.make(e.shape,{values:n})},e.prototype.exp=function(e){this.assertNotComplex(e,"exp");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r=0?a:Math.exp(a)-1}return Q.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){this.assertNotComplex([e,t],"eluDer");for(var n=new Float32Array(t.size),r=t.dataSync(),a=e.dataSync(),i=0;i=1?a[i]:a[i]*(o+1)}return Q.make(t.shape,{values:n})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return Q.make(e.shape,{values:t})},e.prototype.clip=function(e,t,n){this.assertNotComplex(e,"clip");for(var r=new Float32Array(e.size),a=e.dataSync(),i=0;in?n:o-t,s=r[a]0?1:t}return Q.make(e.shape,{values:n})},e.prototype.conv2d=function(e,t,n){this.assertNotComplex([e,t],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Dr(n.outShape,e.dtype),c=e.dataSync(),f=t.dataSync(),p=l.values,h=0;h=n.inHeight))for(var x=b*t.strides[0],_=d+w*e.strides[1],E=0;E=n.inWidth))for(var I=x+O*t.strides[1],C=_+k*n.inChannels,P=I,A=0;A=n.inHeight))for(var _=w*t.strides[0],E=m+x*e.strides[1],N=0;N=n.inWidth))for(var C=_+k*t.strides[1],P=E+I*n.inChannels,A=S,T=C,M=0;Mx?x=O:"avg"===n&&(_+=O,E++)}if(isNaN(x))break}s.set("avg"===n?_/E:x,f,h,y,p)}return s.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var n=Dr(t.outShape,"int32"),r=t.strideHeight,a=t.strideWidth,i=t.filterHeight,o=t.filterWidth,s=t.padInfo.top,u=t.padInfo.left,l=0;lb&&(b=S,w=_*o+N)}n.set(w,l,f,m,c)}return n.toTensor()},e.prototype.maxPoolBackprop=function(e,t,n,r){this.assertNotComplex([t,n],"maxPoolBackprop");for(var a=this.maxPoolPositions(t,r),i=r.strideHeight,o=r.strideWidth,s=r.filterHeight,u=r.filterWidth,l=u-1-r.padInfo.left,c=s-1-r.padInfo.top,f=Dr(t.shape,"float32"),p=0;p=r.outHeight||Math.floor(w)!==w))for(var x=0;x=r.outWidth||Math.floor(_)!==_)){var E=s*u-1-a.get(p,w,_,h)===b*u+x?1:0;0!==E&&(v+=e.get(p,w,_,h)*E)}}}f.set(v,p,d,m,h)}return f.toTensor()},e.prototype.avgPoolBackprop=function(e,t,n){this.assertNotComplex([e,t],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=o-1-n.padInfo.left,u=i-1-n.padInfo.top,l=Dr(t.shape,"float32"),c=1/(i*o),f=0;f=n.outHeight||Math.floor(b)!==b))for(var w=0;w=n.outWidth||Math.floor(x)!==x||(y+=e.get(f,b,x,p))}}l.set(y*c,f,h,d,p)}return l.toTensor()},e.prototype.cast=function(e,t){return Ot(e,t,this)},e.prototype.reshape=function(e,t){return kt(e,t)},e.prototype.avgPool=function(e,t){return this.assertNotComplex(e,"avgPool"),this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,n,r){this.assertNotComplex(e,"resizeBilinear");for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=Dr([i,t,n,u],e.dtype),c=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/h[0],m=p[1]/h[1],g=0;g1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=1/(p[0]/h[0]),m=1/(p[1]/h[1]),g=2*Math.ceil(d)+2,y=2*Math.ceil(m)+2,v=0;v=l))for(var C=0;C=c)){var A=p[0]*(I/h[0]),T=p[1]*(P/h[1]),M=Math.min(i-1,n?Math.round(A):Math.floor(A)),R=Math.min(o-1,n?Math.round(T):Math.floor(T));b===M&&w===R&&(O+=e.get(v,I,P,S))}}}f.set(O,v,b,w,S)}return f.toTensor()},e.prototype.batchNormalization=function(e,t,n,r,a,i){this.assertNotComplex([e,t,n,a,i],"batchNormalization");for(var o=e.dataSync(),s=t.dataSync(),u=n.dataSync(),l=a?a.dataSync():new Float32Array([1]),c=i?i.dataSync():new Float32Array([0]),f=new Float32Array(o.length),p=c.length,h=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w=p&&(g=0),y>=m&&(y=0),v>=h&&(v=0),b>=d&&(b=0);return st(f,e.shape)},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){this.assertNotComplex(e,"localResponseNormalization4D");var i=e.shape[3],o=i-1,s=e.dataSync(),u=b(e.shape),l=new Float32Array(u);function c(e){for(var n=e%i,r=e-n+Math.max(0,n-t),a=e-n+Math.min(n+t,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var f=0;f=0&&e.get(i)1,"blockSize should be > 1 for depthToSpace, but was: "+t);for(var r=e.shape[0],a=e.shape[1],i=e.shape[2],o=e.shape[3],s=a*t,u=i*t,l=o/(t*t),c=e.dataSync(),f=new Float32Array(r*s*u*l),p=0,h=0;h=s))for(var k=p>1?(N-_)*(u-1)/(p-1):0,I=h>1?(S-E)*(l-1)/(h-1):0,C=0;C1?_*(u-1)+C*k:.5*(_+N)*(u-1);if(P<0||P>u-1)for(var A=0;A1?E*(l-1)+A*I:.5*(E+S)*(l-1))<0||$>l-1)for(T=0;T1?E*(l-1)+A*I:.5*(E+S)*(l-1))<0||$>l-1)for(T=0;T0,"scheme must not be an empty string.");var r=e.getInstance();d(null==r.managers[t],"A model store manager is already registered for scheme '"+t+"'."),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function gs(e){if(-1===e.indexOf(ds))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ms.getSchemes().join(","));return{scheme:e.split(ds)[0],path:e.split(ds)[1]}}function ys(e,t,n){return void 0===n&&(n=!1),l(this,void 0,void 0,function(){var r,a,i,o,s,u,l,f,p;return c(this,function(c){switch(c.label){case 0:return d(e!==t,"Old path and new path are the same: '"+e+"'"),d((r=hs.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),d(r.length<2,"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."),a=r[0],d((i=hs.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),d(i.length<2,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."),o=i[0],s=gs(e).scheme,u=gs(e).path,l=s===gs(e).scheme,[4,a.load()];case 1:return f=c.sent(),n&&l?[4,ms.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,o.save(f)];case 4:return p=c.sent(),!n||l?[3,6]:[4,ms.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var vs="models_store",bs="model_info_store";function ws(){if(!me.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=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 xs(e){var t=e.result;t.createObjectStore(vs,{keyPath:"modelPath"}),t.createObjectStore(bs,{keyPath:"modelPath"})}var _s=function(){function e(e){if(this.indexedDB=ws(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,this.databaseAction(this.modelPath)]})})},e.prototype.databaseAction=function(e,t){var n=this;return new Promise(function(e,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return xs(a)},a.onsuccess=function(){var i=a.result;if(null==t){var o=i.transaction(vs,"readonly"),s=o.objectStore(vs).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=ps(t),c=i.transaction(bs,"readwrite"),f=c.objectStore(bs),p=f.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var a=(u=i.transaction(vs,"readwrite")).objectStore(vs).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});a.onsuccess=function(){return e({modelArtifactsInfo:l})},a.onerror=function(e){var t=(f=c.objectStore(bs)).delete(n.modelPath);t.onsuccess=function(){return i.close(),r(a.error)},t.onerror=function(e){return i.close(),r(a.error)}}},p.onerror=function(e){return i.close(),r(p.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(e){return r(a.error)}})},e.URL_SCHEME="indexeddb://",e}(),Es=function(e){return me.get("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(_s.URL_SCHEME)?function(e){return new _s(e)}(e.slice(_s.URL_SCHEME.length)):null};hs.registerSaveRouter(Es),hs.registerLoadRouter(Es);var Ns=function(){function e(){this.indexedDB=ws()}return e.prototype.listModels=function(){return l(this,void 0,void 0,function(){var e=this;return c(this,function(t){return[2,new Promise(function(t,n){var r=e.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return xs(r)},r.onsuccess=function(){var e=r.result,a=e.transaction(bs,"readonly"),i=a.objectStore(bs).getAll();i.onsuccess=function(){for(var e={},n=0,r=i.result;n0,"URL path for browserHTTPRequest must not be null, undefined or empty."),Array.isArray(e)&&d(2===e.length,"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+e.length+")."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest: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"),[4,fetch(this.path,t)];case 1:if(200===(a=i.sent()).status)return[2,{modelArtifactsInfo:ps(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,Array.isArray(this.path)?this.loadBinaryModel():this.loadJSONModel()]})})},e.prototype.loadBinaryTopology=function(){return l(this,void 0,void 0,function(){var e;return c(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch(this.path[0],this.requestInit)];case 1:return[4,t.sent().arrayBuffer()];case 2:return[2,t.sent()];case 3:throw e=t.sent(),new Error(this.path[0]+" not found. "+e);case 4:return[2]}})})},e.prototype.loadBinaryModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return e=this.loadBinaryTopology(),[4,fetch(this.path[1],this.requestInit)];case 1:return t=u.sent(),[4,Promise.all([e,t])];case 2:return n=u.sent(),r=n[0],[4,n[1].json()];case 3:return null==(a=u.sent())?[3,5]:[4,this.loadWeights(a)];case 4:s=u.sent(),i=s[0],o=s[1],u.label=5;case 5:return[2,{modelTopology:r,weightSpecs:i,weightData:o}]}})})},e.prototype.loadJSONModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:return[4,s.sent().json()];case 2:if(e=s.sent(),t=e.modelTopology,n=e.weightsManifest,null==t&&null==n)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==n?[3,4]:(i=e.weightsManifest,[4,this.loadWeights(i)]);case 3:o=s.sent(),r=o[0],a=o[1],s.label=4;case 4:return[2,{modelTopology:t,weightSpecs:r,weightData:a}]}})})},e.prototype.loadWeights=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o,s,u,l;return c(this,function(c){switch(c.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=[],r=0,a=e;r0&&(e=u({weightSpecs:this.weightSpecs},e)),null!=this.weightData&&this.weightData.byteLength>0&&(e=u({weightData:this.weightData},e)),[2,e]})})},e}(),Hs=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){return[2,this.saveHandler(e)]})})},e}(),Ks=hs.registerSaveRouter,Xs=hs.registerLoadRouter,Ys=hs.getSaveHandlers,Js=hs.getLoadHandlers,Zs=Object.freeze({browserFiles:function(e){return new Fs(e)},browserHTTPRequest:$s,concatenateArrayBuffers:cs,decodeWeights:ss,encodeWeights:function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:for(r in t=[],n=[],e){if("float32"!==(a=e[r]).dtype&&"int32"!==a.dtype&&"bool"!==a.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+a.dtype);t.push({name:r,shape:a.shape,dtype:a.dtype}),n.push(a.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0,n=[];e.forEach(function(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)});var r=new Uint8Array(t),a=0;return n.forEach(function(e){r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}(i.sent()),specs:t}]}})})},fromMemory:function(e,t,n){return new Gs(e,t,n)},getLoadHandlers:Js,getModelArtifactsInfoForJSON:ps,getSaveHandlers:Ys,loadWeights:function(e,t,n,r){return void 0===t&&(t=""),l(this,void 0,void 0,function(){var a,i,o,s,u,l,f,p,h,d;return c(this,function(c){switch(c.label){case 0:if(a=e.map(function(){return!1}),i={},o=null!=n?n.map(function(){return!1}):[],s=[],e.forEach(function(e,t){var r=0;e.weights.forEach(function(e){var u="quantization"in e?e.quantization.dtype:e.dtype,l=os[u]*b(e.shape),c=function(){a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:r,sizeBytes:l})};null!=n?n.forEach(function(t,n){t===e.name&&(c(),o[n]=!0)}):c(),s.push(e.name),r+=l})}),!o.every(function(e){return e}))throw u=n.filter(function(e,t){return!o[t]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=a.reduce(function(e,t,n){return t&&e.push(n),e},[]),f=[],l.forEach(function(n){e[n].paths.forEach(function(e){var n=t+(t.endsWith("/")?"":"/")+e;f.push(n)})}),[4,Vs(f,r)];case 1:return p=c.sent(),h={},d=0,l.forEach(function(t){for(var n=e[t].paths.length,r=0,a=0;a0,"Class being registered has an empty-string as its className, which is disallowed."),eu.register(e)}var nu=Object.freeze({Serializable:Qs,SerializationMap:eu,registerClass:tu});function ru(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),e instanceof Q||t instanceof Q){if(e instanceof Q&&t instanceof Q){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!w(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".")}}else{var r=e.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+a)}var i,o;if(i=e instanceof Q?e.dataSync():e,o=t instanceof Q?t.dataSync():t,i.length!==o.length)throw new Error("Arrays have different lengths actual: "+i.length+" vs expected: "+o.length+".\nActual: "+i+".\nExpected: "+o+".");for(var s=0;sn)}var iu=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},ALL_ENVS:{},expectArraysClose:ru,expectPromiseToFail:function(e,t){e().then(function(){return t.fail()},function(){return t()})},expectArraysEqual:function(e,t){return ru(e,t,0)},expectNumbersClose:function(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),!au(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t)},expectValuesInRange:function(e,t,n){var r;r=e instanceof Q?e.dataSync():e;for(var a=0;an)throw new Error("Value out of range:"+r[a]+" low: "+t+", high: "+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),ou="0.13.0",su=Object.freeze({gpgpu_util:ar,webgl_util:Ln,MathBackendWebGL:ca,GPGPUContext:ir}),uu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),a=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(e){return i[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return xe(e,t)},t}(Qs),lu=function(e){function t(t,n,r){void 0===r&&(r=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=n,a.epsilon=r,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=Se(rt(-t)),a.rhoScalar=Se(rt(n)),a.oneMinusRho=Se(rt(1-n)),null===r&&(r=me.get("EPSILON")),a.epsilonScalar=Se(rt(r)),a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ne(function(){t.accumulatedGrads[n]=_t(a).variable(!1)}),null==r.accumulatedUpdates[n]&&Ne(function(){t.accumulatedUpdates[n]=_t(a).variable(!1)});var i=e[n],o=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];Ne(function(){var e=t.rhoScalar.mul(o).add(t.oneMinusRho.mul(i.square())),r=s.add(t.epsilonScalar).sqrt().div(o.add(t.epsilonScalar).sqrt()).mul(i),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(r.square()));t.accumulatedGrads[n].assign(e),t.accumulatedUpdates[n].assign(u);var l=t.c.mul(r).add(a);a.assign(l)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(uu);tu(lu);var cu=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Se(rt(-t)),r.epsilon=Se(rt(me.get("EPSILON"))),r}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ne(function(){t.accumulatedGrads[n]=pt(a.shape,t.initialAccumulatorValue).variable(!1)});var i=e[n],o=r.accumulatedGrads[n];Ne(function(){var e=o.add(i.square());t.accumulatedGrads[n].assign(e);var r=t.c.mul(i.div(e.add(t.epsilon).sqrt())).add(a);a.assign(r)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(uu);tu(cu);var fu=function(e){function t(t,n,r,a){void 0===a&&(a=null);var i=e.call(this)||this;return i.learningRate=t,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment={},i.accumulatedSecondMoment={},i.c=Se(rt(-t)),i.beta1Scalar=Se(rt(n)),i.beta2Scalar=Se(rt(r)),Ne(function(){i.accBeta1=rt(n).variable(),i.accBeta2=rt(r).variable()}),i.oneMinusBeta1=Se(rt(1-n)),i.oneMinusBeta2=Se(rt(1-r)),i.one=Se(rt(1)),null===a&&(a=me.get("EPSILON")),i.epsScalar=Se(rt(a)),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ne(function(){var n=t.one.sub(t.accBeta1),r=t.one.sub(t.accBeta2);for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=_t(i).variable(o)}null==t.accumulatedSecondMoment[a]&&(o=!1,t.accumulatedSecondMoment[a]=_t(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),p=c.div(n),h=f.div(r);t.accumulatedFirstMoment[a].assign(c),t.accumulatedSecondMoment[a].assign(f);var d=t.c.mul(p.div(t.epsScalar.add(h.sqrt()))).add(i);i.assign(d)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(uu);tu(fu);var pu=function(e){function t(t,n,r,a,i){void 0===a&&(a=null),void 0===i&&(i=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment={},o.accumulatedWeightedInfNorm={},o.c=Se(rt(-t)),o.beta1Scalar=Se(rt(n)),o.beta2Scalar=Se(rt(r)),o.decayScalar=Se(rt(i)),Ne(function(){o.iteration=rt(0).variable(),o.accBeta1=rt(n).variable()}),o.oneMinusBeta1=Se(rt(1-n)),o.one=Se(rt(1)),null===a&&(a=me.get("EPSILON")),o.epsScalar=Se(rt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ne(function(){var n=t.one.sub(t.accBeta1),r=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=_t(i).variable(o)}null==t.accumulatedWeightedInfNorm[a]&&(o=!1,t.accumulatedWeightedInfNorm[a]=_t(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l),p=s.abs(),h=f.maximum(p);t.accumulatedFirstMoment[a].assign(c),t.accumulatedWeightedInfNorm[a].assign(h);var d=r.div(n).mul(c.div(t.epsScalar.add(h))).add(i);i.assign(d)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(uu);tu(pu);var hu=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(n){var r=e[n],a=me.engine.registeredVariables[n];Ne(function(){var e=t.c.mul(r).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Se(rt(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(uu);tu(hu);var du=function(e){function t(t,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=n,a.useNesterov=r,a.m=rt(a.momentum),a.accumulations={},a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulations[n]&&Ne(function(){t.accumulations[n]=_t(a).variable(!1)});var i=r.accumulations[n],o=e[n];Ne(function(){var e,r=t.m.mul(i).add(o);e=t.useNesterov?t.c.mul(o.add(r.mul(t.m))).add(a):t.c.mul(r).add(a),t.accumulations[n].assign(r),a.assign(e)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(hu);tu(du);var mu=function(e){function t(t,n,r,a,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=null),void 0===i&&(i=!1);var o=e.call(this)||this;return o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares={},o.accumulatedMeanGrads={},o.accumulatedMoments={},o.c=Se(rt(t)),o.decayScalar=Se(rt(n)),o.momentumScalar=Se(rt(r)),o.oneMinusDecay=Se(rt(1-n)),o.centered=i,null===a&&(a=me.get("EPSILON")),o.epsilonScalar=Se(rt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&Ne(function(){t.accumulatedMeanSquares[n]=_t(a).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&Ne(function(){t.accumulatedMeanGrads[n]=_t(a).variable(!1)}),null==r.accumulatedMoments[n]&&Ne(function(){t.accumulatedMoments[n]=_t(a).variable(!1)});var i=r.accumulatedMeanSquares[n],o=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=e[n];Ne(function(){var e=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var r=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(r.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[n].assign(e),t.accumulatedMeanGrads[n].assign(r),t.accumulatedMoments[n].assign(l);var c=a.sub(l);a.assign(c)}else{var f=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(f.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[n].assign(f),t.accumulatedMoments[n].assign(l),c=a.sub(l),a.assign(c)}})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(uu);tu(mu);var gu=function(){function e(){}return e.sgd=function(e){return new hu(e)},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new du(e,t,n)},e.rmsprop=function(e,t,n,r,a){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new mu(e,t,n,r,a)},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new fu(e,t,n,r)},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=null),new lu(e,t,n)},e.adamax=function(e,t,n,r,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new pu(e,t,n,r,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new cu(e,t)},e}(),yu={sgd:gu.sgd,momentum:gu.momentum,adadelta:gu.adadelta,adagrad:gu.adagrad,rmsprop:gu.rmsprop,adamax:gu.adamax,adam:gu.adam},vu=de.setBackend,bu=de.getBackend,wu=de.disposeVariables,xu=de.memory;J=ns}).call(this,n(46),n(26),n(162).setImmediate,n(16).Buffer)},function(e,t,n){var r=n(7),a=n(44),i=n(30),o=n(29),s=n(43),u=function(e,t,n){var l,c,f,p,h=e&u.F,d=e&u.G,m=e&u.S,g=e&u.P,y=e&u.B,v=d?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,b=d?a:a[t]||(a[t]={}),w=b.prototype||(b.prototype={});for(l in d&&(n=t),n)f=((c=!h&&v&&void 0!==v[l])?v:n)[l],p=y&&c?s(f,r):g&&"function"==typeof f?s(Function.call,f):f,v&&o(v,l,f,e&u.U),b[l]!=f&&i(b,l,p),g&&w[l]!=f&&(w[l]=f)};r.core=a,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t,n){"use strict";n.r(t);var r=n(1),a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}; +var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function s(e,t){function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var u=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]0;)r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n}function p(e,t,n){return Math.max(e,Math.min(t,n))}function h(e,t){var n=Math.random();return t*n+(1-n)*e}function d(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function m(e,t,n){void 0===n&&(n=""),d(w(e,t),n+" Shapes "+e+" and "+t+" must match")}function g(e){d(null!=e,"The input to the tensor constructor must be a non-null value.")}function y(e,t){if(void 0===t&&(t=[]),Array.isArray(e))for(var n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"}),d(t.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+t.length+" elements"});for(var a=n.slice(1),i=0;i1;--t)if(e%t==0)return[t,e/t];return[1,e]}function E(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function N(e,t,n){return void 0===t&&(t=function(e){return 0}),new Promise(function(r,a){var i=0,o=function(){if(e())r();else{var s=t(++i);null!=n&&i>=n?a():setTimeout(o,s)}};o()})}function O(e,t){for(var n=1,r=-1,a=0;a=0)n*=e[a];else if(-1===e[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-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);var i=e.slice();return i[r]=t/n,i}function k(e,t){for(var n=[],r=[],a=0,i=0;ii)&&1===e[i]&&(n.push(e[i]),r.push(i)),t[a]<=i&&a++}1!==e[i]&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function I(e,t){var 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 C(e,t,n){if("float32"===t)for(var r=0;r=0;--r)n[r]=n[r+1]*e[r+1];return n}function L(e,t,n){return function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t)?e:(Array.isArray(e)&&(e=y(e)),function(e,t,n){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return n&&A(e,t),new Int32Array(e);if("bool"===t){for(var r=new Uint8Array(e.length),a=0;a1)for(var l=0;lq){var c=$*s,f=Array.from(t.subarray(0,c)),p=Array.from(t.subarray(u-$*s,u));return"complex64"===r&&(f=K(f),p=K(p)),["["+f.map(function(e,t){return H(e,i[t])}).join(", ")+", ..., "+p.map(function(e,t){return H(e,i[u-$+t])}).join(", ")+"]"]}return["["+("complex64"===r?K(t):Array.from(t)).map(function(e,t){return H(e,i[t])}).join(", ")+"]"]}var h=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>q){for(var y=0;y<$;y++){var v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,r,d,i,!1))}for(g.push("..."),y=u-$;y {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),a=re(e);a.forEach(function(e){return r.add(e.id)});for(var i=0;i0,"gradients() received an empty list of xs."),this.tidy("gradients",function(){var i=e();d(i instanceof Q,"The result y returned by f() must be a tensor.");var o=function(e,t,n){for(var r={},a={},i=0;i=0;i--)for(o=(d=e[i]).inputs,c=0;c0)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.");var s={};return s[i.id]=null==n?function(e){var t=z(b(e),"float32");return Q.make(e,{values:t})}(i.shape):n,function(e,t){for(var n=function(n){var r=t[n],a=[];if(r.outputs.forEach(function(t){var n=e[t.id];if(null!=n)a.push(n);else{var r=Q.make(t.shape,{values:B(t.size,t.dtype)},t.dtype);a.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var i=r.gradient(1===r.outputs.length?a[0]:a);for(var o in r.inputs){if(!(o in i))throw new Error("Cannot backprop through input "+o+". Available gradients found: "+Object.keys(i)+".");var s=i[o](),u=r.inputs[o];if(!w(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+o+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==e[u.id])e[u.id]=s;else{var l=e[u.id];e[u.id]=l.add(s),l.dispose()}}},r=t.length-1;r>=0;r--)n(r)}(s,o),{value:i,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return d(R(e),"The f passed in customGrad(f) must be a function."),function(){for(var n,r,a=[],i=0;i {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e},e}();!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(ae||(ae={}));var oe=[{name:"DEBUG",type:ae.BOOLEAN},{name:"IS_BROWSER",type:ae.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:ae.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:ae.BOOLEAN},{name:"WEBGL_VERSION",type:ae.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:ae.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:ae.BOOLEAN},{name:"BACKEND",type:ae.STRING},{name:"EPSILON",type:ae.NUMBER}];function se(e,t){var n;try{n=fe(e,t)}catch(e){return!1}return null!=n&&(pe(n),!0)}var ue="tfjsflags";function le(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=function(e){var t={};return window.location.search.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r0?0:function(e,t){if(0===e)return 0;var n,r=fe(e,t);return n=ce(r,"EXT_disjoint_timer_query_webgl2")&&2===e?2:ce(r,"EXT_disjoint_timer_query")?1:0,null!=r&&pe(r),n}(n,this.get("IS_BROWSER"))}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===t)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!function(){var e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return se(2,this.get("IS_BROWSER"))?2:se(1,this.get("IS_BROWSER"))?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(e,t){if(0===e)return!1;var n=fe(e,t);if(1===e){if(!ce(n,"OES_texture_float"))return!1;if(!ce(n,"WEBGL_color_buffer_float"))return!1}else if(!ce(n,"EXT_color_buffer_float"))return!1;var r=he(n,e);return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("WEBGL_FENCE_API_ENABLED"===t)return function(e,t){if(2!==e)return!1;var n=fe(e,t),r=null!=n.fenceSync;return pe(n),r}(this.get("WEBGL_VERSION"),this.get("IS_BROWSER"));if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:.001;throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(e){this.features=Object.assign({},e)},t.prototype.reset=function(){this.features=le(),null!=this.globalEngine&&(this.globalEngine=null)},t.prototype.initBackend=function(e,t){var n=this;if(void 0===t&&(t=!1),this.backendName=e,this.engines[e])this.globalEngine=this.engines[e];else{var r=this.findBackend(e);this.globalEngine=new ie(r,t,function(){return n.get("DEBUG")}),this.engines[e]=this.globalEngine}},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},t.prototype.registerBackend=function(e,t,n,r){var a=this;if(void 0===n&&(n=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=r&&r(function(){return a.engine}),!1;try{var i=t();return this.registry[e]={backend:i,priority:n},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},t.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e],e in this.engines&&delete this.engines[e]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initDefaultBackend(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(this.get("BACKEND"),!1)},t}(),me=function(){var t=function(){var t;if("undefined"!=typeof window)t=window;else{if(void 0===e)throw new Error("Could not find a global object");t=e}return t}();return null==t.ENV&&(t.ENV=new de(le()),Z(function(){return t.ENV.engine})),t.ENV}(),ge=Object.freeze({Environment:de,ENV:me});function ye(e){return d(R(e),"The f passed in grad(f) must be a function"),function(t,n){return d(t instanceof Q,"The x passed in grad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in grad(f)(x, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Se(i),i[0]})}}function ve(e){return d(R(e),"The f passed in grads(f) must be a function"),function(t,n){return d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in grads(f)(args) must be an array of tensors"),d(null==n||n instanceof Q,"The dy passed in grads(f)(args, dy) must be a tensor"),me.engine.tidy(function(){var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n),a=r.value,i=r.grads;return null!=n&&m(a.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Se(i),i})}}function be(e){return d(R(e),"The f passed in valueAndGrad(f) must be a function"),function(t,n){d(t instanceof Q,"The x passed in valueAndGrad(f)(x) must be a tensor"),d(null==n||n instanceof Q,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var r=me.engine.gradients(function(){return e(t)},[t],n),a=r.grads,i=r.value;return Se(a),{grad:a[0],value:i}}}function we(e){return d(R(e),"The f passed in valueAndGrads(f) must be a function"),function(t,n){d(Array.isArray(t)&&t.every(function(e){return e instanceof Q}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),d(null==n||n instanceof Q,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var r=me.engine.gradients(function(){return e.apply(void 0,t)},t,n);return null!=n&&m(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Se(r.grads),r}}function xe(e,t){if(d(R(e),"The f passed in variableGrads(f) must be a function"),d(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof ee}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var n in t=[],me.engine.registeredVariables)t.push(me.engine.registeredVariables[n]);var r=t.length;d((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable.");var a=me.engine.gradients(e,t,null,!0),i=a.value,o=a.grads;d(o.some(function(e){return 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()."),d(0===i.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+i.rank+" tensor");var s={};return t.forEach(function(e,t){null!=o[t]&&(s[e.name]=o[t])}),{value:i,grads:s}}function _e(e){return me.engine.customGrad(e)}function Se(e){if(e.filter(function(e){return 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.")}var Ee=de.tidy,Ne=de.keep,Oe=de.dispose,ke=de.time;function Ie(){for(var e=[],t=0;t=2*t+1||a%2==1?o.push(a):i.push(a);r.push.apply(r,i),r.push(0),r.push.apply(r,o)}return r}function Pe(e,t,n,r){void 0===r&&(r=!0);var a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(var i=1;i=-n&&e0?a>=c[t]:a<=c[t]);a+=r[t])n+=1;return n}),[l,h,f]}function Ge(e,t,n,r,a){var i=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),p(0,i,o-1)}function He(e,t,n,r,a){var i=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var o=r[a];return i<0&&(i+=o),n[a]>0?p(0,i,o):p(-1,i,o-1)}function Ke(e,t,n,r){if(void 0===r&&(r="float32"),r=r||"float32",e instanceof Q)return e;if(!T(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e)throw new Error("Argument '"+t+"' passed to '"+n+"' must be a Tensor or TensorLike, but got "+e.constructor.name);var a=v(e);return T(e)||Array.isArray(e)||(e=[e]),Q.make(a,{values:L(e,r,me.get("DEBUG"))},r)}function Xe(e,t,n){if(!Array.isArray(e))throw new Error("Argument "+t+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return e.map(function(e,r){return Ke(e,t+"["+r+"]",n)})}function Ye(e){var 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.");var n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var a=function(){for(var e=[],t=0;t1)return ct([0],r);var a=B(Math.abs(Math.ceil((t-e)/n)),r);ta}).sort(function(e,t){return t.score-e.score}),o=[],s=0;s=0;--p)if(Ct(e,c,o[p])>=r){f=!0;break}if(!f&&(o.push(c),o.length>=n))break}return rt(o,"int32")}function Ct(e,t,n){var r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),f=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(s-i)*(u-o),d=(f-l)*(p-c);if(h<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),y=Math.min(s,f),v=Math.min(u,p),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(h+d-b)}function At(e,t,n){var r=Array(e.rank).fill(0),a=e.shape.slice();return t.map(function(t){a[n]=t;var i=e.slice(r,a);return r[n]+=t,i})}function Pt(e,t,n,r,a){for(var i=t[t.length-1],o=[e.length/i,i],s=o[0],u=o[1],l=I(n,s*r),c=I("int32",s*r),f=0;f1&&1===o&&r.unshift(i)}return r}function Mt(e,t){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Rt(e,t){for(var n=[],r=Math.max(e.length,t.length),a=0;a1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});a=a.join("\n");var i=e.map(function(e){return function(e,t,n){var r=function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1)+"Flat",r=b(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform)return 1===r?"float "+n+"(int index) {return "+t+";}":"\n float "+n+"(int index) {\n for (int i = 0; i < "+r+"; i++) {\n if (i == index) {\n return "+t+"[i];\n }\n }\n }\n ";var a=e.shapeInfo.texShape,i=a[0],o=a[1];return 1===o&&1===i?"\n float "+n+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ":1===o?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+i+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index) + 0.5) / "+o+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = UVfrom1D("+i+", "+o+", index);\n return sampleTexture("+t+", uv);\n }\n "}(e);return r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+n+"() {return "+t+";}":"\n float "+n+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}(t);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+n+"(int index) {\n return "+n+"Flat(index);\n }\n "}(t);case 2:return function(t){var n=t.shapeInfo.logicalShape,r=t.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),i=t.shapeInfo.texShape;if(null!=i&&w(n,i)){var o=i[0];return"\n float "+a+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var s=k(n),u=s.newShape,l=s.keptDims,c=u;if(c.lengths||o.length>0),c=function(e){for(var t=0;t=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+n+"("+(i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}(e,t,a,i);var p=b(e.shapeInfo.logicalShape),h="";l&&c&&(h="\n int mainPart = index / "+p+";\n index -= mainPart * "+p+";\n ");var d=t.texShape;if(f)return 1===p?"float "+i+"() {return "+r+";}":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return w(m,d)?"\n float "+i+"() {\n return sampleTexture("+r+", resultUV);\n }\n ":"\n float "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+d[0]+", "+d[1]+"));\n int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+r+", uv);\n }\n "}(e,t,n)),r}(e,t,r)}).join("\n"),o=t.texShape,s=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}(0,t);case 2:return function(e,t){return w(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}(e,t);case 3:return function(e,t){var n=e[1]*e[2],r=e[2];return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+n+";\n index -= r * "+n+";\n int c = index / "+r+";\n int d = index - c * "+r+";\n return ivec3(r, c, d);\n }\n "}(e,t);case 4:return function(e,t){var n=e[3],r=e[2]*n,a=e[1]*r;return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+a+";\n index -= r * "+a+";\n\n int c = index / "+r+";\n index -= c * "+r+";\n\n int d = index / "+n+";\n int d2 = index - d * "+n+";\n\n return ivec4(r, c, d, d2);\n }\n "}(e,t);case 5:return function(e,t){var n=e[4],r=e[3]*n,a=e[2]*r,i=e[1]*a;return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+i+";\n index -= r * "+i+";\n\n int c = index / "+a+";\n index -= c * "+a+";\n\n int d = index / "+r+";\n index -= d * "+r+";\n\n int d2 = index / "+n+";\n int d3 = index - d2 * "+n+";\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(e,t);case 6:return function(e,t){var n=e[5],r=e[4]*n,a=e[3]*r,i=e[2]*a,o=e[1]*i;return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+o+";\n index -= r * "+o+";\n\n int c = index / "+i+";\n index -= c * "+i+";\n\n int d = index / "+a+";\n index -= d * "+a+";\n\n int d2 = index / "+r+";\n index -= d2 * "+r+";\n\n int d3 = index / "+n+";\n int d4 = index - d3 * "+n+";\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}(t.logicalShape,o);return[Ut,Ft,Vt,a,s,i,n].join("\n")}var Ft="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",Vt="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",Ut="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\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 bool isNaN(float val) {\n return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\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 \nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n";function Wt(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function qt(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function $t(e,t){return t.map(function(t){return e[t]}).join(", ")}function Gt(e,t){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 sum for rank "+e+" is not yet supported")}var Ht,Kt,Xt=function(){function e(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 "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}();function Yt(e,t){return[t,e]}function Jt(e,t){return e*t}function Zt(e,t,n){var r=function(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t}(e.length,n);if(t.length= "+r);for(var a=0,i=0;ir||n>r)throw a="["+t+"x"+n+"]",new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function Sn(e){return Mn(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function En(e,t,n,r,a,i,o){var s=e.getAttribLocation(t,n);return-1!==s&&(an(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),an(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,i,o)}),an(e,function(){return e.enableVertexAttribArray(s)}),!0)}function Nn(e,t,n){Rn(e,n),an(e,function(){return e.activeTexture(e.TEXTURE0+n)}),an(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function On(e,t,n){return Mn(e,function(){return e.getUniformLocation(t,n)},'uniform "'+n+'" not present in program.')}function kn(e,t,n){return e.getUniformLocation(t,n)}function In(e,t,n,r,a){an(e,function(){return Nn(e,n,a)}),an(e,function(){return e.uniform1i(r,a)})}function Cn(e,t,n){an(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,n)}),an(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function An(e,t){an(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),an(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function Pn(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Tn(e,t))}function Tn(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function Mn(e,t,n){var r=an(e,function(){return t()});if(null==r)throw new Error(n);return r}function Rn(e,t){var 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 Dn(e,t){2!==t.length&&(t=k(t).newShape);var n=bn(e),r=b(t);return t.length<=1&&r<=n?[r,1]:2===t.length&&t[0]<=n&&t[1]<=n?t:3===t.length&&t[0]<=n&&t[1]*t[2]<=n?[t[0],t[1]*t[2]]:4===t.length&&t[0]<=n&&t[1]*t[2]*t[3]<=n?[t[0],t[1]*t[2]*t[3]]:S(r)}var jn=Object.freeze({createWebGLRenderingContext:nn,createWebGLRenderingContextFromCanvas:rn,callAndCheck:an,enableDebugWebGLErrorChecking:sn,checkWebGLError:un,getWebGLErrorMessage:ln,getExtensionOrThrow:cn,createVertexShader:fn,createFragmentShader:pn,createProgram:dn,linkProgram:mn,validateProgram:gn,createStaticVertexBuffer:yn,createStaticIndexBuffer:vn,queryMaxTextureSize:bn,getNumChannels:wn,createTexture:xn,validateTextureSize:_n,createFramebuffer:Sn,bindVertexBufferToProgramAttribute:En,bindTextureUnit:Nn,unbindTextureUnit:function(e,t){Rn(e,t),an(e,function(){return e.activeTexture(e.TEXTURE0+t)}),an(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:On,getProgramUniformLocation:kn,bindTextureToProgramUniformSampler:In,bindCanvasToFramebuffer:function(e){an(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),an(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),an(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})},bindColorTextureToFramebuffer:Cn,unbindColorTextureFromFramebuffer:An,validateFramebuffer:Pn,getFramebufferErrorMessage:Tn,getTextureShapeFromLogicalShape:Dn});function Ln(e){var t,n={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};return an(t=null!=e?rn(e,n):nn(n),function(){return t.disable(t.DEPTH_TEST)}),an(t,function(){return t.disable(t.STENCIL_TEST)}),an(t,function(){return t.disable(t.BLEND)}),an(t,function(){return t.disable(t.DITHER)}),an(t,function(){return t.disable(t.POLYGON_OFFSET_FILL)}),an(t,function(){return t.disable(t.SAMPLE_COVERAGE)}),an(t,function(){return t.enable(t.SCISSOR_TEST)}),an(t,function(){return t.enable(t.CULL_FACE)}),an(t,function(){return t.cullFace(t.BACK)}),t}function zn(e){return fn(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Bn(e){return yn(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Fn(e){return vn(e,new Uint16Array([0,1,2,2,1,3]))}function Vn(e,t){var n,r,a,i,o,s,u,l=e;return 2===me.get("WEBGL_VERSION")?(n=l.R32F,r=l.R16F,a=l.RGBA32F,i=l.RED,o=4,s=1,u=l.HALF_FLOAT):(n=e.RGBA,r=e.RGBA,a=l.RGBA,i=e.RGBA,o=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:o,defaultNumChannels:s,textureTypeHalfFloat:u}}function Un(e,t,n,r,a,i){_n(e,t,n);var o=xn(e),s=e.TEXTURE_2D;return an(e,function(){return e.bindTexture(s,o)}),an(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),an(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),an(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),an(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),an(e,function(){return e.texImage2D(s,0,r,t,n,0,a,i,null)}),an(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),o}function Wn(e,t,n,r){var a=Yt(t,n);return Un(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,e.FLOAT)}function qn(e,t,n,r){var a=Yt(t,n);return Un(e,a[0],a[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function $n(e,t,n,r){var a=Yt(t,n);return Un(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function Gn(e,t,n,r){var a=Qt(t,n);return Un(e,a[0],a[1],r.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function Hn(e,t,n){return an(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),En(e,t,"clipSpacePos",n,3,20,0)&&En(e,t,"uv",n,2,20,12)}function Kn(e,t,n){an(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),an(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}),an(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Xn(e,t,n,r,a,i){_n(e,n,r),an(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),an(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,i,e.FLOAT,a)}),an(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function Yn(e,t,n,r,a,i,o){var s,u=Yt(n,r),l=u[0],c=u[1];1===o.defaultNumChannels?s=a:function(e,t,n){var r=Jt(e.length,n);if(t.length= "+r);for(var a=0,i=0;i= "+a);for(var i=Qt(t,n),o=i[0],s=i[1],u=n%2==1,l=t%2==1,c=Math.floor(n/2),f=Math.floor(t/2),p=u?4:0,h=n,d=0,m=0;m= "+a);for(var i=n%2==1,o=t%2==1,s=Math.floor(n/2),u=Math.floor(t/2),l=Qt(t,n),c=l[0],f=l[1],p=i?4:0,h=n+(i?1:0),d=0,m=0,g=n,y=0;y0?(t=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(t,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:t,isFencePassed:n}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,function(){return nr(r.gl,t,n,r.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=pn(t,e),r=zn(t),a=dn(t);return an(t,function(){return t.attachShader(a,r)}),an(t,function(){return t.attachShader(a,n)}),mn(t,a),this.autoDebugValidate&&gn(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=Hn(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&an(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&gn(this.gl,this.program),an(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?On(this.gl,e,t):kn(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),an(this.gl,function(){return n.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),In(this.gl,this.program,e,t,n)},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=Qt(t,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(e,a,i)},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&gn(this.gl,this.program),Pn(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),an(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),an(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=cn(this.gl,2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return l(this,void 0,void 0,function(){var t=this;return c(this,function(n){switch(n.label){case 0:return[4,N(function(){return t.isQueryAvailable(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(e,me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise(function(n){t.addItemToPoll(function(){return e.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var e=function(e){for(var t=0,n=e.length-1,r=-1;t<=n;){var a=t+n>>1;e[a]()?(r=a,t=a+1):n=a-1}return r}(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var n=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||N(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),Cn(this.gl,e,this.framebuffer),this.autoDebugValidate&&Pn(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Cn(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Pn(this.gl)):An(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var n=t();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;Cn(r,e,this.framebuffer),this.autoDebugValidate&&Pn(r),this.outputTexture=e,an(r,function(){return r.viewport(0,0,t,n)}),an(r,function(){return r.scissor(0,0,t,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var a=this;this.throwIfDisposed(),an(this.gl,function(){return a.gl.scissor(e,t,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function ir(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(function(e,n){var r=e.logicalShape,a=t[n],i=a.shape;if(!w(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var o=e.texShape,s=a.isUniform?null:a.texData.texShape;if(!w(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var or=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\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 "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e)}},e}(),sr=function(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterHeight,a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,s=e.padInfo.top,u=e.padInfo.left;this.outputShape=e.outShape;var l="avg"===t,c="0.0";if(l||(c="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\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 < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+a+"; wC++) {\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 >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+a+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var p=4*Math.floor(a/4),h=a%4,d="\n if ("+l+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\n const float initializationValue = "+c+";\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("+c+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n "+d+"\n }\n\n int xC = xCCorner + "+p+";\n if ("+(1===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(2===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(3===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n "+d+"\n }\n }\n setOutput("+f+");\n }\n "}},ur=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=Wt(this.rank),n=function(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){if(null!=t.startLoc||(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null!=t.startLoc))if(1===t.rank)n.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)n.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)n.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");n.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}(),lr=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t){var n,r=cr(t),a=fr(e,r);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),r===Kt.FLOAT32?n=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===Kt.FLOAT16?n=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===Kt.UNSIGNED_BYTE&&(n=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(n),n},e.prototype.releaseTexture=function(e,t,n){var r=fr(t,cr(n));r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(e),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[r],i=a.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function cr(e){if(e===Ht.DOWNLOAD||e===Ht.PIXELS)return Kt.UNSIGNED_BYTE;if(e===Ht.UPLOAD)return Kt.FLOAT32;if(e===Ht.RENDER)return me.get("WEBGL_RENDER_FLOAT32_ENABLED")?Kt.FLOAT32:Kt.FLOAT16;throw new Error("Unknown logical texture type "+e)}function fr(e,t){return e[0]+"_"+e[1]+"_"+t}var pr=1.7580993408473768,hr=1.0507009873554805,dr=function(){function e(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float NAN;\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 "}return e.prototype.getCustomSetupFunc=function(){var e=this;return function(t,n){null==e.startLoc&&(e.startLoc=t.getUniformLocationNoThrow(n,"NAN"),null==e.startLoc)||t.gl.uniform1f(e.startLoc,NaN)}},e}(),mr="if (isNaN(x)) return x;",gr=Ye({concat_:function(e,t){void 0===t&&(t=0),d(e.length>=1,"Pass at least one tensor to concat");var n=Xe(e,"tensors","concat"),r=Ue(n.map(function(e){return e.shape}),t);if(0===b(r))return tt([],r);if(1===(n=n.filter(function(e){return e.size>0})).length)return n[0];var a=Le(t,n[0].shape)[0],i=n.map(function(e){return e.shape});!function(e,t){var n=e[0].length;e.forEach(function(e,t){d(e.length===n,"Error in concat"+n+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+n+")")}),d(t>=0&&t>>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}(e),a=t&&t.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),Er=_r(function(e){!function(e,t,n){function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),Nr=_r(function(e){!function(e,t,n){function r(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 a(e,t){var n=new function(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()}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),Or=_r(function(e){!function(e,t,n){function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new function(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)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),kr=_r(function(e){!function(e,t,n){function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new function(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,o,s=[],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&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;e.w=o,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),Ir=_r(function(e){!function(e,t,n){function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new function(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 i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),Cr=_r(function(e){!function(t,r){var a,i=this,o=256,s=6,u="random",l=r.pow(o,s),c=r.pow(2,52),f=2*c,p=o-1;function h(e,n,h){var y=[],v=m(function e(t,n){var r,a=[],i=typeof t;if(n&&"object"==i)for(r in t)try{a.push(e(t[r],n-1))}catch(e){}return a.length?a:"string"==i?t:t+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[e,g(t)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(o):(e=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(e)),g(e)}catch(e){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(t)]}}():e,3),y),b=new function(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);a=f;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,m(g(b.S),t),(n.pass||h||function(e,t,n,a){return a&&(a.S&&d(a,b),e.state=function(){return d(b,{})}),n?(r[u]=e,t):e})(w,v,"global"in n?n.global:this==r,n.state)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function m(e,t){for(var n,r=e+"",a=0;a=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(t)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}();function Tr(e,t){return l(this,void 0,void 0,function(){var n,r,a,i,o,s,u,l,f,p,h,d,m,g,y,v,b,w,x,_;return c(this,function(c){switch(c.label){case 0:if(2!==(n=Ke(e,"img","toPixels","int32")).rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(o=2===n.rank?1:n.shape[2])>4||2===o)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+o);return s=n.min(),u=n.max(),[4,s.data()];case 1:return l=c.sent()[0],[4,u.data()];case 2:if(f=c.sent()[0],s.dispose(),u.dispose(),"float32"===n.dtype){if(l<0||f>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+f+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(l<0||f>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+f+"].")}return[4,n.data()];case 3:for(p=c.sent(),h="float32"===n.dtype?255:1,d=new Uint8ClampedArray(i*a*4),m=0;m=1+t.length,"input rank should be > than [blockShape] but got "+r.rank),d(n.length===t.length,"crops.shape[0] must be equal to [blockShape] but got "+n.length),d(r.shape[0]%a==0,"input tensor batch must be divisible by prod( blockShape )"),me.engine.runKernel(function(e){return e.batchToSpaceND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.spaceToBatchND(t,n)}}})}}),jr=Ye({cast_:function(e,t){var n=Ke(e,"x","cast");return me.engine.runKernel(function(e){return e.cast(n,t)},{$x:n},function(e){return{$x:function(){return e.clone()}}})}}),Lr=Ye({clone_:function(e){var t=Ke(e,"x","clone");return me.engine.runKernel(function(e){return Q.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),zr=Ye({cumsum_:function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=Ke(e,"x","cumsum"),i=Be([t|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=Ve(1,a.rank)[0],u=me.engine.runKernel(function(e){return e.cumsum(o,s,n,r)},{permutedX:o},function(e){return{permutedX:function(){return e.cumsum(t,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),Br=Ye({depthToSpace_:function(e,t,n){void 0===n&&(n="NHWC");var r=Ke(e,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return d(a*t>=0,"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(i*t>=0,"Negative dimension size caused by overflow when multiplying\n "+i+" and "+t+" for depthToSpace with input shape\n "+r.shape),d(o%(t*t)==0,"Dimension size must be evenly divisible by "+t*t+" but is "+o+" for depthToSpace with input shape "+r.shape),me.engine.runKernel(function(e){return e.depthToSpace(r,t,n)},{$x:r})}}),Fr=Ye({expandDims_:function(e,t){void 0===t&&(t=0);var n=Ke(e,"x","expandDims");d(t<=n.rank,"Axis must be <= rank of the tensor");var r=n.shape.slice();return t<0&&(d(-(n.rank+1)<=t,"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"),t=n.rank+t+1),r.splice(t,0,1),Qr(n,r)}}),Vr=Ye({eye_:function(e,t,n,r){void 0===r&&(r="float32"),null==t&&(t=e);for(var a=Mr([e,t],r),i=e<=t?e:t,o=0;o4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return me.engine.fromPixels(e,t)}}),Wr=Ye({multinomial_:function(e,t,n,r){void 0===r&&(r=!1);var a=Ke(e,"logits","multinomial"),i=a.size,o=a.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?a.as2D(1,-1):a,u=me.engine.runKernel(function(e){return e.multinomial(s,r,t,n)},{logits2D:s});return 1===o?u.as1D():u}}),qr=Ye({oneHot_:function(e,t,n,r){void 0===n&&(n=1),void 0===r&&(r=0);var a=Ke(e,"indices","oneHot","int32");if(d("int32"===a.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return me.engine.runKernel(function(e){return e.oneHot(a,t,n,r)},{$indices:a},function(e){return{$indices:function(){return xt(a)}}})}}),$r=Ye({pad_:function(e,t,n){void 0===n&&(n=0);var r=Ke(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a=t.map(function(e){return e[0]});return me.engine.runKernel(function(e){return e.pad(r,t,n)},{$x:r},function(e){return{$x:function(){return e.slice(a,r.shape)}}})}}),Gr=Ye({pad1d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length,"Invalid number of paddings. Must be length of 2."),$r(e,[t],n)}}),Hr=Ye({pad2d_:function(e,t,n){return void 0===n&&(n=0),d(2===t.length&&2===t[0].length&&2===t[1].length,"Invalid number of paddings. Must be length of 2 each."),$r(e,t,n)}}),Kr=Ye({pad3d_:function(e,t,n){return void 0===n&&(n=0),d(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."),$r(e,t,n)}}),Xr=Ye({pad4d_:function(e,t,n){return void 0===n&&(n=0),d(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."),$r(e,t,n)}}),Yr=Ye({rand_:function(e,t,n){var r=b(e),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(var i=0;i=1+t.length,"input rank "+r.rank+" should be > than [blockShape] "+t.length),d(n.length===t.length,"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+t.length),d(r.shape.reduce(function(e,r,a){return 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()),me.engine.runKernel(function(e){return e.spaceToBatchND(r,t,n)},{$x:r},function(e){return{$x:function(){return e.batchToSpaceND(t,n)}}})}}),ta=Ye({squeeze_:function(e,t){var n=Ke(e,"x","squeeze");return Qr(n,k(n.shape,t).newShape)}}),na=Ye({stack_:function(e,t){void 0===t&&(t=0);var n=Xe(e,"tensors","stack");if(d(n.length>=1,"Pass at least one tensor to tf.stack"),1===n.length)return n[0].expandDims(t);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;d(t<=r,"Axis must be <= rank of the tensor"),n.forEach(function(e){m(a,e.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(e){d(i===e.dtype,"All tensors passed to stack must have matching dtypes")});var o=n.map(function(e){return e.expandDims(t)});return gr(o,t)}}),ra=Ye({tile_:function(e,t){var n=Ke(e,"x","tile");return d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of reps "+t+"."),me.engine.runKernel(function(e){return e.tile(n,t)},{$x:n},function(e){return{$x:function(){var r=xt(n);if(1===n.rank)for(var a=0;a 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\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "}(a);this.compileAndRun(s,[o],i,null,!1);var u=this.texData.get(i.dataId),l=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture,u.texShape[0],u.texShape[1]);return o.dispose(),i.dispose(),l},e.prototype.time=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),a=y(this.activeTimers),this.activeTimers=t,r&&(this.programTimersStack=null),[4,Promise.all(a).then(function(e){var t=0;return e.forEach(function(e){return t+=e}),t})];case 1:return i=s.sent(),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:i,wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return l(this,void 0,void 0,function(){var t;return c(this,function(n){return me.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),n=t.texture,r=t.texShape,a=t.usage,i=t.complexTensors;null!=n&&this.releaseTexture(e,n,r,a),null!=i&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.getCanvas=function(){return this.canvas},e.prototype.complex=function(e,t){var n=Q.make(e.shape,{},"complex64");return this.texData.get(n.dataId).complexTensors={real:me.engine.keep(e.clone()),imag:me.engine.keep(t.clone())},n},e.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},e.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},e.prototype.slice=function(e,t,n){var r=new ur(n),a=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,a)},e.prototype.stridedSlice=function(e,t,n,r,a,i,o,s,u){var l=$e(e.shape,t,n,r,a,i,o,s,u),c=l[0],f=l[1],p=l[2],h=f.filter(function(e,t){return-1===p.indexOf(t)});if(h.some(function(e){return 0===e}))return tt([],h);var d=new function(e,t,n,r){this.variableNames=["x"];var a=n.filter(function(e,t){return-1===r.indexOf(t)});this.outputShape=a;var i=n.length,o=Wt(n.length),s=Wt(a.length),u="";if(1===i)u="coords * strides + begin";else{var l=0;u=n.map(function(e,t){return-1===r.indexOf(t)?(l++,1===a.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(l-1)+"] * strides["+t+"] + begin["+t+"]"):"begin["+t+"]"}).join(",")}this.userCode="\n "+o+" begin = "+o+"("+e+");\n "+o+" strides = "+o+"("+t+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "}(c,r,f,p);return this.compileAndRun(d,[e])},e.prototype.reverse=function(e,t){var n=new function(e,t){this.variableNames=["x"];var 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){var r=e.map(function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),a=Wt(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "}(e.shape,t);return this.compileAndRun(n,[e])},e.prototype.concat2Tensors=function(e,t,n){var r=Ue([e.shape,t.shape],n),a=e.as2D(-1,b(e.shape.slice(n))),i=t.as2D(-1,b(t.shape.slice(n))),o=new function(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=Ue([e,t],1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "}(a.shape,i.shape);return this.compileAndRun(o,[a,i]).reshape(r)},e.prototype.concat=function(e,t){if(1===e.length)return e[0];for(var n=e[0],r=1;r= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "}(e.shape,t,n,r,a);return this.compileAndRun(i,[e])},e.prototype.LRNGrad=function(e,t,n,r,a,i,o){var s=new function(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 "}(t.shape,r,a,i,o);return this.compileAndRun(s,[t,n,e])},e.prototype.tile=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.transpose=function(e,t){var n=new function(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r6)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),a=0;a4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=Ce(e.shape,t,r),i=Ae(a.length,t.length),o=Pe(e.shape,t,r),s=Te(n,t.length),u=Me(o,n,t.length);return e.reshape(a).transpose(i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(e,t,n){d(e.rank<=4,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var r=t.reduce(function(e,t){return e*t}),a=[[0,0]];a.push.apply(a,n);for(var i=1+t.length;i= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(o="0.0",f="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var h="";a%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\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("+o+");\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; 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 "+f+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+f+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+f+"\n }\n setOutput("+u+");\n }\n "}({windowSize:qe(a),inSize:a,batchSize:r},t),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],n);return this.compileAndRun(i,[e],l),1===l.shape[1]?l:this.reduce(l,t,n)},e.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],a=e.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=new function(e,t,n){this.variableNames=["A"];var r=e.windowSize,a=e.batchSize,i=e.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===t?">":"<",u=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 = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\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 "}({windowSize:qe(a),inSize:a,batchSize:r},t,null==n),o=i.outputShape,s=o[0],u=o[1],l=this.makeOutputArray([s,u],"int32"),c=[e];return null!=n&&c.push(n),this.compileAndRun(i,c,l),1===l.shape[1]?l:this.argReduce(e,t,l)},e.prototype.sum=function(e,t){ze("sum",t,e.rank);var n=De(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a),o=Et(e.dtype);return this.reduce(i,"sum",o).reshape(r)},e.prototype.unsortedSegmentSum=function(e,t,n){var r=0,a=Be([r],e.rank),i=e;null!=a&&(i=e.transpose(a),r=Ve(1,e.rank)[0]);var o=function(e,t,n){for(var r=[],a=e.length,i=0;it||n===e){r=!0;break}n=D(e,n+1)}return n}(o,a),u=new function(e,t){this.variableNames=["x","segmentIds"];var n=e.windowSize,r=e.batchSize,a=e.inSize,i=e.numSegments,o=i*Math.ceil(a/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, filter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var f="";a%n>0&&(f="\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 "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+f+"\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 < "+s+"; 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 filter = 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 "+l+"\n }\n\n int inIdx = inOffset + "+s+";\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\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 filter = 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 "+l+"\n }\n setOutput(sumValue);\n }\n "}({windowSize:s,inSize:o,batchSize:i,numSegments:a},t),l=u.outputShape,c=l[0],f=l[1],p=this.makeOutputArray([c,f],r);return this.compileAndRun(u,[e,n],p),p.shape[1]===a?p:(n=ht(0,a).tile([o/s]),this.segOpCompute(p,t,n,r,a))},e.prototype.argMin=function(e,t){var n=[t];ze("argMin",n,e.rank);var r=De(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"min").reshape(a)},e.prototype.argMax=function(e,t){var n=[t];ze("argMax",n,e.rank);var r=De(e.shape,n),a=r[0],i=b(r[1]),o=e.as2D(-1,i);return this.argReduce(o,"max").reshape(a)},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new function(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,a=e[e.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Wt(r)+" coords = getOutputCoords();\n int end = "+Gt(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+Gt(r,"coords")+" = idx;\n val += getX("+function(e,t){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 sum for rank "+e+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "}(e.shape,n,r);return this.compileAndRun(a,[e])},e.prototype.equal=function(e,t){var n=new zt("return float(a == b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.notEqual=function(e,t){var n=new zt("return float(a != b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.less=function(e,t){var n=new zt("return float(a < b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.lessEqual=function(e,t){var n=new zt("return float(a <= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greater=function(e,t){var n=new zt("return float(a > b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.greaterEqual=function(e,t){var n=new zt("return float(a >= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalNot=function(e){var t=new dr(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},e.prototype.logicalAnd=function(e,t){var n=new zt("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.logicalOr=function(e,t){var n=new zt("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r)},e.prototype.select=function(e,t,n){var r=new function(e,t,n){var 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{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "}(e.rank,t.shape,t.rank),a=this.makeOutputArray(r.outputShape,St(t.dtype,n.dtype));return this.compileAndRun(r,[e,t,n],a)},e.prototype.where=function(e){Ie("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return oa(e.shape,t)},e.prototype.topk=function(e,t,n){return Pt(e.dataSync(),e.shape,e.dtype,t)},e.prototype.min=function(e,t){ze("min",t,e.rank);var n=De(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.mod=function(e,t){var n=new zt("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,t.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[e,t],null,r)},e.prototype.max=function(e,t){ze("max",t,e.rank);var n=De(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.all=function(e,t){ze("all",t,e.rank);var n=De(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(e,t){ze("any",t,e.rank);var n=De(e.shape,t),r=n[0],a=b(n[1]),i=e.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.squaredDifference=function(e,t){var n=new zt("return (a - b) * (a - b);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.realDivide=function(e,t){var n=new zt("if (a == b) return 1.0;\n return a / b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e,t],r)},e.prototype.floorDiv=function(e,t){var n=new zt("\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[e,t],r)},e.prototype.add=function(e,t){if("complex64"===e.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(e,t,jt);var n=new zt(jt,e.shape,t.shape),r=this.makeOutputArray(n.outputShape,St(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r)},e.prototype.complexSeparableBinaryOp=function(e,t,n){var r=this,a=this.texData.get(e.dataId),i=this.texData.get(t.dataId),o=[[a.complexTensors.real,i.complexTensors.real],[a.complexTensors.imag,i.complexTensors.imag]].map(function(a){var i=a[0],o=a[1],s=new zt(n,e.shape,t.shape),u=r.makeOutputArray(s.outputShape,St(i.dtype,o.dtype)),l=r.makeComplexComponentTensorHandle(e,i),c=r.makeComplexComponentTensorHandle(t,o);return r.compileAndRun(s,[l,c],u)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},e.prototype.addN=function(e){for(var t=e[0],n=1;n 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");return this.compileAndRun(t,[e])},e.prototype.exp=function(e){var t=new dr(e.shape,"return exp(x);");return this.compileAndRun(t,[e])},e.prototype.expm1=function(e){var t=new dr(e.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[e])},e.prototype.log=function(e){var t=new dr(e.shape,"if (x < 0.0) return NAN;\n return log(x);"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.log1p=function(e){var t=new dr(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},e.prototype.sqrt=function(e){var t=new dr(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},e.prototype.rsqrt=function(e){var t=new dr(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},e.prototype.square=function(e){var t=new dr(e.shape,"return x * x;");return this.compileAndRun(t,[e])},e.prototype.reciprocal=function(e){var t=new dr(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},e.prototype.relu=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(t,[e])},e.prototype.elu=function(e){var t=new dr(e.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[e])},e.prototype.eluDer=function(e,t){var n=new zt("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.selu=function(e){var t=new dr(e.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[e])},e.prototype.int=function(e){var t=new dr(e.shape,"return float(int(x));"),n=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],n)},e.prototype.clip=function(e,t,n){var r=new function(e,t,n){this.variableNames=["A"],this.outputShape=e,this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, float("+t+"), float("+n+")));\n }\n "}(e.shape,t,n);return this.compileAndRun(r,[e])},e.prototype.abs=function(e){var t=new dr(e.shape,"return abs(x);");return this.compileAndRun(t,[e])},e.prototype.sigmoid=function(e){var t=new dr(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},e.prototype.softplus=function(e){var t=new dr(e.shape,"\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");return this.compileAndRun(t,[e])},e.prototype.sin=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n return sin(x);\n");return this.compileAndRun(t,[e])},e.prototype.cos=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n return cos(x);\n");return this.compileAndRun(t,[e])},e.prototype.tan=function(e){var t=new dr(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},e.prototype.asin=function(e){var t=new dr(e.shape,"return asin(x);");return this.compileAndRun(t,[e])},e.prototype.acos=function(e){var t=new dr(e.shape,"return acos(x);");return this.compileAndRun(t,[e])},e.prototype.atan=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e])},e.prototype.atan2=function(e,t){var n=new zt("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t])},e.prototype.sinh=function(e){var t=new dr(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.cosh=function(e){var t=new dr(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e])},e.prototype.tanh=function(e){var t=new dr(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e])},e.prototype.asinh=function(e){var t=new dr(e.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e])},e.prototype.acosh=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.atanh=function(e){var t=new dr(e.shape,"if (isNaN(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;"),n=t.getCustomSetupFunc();return this.compileAndRun(t,[e],null,n)},e.prototype.erf=function(e){var t=new dr(e.shape,'\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 = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(t,[e])},e.prototype.step=function(e,t){var n=new dr(e.shape,function(e){return void 0===e&&(e=0),mr+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}(t));return this.compileAndRun(n,[e])},e.prototype.conv2d=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,n=e.padInfo.left,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),c=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+a+");\n const ivec2 pads = ivec2("+t+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * 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 < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\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 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 dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - 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 float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.conv2dDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left;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 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2D=function(e,t,n){var r=new function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,n=e.inWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,o=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,f=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+r+", "+a+");\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 / "+f+";\n int q = d2 - d1 * "+f+";\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 // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\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 setOutput(dotProd);\n }\n "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[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 // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var 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 // TODO: 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 "}(n);return this.compileAndRun(r,[e,t])},e.prototype.maxPool=function(e,t){var n=new sr(t,"max",!1),r=this.makeOutputArray(n.outputShape,e.dtype);return this.compileAndRun(n,[e],r)},e.prototype.avgPool=function(e,t){var n=new sr(t,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e],r)},e.prototype.maxPoolBackprop=function(e,t,n,r){var a=new sr(r,"max",!0),i=this.compileAndRun(a,[t]),o=new function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=t*n-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+s+" - 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 * "+n+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}(r),s=this.makeOutputArray(o.outputShape,t.dtype),u=this.compileAndRun(o,[e,i],s);return i.dispose(),u},e.prototype.avgPoolBackprop=function(e,t,n){var r=new function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n const float avgMultiplier = float("+s+");\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 < "+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 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 float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}(n),a=this.makeOutputArray(r.outputShape,t.dtype);return this.compileAndRun(r,[e],a)},e.prototype.cast=function(e,t){return Nt(e,t,this)},e.prototype.reshape=function(e,t){return Ot(e,t)},e.prototype.resizeBilinear=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\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 "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeBilinearBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-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), "+(i-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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.resizeNearestNeighbor=function(e,t,n,r){var a=new function(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "}(e.shape,t,n,r);return this.compileAndRun(a,[e])},e.prototype.resizeNearestNeighborBackprop=function(e,t,n){var r=new function(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=l[0]/c[0],p=l[1]/c[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\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 >= "+s+") {\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 >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 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 "}(e,t,n);return this.compileAndRun(r,[e])},e.prototype.multinomial=function(e,t,n,r){var a=t?e:Je(e),i=a.shape[0],o=a.shape[1],s=new or(i,o,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],u,l)},e.prototype.oneHot=function(e,t,n,r){var a=new function(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 "}(e.size,t,n,r);return this.compileAndRun(a,[e])},e.prototype.nonMaxSuppression=function(e,t,n,r,a){return Ie("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),It(e.dataSync(),t.dataSync(),n,r,a)},e.prototype.cropAndResize=function(e,t,n,r,a,i){var o=new function(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=e[0],o=e[1],s=e[2],u=e[3],l=t[0],c=n[0],f=n[1];this.outputShape=[l,c,f,u];var p="bilinear"===r?1:0,h=[o-1+".0",s-1+".0"],d=h[0],m=h[1],g=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=f>1?[""+(s-1)/(f-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],_=w[1],S=w[2];this.userCode="\n const float height_ratio = float("+y+");\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 = "+v+";\n float width_scale = "+_+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "}(e.shape,t.shape,r,a,i);return this.compileAndRun(o,[e,t,n])},e.prototype.depthToSpace=function(e,t,n){d(t>1,"blockSize should be > 1 for depthToSpace, but was: "+t);var r=e.shape[0],a=("NHWC"===n?e.shape[1]:e.shape[2])*t,i=("NHWC"===n?e.shape[2]:e.shape[3])*t,o=("NHWC"===n?e.shape[3]:e.shape[1])/(t*t),s=new Xt("NHWC"===n?[r,a,i,o]:[r,o,a,i],t,n);return this.compileAndRun(s,[e])},e.prototype.split=function(e,t,n){return At(e,t,n)},e.prototype.makeOutputArray=function(e,t){return Q.make(e,{},t)},e.prototype.compileAndRun=function(e,t,n,r,a){var i=this;if(void 0===a&&(a=!0),null==n&&(n=this.makeOutputArray(e.outputShape,t[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=I(n.dtype,0),n;var o=t.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var t=i.texData.get(e.dataId);return null==t.texture&&b(e.shape)<=32?{shape:e.shape,texData:null,isUniform:!0,uniformValues:i.readSync(e.dataId)}:(i.uploadToGPU(e.dataId),{shape:e.shape,texData:t,isUniform:!1})});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(e,t,n){var r="";o.concat(n).forEach(function(e){r+=e.shape+"_"+(e.isUniform?"uniform":e.texData.texShape)});var a=e.userCode,i=(!0===e.supportsBroadcasting).toString();return e.constructor.name+"_"+i+"_"+r+"_"+a}(e,0,u),c=this.getAndSaveBinary(l,function(){return function(e,t,n,r){for(var a=t.userCode,i=n.map(function(e,n){var r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform};return{name:t.variableNames[n],shapeInfo:r}}),o=i.map(function(e){return e.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1},u=Bt(i,s,a,!0===t.supportsBroadcasting),l=e.createProgram(u),c={},f=0;fthis.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;p>0&&this.lruDataGPU.length>0;){var h=this.lruDataGPU.shift(),d=this.texData.get(h),m=d.shape,g=d.dtype;p-=this.computeBytes(m,g),this.read(h)}return f&&(s=this.endTimer(s),this.activeTimers.push(this.getQueryTime(s))),n},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixelsCanvas&&this.fromPixelsCanvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.floatPrecision=function(){var e=this;return Ee(function(){return e.abs(nt(1e-8)).get()>0?32:16})},e.prototype.throwIfNoData=function(e){if(!this.texData.has(e))throw new Error("WebGL backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends")},e.prototype.uploadToGPU=function(e){this.throwIfNoData(e);var t=this.texData.get(e),n=t.shape,r=t.values,a=t.texture,i=(t.dtype,t.usage);if(null==a){var o,s=null!=this.activeTimers;s&&(o=performance.now());var u=Dn(this.gpgpu.gl,n);t.texShape=u;var l=this.acquireTexture(e,u,i);t.texture=l,null!=r&&(this.gpgpu.uploadMatrixToTexture(l,u[0],u[1],r instanceof Float32Array?r:new Float32Array(r)),t.values=null,s&&(this.uploadWaitMs+=performance.now()-o))}else this.lruDataGPU.indexOf(e)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),this.lruDataGPU.push(e))},e.prototype.cacheOnCPU=function(e,t){var n=this.delayedStorage,r=this.texData.get(e),a=r.texture,i=r.texShape,o=r.dtype,s=r.usage;n&&null!=a&&(this.releaseTexture(e,a,i,s),r.texture=null,r.texShape=null),r.usage=Ht.UPLOAD,null!=t&&(r.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r=0&&this.lruDataGPU.splice(s,1),this.numBytesInGPU-=this.computeBytes(i,o),this.textureManager.releaseTexture(t,n,r)},e.prototype.acquireTexture=function(e,t,n){var r=this.texData.get(e),a=r.shape,i=r.dtype;return this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(a,i),this.textureManager.acquireTexture(t,n)},e.prototype.computeBytes=function(e,t){return b(e)*M(t)},e}();me.get("IS_BROWSER")&&me.registerBackend("webgl",function(){return new ua},2,Z);var la=Ye({abs_:function(e){var t=Ke(e,"x","abs");return me.engine.runKernel(function(e){return e.abs(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().step(-1))}}})}}),ca=Ye({acos_:function(e){var t=Ke(e,"x","acos");return me.engine.runKernel(function(e){return e.acos(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(nt(1).sub(t.toFloat().square()).sqrt()).neg()}}})}}),fa=Ye({acosh_:function(e){var t=Ke(e,"x","acosh");return me.engine.runKernel(function(e){return e.acosh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().square().sub(nt(1)).sqrt())}}})}}),pa=Ye({asin_:function(e){var t=Ke(e,"x","asin");return me.engine.runKernel(function(e){return e.asin(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(nt(1).sub(t.toFloat().square()).sqrt())}}})}}),ha=Ye({asinh_:function(e){var t=Ke(e,"x","asinh");return me.engine.runKernel(function(e){return e.asinh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(nt(1).add(t.toFloat().square()).sqrt())}}})}}),da=Ye({atan_:function(e){var t=Ke(e,"x","atan");return me.engine.runKernel(function(e){return e.atan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(nt(1).add(t.toFloat().square()))}}})}}),ma=Ye({atanh_:function(e){var t=Ke(e,"x","atanh");return me.engine.runKernel(function(e){return e.atanh(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(nt(1).sub(t.toFloat().square()))}}})}}),ga=Ye({ceil_:function(e){var t=Ke(e,"x","ceil");return me.engine.runKernel(function(e){return e.ceil(t)},{$x:t},function(e){return{$x:function(){return xt(e)}}})}}),ya=Ye({clipByValue_:function(e,t,n){var r=Ke(e,"x","clipByValue");return d(t<=n,"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."),me.engine.runKernel(function(e){return e.clip(r,t,n)},{$x:r},function(e){return{$x:function(){return e.where(r.greaterEqual(nt(t)).logicalAnd(r.lessEqual(nt(n))),xt(e))}}})}}),va=Ye({cos_:function(e){var t=Ke(e,"x","cos");return me.engine.runKernel(function(e){return e.cos(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sin().neg().mulStrict(e)}}})}}),ba=Ye({cosh_:function(e){var t=Ke(e,"x","cosh");return me.engine.runKernel(function(e){return e.cosh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().sinh().mulStrict(e)}}})}}),wa=Ye({erf_:function(e){var t=Ke(e,"x","erf");return d("int32"===t.dtype||"float32"===t.dtype,"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=t.toFloat()),me.engine.runKernel(function(e){return e.erf(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(nt(2/Math.sqrt(Math.PI)).mul(t.square().neg().exp()))}}})}}),xa=Ye({exp_:function(e){var t=Ke(e,"x","exp");return me.engine.runKernel(function(e,n){return n(e.exp(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n)}}})}}),_a=Ye({expm1_:function(e){var t=Ke(e,"x","expm1");return me.engine.runKernel(function(e){return e.expm1(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.exp())}}})}}),Sa=Ye({floor_:function(e){var t=Ke(e,"x","floor");return me.engine.runKernel(function(e){return e.floor(t)},{$x:t},function(e){return{$x:function(){return xt(e)}}})}}),Ea=Ye({log_:function(e){var t=Ke(e,"x","log");return me.engine.runKernel(function(e){return e.log(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat())}}})}}),Na=Ye({log1p_:function(e){var t=Ke(e,"x","log1p");return me.engine.runKernel(function(e){return e.log1p(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.add(nt(1)))}}})}}),Oa=Ye({logSigmoid_:function(e){var t=Ke(e,"x","logSigmoid");return me.engine.runKernel(function(e){return e.softplus(t.neg()).neg()},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.neg().sigmoid())}}})}}),ka=Ye({neg_:function(e){var t=Ke(e,"x","neg");return me.engine.runKernel(function(e){return e.neg(t)},{$x:t},function(e){return{$x:function(){return e.neg()}}})}}),Ia=Ye({reciprocal_:function(e){var t=Ke(e,"x","reciprocal");return me.engine.runKernel(function(e){return e.reciprocal(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.square().neg())}}})}}),Ca=Ye({round_:function(e){var t=Ke(e,"x","round");return me.engine.runKernel(function(e){return e.round(t)},{$x:t},function(e){return{$x:function(){return xt(e)}}})}}),Aa=Ye({rsqrt_:function(e){var t=Ke(e,"x","rsqrt");return me.engine.runKernel(function(e){return e.rsqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.pow(nt(1.5)).mul(nt(2))).neg()}}})}}),Pa=Ye({sigmoid_:function(e){var t=Ke(e,"x","sigmoid");return me.engine.runKernel(function(e,n){return n(e.sigmoid(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return e.mulStrict(n.mul(nt(1).sub(n)))}}})}}),Ta=Ye({sign_:function(e){var t=Ke(e,"x","sign");return me.engine.runKernel(function(e){return e.sign(t)},{$x:t},function(e){return{$x:function(){return xt(e)}}})}}),Ma=Ye({sin_:function(e){var t=Ke(e,"x","sin");return me.engine.runKernel(function(e){return e.sin(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cos().mulStrict(e)}}})}}),Ra=Ye({sinh_:function(e){var t=Ke(e,"x","sinh");return me.engine.runKernel(function(e){return e.sinh(t)},{$x:t},function(e){return{$x:function(){return t.toFloat().cosh().mulStrict(e)}}})}}),Da=Ye({softplus_:function(e){var t=Ke(e,"x","softplus");return me.engine.runKernel(function(e){return e.softplus(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.sigmoid())}}})}}),ja=Ye({sqrt_:function(e){var t=Ke(e,"x","sqrt");return me.engine.runKernel(function(e){return e.sqrt(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.toFloat().sqrt().mul(nt(2)))}}})}}),La=Ye({square_:function(e){var t=Ke(e,"x","square");return me.engine.runKernel(function(e){return e.square(t)},{$x:t},function(e){return{$x:function(){return e.mulStrict(t.toFloat().mul(nt(2)))}}})}}),za=Ye({step_:function(e,t){void 0===t&&(t=0);var n=Ke(e,"x","step");return me.engine.runKernel(function(e){return e.step(n,t)},{$x:n},function(e){return{$x:function(){return xt(e)}}})}}),Ba=Ye({tan_:function(e){var t=Ke(e,"x","tan");return me.engine.runKernel(function(e){return e.tan(t)},{$x:t},function(e){return{$x:function(){return e.divStrict(t.cos().square())}}})}}),Fa=Ye({tanh_:function(e){var t=Ke(e,"x","tanh");return me.engine.runKernel(function(e,n){return n(e.tanh(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return nt(1).sub(n.square()).mulStrict(e)}}})}});function Va(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}var Ua=Ye({batchNormalization2d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Ke(e,"x","batchNormalization"),l=Ke(t,"mean","batchNormalization"),c=Ke(n,"variance","batchNormalization");return null!=a&&(o=Ke(a,"scale","batchNormalization")),null!=i&&(s=Ke(i,"offset","batchNormalization")),d(2===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(2===l.rank||1===l.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."),d(2===c.rank||1===c.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."),null!=o&&d(2===o.rank||1===o.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."),null!=s&&d(2===s.rank||1===s.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."),$a(u,l,c,r,o,s)}}),Wa=Ye({batchNormalization3d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Ke(e,"x","batchNormalization"),l=Ke(t,"mean","batchNormalization"),c=Ke(n,"variance","batchNormalization");return null!=a&&(o=Ke(a,"scale","batchNormalization")),null!=i&&(s=Ke(i,"offset","batchNormalization")),d(3===u.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+u.rank+"."),d(3===l.rank||1===l.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."),d(3===c.rank||1===c.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."),null!=o&&d(3===o.rank||1===o.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."),null!=s&&d(3===s.rank||1===s.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."),$a(u,l,c,r,o,s)}}),qa=Ye({batchNormalization4d_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u=Ke(e,"x","batchNormalization"),l=Ke(t,"mean","batchNormalization"),c=Ke(n,"variance","batchNormalization");return null!=a&&(o=Ke(a,"scale","batchNormalization")),null!=i&&(s=Ke(i,"offset","batchNormalization")),d(4===u.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+u.rank+"."),d(4===l.rank||1===l.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."),d(4===c.rank||1===c.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."),null!=o&&d(4===o.rank||1===o.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."),null!=s&&d(4===s.rank||1===s.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."),$a(u,l,c,r,o,s)}}),$a=Ye({batchNormalization_:function(e,t,n,r,a,i){void 0===r&&(r=.001);var o,s,u,l=Ke(e,"x","batchNormalization"),c=Ke(t,"mean","batchNormalization"),f=Ke(n,"variance","batchNormalization");return null!=a&&(o=Ke(a,"scale","batchNormalization")),null!=i&&(s=Ke(i,"offset","batchNormalization")),d(c.rank===f.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),d(null==s||c.rank===s.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),d(null==o||c.rank===o.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,me.engine.runKernel(function(e){return e.batchNormalization(u,Va(c),Va(f),r,Va(o),Va(s))},{$x:l,$mean:c,$variance:f,$scale:o,$offset:s},function(e){var t=null==o?nt(1):o,n=Mt(c.shape,u.shape),a=[];if(1===c.rank){for(var i=0;i=2&&i.rank>=2&&a.rank===i.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."),d(w(c,f),"Error in matMul: outer dimensions ("+c+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."),d(o===s,"Error in matMul: inner shapes ("+o+") and ("+s+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match.");var m=a.shape.slice(0,-2).concat([u,l]),g=n?a.as3D(p,o,u):a.as3D(p,u,o),y=r?i.as3D(h,l,s):i.as3D(h,s,l);return me.engine.runKernel(function(e){return e.batchMatMul(g,y,n,r)},{$a:g,$b:y},function(e){return n||r?!n&&r?{$a:function(){return e.matMul(y.toFloat(),!1,!1)},$b:function(){return e.matMul(g.toFloat(),!0,!1)}}:n&&!r?{$a:function(){return y.toFloat().matMul(e,!1,!0)},$b:function(){return g.toFloat().matMul(e,!1,!1)}}:{$a:function(){return y.toFloat().matMul(e,!0,!0)},$b:function(){return e.matMul(g.toFloat(),!0,!0)}}:{$a:function(){return e.matMul(y.toFloat(),!1,!0)},$b:function(){return g.toFloat().matMul(e,!0,!1)}}}).reshape(m)}}),oi=Ye({dot_:function(e,t){var n=Ke(e,"t1","dot"),r=Ke(t,"t2","dot");d(!(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+".");var a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return d(a===i,"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+i+"."),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),si=Ye({outerProduct_:function(e,t){var n=Ke(e,"v1","outerProduct"),r=Ke(t,"v2","outerProduct");return d(1===n.rank&&1===r.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),ui=Ye({reverse_:function(e,t){var n=Ke(e,"x","reverse");if(0===n.rank)return n.clone();var r=Le(t,n.shape);return me.engine.runKernel(function(e){return e.reverse(n,r)},{$x:n},function(e){return{$x:function(){return e.reverse(r)}}}).reshapeAs(n)}}),li=Ye({reverse1d_:function(e){var t=Ke(e,"x","reverse");return d(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),ui(t,0)}}),ci=Ye({reverse2d_:function(e,t){var n=Ke(e,"x","reverse");return d(2===n.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+n.rank+"."),ui(n,t)}}),fi=Ye({reverse3d_:function(e,t){var n=Ke(e,"x","reverse");return d(3===n.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+n.rank+"."),ui(n,t)}}),pi=Ye({reverse4d_:function(e,t){var n=Ke(e,"x","reverse");return d(4===n.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+n.rank+"."),ui(n,t)}}),hi=Ye({maxPool_:function(e,t,n,r,a){var i=Ke(e,"x","maxPool"),o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ga(o.shape,t,n,r,a),l=me.engine.runKernel(function(e,t){return t(e.maxPool(o,u))},{x:o},function(e,a){var i=a[0];return{x:function(){return function(e,t,n,r,a,i,o){var s=Ke(e,"dy","maxPoolBackprop"),u=Ke(t,"input","maxPoolBackprop"),l=Ke(n,"output","maxPoolBackprop");d(u.rank===s.rank,"Rank of input ("+u.rank+") does not match rank of dy ("+s.rank+")"),d(4===s.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+s.rank+"."),d(4===u.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+".");var c=Ga(u.shape,r,a,i,o);return me.engine.runKernel(function(e){return e.maxPoolBackprop(s,u,l,c)},{$dy:s,$input:u})}(e,o,i,t,n,r)}}});return s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),di=Ye({avgPool_:function(e,t,n,r,a){var i=Ke(e,"x","avgPool");d("float32"===i.dtype,"The input dtype to avgPool must be float32");var o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===o.rank,"Error in avgPool: x must be rank 4 but got rank "+o.rank+"."),null!=a&&d(x(r),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+".");var u=Ga(o.shape,t,n,r),l=me.engine.runKernel(function(e){return e.avgPool(o,u)},{x:o},function(e){return{x:function(){return function(e,t,n,r,a){var i=Ke(e,"dy","avgPoolBackprop"),o=Ke(t,"input","avgPoolBackprop");d(o.rank===i.rank,"Rank of input ("+o.rank+") does not match rank of dy ("+i.rank+")");var s=o,u=i,l=!1;3===o.rank&&(l=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]),u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===u.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),d(4===s.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+".");var c=Ga(s.shape,n,r,a),f=me.engine.runKernel(function(e){return e.avgPoolBackprop(u,s,c)},{dy4D:u,input4D:s});return l?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(e,o,t,n,r)}}});return l=l.cast(i.dtype),s?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}}),mi=Ye({slice_:function(e,t,n){var r,a,i=Ke(e,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof t?[t].concat(new Array(i.rank-1).fill(0)):t.length=0?e:(d(-1===e,"Bad value in size"),i.shape[t]-r[t])}),function(e,t,n){d(e.rank===t.length,"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."),d(e.rank===n.length,"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+").");for(var r=0;r0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Mt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.reshape(r.shape)}}})}}),Wi=Ye({addN_:function(e){d(Array.isArray(e),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(e.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length});var t=e.map(function(e,t){return Ke(e,"tensors"+t,"addN")}),n=t[0];t.forEach(function(e){if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(e){if(!w(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=t;return me.engine.runKernel(function(e){return e.addN(t)},r,function(e){var n={};return t.forEach(function(t,r){n[r]=function(){return e.clone()}}),n})}}),qi=Ye({addStrict_:function(e,t){return m(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),$i=Ye({atan2_:function(e,t){var n=Ke(e,"a","atan2"),r=Ke(t,"b","atan2");ne(n,r);var a=Rt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.atan2(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=Ui(n.square(),r.square()),i=e.mul(r.div(t)),o=Mt(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var t=Ui(n.square(),r.square()),i=ka(e.mul(n.div(t))),o=Mt(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Gi=Ye({div_:function(e,t){var n,r=Ke(e,"a","div"),a=Ke(t,"b","div");if(ne(r,a),"int32"===r.dtype&&"int32"===a.dtype)return Ki(r,a);n=function(e){return e.realDivide(r,a)};var i=Rt(r.shape,a.shape);return me.engine.runKernel(n,{$a:r,$b:a},function(e){return{$a:function(){var t=e.div(a.toFloat()),n=Mt(r.shape,i);return n.length>0?t.sum(n).reshape(r.shape):t},$b:function(){var t=e.mul(r.toFloat()),n=Mt(a.shape,i);n.length>0&&(t=t.sum(n).reshape(a.shape));var o=a.square();return t.div(o.toFloat()).neg()}}})}}),Hi=Ye({divStrict_:function(e,t){return m(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),Ki=Ye({floorDiv_:function(e,t){var n=Ke(e,"a","floorDiv"),r=Ke(t,"b","floorDiv");ne(n,r);var a=Rt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.floorDiv(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.div(r.toFloat()),i=Mt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Mt(r.shape,a);i.length>0&&(t=t.sum(i).reshape(r.shape));var o=r.square();return t.div(o.toFloat()).neg()}}})}}),Xi=Ye({maximum_:function(e,t){var n=Ke(e,"a","maximum"),r=Ke(t,"b","maximum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Rt(n.shape,r.shape),me.engine.runKernel(function(e){return e.maximum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.greaterEqual(r).toFloat())},$b:function(){return e.mul(n.less(r).toFloat())}}})}}),Yi=Ye({maximumStrict_:function(e,t){return m(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),Ji=Ye({minimum_:function(e,t){var n=Ke(e,"a","minimum"),r=Ke(t,"b","minimum");return ne(n,r),"bool"===n.dtype&&(n=n.toInt()),"bool"===r.dtype&&(r=r.toInt()),Rt(n.shape,r.shape),me.engine.runKernel(function(e){return e.minimum(n,r)},{$a:n,$b:r},function(e){return{$a:function(){return e.mul(n.lessEqual(r).toFloat())},$b:function(){return e.mul(n.greater(r).toFloat())}}})}}),Zi=Ye({minimumStrict_:function(e,t){return m(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),Qi=Ye({mod_:function(e,t){var n=Ke(e,"a","mod"),r=Ke(t,"b","mod");ne(n,r);var a=Rt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.mod(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=Mt(n.shape,a);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(r).floor().neg()),i=Mt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),eo=Ye({modStrict_:function(e,t){return m(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),to=Ye({mul_:function(e,t){var n=Ke(e,"a","mul"),r=Ke(t,"b","mul");ne(n,r);var a=Rt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.multiply(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e.mul(r.toFloat()),i=Mt(n.shape,a);return i.length>0?t.sum(i).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),i=Mt(r.shape,a);return i.length>0?t.sum(i).reshape(r.shape):t}}})}}),no=Ye({mulStrict_:function(e,t){return m(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),ro=Ye({pow_:function(e,t){var n=Ke(e,"base","pow"),r=Ke(t,"exp","pow"),a=Rt(n.shape,r.shape);return e=n.cast(St(n.dtype,r.dtype)),t=r.cast(St(n.dtype,r.dtype)),me.engine.runKernel(function(e,t){return t(e.pow(n,r))},{$base:n,$exp:r},function(e,t){var i=t[0];return{$base:function(){var t=e.mul(r.toFloat().mul(i.div(n))),o=Mt(n.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(n.shape)},$exp:function(){var t=e.mul(i.mul(n.log()).toFloat()),o=Mt(r.shape,a);return o.length>0&&(t=t.sum(o)),t.reshape(r.shape)}}})}}),ao=Ye({powStrict_:function(e,t){return m(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}}),io=Ye({squaredDifference_:function(e,t){var n=Ke(e,"a","squaredDifference"),r=Ke(t,"b","squaredDifference");return ne(n,r),Rt(n.shape,r.shape),me.engine.runKernel(function(e){return e.squaredDifference(n,r)},{$a:n,$b:r},function(e){var t=nt(2);return{$a:function(){return e.mul(n.sub(r).mul(t))},$b:function(){return e.mul(r.sub(n).mul(t))}}})}}),oo=Ye({squaredDifferenceStrict_:function(e,t){return m(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),so=Ye({sub_:function(e,t){var n=Ke(e,"a","sub"),r=Ke(t,"b","sub");ne(n,r);var a=Rt(n.shape,r.shape);return me.engine.runKernel(function(e){return e.subtract(n,r)},{$a:n,$b:r},function(e){return{$a:function(){var t=e,r=Mt(n.shape,a);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,n=Mt(r.shape,a);return n.length>0&&(t=t.sum(n)),t.neg().reshape(r.shape)}}})}}),uo=Ye({subStrict_:function(e,t){return m(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),lo=Ye({logicalAnd_:function(e,t){var n=Ke(e,"a","logicalAnd","bool"),r=Ke(t,"b","logicalAnd","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Rt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalAnd(n,r)},{$a:n,$b:r})}}),co=Ye({logicalNot_:function(e){var t=Ke(e,"x","logicalNot","bool");return d("bool"===t.dtype,"Error Array must be of type bool."),me.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})}}),fo=Ye({logicalOr_:function(e,t){var n=Ke(e,"a","logicalOr","bool"),r=Ke(t,"b","logicalOr","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Rt(n.shape,r.shape),me.engine.runKernel(function(e){return e.logicalOr(n,r)},{$a:n,$b:r})}}),po=Ye({logicalXor_:function(e,t){var n=Ke(e,"a","logicalXor","bool"),r=Ke(t,"b","logicalXor","bool");return d("bool"===n.dtype&&"bool"===r.dtype,"Error Array must be of type bool."),Rt(n.shape,r.shape),fo(e,t).logicalAnd(lo(e,t).logicalNot())}}),ho=Ye({where_:function(e,t,n){var r=Ke(t,"a","where"),a=Ke(n,"b","where"),i=Ke(e,"condition","where","bool");return d("bool"===i.dtype,"Error Condition must be of type bool."),m(r.shape,a.shape,"Error in where: "),1===i.rank?d(i.shape[0]===r.shape[0],"The first dimension of `a` must match the size of `condition`."):m(i.shape,a.shape,"Error in where: "),me.engine.runKernel(function(e){return e.select(i,r,a)},{$condition:i,$a:r,$b:a},function(e){return{$condition:function(){return xt(i)},$a:function(){return e.mul(i.cast(r.dtype))},$b:function(){return e.mul(i.logicalNot().cast(a.dtype))}}})}}),mo=function(e){return l(this,void 0,void 0,function(){var t,n,r;return c(this,function(a){switch(a.label){case 0:return d("bool"===(t=Ke(e,"condition","where","bool")).dtype,"Condition must be of type bool."),[4,t.data()];case 1:return n=a.sent(),r=oa(t.shape,n),e!==t&&t.dispose(),[2,r]}})})},go=Ye({elu_:function(e){var t=Ke(e,"x","elu");return me.engine.runKernel(function(e,n){return n(e.elu(t))},{$x:t},function(e,t){var n=t[0];return{$x:function(){return me.engine.runKernel(function(t){return t.eluDer(e,n)},{dy:e,y:n})}}})}}),yo=Ye({leakyRelu_:function(e,t){void 0===t&&(t=.2);var n=Ke(e,"x","leakyRelu");return Xi(nt(t).mul(n),n)}}),vo=Ye({prelu_:function(e,t){var n=Ke(e,"x","prelu"),r=Ke(t,"alpha","prelu"),a=nt(0);return Xi(a,n).add(r.mul(Ji(a,n)))}}),bo=Ye({relu_:function(e){var t=Ke(e,"x","relu");return"bool"===t.dtype?t.toInt():me.engine.runKernel(function(e){return e.relu(t)},{$x:t},function(e){var n=t.step();return{$x:function(){return e.mulStrict(n.toFloat())}}})}}),wo=Ye({selu_:function(e){var t=Ke(e,"x","selu");return me.engine.runKernel(function(e){return e.selu(t)},{$x:t},function(e){return{$x:function(){var n=t.greater(nt(0)),r=nt(pr),a=nt(hr),i=e.mul(a),o=e.mul(r).mul(t.toFloat().exp());return ho(n,i,o)}}})}}),xo=Ye({transpose_:function(e,t){var n=Ke(e,"x","transpose");return null==t&&(t=n.shape.map(function(e,t){return t}).reverse()),d(n.rank===t.length,"Error in transpose: rank of input "+n.rank+" must match length of perm "+t+"."),t.forEach(function(e){d(e>=0&&ea)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+t);var i=me.engine.runKernel(function(e){return e.topk(r,t,n)},{$x:r});return{values:i[0],indices:i[1]}}});!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"}(Oo||(Oo={}));var Ro=Ye({absoluteDifference_:function(e,t,n,r){void 0===r&&(r=Oo.SUM_BY_NONZERO_WEIGHTS);var a=Ke(e,"labels","absoluteDifference"),i=Ke(t,"predictions","absoluteDifference"),o=null;null!=n&&(o=Ke(n,"weights","absoluteDifference")),m(a.shape,i.shape,"Error in absoluteDifference: ");var s=a.sub(i).abs();return Do(s,o,r)}}),Do=Ye({computeWeightedLoss_:function(e,t,n){void 0===n&&(n=Oo.SUM_BY_NONZERO_WEIGHTS);var r=Ke(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=Ke(t,"weights","computeWeightedLoss"));var i=null==a?r:r.mul(a);if(n===Oo.NONE)return i;if(n===Oo.SUM)return i.sum();if(n===Oo.MEAN){if(null==a)return i.mean();var o=b(r.shape)/b(a.shape),s=i.sum().div(a.sum());return o>1?s.div(nt(o)):s}if(n===Oo.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(nt(r.size));var u=a.mul(lt(r.shape)).notEqual(nt(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),jo=Ye({cosineDistance_:function(e,t,n,r,a){void 0===a&&(a=Oo.SUM_BY_NONZERO_WEIGHTS);var i=Ke(e,"labels","cosineDistance"),o=Ke(t,"predictions","cosineDistance"),s=null;null!=r&&(s=Ke(r,"weights","cosineDistance")),m(i.shape,o.shape,"Error in cosineDistance: ");var u=nt(1).sub(i.mul(o).sum(n,!0));return Do(u,s,a)}}),Lo=Ye({hingeLoss_:function(e,t,n,r){void 0===r&&(r=Oo.SUM_BY_NONZERO_WEIGHTS);var a=Ke(e,"labels","hingeLoss"),i=Ke(t,"predictions","hingeLoss"),o=null;null!=n&&(o=Ke(n,"weights","hingeLoss")),m(a.shape,i.shape,"Error in hingeLoss: ");var s=nt(1);a=nt(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return Do(u,o,r)}}),zo=Ye({huberLoss_:function(e,t,n,r,a){void 0===r&&(r=1),void 0===a&&(a=Oo.SUM_BY_NONZERO_WEIGHTS);var i=Ke(e,"labels","huberLoss"),o=Ke(t,"predictions","huberLoss"),s=null;null!=n&&(s=Ke(n,"weights","huberLoss")),m(i.shape,o.shape,"Error in huberLoss: ");var u=nt(r),l=o.sub(i).abs(),c=Ji(l,u),f=l.sub(c),p=nt(.5).mul(c.square()).add(u.mul(f));return Do(p,s,a)}}),Bo=Ye({logLoss_:function(e,t,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=Oo.SUM_BY_NONZERO_WEIGHTS);var i=Ke(e,"labels","logLoss"),o=Ke(t,"predictions","logLoss"),s=null;null!=n&&(s=Ke(n,"weights","logLoss")),m(i.shape,o.shape,"Error in logLoss: ");var u=nt(1),l=nt(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return Do(c,s,a)}}),Fo=Ye({meanSquaredError_:function(e,t,n,r){void 0===r&&(r=Oo.SUM_BY_NONZERO_WEIGHTS);var a=Ke(e,"labels","meanSquaredError"),i=Ke(t,"predictions","meanSquaredError"),o=null;null!=n&&(o=Ke(n,"weights","meanSquaredError")),m(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return Do(s,o,r)}}),Vo=Ye({sigmoidCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Oo.SUM_BY_NONZERO_WEIGHTS);var i=Ke(e,"multiClassLabels","sigmoidCrossEntropy"),o=Ke(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Ke(n,"weights","sigmoidCrossEntropy")),m(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=nt(r),l=nt(1),c=nt(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var f=function(e,t){var n=Ke(e,"labels","sigmoidCrossEntropyWithLogits"),r=Ke(t,"logits","sigmoidCrossEntropyWithLogits");m(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),i=r.mul(n),o=r.abs().neg().exp().log1p();return a.sub(i).add(o)}(i,o);return Do(f,s,a)}}),Uo=Ye({softmaxCrossEntropy_:function(e,t,n,r,a){void 0===r&&(r=0),void 0===a&&(a=Oo.SUM_BY_NONZERO_WEIGHTS);var i=Ke(e,"onehotLabels","softmaxCrossEntropy"),o=Ke(t,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Ke(n,"weights","softmaxCrossEntropy")),m(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=nt(r),l=nt(1),c=nt(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var f=function(e,t,n){if(void 0===n&&(n=-1),-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);return _e(function(e,t){var r=t.logSumExp([n],!0),a=t.toFloat().sub(r);return{value:a.mul(e).neg().sum([n]),gradFunc:function(t){var r=je(t.shape,[n]);return[t.reshape(r).mul(e.toFloat().sub(a.exp())),t.reshape(r).mul(a.exp().sub(e.toFloat()))]}}})(e,t)}(i,o);return Do(f,s,a)}}),Wo=Object.freeze({get Reduction(){return Oo},absoluteDifference:Ro,computeWeightedLoss:Do,cosineDistance:jo,hingeLoss:Lo,huberLoss:zo,logLoss:Bo,meanSquaredError:Fo,sigmoidCrossEntropy:Vo,softmaxCrossEntropy:Uo});function qo(e,t){return void 0===t&&(t=!1),me.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var n=e.shape[0],r=e.shape[1],a=Vr(n),i=e.clone(),o=at([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(e){var t,u=i,l=s,c=a;t=me.engine.tidy(function(){var t=i.slice([e,e],[n-e,1]),u=t.norm(),l=i.slice([e,e],[1,1]),c=l.sign().neg(),f=l.sub(c.mul(u)),p=t.div(f);s=1===p.shape[0]?o.clone():o.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var h=c.matMul(f).div(u).neg(),d=i.slice([e,0],[n-e,r]),m=h.mul(s);i=0===e?d.sub(m.matMul(s.transpose().matMul(d))):i.slice([0,0],[e,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=a.slice([0,e],[n,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[n,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,i,a]}),s=t[0],i=t[1],a=t[2],Oe([u,l,c])},c=0;cr&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]})}var $o=Ye({gramSchmidt_:function(e){var t;if(Array.isArray(e)){t=!1,d(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var n=e[0].shape[0],r=1;r0)for(var n=0;n= 2, but got rank "+e.rank);if(2===e.rank)return qo(e,t);var n=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),r=[],a=[];return ia(e.reshape([n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var n=qo(e,t),i=n[0],o=n[1];r.push(i),a.push(o)}),[na(r,0).reshape(e.shape),na(a,0).reshape(e.shape)]}}),Ho=Object.freeze({gramSchmidt:$o,qr:Go});function Ko(e,t,n,r,a){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY);var i=e.shape[0];return n=Math.min(n,i),d(0<=r&&r<=1,"iouThreshold must be in [0, 1], but was '"+r+"'"),d(2===e.rank,"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"),d(4===e.shape[1],"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),d(1===t.rank,"scores must be a 1D tensor"),d(t.shape[0]===i,"scores has incompatible shape with boxes. Expected "+i+", but was "+t.shape[0]),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a}}var Xo=Ye({resizeBilinear_:function(e,t,n){void 0===n&&(n=!1);var r=Ke(e,"images","resizeBilinear");d(3===r.rank||4===r.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeBilinear(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Yo=Ye({resizeNearestNeighbor_:function(e,t,n){void 0===n&&(n=!1);var r=Ke(e,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."),d(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),d("float32"===r.dtype||"int32"===r.dtype,"`images` must have `int32` or `float32` as dtype");var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=t[0],s=t[1],u=me.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,o,s,n)},{batchImages:a},function(e,t){return{batchImages:function(){return me.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Jo=Ye({nonMaxSuppression_:function(e,t,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=Ke(e,"boxes","nonMaxSuppression"),o=Ke(t,"scores","nonMaxSuppression"),s=Ko(i,o,n,r,a);return n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,me.engine.runKernel(function(e){return e.nonMaxSuppression(i,o,n,r,a)},{$boxes:i})}}),Zo=Object.freeze({resizeBilinear:Xo,resizeNearestNeighbor:Yo,nonMaxSuppression:Jo,nonMaxSuppressionAsync:function(e,t,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),l(this,void 0,void 0,function(){var i,o,s,u,l,f;return c(this,function(c){switch(c.label){case 0:return i=Ke(e,"boxes","nonMaxSuppressionAsync"),o=Ke(t,"scores","nonMaxSuppressionAsync"),s=Ko(i,o,n,r,a),n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold,[4,i.data()];case 1:return u=c.sent(),[4,o.data()];case 2:return l=c.sent(),f=It(u,l,n,r,a),i!==e&&i.dispose(),o!==t&&o.dispose(),[2,f]}})})},cropAndResize:function(e,t,n,r,a,i){var o=Ke(e,"image","cropAndResize","float32"),s=Ke(t,"boxes","cropAndResize","float32"),u=Ke(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return d(4===o.rank,"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."),d(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."),d(1===u.rank&&u.shape[0]===l,"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."),d("int32"===u.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+u.dtype+"."),d(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),d(r[0]>=1&&r[1]>=1,"cropSize must be atleast [1,1], but was "+r),d("bilinear"===a||"nearest"===a,"method must be bilinear or nearest, but was "+a),me.engine.runKernel(function(e,t){return e.cropAndResize(o,s,u,r,a,i)},{$image:o,$boxes:s})}}),Qo=Object.freeze({image:Zo,linalg:Ho,losses:Wo,op:Ye,batchNormalization2d:Ua,batchNormalization3d:Wa,batchNormalization4d:qa,batchNormalization:$a,complex:Ze,real:Qe,imag:et,concat:gr,concat1d:yr,concat2d:vr,concat3d:br,concat4d:wr,split:xr,conv1d:ei,conv2d:ti,depthwiseConv2d:ni,separableConv2d:ri,conv2dTranspose:ai,matMul:ii,dot:oi,outerProduct:si,reverse:ui,reverse1d:li,reverse2d:ci,reverse3d:fi,reverse4d:pi,maxPool:hi,avgPool:di,slice:mi,slice1d:gi,slice2d:yi,slice3d:vi,slice4d:bi,abs:la,acos:ca,acosh:fa,asin:pa,asinh:ha,atan:da,atanh:ma,ceil:ga,clipByValue:ya,cos:va,cosh:ba,erf:wa,exp:xa,expm1:_a,floor:Sa,log:Ea,log1p:Na,logSigmoid:Oa,neg:ka,reciprocal:Ia,round:Ca,rsqrt:Aa,sigmoid:Pa,sign:Ta,sin:Ma,sinh:Ra,softplus:Da,sqrt:ja,square:La,step:za,tan:Ba,tanh:Fa,all:wi,any:xi,argMax:_i,argMin:Si,logSumExp:Ei,max:Ni,mean:Oi,min:ki,moments:Ii,sum:Ci,equal:Ai,equalStrict:Pi,greater:Ti,greaterEqual:Mi,greaterEqualStrict:Ri,greaterStrict:Di,less:ji,lessEqual:Li,lessEqualStrict:zi,lessStrict:Bi,notEqual:Fi,notEqualStrict:Vi,add:Ui,addN:Wi,addStrict:qi,atan2:$i,div:Gi,divStrict:Hi,floorDiv:Ki,maximum:Xi,maximumStrict:Yi,minimum:Ji,minimumStrict:Zi,mod:Qi,modStrict:eo,mul:to,mulStrict:no,pow:ro,powStrict:ao,squaredDifference:io,squaredDifferenceStrict:oo,sub:so,subStrict:uo,elu:go,leakyRelu:yo,prelu:vo,relu:bo,selu:wo,logicalAnd:lo,logicalNot:co,logicalOr:fo,logicalXor:po,where:ho,whereAsync:mo,buffer:Mr,toPixels:Tr,print:Rr,batchToSpaceND:Dr,cast:jr,clone:Lr,cumsum:zr,depthToSpace:Br,expandDims:Fr,eye:Vr,fromPixels:Ur,multinomial:Wr,oneHot:qr,pad:$r,pad1d:Gr,pad2d:Hr,pad3d:Kr,pad4d:Xr,rand:Yr,randomNormal:Jr,randomUniform:Zr,reshape:Qr,spaceToBatchND:ea,squeeze:ta,stack:na,tile:ra,truncatedNormal:aa,unstack:ia,fill:ft,linspace:pt,ones:lt,range:ht,scalar:nt,tensor:tt,tensor1d:rt,tensor2d:at,tensor3d:it,tensor4d:ot,tensor5d:st,tensor6d:ut,zeros:ct,onesLike:wt,zerosLike:xt,transpose:xo,softmax:Je,localResponseNormalization:_o,norm:So,gather:ko,unsortedSegmentSum:Io,basicLSTMCell:Co,multiRNNCell:Ao,movingAverage:Po,stridedSlice:To,topk:Mo}),es=function(){function e(){this.blockSize=48,this.data=new WeakMap,this.firstUse=!0,me.get("IS_BROWSER")&&(this.canvas=document.createElement("canvas"))}return e.prototype.register=function(e,t,n){if(this.firstUse&&(this.firstUse=!1,me.get("IS_NODE")&&Ie("\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============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:n})},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.throwIfNoData(e),this.data.get(e).values=t},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var n,r;if(me.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else if(e instanceof ImageData)n=e.data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(null==this.canvas)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.canvas.width=e.width,this.canvas.height=e.height,this.canvas.getContext("2d").drawImage(e,0,0,e.width,e.height),n=this.canvas.getContext("2d").getImageData(0,0,e.width,e.height).data}if(4===t)r=new Int32Array(n);else{var a=e.width*e.height;r=new Int32Array(a*t);for(var i=0;ip&&(p=m,h=d)}u[c]=h}return o},e.prototype.cumsum=function(e,t,n,r){if(this.assertNotComplex(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=St(e.dtype,"int32"),i=ct(e.shape,a),o=i.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=r?function(e,t){return e+u-t-1}:function(e,t){return e+t},c=0;ct?1:0})},e.prototype.greaterEqual=function(e,t){return this.assertNotComplex([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){this.assertNotComplex(e,"logicalNot");for(var t=e.dataSync(),n=new Int32Array(t.length),r=0;r1||1===t.rank?1:t.shape[1],c=0;c=0&&t>=0?n:(n+t)%t})},e.prototype.max=function(e,t){this.assertNotComplex(e,"max"),ze("max",t,e.rank);for(var n=De(e.shape,t),r=n[0],a=n[1],i=ct(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;lf&&(f=h)}s[l]=f}return i},e.prototype.maximum=function(e,t){return this.assertNotComplex([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){this.assertNotComplex(e,"all"),ze("all",t,e.rank);for(var n=De(e.shape,t),r=n[0],a=n[1],i=ct(r,e.dtype),o=b(a),s=i.dataSync(),u=e.dataSync(),l=0;l0?n[r]=1:n[r]=0;return Q.make(e.shape,{values:n})},e.prototype.round=function(e){this.assertNotComplex(e,"round");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r.5?n[r]=Math.ceil(t[r]):n[r]=a%2==0?a:a+1}return Q.make(e.shape,{values:n})},e.prototype.exp=function(e){this.assertNotComplex(e,"exp");for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r=0?a:Math.exp(a)-1}return Q.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){this.assertNotComplex([e,t],"eluDer");for(var n=new Float32Array(t.size),r=t.dataSync(),a=e.dataSync(),i=0;i=1?a[i]:a[i]*(o+1)}return Q.make(t.shape,{values:n})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return Q.make(e.shape,{values:t})},e.prototype.clip=function(e,t,n){this.assertNotComplex(e,"clip");for(var r=new Float32Array(e.size),a=e.dataSync(),i=0;in?n:o-t,s=r[a]0?1:t}return Q.make(e.shape,{values:n})},e.prototype.conv2d=function(e,t,n){this.assertNotComplex([e,t],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Mr(n.outShape,e.dtype),c=e.dataSync(),f=t.dataSync(),p=l.values,h=0;h=n.inHeight))for(var x=b*t.strides[0],_=d+w*e.strides[1],S=0;S=n.inWidth))for(var I=x+O*t.strides[1],C=_+k*n.inChannels,A=I,P=0;P=n.inHeight))for(var _=w*t.strides[0],S=m+x*e.strides[1],E=0;E=n.inWidth))for(var C=_+k*t.strides[1],A=S+I*n.inChannels,P=N,T=C,M=0;Mx?x=O:"avg"===n&&(_+=O,S++)}if(isNaN(x))break}s.set("avg"===n?_/S:x,f,h,y,p)}return s.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var n=Mr(t.outShape,"int32"),r=t.strideHeight,a=t.strideWidth,i=t.filterHeight,o=t.filterWidth,s=t.padInfo.top,u=t.padInfo.left,l=0;lb&&(b=N,w=_*o+E)}n.set(w,l,f,m,c)}return n.toTensor()},e.prototype.maxPoolBackprop=function(e,t,n,r){this.assertNotComplex([t,n],"maxPoolBackprop");for(var a=this.maxPoolPositions(t,r),i=r.strideHeight,o=r.strideWidth,s=r.filterHeight,u=r.filterWidth,l=u-1-r.padInfo.left,c=s-1-r.padInfo.top,f=Mr(t.shape,"float32"),p=0;p=r.outHeight||Math.floor(w)!==w))for(var x=0;x=r.outWidth||Math.floor(_)!==_)){var S=s*u-1-a.get(p,w,_,h)===b*u+x?1:0;0!==S&&(v+=e.get(p,w,_,h)*S)}}}f.set(v,p,d,m,h)}return f.toTensor()},e.prototype.avgPoolBackprop=function(e,t,n){this.assertNotComplex([e,t],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=o-1-n.padInfo.left,u=i-1-n.padInfo.top,l=Mr(t.shape,"float32"),c=1/(i*o),f=0;f=n.outHeight||Math.floor(b)!==b))for(var w=0;w=n.outWidth||Math.floor(x)!==x||(y+=e.get(f,b,x,p))}}l.set(y*c,f,h,d,p)}return l.toTensor()},e.prototype.cast=function(e,t){return Nt(e,t,this)},e.prototype.reshape=function(e,t){return Ot(e,t)},e.prototype.avgPool=function(e,t){return this.assertNotComplex(e,"avgPool"),this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,n,r){this.assertNotComplex(e,"resizeBilinear");for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=Mr([i,t,n,u],e.dtype),c=[r&&t>1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/h[0],m=p[1]/h[1],g=0;g1?o-1:o,r&&n>1?s-1:s],f=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=0;p1?i-1:i,n&&c>1?o-1:o],h=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=1/(p[0]/h[0]),m=1/(p[1]/h[1]),g=2*Math.ceil(d)+2,y=2*Math.ceil(m)+2,v=0;v=l))for(var C=0;C=c)){var P=p[0]*(I/h[0]),T=p[1]*(A/h[1]),M=Math.min(i-1,n?Math.round(P):Math.floor(P)),R=Math.min(o-1,n?Math.round(T):Math.floor(T));b===M&&w===R&&(O+=e.get(v,I,A,N))}}}f.set(O,v,b,w,N)}return f.toTensor()},e.prototype.batchNormalization=function(e,t,n,r,a,i){this.assertNotComplex([e,t,n,a,i],"batchNormalization");for(var o=e.dataSync(),s=t.dataSync(),u=n.dataSync(),l=a?a.dataSync():new Float32Array([1]),c=i?i.dataSync():new Float32Array([0]),f=new Float32Array(o.length),p=c.length,h=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w=p&&(g=0),y>=m&&(y=0),v>=h&&(v=0),b>=d&&(b=0);return ot(f,e.shape)},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){this.assertNotComplex(e,"localResponseNormalization4D");var i=e.shape[3],o=i-1,s=e.dataSync(),u=b(e.shape),l=new Float32Array(u);function c(e){for(var n=e%i,r=e-n+Math.max(0,n-t),a=e-n+Math.min(n+t,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var f=0;f=0&&e.get(i)1,"blockSize should be > 1 for depthToSpace, but was: "+t);for(var r=e.shape[0],a=e.shape[1],i=e.shape[2],o=e.shape[3],s=a*t,u=i*t,l=o/(t*t),c=e.dataSync(),f=new Float32Array(r*s*u*l),p=0,h=0;h=s))for(var k=p>1?(E-_)*(u-1)/(p-1):0,I=h>1?(N-S)*(l-1)/(h-1):0,C=0;C1?_*(u-1)+C*k:.5*(_+E)*(u-1);if(A<0||A>u-1)for(var P=0;P1?S*(l-1)+P*I:.5*(S+N)*(l-1))<0||$>l-1)for(T=0;T1?S*(l-1)+P*I:.5*(S+N)*(l-1))<0||$>l-1)for(T=0;T0,"scheme must not be an empty string.");var r=e.getInstance();d(null==r.managers[t],"A model store manager is already registered for scheme '"+t+"'."),r.managers[t]=n},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function hs(e){if(-1===e.indexOf(fs))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ps.getSchemes().join(","));return{scheme:e.split(fs)[0],path:e.split(fs)[1]}}function ds(e,t,n){return void 0===n&&(n=!1),l(this,void 0,void 0,function(){var r,a,i,o,s,u,l,f,p;return c(this,function(c){switch(c.label){case 0:return d(e!==t,"Old path and new path are the same: '"+e+"'"),d((r=cs.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),d(r.length<2,"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."),a=r[0],d((i=cs.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),d(i.length<2,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."),o=i[0],s=hs(e).scheme,u=hs(e).path,l=s===hs(e).scheme,[4,a.load()];case 1:return f=c.sent(),n&&l?[4,ps.getManager(s).removeModel(u)]:[3,3];case 2:c.sent(),c.label=3;case 3:return[4,o.save(f)];case 4:return p=c.sent(),!n||l?[3,6]:[4,ps.getManager(s).removeModel(u)];case 5:c.sent(),c.label=6;case 6:return[2,p.modelArtifactsInfo]}})})}var ms="models_store",gs="model_info_store";function ys(){if(!me.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=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 vs(e){var t=e.result;t.createObjectStore(ms,{keyPath:"modelPath"}),t.createObjectStore(gs,{keyPath:"modelPath"})}var bs=function(){function e(e){if(this.indexedDB=ys(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,this.databaseAction(this.modelPath)]})})},e.prototype.databaseAction=function(e,t){var n=this;return new Promise(function(e,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return vs(a)},a.onsuccess=function(){var i=a.result;if(null==t){var o=i.transaction(ms,"readonly"),s=o.objectStore(ms).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts)},s.onerror=function(e){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=ls(t),c=i.transaction(gs,"readwrite"),f=c.objectStore(gs),p=f.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var a=(u=i.transaction(ms,"readwrite")).objectStore(ms).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:l});a.onsuccess=function(){return e({modelArtifactsInfo:l})},a.onerror=function(e){var t=(f=c.objectStore(gs)).delete(n.modelPath);t.onsuccess=function(){return i.close(),r(a.error)},t.onerror=function(e){return i.close(),r(a.error)}}},p.onerror=function(e){return i.close(),r(p.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(e){return r(a.error)}})},e.URL_SCHEME="indexeddb://",e}(),ws=function(e){return me.get("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(bs.URL_SCHEME)?function(e){return new bs(e)}(e.slice(bs.URL_SCHEME.length)):null};cs.registerSaveRouter(ws),cs.registerLoadRouter(ws);var xs=function(){function e(){this.indexedDB=ys()}return e.prototype.listModels=function(){return l(this,void 0,void 0,function(){var e=this;return c(this,function(t){return[2,new Promise(function(t,n){var r=e.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return vs(r)},r.onsuccess=function(){var e=r.result,a=e.transaction(gs,"readonly"),i=a.objectStore(gs).getAll();i.onsuccess=function(){for(var e={},n=0,r=i.result;n0,"URL path for browserHTTPRequest must not be null, undefined or empty."),Array.isArray(e)&&d(2===e.length,"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+e.length+")."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest: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"),[4,fetch(this.path,t)];case 1:if(200===(a=i.sent()).status)return[2,{modelArtifactsInfo:ls(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return l(this,void 0,void 0,function(){return c(this,function(e){return[2,Array.isArray(this.path)?this.loadBinaryModel():this.loadJSONModel()]})})},e.prototype.loadBinaryTopology=function(){return l(this,void 0,void 0,function(){var e;return c(this,function(t){switch(t.label){case 0:return t.trys.push([0,3,,4]),[4,fetch(this.path[0],this.requestInit)];case 1:return[4,t.sent().arrayBuffer()];case 2:return[2,t.sent()];case 3:throw e=t.sent(),new Error(this.path[0]+" not found. "+e);case 4:return[2]}})})},e.prototype.loadBinaryModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s;return c(this,function(u){switch(u.label){case 0:return e=this.loadBinaryTopology(),[4,fetch(this.path[1],this.requestInit)];case 1:return t=u.sent(),[4,Promise.all([e,t])];case 2:return n=u.sent(),r=n[0],[4,n[1].json()];case 3:return null==(a=u.sent())?[3,5]:[4,this.loadWeights(a)];case 4:s=u.sent(),i=s[0],o=s[1],u.label=5;case 5:return[2,{modelTopology:r,weightSpecs:i,weightData:o}]}})})},e.prototype.loadJSONModel=function(){return l(this,void 0,void 0,function(){var e,t,n,r,a,i,o;return c(this,function(s){switch(s.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:return[4,s.sent().json()];case 2:if(e=s.sent(),t=e.modelTopology,n=e.weightsManifest,null==t&&null==n)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==n?[3,4]:(i=e.weightsManifest,[4,this.loadWeights(i)]);case 3:o=s.sent(),r=o[0],a=o[1],s.label=4;case 4:return[2,{modelTopology:t,weightSpecs:r,weightData:a}]}})})},e.prototype.loadWeights=function(e){return l(this,void 0,void 0,function(){var t,n,r,a,i,o,s,u,l;return c(this,function(c){switch(c.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,n=[],r=0,a=e;r0&&(e=u({weightSpecs:this.weightSpecs},e)),null!=this.weightData&&this.weightData.byteLength>0&&(e=u({weightData:this.weightData},e)),[2,e]})})},e}(),qs=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return l(this,void 0,void 0,function(){return c(this,function(t){return[2,this.saveHandler(e)]})})},e}(),$s=cs.registerSaveRouter,Gs=cs.registerLoadRouter,Hs=cs.getSaveHandlers,Ks=cs.getLoadHandlers,Xs=Object.freeze({browserFiles:function(e){return new Ls(e)},browserHTTPRequest:Us,concatenateArrayBuffers:ss,decodeWeights:as,encodeWeights:function(e){return l(this,void 0,void 0,function(){var t,n,r,a;return c(this,function(i){switch(i.label){case 0:for(r in t=[],n=[],e){if("float32"!==(a=e[r]).dtype&&"int32"!==a.dtype&&"bool"!==a.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+a.dtype);t.push({name:r,shape:a.shape,dtype:a.dtype}),n.push(a.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0,n=[];e.forEach(function(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)});var r=new Uint8Array(t),a=0;return n.forEach(function(e){r.set(new Uint8Array(e.buffer),a),a+=e.byteLength}),r.buffer}(i.sent()),specs:t}]}})})},fromMemory:function(e,t,n){return new Ws(e,t,n)},getLoadHandlers:Ks,getModelArtifactsInfoForJSON:ls,getSaveHandlers:Hs,loadWeights:function(e,t,n,r){return void 0===t&&(t=""),l(this,void 0,void 0,function(){var a,i,o,s,u,l,f,p,h,d;return c(this,function(c){switch(c.label){case 0:if(a=e.map(function(){return!1}),i={},o=null!=n?n.map(function(){return!1}):[],s=[],e.forEach(function(e,t){var r=0;e.weights.forEach(function(e){var u="quantization"in e?e.quantization.dtype:e.dtype,l=rs[u]*b(e.shape),c=function(){a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:r,sizeBytes:l})};null!=n?n.forEach(function(t,n){t===e.name&&(c(),o[n]=!0)}):c(),s.push(e.name),r+=l})}),!o.every(function(e){return e}))throw u=n.filter(function(e,t){return!o[t]}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return l=a.reduce(function(e,t,n){return t&&e.push(n),e},[]),f=[],l.forEach(function(n){e[n].paths.forEach(function(e){var n=t+(t.endsWith("/")?"":"/")+e;f.push(n)})}),[4,zs(f,r)];case 1:return p=c.sent(),h={},d=0,l.forEach(function(t){for(var n=e[t].paths.length,r=0,a=0;a0,"Class being registered has an empty-string as its className, which is disallowed."),Js.register(e)}var Qs=Object.freeze({Serializable:Ys,SerializationMap:Js,registerClass:Zs});function eu(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),e instanceof Q||t instanceof Q){if(e instanceof Q&&t instanceof Q){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!w(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".")}}else{var r=e.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+a)}var i,o;if(i=e instanceof Q?e.dataSync():e,o=t instanceof Q?t.dataSync():t,i.length!==o.length)throw new Error("Arrays have different lengths actual: "+i.length+" vs expected: "+o.length+".\nActual: "+i+".\nExpected: "+o+".");for(var s=0;sn)}var nu=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},ALL_ENVS:{},expectArraysClose:eu,expectPromiseToFail:function(e,t){e().then(function(){return t.fail()},function(){return t()})},expectArraysEqual:function(e,t){return eu(e,t,0)},expectNumbersClose:function(e,t,n){if(null==n&&(n=me.get("TEST_EPSILON")),!tu(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t)},expectValuesInRange:function(e,t,n){var r;r=e instanceof Q?e.dataSync():e;for(var a=0;an)throw new Error("Value out of range:"+r[a]+" low: "+t+", high: "+n)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}}),ru="0.12.17",au=Object.freeze({gpgpu_util:rr,webgl_util:jn,MathBackendWebGL:ua,GPGPUContext:ar}),iu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),a=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(e){return i[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return xe(e,t)},t}(Ys),ou=function(e){function t(t,n,r){void 0===r&&(r=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=n,a.epsilon=r,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=Ne(nt(-t)),a.rhoScalar=Ne(nt(n)),a.oneMinusRho=Ne(nt(1-n)),null===r&&(r=me.get("EPSILON")),a.epsilonScalar=Ne(nt(r)),a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ee(function(){t.accumulatedGrads[n]=xt(a).variable(!1)}),null==r.accumulatedUpdates[n]&&Ee(function(){t.accumulatedUpdates[n]=xt(a).variable(!1)});var i=e[n],o=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];Ee(function(){var e=t.rhoScalar.mul(o).add(t.oneMinusRho.mul(i.square())),r=s.add(t.epsilonScalar).sqrt().div(o.add(t.epsilonScalar).sqrt()).mul(i),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(r.square()));t.accumulatedGrads[n].assign(e),t.accumulatedUpdates[n].assign(u);var l=t.c.mul(r).add(a);a.assign(l)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(iu);Zs(ou);var su=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Ne(nt(-t)),r.epsilon=Ne(nt(me.get("EPSILON"))),r}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Ee(function(){t.accumulatedGrads[n]=ft(a.shape,t.initialAccumulatorValue).variable(!1)});var i=e[n],o=r.accumulatedGrads[n];Ee(function(){var e=o.add(i.square());t.accumulatedGrads[n].assign(e);var r=t.c.mul(i.div(e.add(t.epsilon).sqrt())).add(a);a.assign(r)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(iu);Zs(su);var uu=function(e){function t(t,n,r,a){void 0===a&&(a=null);var i=e.call(this)||this;return i.learningRate=t,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment={},i.accumulatedSecondMoment={},i.c=Ne(nt(-t)),i.beta1Scalar=Ne(nt(n)),i.beta2Scalar=Ne(nt(r)),Ee(function(){i.accBeta1=nt(n).variable(),i.accBeta2=nt(r).variable()}),i.oneMinusBeta1=Ne(nt(1-n)),i.oneMinusBeta2=Ne(nt(1-r)),i.one=Ne(nt(1)),null===a&&(a=me.get("EPSILON")),i.epsScalar=Ne(nt(a)),i}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ee(function(){var n=t.one.sub(t.accBeta1),r=t.one.sub(t.accBeta2);for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=xt(i).variable(o)}null==t.accumulatedSecondMoment[a]&&(o=!1,t.accumulatedSecondMoment[a]=xt(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),p=c.div(n),h=f.div(r);t.accumulatedFirstMoment[a].assign(c),t.accumulatedSecondMoment[a].assign(f);var d=t.c.mul(p.div(t.epsScalar.add(h.sqrt()))).add(i);i.assign(d)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(iu);Zs(uu);var lu=function(e){function t(t,n,r,a,i){void 0===a&&(a=null),void 0===i&&(i=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment={},o.accumulatedWeightedInfNorm={},o.c=Ne(nt(-t)),o.beta1Scalar=Ne(nt(n)),o.beta2Scalar=Ne(nt(r)),o.decayScalar=Ne(nt(i)),Ee(function(){o.iteration=nt(0).variable(),o.accBeta1=nt(n).variable()}),o.oneMinusBeta1=Ne(nt(1-n)),o.one=Ne(nt(1)),null===a&&(a=me.get("EPSILON")),o.epsScalar=Ne(nt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Ee(function(){var n=t.one.sub(t.accBeta1),r=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var i=me.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=xt(i).variable(o)}null==t.accumulatedWeightedInfNorm[a]&&(o=!1,t.accumulatedWeightedInfNorm[a]=xt(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],c=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),f=t.beta2Scalar.mul(l),p=s.abs(),h=f.maximum(p);t.accumulatedFirstMoment[a].assign(c),t.accumulatedWeightedInfNorm[a].assign(h);var d=r.div(n).mul(c.div(t.epsScalar.add(h))).add(i);i.assign(d)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(iu);Zs(lu);var cu=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n}return s(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(n){var r=e[n],a=me.engine.registeredVariables[n];Ee(function(){var e=t.c.mul(r).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Ne(nt(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(iu);Zs(cu);var fu=function(e){function t(t,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=n,a.useNesterov=r,a.m=nt(a.momentum),a.accumulations={},a}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulations[n]&&Ee(function(){t.accumulations[n]=xt(a).variable(!1)});var i=r.accumulations[n],o=e[n];Ee(function(){var e,r=t.m.mul(i).add(o);e=t.useNesterov?t.c.mul(o.add(r.mul(t.m))).add(a):t.c.mul(r).add(a),t.accumulations[n].assign(r),a.assign(e)})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(cu);Zs(fu);var pu=function(e){function t(t,n,r,a,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=null),void 0===i&&(i=!1);var o=e.call(this)||this;return o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares={},o.accumulatedMeanGrads={},o.accumulatedMoments={},o.c=Ne(nt(t)),o.decayScalar=Ne(nt(n)),o.momentumScalar=Ne(nt(r)),o.oneMinusDecay=Ne(nt(1-n)),o.centered=i,null===a&&(a=me.get("EPSILON")),o.epsilonScalar=Ne(nt(a)),o}return s(t,e),t.prototype.applyGradients=function(e){var t=this,n=function(n){var a=me.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&Ee(function(){t.accumulatedMeanSquares[n]=xt(a).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&Ee(function(){t.accumulatedMeanGrads[n]=xt(a).variable(!1)}),null==r.accumulatedMoments[n]&&Ee(function(){t.accumulatedMoments[n]=xt(a).variable(!1)});var i=r.accumulatedMeanSquares[n],o=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=e[n];Ee(function(){var e=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var r=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(r.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[n].assign(e),t.accumulatedMeanGrads[n].assign(r),t.accumulatedMoments[n].assign(l);var c=a.sub(l);a.assign(c)}else{var f=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(f.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[n].assign(f),t.accumulatedMoments[n].assign(l),c=a.sub(l),a.assign(c)}})},r=this;for(var a in e)n(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(iu);Zs(pu);var hu=function(){function e(){}return e.sgd=function(e){return new cu(e)},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new fu(e,t,n)},e.rmsprop=function(e,t,n,r,a){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new pu(e,t,n,r,a)},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new uu(e,t,n,r)},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=null),new ou(e,t,n)},e.adamax=function(e,t,n,r,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new lu(e,t,n,r,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new su(e,t)},e}(),du={sgd:hu.sgd,momentum:hu.momentum,adadelta:hu.adadelta,adagrad:hu.adagrad,rmsprop:hu.rmsprop,adamax:hu.adamax,adam:hu.adam},mu=de.setBackend,gu=de.getBackend,yu=de.disposeVariables,vu=de.memory;J=Qo}.call(this,n(46),n(26),n(162).setImmediate,n(16).Buffer)},function(e,t,n){var r=n(7),a=n(44),i=n(30),o=n(29),s=n(43),u=function(e,t,n){var l,c,f,p,h=e&u.F,d=e&u.G,m=e&u.S,g=e&u.P,y=e&u.B,v=d?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,b=d?a:a[t]||(a[t]={}),w=b.prototype||(b.prototype={});for(l in d&&(n=t),n)f=((c=!h&&v&&void 0!==v[l])?v:n)[l],p=y&&c?s(f,r):g&&"function"==typeof f?s(Function.call,f):f,v&&o(v,l,f,e&u.U),b[l]!=f&&i(b,l,p),g&&w[l]!=f&&(w[l]=f)};r.core=a,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t,n){"use strict";n.r(t);var r=n(0),a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}; /** * @license * Copyright 2018 Google LLC. All Rights Reserved. @@ -48,14 +48,14 @@ var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__p * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= - */function i(e,t){function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]t?1:0}(e,t)}function R(e){if(null==e)return e;for(var t=[],n=0,r=e;n=0),N(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(function(e){return typeof e===t})}function B(e,t){return Object(r.od)(function(){return Object(r.Tc)(Object(r.dd)(Object(r.Pb)(e,e),t,!0))})}var z=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.getConfig=function(){return{}},t}(r.Ec.Serializable),F=function(e){function t(t){var n=e.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){var n=B(e,t.axis),a=Object(r.O)(n,0,t.maxValue);return Object(r.Ob)(e,Object(r.Ha)(a,Object(r.s)(y(c()),n)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(z);r.Ec.registerClass(F);var V=function(e){function t(t){var n=e.call(this)||this;return n.defaultAxis=0,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){return Object(r.Ha)(e,Object(r.s)(y(c()),B(e,t.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(z);r.Ec.registerClass(V);var U=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e){return Object(r.sc)(e)},t.className="NonNeg",t}(z);r.Ec.registerClass(U);var W=function(e){function t(t){var n=e.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=t.minValue?t.minValue:n.defaultMinValue,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.rate=null!=t.rate?t.rate:n.defaultRate,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){var n=B(e,t.axis),a=Object(r.s)(Object(r.Ob)(y(t.rate),Object(r.O)(n,t.minValue,t.maxValue)),Object(r.Ob)(y(1-t.rate),n));return Object(r.Ob)(e,Object(r.Ha)(a,Object(r.s)(y(c()),n)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(z);r.Ec.registerClass(W);var q={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function $(e){return A(e)}function G(e,t){return void 0===t&&(t={}),T(e,r.Ec.SerializationMap.getMap().classNameMap,t,"constraint")}function H(e){return null==e?null:"string"==typeof e?G({className:e in q?q[e]:e,config:{}}):e instanceof z?e:G(e)}var K=Object.freeze({maxNorm:function(e){return new F(e)},unitNorm:function(e){return new V(e)},nonNeg:function(){return new U},minMaxNorm:function(e){return new W(e)}}),X=new Map,Y=["channelsFirst","channelsLast"];function J(e){j(Y,"DataFormat",e)}var Z=["valid","same","causal"];function Q(e){j(Z,"PaddingMode",e)}var ee=["max","avg"],te=[],ne="/";function re(e,t){te.push(e);try{var n=t();return te.pop(),n}catch(e){throw te.pop(),e}}function ae(e){if(!se(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===te.length?"":te.join(ne)+ne)+e}function ie(e){if(!se(e))throw new Error("Not a valid tensor name: '"+e+"'");X.has(e)||X.set(e,0);var t=X.get(e);if(X.set(e,X.get(e)+1),t>0){var n=e+"_"+t;return X.set(n,1),n}return e}var oe=new RegExp(/^[A-Za-z][A-Za-z0-9\._\/]*$/);function se(e){return!!e.match(oe)}function ue(e){return e===parseInt(e.toString(),10)}function le(e,t,n){null==t&&(t=0),null==n&&(n=e.length);for(var r=1,a=t;a= 2 but got x shape = "+e.shape+" and y shape = "+t.shape);if(t.rank>=3&&(a=e.shape.slice(-1)[0])!==(s=t.shape.slice(-2)[0]))throw new x("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and y shape = "+t.shape);if(2===e.rank&&2===t.rank)return Object(r.Ab)(e,t);var n=e.shape.slice(),a=n.pop();e=e.reshape([-1,a]);var i=t.shape.slice(),o=i.pop(),s=i.pop(),u=i.concat([o]),l=Array.from({length:t.rank},function(e,n){return 0===n?t.rank-2:n<=t.rank-2?n-1:n});t=t.transpose(l).reshape([s,-1]);var c=n.concat(u);return Object(r.Ab)(e,t).reshape(c)}function Ne(e,t,n){return Object(r.od)(function(){return t=Array.isArray(t)?Object(r.hd)(t,"int32"):t.toInt(),Object(r.Xa)(e,t,n)})}function Se(e){return Object(r.Pb)(e,e)}function Oe(e,t,n){return Object(r.od)(function(){if(null==n&&(n="channelsLast"),J(n),1!==t.rank&&t.rank!==e.rank)throw new w("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e.rank);var r,a=t.shape;if(5===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1,1])):e.add(t.reshape([1,a[3],a[0],a[1],a[2]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(4===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1])):e.add(t.reshape([1,a[2],a[0],a[1]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(3===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1])):e.add(t.reshape([1,a[1],a[0]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,a[0]])):e.add(t.reshape([1].concat(a))));else{if(!(e.rank<3))throw new w("Unsupported input rank by biasAdd: "+e.rank);r=e.add(t)}return r})}function ke(e,t,n,a){return Object(r.od)(function(){if(null!=n&&!r.yd.arraysEqual(e.shape,n))throw new x("Non-default noise shape is not implemented yet: "+JSON.stringify(n));if(null!=a)throw new x("seed is not implemented for dropout yet.");var i=Object(r.Zc)(Object(r.s)(Object(r.Sb)(t),Object(r.oc)(e.shape,0,1,"float32")));return i=Object(r.Ob)(Object(r.Ha)(y(1),Object(r.bd)(y(1),t)),i),Object(r.Ob)(e,i)})}function Ie(e,t,n){return void 0===n&&(n=!1),n?e():t()}var Ce=["fanIn","fanOut","fanAvg"],Pe=["normal","uniform"],Ae=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(r.Ec.Serializable),Te=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e,t){return Object(r.Hd)(e,t)},t.className="Zeros",t}(Ae);r.Ec.registerClass(Te);var Me=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e,t){return Object(r.Yb)(e,t)},t.className="Ones",t}(Ae);r.Ec.registerClass(Me);var Re=function(e){function t(t){var n=e.call(this)||this;if("object"!=typeof t)throw new w("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new w("config must have value set but got "+t);return n.value=t.value,n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){return Object(r.Ob)(Object(r.Bc)(n.value),Object(r.Yb)(e,t))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(Ae);r.Ec.registerClass(Re);var De=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){return Object(r.oc)(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(Ae);r.Ec.registerClass(De);var je=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x("randomNormal does not support dType "+t+".");return _e(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(Ae);r.Ec.registerClass(je);var Le=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x("truncatedNormal does not support dType "+t+".");return Object(r.vd)(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(Ae);r.Ec.registerClass(Le);var Be=function(e){function t(t){var n=e.call(this)||this;return n.gain=null!=t.gain?Object(r.Bc)(t.gain):y(1),n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){if(2!==e.length||e[0]!==e[1])throw new w("Identity matrix initializer can only be used for 2D square matrices.");return Object(r.Ob)(n.gain,Object(r.Sa)(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain.get()}},t.className="Identity",t}(Ae);r.Ec.registerClass(Be);var ze=function(e){function t(t){var n=e.call(this)||this;if(t.scale<0)throw new w("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=t.mode,function(e){j(Ce,"FanMode",e)}(n.mode),n.distribution=t.distribution,function(e){j(Pe,"Distribution",e)}(n.distribution),n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){var n=function(e,t){var n,r;if(void 0===t&&(t="channelsLast"),J(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length))if("channelsFirst"===t){var a=le(e,2);n=e[1]*a,r=e[0]*a}else"channelsLast"===t&&(a=le(e,0,e.length-2),n=e[e.length-2]*a,r=e[e.length-1]*a);else{var i=le(e);n=Math.sqrt(i),r=Math.sqrt(i)}return[n,r]}(e),a=n[0],i=n[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,a):"fanOut"===this.mode?o/=Math.max(1,i):o/=Math.max(1,(a+i)/2),"normal"===this.distribution){var s=Math.sqrt(o);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x(this.getClassName()+" does not support dType "+t+".");return Object(r.vd)(e,0,s,t,this.seed)}var u=Math.sqrt(3*o);return Object(r.oc)(e,-u,u,t)},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(Ae);r.Ec.registerClass(ze);var Fe=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return ze.className},t}(ze),Ve=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return ze.className},t}(ze),Ue=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return ze.className},t}(ze),We=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return ze.className},t}(ze),qe=function(e){function t(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new x("Random seed is not implemented for Orthogonal Initializer yet.");return n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){if(2!==e.length)throw new x("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=_e(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),a=r.ob.gramSchmidt(t);return e[0]>e[1]&&(a=a.transpose()),Object(r.Ob)(y(n.gain),a)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(Ae);r.Ec.registerClass(qe);var $e={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Ge(e,t){return void 0===t&&(t={}),T(e,r.Ec.SerializationMap.getMap().classNameMap,t,"initializer")}function He(e){return A(e)}function Ke(e){if("string"==typeof e){var t=e in $e?$e[e]:e;return"GlorotUniform"===t?new Fe:"GlorotNormal"===t?new Ve:"HeNormal"===t?new Ue:"LeCunNormal"===t?new We:Ge({className:t,config:{}})}return e instanceof Ae?e:Ge(e)}var Xe=Object.freeze({zeros:function(){return new Te},ones:function(){return new Me},constant:function(e){return new Re(e)},randomUniform:function(e){return new De(e)},randomNormal:function(e){return new je(e)},truncatedNormal:function(e){return new Le(e)},identity:function(e){return new Be(e)},varianceScaling:function(e){return new ze(e)},glorotUniform:function(e){return new Fe(e)},glorotNormal:function(e){return new Ve(e)},heNormal:function(e){return new Ue(e)},leCunNormal:function(e){return new We(e)},orthogonal:function(e){return new qe(e)}});function Ye(e){return Array.isArray(e)&&Array.isArray(e[0])}function Je(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function Ze(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new w("Expected Tensor length to be 1; got "+e.length);t=e[0]}else t=e;return t}function Qe(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new w("Expected exactly 1 Shape; got "+e.length)}return e}function et(e){for(var t=0,n=0,r=e;n1)throw new v("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new v("Layer "+this.name+" is not connected, no input to return.");return O(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new v("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new v("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return O(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this._trainableWeights:[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=k(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=k(this.inputSpec);if(e.length!==t.length)throw new w("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var n=0;n=0?o[u]:o[o.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new w("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+o+".")}}if(null!=a.shape)for(var f=0;f0&&Array.isArray(d[0])?d.map(function(r,a){return new ot(g,r,n,k(e),t,n.name,a)}):new ot(g,d,n,k(e),t,n.name),n.addInboundNode(e,m,null,null,h,d,t),n._refCount++,null!=n.activityRegularizer)throw new x("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},t.prototype.warnOnIncompatibleInputShape=function(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(e)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var t=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)}),t&&console.warn("The shape of the input tensor ("+JSON.stringify(e)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new v("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,n=this.inboundNodes;te.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(n-this.batchStartMillis),this.batchDurationsMillis.length>=e.DECISION_BATCH_COUNT&&(a=this.batchDurationsMillis.reduce(function(e,t){return e+t})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=Math.round(e.THRESHOLD_MILLIS/a),this.autoYieldEveryBatches<1&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=r.yd.now(),this.lastYieldBatchCount=this.batchCount,[3,6];case 3:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,Object(r.Tb)()]:[3,6];case 4:return i.sent(),[4,this.resolveOneTensorInLogs(t)];case 5:i.sent(),this.lastYieldBatchCount=this.batchCount,i.label=6;case 6:return[3,9];case 7:return"batch"!==this.yieldEvery?[3,9]:[4,Object(r.Tb)()];case 8:i.sent(),i.label=9;case 9:return[2]}})})},e.prototype.maybeYieldOnEpoch=function(){return s(this,void 0,void 0,function(){return u(this,function(e){switch(e.label){case 0:return"epoch"!==this.yieldEvery?[3,2]:[4,Object(r.Tb)()];case 1:e.sent(),e.label=2;case 2:return[2]}})})},e.SKIP_FIRST_BATCHES=1,e.DECISION_BATCH_COUNT=2,e.THRESHOLD_MILLIS=16,e}(),yt=function(e){function t(t){var n=e.call(this)||this;return n.yieldEvery=t||"auto",n}return i(t,e),t.prototype.onTrainBegin=function(e){return s(this,void 0,void 0,function(){return u(this,function(e){return this.autoYielder=new gt(this.yieldEvery),[2]})})},t.prototype.onEpochBegin=function(e){return s(this,void 0,void 0,function(){return u(this,function(e){return this.seen=0,this.totals={},[2]})})},t.prototype.onBatchEnd=function(e,t){return s(this,void 0,void 0,function(){var e,n,a,i,o=this;return u(this,function(s){switch(s.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(t)];case 1:for(i in s.sent(),null==t&&(t={}),e=null==t.size?0:t.size,this.seen+=e,n=function(n){var i=t[n];if("number"==typeof i)a.totals.hasOwnProperty(n)||(a.totals[n]=0),a.totals[n]=a.totals[n]+i*e;else{var s=void 0;n in a.totals?s=a.totals[n]:a.totals[n]=y(0),a.totals[n]=Object(r.od)(function(){return Object(r.s)(o.totals[n],Object(r.Ob)(i,y(e)))}),null!=s&&s.dispose()}},a=this,t)n(i);return[2]}})})},t.prototype.onEpochEnd=function(e,t){return s(this,void 0,void 0,function(){var e,n,a,i,o,s=this;return u(this,function(u){switch(u.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(u.sent(),null!=t)for(e=function(e){if(null==n.totals[e])return"continue";"number"==typeof n.totals[e]?t[e]=n.totals[e]/n.seen:Object(r.od)(function(){t[e]=Object(r.Ob)(Object(r.Ha)(y(1),y(s.seen)),s.totals[e]),s.totals[e].dispose(),Object(r.ib)(t[e])})},n=this,a=0,i=this.params.metrics;a=0&&Number.isInteger(t),"Verbosity level is expected to be an integer >= 0, but got "+t),e.checkForDuplicate(n),null==e.constructors[t]&&(e.constructors[t]=[]),e.constructors[t].push(n)},e.checkForDuplicate=function(t){for(var n in e.constructors)e.constructors[+n].forEach(function(e){if(e===t)throw new w("Duplicate callback constructor.")})},e.clear=function(){e.constructors={}},e.createCallbacks=function(t){var n=[];for(var r in e.constructors){var a=+r;t>=a&&n.push.apply(n,e.constructors[a])}return n.map(function(e){return new e})},e}();function xt(e,t){return Object(r.od)(function(){var n=Object(r.dd)(Se(e),t,!0),a=Object(r.Ob)(Object(r.Bc)(c()),Object(r.Zb)(e)),i=Object(r.Tc)(Object(r.Db)(n,a));return Object(r.Ha)(e,i)})}function _t(e,t){return Object(r.od)(function(){return Object(r.Fb)(Se(Object(r.bd)(t,e)),-1)})}function Et(e,t){return Object(r.od)(function(){return Object(r.Fb)(Object(r.p)(Object(r.bd)(t,e)),-1)})}function Nt(e,t){return Object(r.od)(function(){var n=Object(r.bd)(e,t),a=Object(r.O)(Object(r.p)(e),c(),Number.MAX_VALUE),i=Object(r.p)(Object(r.Ha)(n,a));return Object(r.Ob)(y(100),Object(r.Fb)(i,-1))})}function St(e,t){return Object(r.od)(function(){var n=y(1),a=Object(r.O)(t,c(),Number.MAX_VALUE),i=Object(r.rb)(Object(r.s)(n,a)),o=Object(r.O)(e,c(),Number.MAX_VALUE),s=Object(r.rb)(Object(r.s)(n,o));return Object(r.Fb)(Se(Object(r.bd)(i,s)),-1)})}function Ot(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.Db)(n,Object(r.bd)(a,Object(r.Ob)(e,t)));return Object(r.Fb)(Se(i),-1)})}function kt(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.Db)(n,Object(r.bd)(a,Object(r.Ob)(e,t)));return Object(r.Fb)(i,-1)})}function It(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.dd)(Object(r.Ob)(e,t),-1),o=Object(r.Bb)(Object(r.Ob)(Object(r.bd)(a,e),t),-1);return Object(r.Db)(n,Object(r.s)(a,Object(r.bd)(o,i)))})}function Ct(e,t){return Object(r.od)(function(){var n=y(Math.log(2)),a=Object(r.bd)(t,e),i=Object(r.bd)(Object(r.s)(a,Object(r.Qc)(Object(r.Ob)(y(-2),a))),n);return Object(r.Fb)(i,-1)})}function Pt(e,t,n){return void 0===n&&(n=!1),Object(r.od)(function(){if(n)t=Object(r.Pc)(t);else{var a=Object(r.dd)(t,t.shape.length-1,!0);t=Object(r.Ha)(t,a)}return t=Object(r.O)(t,c(),1-c()),Object(r.Sb)(Object(r.dd)(Object(r.Ob)(e.toFloat(),Object(r.rb)(t)),t.shape.length-1))})}function At(e,t,n){return void 0===n&&(n=!1),Object(r.od)(function(){var a=Object(r.Ua)(function(e){var t=[le(e.shape)];return e.reshape(t)}(e)).toInt(),i=t.shape;return Pt(Object(r.Xb)(a,i[i.length-1]).reshape(i),t,n)})}function Tt(e,t){return Object(r.od)(function(){var n;return n=Object(r.O)(t,c(),1-c()),n=Object(r.rb)(Object(r.Ha)(n,Object(r.bd)(Object(r.Zb)(n),n))),Object(r.Fb)(function(e,t){return Object(r.od)(function(){var n=Object(r.Db)(t,Object(r.Id)(t)),a=Object(r.Ob)(t,e),i=Object(r.rb)(Object(r.s)(y(1),Object(r.Pa)(Object(r.Sb)(Object(r.p)(t)))));return Object(r.s)(Object(r.bd)(n,a),i)})}(e,n),-1)})}function Mt(e,t){return Object(r.od)(function(){var n=Object(r.O)(e,c(),1),a=Object(r.O)(t,c(),1);return Object(r.dd)(Object(r.Ob)(e,Object(r.rb)(Object(r.Ha)(n,a))),-1)})}function Rt(e,t){return Object(r.od)(function(){var n=Object(r.rb)(Object(r.s)(y(c()),t));return Object(r.Fb)(Object(r.bd)(t,Object(r.Ob)(e,n)),-1)})}function Dt(e,t){return Object(r.od)(function(){var n=xt(e,-1),a=xt(t,-1),i=Object(r.Ob)(n,a);return Object(r.Sb)(Object(r.dd)(i,-1))})}function jt(e){var t={meanSquaredError:_t,meanAbsoluteError:Et,meanAbsolutePercentageError:Nt,meanSquaredLogarithmicError:St,squaredHinge:Ot,hinge:kt,categoricalHinge:It,logcosh:Ct,categoricalCrossentropy:Pt,sparseCategoricalCrossentropy:At,binaryCrossentropy:Tt,kullbackLeiblerDivergence:Mt,poisson:Rt,cosineProximity:Dt};if("string"==typeof e){if(e in t)return t[e];var n="Unknown loss "+e;throw e.toLowerCase().includes("softmaxcrossentropy")&&(n="Unknown loss "+e+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new w(n)}return e}function Lt(e,t){return Object(r.od)(function(){var n=Object(r.Ob)(y(.5),Object(r.Zb)(t)),a=de(Object(r.bb)(t,n),e.dtype);return Object(r.Fb)(Object(r.Ma)(e,a),-1)})}function Bt(e,t){return Object(r.od)(function(){return de(Object(r.Ma)(Object(r.x)(e,-1),Object(r.x)(t,-1)),"float32")})}function zt(e,t){return Object(r.od)(function(){var n=y(1);return Object(r.vb)(e.equal(n),t.equal(n)).sum().cast("float32")})}function Ft(e,t){return Object(r.od)(function(){var n=y(0),a=zt(e,t),i=function(e,t){return Object(r.od)(function(){var n=y(1),a=y(0);return Object(r.vb)(e.equal(a),t.equal(n)).sum().cast("float32")})}(e,t),o=a.add(i);return Object(r.Fd)(Object(r.bb)(o,n),a.div(o),n).cast("float32")})}function Vt(e,t){return Tt(e,t)}function Ut(e,t){throw new x}var Wt=_t,qt=_t,$t=Et,Gt=Et,Ht=Nt,Kt=Nt,Xt=Pt,Yt=Dt,Jt=At;function Zt(e,t,n){void 0===n&&(n=console.log);for(var r="",a=0;a0&&(r=r.slice(0,r.length-1)+" "),r=(r+=e[a]).slice(0,t[a]),r+=" ".repeat(t[a]-r.length);n(r)}function Qt(e,t,n){var r;try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}Zt([e.name+" ("+e.getClassName()+")",r,e.countParams().toString()],t,n)}function en(e,t,n,r){var a;try{a=JSON.stringify(e.outputShape)}catch(e){a="multiple"}for(var i=[],o=0,s=e.inboundNodes;o0&&-1===n.indexOf(u)))for(var l=0;l1 nodes"),N(0===l,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(l);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var p=0;p=0;)a.splice(a.indexOf(u),1);E.push(u)}},O=[],k=[],I=0,C=r.outputs;Ir?1:0});for(var K=0,X=H;K0)throw new w("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],t=0,n=this.layers;t0)throw new w(p.length+" of "+a+" weights are not set: "+p)}at(c)}(e,this.layers,a):function(e,t,n){void 0===n&&(n=!1);for(var a=e.keras_version,i=(e.backend,t.map(function(e){return e.name})),o={},s=0,u=t;s1)for(var s=0,u=o;s0){for(var h=[],d=0;d0&&e.apply(O(i),r)}function o(e){var r=e.name,i=tn(e,null!=t.customObjects?t.customObjects:{});n[r]=i;for(var o=0,s=e.inboundNodes;o0)i=!0;else if(pn(e)){for(var o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new w("Error when checking model "+a+" expected no data, but got "+e)}return[]}if(null==e)return t.map(function(e){return null});var s;if(pn(e)){e=e,s=[];for(var u=0,l=t;u1)throw new w("The model "+a+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e]}for(var f=0;f=0&&d!==m)throw new w("Error when checking "+a+": expected "+t[f]+" to have shape ["+n[f]+"], but got array with shape ["+p.shape+"].")}}return s}function dn(e,t){for(var n=[],r=0,a=null;r=e&&(a=e),n.push([r,a]),r=a;return n}function mn(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(function(e){return ge(e,t,n-t)}):ge(e,t,n-t)}function gn(e,t){return Object(r.od)(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return gn(e,t)}):Ne(e,"int32"===t.dtype?t:t.toInt())})}function yn(e,t,n,r,a){var i;if(void 0===r&&(r=!0),void 0===a&&(a=""),Array.isArray(e)){if(e.length!==t.length)throw new w("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+t.length+" Tensor(s), but instead got "+e.length+" Tensors(s).");i=e}else{if(t.length>1)throw new w("The model expects "+t.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");i=[e]}if(null!=n)for(var o=0;o0&&Number.isInteger(e),"batchSize is required to be a positive integer, but got "+e)}!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(on||(on={}));var bn=function(e){function t(t){var n=e.call(this,t)||this;return n.isTraining=!1,n}return i(t,e),t.prototype.summary=function(e,t,n){if(void 0===n&&(n=console.log),!this.built)throw new w("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");!function(e,t,n,r){void 0===r&&(r=console.log);var a,i=function(e){var t=!0,n=[],r=[];for(var a in e.nodesByDepth)n.push(e.nodesByDepth[a]);for(var i=0,o=n;i1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}r.push.apply(r,s)}if(t)for(var u=0,l=e.layers;u1&&(t.metricsTensors.push([n,e]),t.metricsNames.push(t.outputNames[e]+"_loss"))}});var h=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map(function(e){return[]});if(Array.isArray(e))return t.map(function(t){return e});if(null!=e){for(var n=[],r=0,a=t;r1&&(n=t.outputNames[e]+"_"+n),t.metricsNames.push(n),t.metricsTensors.push([r,e])}(e,r,l)},s=0,u=h[e];s0){var c=[];throw t.forEach(function(t,n){null==t&&c.push(e[n])}),new w("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return t},t.prototype.predictLoop=function(e,t,n){var a=this;return void 0===t&&(t=32),void 0===n&&(n=!1),Object(r.od)(function(){var i=a.checkNumSamples(e);if(n)throw new x("Verbose predictLoop() is not implemented yet.");for(var o=dn(i,t),s=[],u=function(t){var n=Object(r.od)(function(){var n=o[t][0],r=o[t][1],i=mn(e,n,r),s=[];if(Array.isArray(i))for(var u=0;u1)throw new w("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(i.length>1)throw new w("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(a.length>0&&i.length>0&&!r.yd.arraysEqual(a,i))throw new w("Input Tensors should have the same number of samples as target Tensors. Found "+a[0]+" input sample(s) and "+i[0]+" target sample(s).")}(e=hn(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=hn(t,this.feedOutputNames,i,!1,"target")),function(e,t,n){for(var r=[_t,Tt,Pt],a=0;a0&&e[0].shape[0]%a!=0)throw new w("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+a+". Found: "+e[0].shape[0]+" sample(s).");return[e,t,null]},t.prototype.fitLoop=function(e,t,n,a,i,o,l,c,f,p,h,d,m,g,y){return s(this,void 0,void 0,function(){var s,v,b,_,E,N,S,O,k=this;return u(this,function(I){switch(I.label){case 0:if(null==a&&(a=32),null==i&&(i=1),null==p&&(p=!0),null==d&&(d=0),s=!1,null!=c&&null!=f&&(s=!0),null!=g&&(s=!0,null==m))throw new w("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(v=this.checkNumSamples(t,a,m,"steps_per_epoch"))&&(b=he(0,v)),null==o&&(o=1),this.history=new vt,_=[new yt(y)].concat(wt.createCallbacks(o)),null!=l&&_.push.apply(_,l),_.push(this.history),(E=new mt(_)).setModel(this),E.setParams({epochs:i,initialEpoch:d,samples:v,steps:m,batchSize:a,verbose:o,doValidation:s,metrics:h}),[4,E.onTrainBegin()];case 1:I.sent(),this.stopTraining_=!1,N=function(i){var o,l,h,d,g;return u(this,function(y){switch(y.label){case 0:return[4,E.onEpochBegin(i)];case 1:if(y.sent(),o={},null==m)return[3,2];throw new x("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===p)throw new x("batch shuffling is not implemneted yet");p&&r.yd.shuffle(b),l=Object(r.hd)(b),h=dn(v,a),d=function(i){var p;return u(this,function(u){switch(u.label){case 0:return p={},[4,E.onBatchBegin(i,p)];case 1:return u.sent(),Object(r.od)(function(){var u=h[i][0],d=h[i][1],m=ge(l,u,d-u);p.batch=i,p.size=d-u;for(var g=gn(t,m),y=e(g),v=0;v1&&(a+="_"+S(e.slice(0,n),r)),t.push(a)}return t},t.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(t){return Object(r.od)(function(){for(var n,a=[],i=t.slice(0,e.inputs.length),o=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),s=[],u=0;u0){if(l=!0,2!==n.validationData.length)throw 3===n.validationData.length?new x("validationData including sample weights is not supported yet."):new w("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+n.validationData+" is invalid.");c=n.validationData[0],f=n.validationData[1],d=this.standardizeUserData(c,f,!0,a),c=d[0],f=d[1],p=c.concat(f)}else null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1?(l=!0,m=Math.floor(o[0].shape[0]*(1-n.validationSplit)),g=o[0].shape[0],c=mn(o,m,g),o=mn(o,0,m),f=mn(s,m,g),s=mn(s,0,m),h=!0,p=c.concat(f)):null!=n.validationSteps&&(l=!0);return y=o.concat(s),this.checkTrainableWeightsConsistency(),v=function(e){var t=e.slice(0,O.inputs.length),n=e.slice(O.inputs.length,O.inputs.length+O.outputs.length),a=[],i=O.collectedTrainableWeights.map(function(e){return e.read()});return[O.optimizer.minimize(function(){for(var e=[],i=0;i1)throw new w("Found more than one ("+n.length+") save handlers for URL '"+e+"'");e=n[0]}if(null==e.save)throw new w("Model.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,r.hb.encodeWeights(this.getNamedWeights(t))];case 1:return a=u.sent(),i=!1,o=null,s=this.toJSON(o,i),[2,e.save({modelTopology:s,weightData:a.data,weightSpecs:a.specs})]}})})},t.className="Model",t}(sn);r.Ec.registerClass(bn);var wn=function(e){function t(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n._updatable=!0,n.built=!1,n.name=null!=t.name?t.name:d("sequential_"),null!=t.layers)for(var r=0,a=t.layers;r0)&&(n=t.sourceLayer,r=t.nodeIndex),0===n.inboundNodes.length)return[t];var a=n.inboundNodes[r];if(0===a.inboundLayers.length)return a.inputTensors;for(var i=[],o=0;o1)throw new w("Found more than one ("+n.length+") load handlers for URL '"+e+"'");e=n[0]}return[2,function(e,t,n){return void 0===n&&(n=!0),s(this,void 0,void 0,function(){var t,a,i,o,s;return u(this,function(u){switch(u.label){case 0:if(null==e.load)throw new w("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(t=u.sent(),null!=(a=t.modelTopology).model_config&&(a=a.model_config),i=tn(function e(t,n){if(null===t)return null;if("string"==typeof t)return C(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var r=[],a=t.length,i=0;i 0 but got "+JSON.stringify(e.filters))},t}(nr),ar=function(e){function t(n){var r=e.call(this,2,n)||this;return t.verifyConfig(n),r}return i(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyConfig=function(e){if("number"!=typeof e.kernelSize&&!L(e.kernelSize,"number",1,2))throw new w("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(rr);r.Ec.registerClass(ar);var ir=function(e){function t(t){var n=e.call(this,t)||this;if(n.inputSpec=[new it({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new w("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return i(t,e),t.prototype.build=function(e){if(4!==(e=Qe(e)).length)throw new w("Input should have rank 4; Received input shape: "+JSON.stringify(e));var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new w("The channel dimension of the inputs should be defined. Found `None`.");var n,r=e[t],a=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new it({ndim:4,axes:(n={},n[t]=r,n)})],this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);if(4!==t.shape.length)throw new w("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var a,i,o=t.shape,s=o[0];"channelsFirst"===n.dataFormat?(a=2,i=3):(a=1,i=2);var u=o[a],l=o[i],c=n.kernelSize[0],f=n.kernelSize[1],p=n.strides[0],h=n.strides[1],d=[s,er(u,p,c,n.padding),er(l,h,f,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(t=Object(r.ud)(t,[0,2,3,1]));var m=Object(r.Y)(t,n.kernel.read(),d,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(m=Object(r.ud)(m,[0,3,1,2])),null!=n.bias&&(m=Oe(m,n.bias.read(),n.dataFormat)),null!=n.activation&&(m=n.activation.apply(m)),m})},t.prototype.computeOutputShape=function(e){var t,n,r,a=(e=Qe(e)).slice();"channelsFirst"===this.dataFormat?(t=1,n=2,r=3):(t=3,n=1,r=2);var i=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[t]=this.filters,a[n]=er(a[n],s,i,this.padding),a[r]=er(a[r],u,o,this.padding),a},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(ar);r.Ec.registerClass(ir);var or=function(e){function t(t){return e.call(this,2,t)||this}return i(t,e),t.className="SeparableConv2D",t}(function(e){function t(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new w("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new w("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new w("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=Ke(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Jn(n.depthwiseRegularizer),r.depthwiseConstraint=H(n.depthwiseConstraint),r.pointwiseInitializer=Ke(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Jn(n.pointwiseRegularizer),r.pointwiseConstraint=H(n.pointwiseConstraint),r}return i(t,e),t.prototype.build=function(e){if((e=Qe(e)).length1)throw new w("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var a=null==e[0]?null:e[0].slice(1),i=1;i1){var v=he(1,u).concat([0]);t.push(Object(r.ud)(h,v)),c=!0}else t.push(h)}var b=n.mergeFunction(t),w=b.rank;if(c)if(null==w){var x=b.shape;g=[m=x[x.length-1]].concat(x.slice(0,x.length-1)),b=Object(r.ud)(b.reshape([-1,m]),[1,0]).reshape(g)}else w>1&&(v=[w-1].concat(he(0,w-1)),b=Object(r.ud)(b,v));return b}return n.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var n=1;n1)throw new w("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return Object(r.od)(function(){return be(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new w("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,a=0,i=t.slice(1);a=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new w("Axis "+t+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new it({ndim:e.length,axes:(r={},r[t]=n,r)})];var r,a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var a=null!=t.training&&t.training,i=Ze(e),o=i.shape,s=o.length,u=he(0,s),l=n.axis>=0?n.axis:n.axis+s;u.splice(l,1);var c=E(1,s);c[l]=o[l];var f=u.slice();f.sort();var p=!r.yd.arraysEqual(f,he(0,s).slice(0,s-1));if(!a)return function(){if(p){var e=n.movingMean.read().reshape(c),t=n.movingVariance.read().reshape(c),r=n.center?n.beta.read().reshape(c):null,a=n.scale?n.gamma.read().reshape(c):null;return Or(i,e,t,r,a,n.epsilon)}return Or(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=function(e,t,n,a,i){return void 0===i&&(i=.001),r.yd.arraysEqual(a.slice().sort(),he(0,e.rank-1))?function(e,t,n,a,i){return void 0===i&&(i=.001),Object(r.od)(function(){var o=Object(r.Mb)(e,a),s=o.mean,u=o.variance;return[Or(e,s,u,n,t,i),s,u]})}(e,t,n,a,i):function(e,t,n,a,i){return void 0===i&&(i=.001),Object(r.od)(function(){for(var o=Object(r.Mb)(e,a),s=o.mean,u=o.variance,l=[],c=0,f=he(0,e.rank);c=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return function(e,t,n){return Object(r.od)(function(){if(4!==e.rank)throw new w("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new w("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new w("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var a;return a="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],Object(r.cc)(e,a)})}(Ze(e),n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ZeroPadding2D",t}(ct);function Cr(e,t,n,a,i,o){return Object(r.od)(function(){var s;J(i),j(ee,"PoolMode",o),Q(a),null==n&&(n=[1,1]),null==a&&(a="valid"),null==i&&(i="channelsLast"),null==o&&(o="max"),e=tr(e,i);var u="same"===a?"same":"valid";return s="max"===o?Object(r.Cb)(e,t,n,u):Object(r.E)(e,t,n,u),"channelsFirst"===i&&(s=Object(r.ud)(s,[0,3,1,2])),s})}r.Ec.registerClass(Ir);var Pr=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new w("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize}if(null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new w("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides}return n.padding=null==t.padding?"valid":t.padding,Q(n.padding),n.inputSpec=[new it({ndim:3})],n}return i(t,e),t.prototype.computeOutputShape=function(e){var t=Qn((e=Qe(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){n.invokeCallHook(e,t),e=me(Ze(e),2);var a=n.poolingFunction(Ze(e),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return Object(r.Xc)(a,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Ar=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"max")},t.className="MaxPooling1D",t}(Pr);r.Ec.registerClass(Ar);var Tr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"avg")},t.className="AveragePooling1D",t}(Pr);r.Ec.registerClass(Tr);var Mr=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new w("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides];return n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,J(n.dataFormat),Q(n.padding),n.inputSpec=[new it({ndim:4})],n}return i(t,e),t.prototype.computeOutputShape=function(e){e=Qe(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=Qn(t,this.poolSize[0],this.padding,this.strides[0]),n=Qn(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return n.invokeCallHook(e,t),n.poolingFunction(Ze(e),n.poolSize,n.strides,n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Rr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"max")},t.className="MaxPooling2D",t}(Mr);r.Ec.registerClass(Rr);var Dr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"avg")},t.className="AveragePooling2D",t}(Mr);r.Ec.registerClass(Dr);var jr=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[new it({ndim:3})],n}return i(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,t){throw new x},t}(ct),Lr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.call=function(e,t){return Object(r.od)(function(){var t=Ze(e);return Object(r.Fb)(t,1)})},t.className="GlobalAveragePooling1D",t}(jr);r.Ec.registerClass(Lr);var Br=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.call=function(e,t){return Object(r.od)(function(){var t=Ze(e);return Object(r.Bb)(t,1)})},t.className="GlobalMaxPooling1D",t}(jr);r.Ec.registerClass(Br);var zr=function(e){function t(t){var n=e.call(this,t)||this;return n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,J(n.dataFormat),n.inputSpec=[new it({ndim:4})],n}return i(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new x},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Fr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);return"channelsLast"===n.dataFormat?Object(r.Fb)(t,[1,2]):Object(r.Fb)(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(zr);r.Ec.registerClass(Fr);var Vr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);return"channelsLast"===n.dataFormat?Object(r.Bb)(t,[1,2]):Object(r.Bb)(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(zr);function Ur(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new w("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function Wr(e,t,n,a,i,o,s,u){void 0===a&&(a=!1),void 0===s&&(s=!1),void 0===u&&(u=!1);var l=t.shape.length;if(l<3)throw new w("Input should be at least 3D, but is "+l+"D.");var c,f,p=[1,0].concat(he(2,l));if(t=Object(r.ud)(t,p),null!=i)throw new x("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=o)throw new x("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),a&&(t=Object(r.uc)(t,0));for(var h=n,d=t.shape[0],m=function(n){var a=ge(t,n,1);a=a.reshape(a.shape.slice(1));var i=Object(r.od)(function(){return e(a,h)});if(f=i[0],u)if(0===n)c=f.expandDims(1);else{var o=Object(r.R)([c,f.expandDims(1)],1);c.dispose(),c=o}h=i[1]},g=0;g1?xe(n,[1,e]):n}):t.cell.stateSize>1?[xe(n,[1,t.cell.stateSize])]:[n]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="RNN",t}(ct);r.Ec.registerClass(qr);var $r=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t}(ct),Gr=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,n.activation=Fn(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=Ke(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Ke(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Ke(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Jn(t.kernelRegularizer),n.recurrentRegularizer=Jn(t.recurrentRegularizer),n.biasRegularizer=Jn(t.biasRegularizer),n.kernelConstraint=H(t.kernelConstraint),n.recurrentConstraint=H(t.recurrentConstraint),n.biasConstraint=H(t.biasConstraint),n.dropout=fe([1,pe([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=fe([1,pe([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return i(t,e),t.prototype.build=function(e){e=Qe(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){if(2!==(e=e).length)throw new w("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var a=e[1];e=e[0];var i,o=null!=t.training&&t.training;01){for(var o=[],s=0;s= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t)},t.prototype.computeOutputShape=function(e){var t=[(e=Qe(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return Wr(function(e,r){return[Ze(n.layer.call(e,t)),[]]},e=Ze(e),[],!1,null,null,!1,!0)[1]})},t.className="TimeDistributed",t}(ea);r.Ec.registerClass(ta);var na=["sum","mul","concat","ave"],ra=function(e){function t(t){var n=e.call(this,t)||this,r=t.layer.getConfig();if(n.forwardLayer=tn({className:t.layer.getClassName(),config:r}),r.goBackwards=!0!==r.goBackwards,n.backwardLayer=tn({className:t.layer.getClassName(),config:r}),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,function(e){j(na,"BidirectionalMergeMode",e)}(t.mergeMode),n.mergeMode=t.mergeMode,t.weights)throw new x("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n.numConstants=null,n}return i(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))},t.prototype.computeOutputShape=function(e){var t,n,r,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(r=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):O(n)},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,a=null==n?null:n.constants;null==n&&(n={});var i=Ur(t,r,a,this.numConstants);if(t=i.inputs,r=i.initialState,a=i.constants,Array.isArray(t)&&(r=t.slice(1),t=t[0]),(null==r||0===r.length)&&null==a)return e.prototype.apply.call(this,t,n);var o=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new w("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,o.push.apply(o,r);var l=r.map(function(e){return new it({shape:e.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=a)throw new x("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof ot,f=0,p=o;f0?a(r(e),9007199254740991):0}},function(e,t){var n=e.exports={version:"2.6.1"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(4),a=n(293),i=n(52),o=Object.defineProperty;t.f=n(14)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),a)try{return o(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){e.exports=!n(8)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){(function(e){!function(e,t){"use strict";function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function a(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function i(e,t,n){if(i.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o=n(435).Buffer}catch(e){}function s(e,t,n){for(var r=0,a=Math.min(e.length,n),i=t;i=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return r}function u(e,t,n,r){for(var a=0,i=Math.min(e.length,n),o=t;o=49?s-49+10:s>=17?s-17+10:s}return a}i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var a=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&a++,16===t?this._parseHex(e,a):this._parseBase(e,t,a),"-"===e[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var a=0;a=0;a-=3)o=e[a]|e[a-1]<<8|e[a-2]<<16,this.words[i]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,i++);else if("le"===n)for(a=0,i=0;a>>26-s&67108863,(s+=24)>=26&&(s-=26,i++);return this.strip()},i.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)a=s(e,n,n+6),this.words[r]|=a<>>26-i&4194303,(i+=24)>=26&&(i-=26,r++);n+6!==t&&(a=s(e,t,n+6),this.words[r]|=a<>>26-i&4194303),this.strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,a=1;a<=67108863;a*=t)r++;r--,a=a/t|0;for(var i=e.length-n,o=i%r,s=Math.min(i,i-o)+n,l=0,c=n;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],c=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var a=0|e.words[0],i=0|t.words[0],o=a*i,s=67108863&o,u=o/67108864|0;n.words[0]=s;for(var l=1;l>>26,f=67108863&u,p=Math.min(l,t.length-1),h=Math.max(0,l-e.length+1);h<=p;h++){var d=l-h|0;c+=(o=(a=0|e.words[d])*(i=0|t.words[h])+f)/67108864|0,f=67108863&o}n.words[l]=0|f,u=0|c}return 0!==u?n.words[l]=0|u:n.length--,n.strip()}i.prototype.toString=function(e,t){var n;if(e=e||10,t=0|t||1,16===e||"hex"===e){n="";for(var a=0,i=0,o=0;o>>24-a&16777215)||o!==this.length-1?l[6-u.length]+u+n:u+n,(a+=2)>=26&&(a-=26,o--)}for(0!==i&&(n=i.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var p=c[e],h=f[e];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var m=d.modn(h).toString(e);n=(d=d.idivn(h)).isZero()?m+n:l[p-m.length]+m+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(e,t){return r(void 0!==o),this.toArrayLike(o,e,t)},i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,n){var a=this.byteLength(),i=n||Math.max(1,a);r(a<=i,"byte array longer than desired length"),r(i>0,"Requested array length <= 0"),this.strip();var o,s,u="le"===t,l=new e(i),c=this.clone();if(u){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),l[s]=o;for(;s=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},i.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;re.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var a=0;a0&&(this.words[a]=~this.words[a]&67108863>>26-n),this.strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,a=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,r=e):(n=e,r=this);for(var a=0,i=0;i>>26;for(;0!==a&&i>>26;if(this.length=n.length,0!==a)this.words[this.length]=a,this.length++;else if(n!==this)for(;ie.length?this.clone().iadd(e):e.clone().iadd(this)},i.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,a=this.cmp(e);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o>26,this.words[o]=67108863&t;for(;0!==i&&o>26,this.words[o]=67108863&t;if(0===i&&o>>13,h=0|o[1],d=8191&h,m=h>>>13,g=0|o[2],y=8191&g,v=g>>>13,b=0|o[3],w=8191&b,x=b>>>13,_=0|o[4],E=8191&_,N=_>>>13,S=0|o[5],O=8191&S,k=S>>>13,I=0|o[6],C=8191&I,P=I>>>13,A=0|o[7],T=8191&A,M=A>>>13,R=0|o[8],D=8191&R,j=R>>>13,L=0|o[9],B=8191&L,z=L>>>13,F=0|s[0],V=8191&F,U=F>>>13,W=0|s[1],q=8191&W,$=W>>>13,G=0|s[2],H=8191&G,K=G>>>13,X=0|s[3],Y=8191&X,J=X>>>13,Z=0|s[4],Q=8191&Z,ee=Z>>>13,te=0|s[5],ne=8191&te,re=te>>>13,ae=0|s[6],ie=8191&ae,oe=ae>>>13,se=0|s[7],ue=8191&se,le=se>>>13,ce=0|s[8],fe=8191&ce,pe=ce>>>13,he=0|s[9],de=8191&he,me=he>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(l+(r=Math.imul(f,V))|0)+((8191&(a=(a=Math.imul(f,U))+Math.imul(p,V)|0))<<13)|0;l=((i=Math.imul(p,U))+(a>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(d,V),a=(a=Math.imul(d,U))+Math.imul(m,V)|0,i=Math.imul(m,U);var ye=(l+(r=r+Math.imul(f,q)|0)|0)+((8191&(a=(a=a+Math.imul(f,$)|0)+Math.imul(p,q)|0))<<13)|0;l=((i=i+Math.imul(p,$)|0)+(a>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,V),a=(a=Math.imul(y,U))+Math.imul(v,V)|0,i=Math.imul(v,U),r=r+Math.imul(d,q)|0,a=(a=a+Math.imul(d,$)|0)+Math.imul(m,q)|0,i=i+Math.imul(m,$)|0;var ve=(l+(r=r+Math.imul(f,H)|0)|0)+((8191&(a=(a=a+Math.imul(f,K)|0)+Math.imul(p,H)|0))<<13)|0;l=((i=i+Math.imul(p,K)|0)+(a>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(w,V),a=(a=Math.imul(w,U))+Math.imul(x,V)|0,i=Math.imul(x,U),r=r+Math.imul(y,q)|0,a=(a=a+Math.imul(y,$)|0)+Math.imul(v,q)|0,i=i+Math.imul(v,$)|0,r=r+Math.imul(d,H)|0,a=(a=a+Math.imul(d,K)|0)+Math.imul(m,H)|0,i=i+Math.imul(m,K)|0;var be=(l+(r=r+Math.imul(f,Y)|0)|0)+((8191&(a=(a=a+Math.imul(f,J)|0)+Math.imul(p,Y)|0))<<13)|0;l=((i=i+Math.imul(p,J)|0)+(a>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(E,V),a=(a=Math.imul(E,U))+Math.imul(N,V)|0,i=Math.imul(N,U),r=r+Math.imul(w,q)|0,a=(a=a+Math.imul(w,$)|0)+Math.imul(x,q)|0,i=i+Math.imul(x,$)|0,r=r+Math.imul(y,H)|0,a=(a=a+Math.imul(y,K)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,K)|0,r=r+Math.imul(d,Y)|0,a=(a=a+Math.imul(d,J)|0)+Math.imul(m,Y)|0,i=i+Math.imul(m,J)|0;var we=(l+(r=r+Math.imul(f,Q)|0)|0)+((8191&(a=(a=a+Math.imul(f,ee)|0)+Math.imul(p,Q)|0))<<13)|0;l=((i=i+Math.imul(p,ee)|0)+(a>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(O,V),a=(a=Math.imul(O,U))+Math.imul(k,V)|0,i=Math.imul(k,U),r=r+Math.imul(E,q)|0,a=(a=a+Math.imul(E,$)|0)+Math.imul(N,q)|0,i=i+Math.imul(N,$)|0,r=r+Math.imul(w,H)|0,a=(a=a+Math.imul(w,K)|0)+Math.imul(x,H)|0,i=i+Math.imul(x,K)|0,r=r+Math.imul(y,Y)|0,a=(a=a+Math.imul(y,J)|0)+Math.imul(v,Y)|0,i=i+Math.imul(v,J)|0,r=r+Math.imul(d,Q)|0,a=(a=a+Math.imul(d,ee)|0)+Math.imul(m,Q)|0,i=i+Math.imul(m,ee)|0;var xe=(l+(r=r+Math.imul(f,ne)|0)|0)+((8191&(a=(a=a+Math.imul(f,re)|0)+Math.imul(p,ne)|0))<<13)|0;l=((i=i+Math.imul(p,re)|0)+(a>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(C,V),a=(a=Math.imul(C,U))+Math.imul(P,V)|0,i=Math.imul(P,U),r=r+Math.imul(O,q)|0,a=(a=a+Math.imul(O,$)|0)+Math.imul(k,q)|0,i=i+Math.imul(k,$)|0,r=r+Math.imul(E,H)|0,a=(a=a+Math.imul(E,K)|0)+Math.imul(N,H)|0,i=i+Math.imul(N,K)|0,r=r+Math.imul(w,Y)|0,a=(a=a+Math.imul(w,J)|0)+Math.imul(x,Y)|0,i=i+Math.imul(x,J)|0,r=r+Math.imul(y,Q)|0,a=(a=a+Math.imul(y,ee)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,ee)|0,r=r+Math.imul(d,ne)|0,a=(a=a+Math.imul(d,re)|0)+Math.imul(m,ne)|0,i=i+Math.imul(m,re)|0;var _e=(l+(r=r+Math.imul(f,ie)|0)|0)+((8191&(a=(a=a+Math.imul(f,oe)|0)+Math.imul(p,ie)|0))<<13)|0;l=((i=i+Math.imul(p,oe)|0)+(a>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(T,V),a=(a=Math.imul(T,U))+Math.imul(M,V)|0,i=Math.imul(M,U),r=r+Math.imul(C,q)|0,a=(a=a+Math.imul(C,$)|0)+Math.imul(P,q)|0,i=i+Math.imul(P,$)|0,r=r+Math.imul(O,H)|0,a=(a=a+Math.imul(O,K)|0)+Math.imul(k,H)|0,i=i+Math.imul(k,K)|0,r=r+Math.imul(E,Y)|0,a=(a=a+Math.imul(E,J)|0)+Math.imul(N,Y)|0,i=i+Math.imul(N,J)|0,r=r+Math.imul(w,Q)|0,a=(a=a+Math.imul(w,ee)|0)+Math.imul(x,Q)|0,i=i+Math.imul(x,ee)|0,r=r+Math.imul(y,ne)|0,a=(a=a+Math.imul(y,re)|0)+Math.imul(v,ne)|0,i=i+Math.imul(v,re)|0,r=r+Math.imul(d,ie)|0,a=(a=a+Math.imul(d,oe)|0)+Math.imul(m,ie)|0,i=i+Math.imul(m,oe)|0;var Ee=(l+(r=r+Math.imul(f,ue)|0)|0)+((8191&(a=(a=a+Math.imul(f,le)|0)+Math.imul(p,ue)|0))<<13)|0;l=((i=i+Math.imul(p,le)|0)+(a>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(D,V),a=(a=Math.imul(D,U))+Math.imul(j,V)|0,i=Math.imul(j,U),r=r+Math.imul(T,q)|0,a=(a=a+Math.imul(T,$)|0)+Math.imul(M,q)|0,i=i+Math.imul(M,$)|0,r=r+Math.imul(C,H)|0,a=(a=a+Math.imul(C,K)|0)+Math.imul(P,H)|0,i=i+Math.imul(P,K)|0,r=r+Math.imul(O,Y)|0,a=(a=a+Math.imul(O,J)|0)+Math.imul(k,Y)|0,i=i+Math.imul(k,J)|0,r=r+Math.imul(E,Q)|0,a=(a=a+Math.imul(E,ee)|0)+Math.imul(N,Q)|0,i=i+Math.imul(N,ee)|0,r=r+Math.imul(w,ne)|0,a=(a=a+Math.imul(w,re)|0)+Math.imul(x,ne)|0,i=i+Math.imul(x,re)|0,r=r+Math.imul(y,ie)|0,a=(a=a+Math.imul(y,oe)|0)+Math.imul(v,ie)|0,i=i+Math.imul(v,oe)|0,r=r+Math.imul(d,ue)|0,a=(a=a+Math.imul(d,le)|0)+Math.imul(m,ue)|0,i=i+Math.imul(m,le)|0;var Ne=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(a=(a=a+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((i=i+Math.imul(p,pe)|0)+(a>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(B,V),a=(a=Math.imul(B,U))+Math.imul(z,V)|0,i=Math.imul(z,U),r=r+Math.imul(D,q)|0,a=(a=a+Math.imul(D,$)|0)+Math.imul(j,q)|0,i=i+Math.imul(j,$)|0,r=r+Math.imul(T,H)|0,a=(a=a+Math.imul(T,K)|0)+Math.imul(M,H)|0,i=i+Math.imul(M,K)|0,r=r+Math.imul(C,Y)|0,a=(a=a+Math.imul(C,J)|0)+Math.imul(P,Y)|0,i=i+Math.imul(P,J)|0,r=r+Math.imul(O,Q)|0,a=(a=a+Math.imul(O,ee)|0)+Math.imul(k,Q)|0,i=i+Math.imul(k,ee)|0,r=r+Math.imul(E,ne)|0,a=(a=a+Math.imul(E,re)|0)+Math.imul(N,ne)|0,i=i+Math.imul(N,re)|0,r=r+Math.imul(w,ie)|0,a=(a=a+Math.imul(w,oe)|0)+Math.imul(x,ie)|0,i=i+Math.imul(x,oe)|0,r=r+Math.imul(y,ue)|0,a=(a=a+Math.imul(y,le)|0)+Math.imul(v,ue)|0,i=i+Math.imul(v,le)|0,r=r+Math.imul(d,fe)|0,a=(a=a+Math.imul(d,pe)|0)+Math.imul(m,fe)|0,i=i+Math.imul(m,pe)|0;var Se=(l+(r=r+Math.imul(f,de)|0)|0)+((8191&(a=(a=a+Math.imul(f,me)|0)+Math.imul(p,de)|0))<<13)|0;l=((i=i+Math.imul(p,me)|0)+(a>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(B,q),a=(a=Math.imul(B,$))+Math.imul(z,q)|0,i=Math.imul(z,$),r=r+Math.imul(D,H)|0,a=(a=a+Math.imul(D,K)|0)+Math.imul(j,H)|0,i=i+Math.imul(j,K)|0,r=r+Math.imul(T,Y)|0,a=(a=a+Math.imul(T,J)|0)+Math.imul(M,Y)|0,i=i+Math.imul(M,J)|0,r=r+Math.imul(C,Q)|0,a=(a=a+Math.imul(C,ee)|0)+Math.imul(P,Q)|0,i=i+Math.imul(P,ee)|0,r=r+Math.imul(O,ne)|0,a=(a=a+Math.imul(O,re)|0)+Math.imul(k,ne)|0,i=i+Math.imul(k,re)|0,r=r+Math.imul(E,ie)|0,a=(a=a+Math.imul(E,oe)|0)+Math.imul(N,ie)|0,i=i+Math.imul(N,oe)|0,r=r+Math.imul(w,ue)|0,a=(a=a+Math.imul(w,le)|0)+Math.imul(x,ue)|0,i=i+Math.imul(x,le)|0,r=r+Math.imul(y,fe)|0,a=(a=a+Math.imul(y,pe)|0)+Math.imul(v,fe)|0,i=i+Math.imul(v,pe)|0;var Oe=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(a=(a=a+Math.imul(d,me)|0)+Math.imul(m,de)|0))<<13)|0;l=((i=i+Math.imul(m,me)|0)+(a>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(B,H),a=(a=Math.imul(B,K))+Math.imul(z,H)|0,i=Math.imul(z,K),r=r+Math.imul(D,Y)|0,a=(a=a+Math.imul(D,J)|0)+Math.imul(j,Y)|0,i=i+Math.imul(j,J)|0,r=r+Math.imul(T,Q)|0,a=(a=a+Math.imul(T,ee)|0)+Math.imul(M,Q)|0,i=i+Math.imul(M,ee)|0,r=r+Math.imul(C,ne)|0,a=(a=a+Math.imul(C,re)|0)+Math.imul(P,ne)|0,i=i+Math.imul(P,re)|0,r=r+Math.imul(O,ie)|0,a=(a=a+Math.imul(O,oe)|0)+Math.imul(k,ie)|0,i=i+Math.imul(k,oe)|0,r=r+Math.imul(E,ue)|0,a=(a=a+Math.imul(E,le)|0)+Math.imul(N,ue)|0,i=i+Math.imul(N,le)|0,r=r+Math.imul(w,fe)|0,a=(a=a+Math.imul(w,pe)|0)+Math.imul(x,fe)|0,i=i+Math.imul(x,pe)|0;var ke=(l+(r=r+Math.imul(y,de)|0)|0)+((8191&(a=(a=a+Math.imul(y,me)|0)+Math.imul(v,de)|0))<<13)|0;l=((i=i+Math.imul(v,me)|0)+(a>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(B,Y),a=(a=Math.imul(B,J))+Math.imul(z,Y)|0,i=Math.imul(z,J),r=r+Math.imul(D,Q)|0,a=(a=a+Math.imul(D,ee)|0)+Math.imul(j,Q)|0,i=i+Math.imul(j,ee)|0,r=r+Math.imul(T,ne)|0,a=(a=a+Math.imul(T,re)|0)+Math.imul(M,ne)|0,i=i+Math.imul(M,re)|0,r=r+Math.imul(C,ie)|0,a=(a=a+Math.imul(C,oe)|0)+Math.imul(P,ie)|0,i=i+Math.imul(P,oe)|0,r=r+Math.imul(O,ue)|0,a=(a=a+Math.imul(O,le)|0)+Math.imul(k,ue)|0,i=i+Math.imul(k,le)|0,r=r+Math.imul(E,fe)|0,a=(a=a+Math.imul(E,pe)|0)+Math.imul(N,fe)|0,i=i+Math.imul(N,pe)|0;var Ie=(l+(r=r+Math.imul(w,de)|0)|0)+((8191&(a=(a=a+Math.imul(w,me)|0)+Math.imul(x,de)|0))<<13)|0;l=((i=i+Math.imul(x,me)|0)+(a>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(B,Q),a=(a=Math.imul(B,ee))+Math.imul(z,Q)|0,i=Math.imul(z,ee),r=r+Math.imul(D,ne)|0,a=(a=a+Math.imul(D,re)|0)+Math.imul(j,ne)|0,i=i+Math.imul(j,re)|0,r=r+Math.imul(T,ie)|0,a=(a=a+Math.imul(T,oe)|0)+Math.imul(M,ie)|0,i=i+Math.imul(M,oe)|0,r=r+Math.imul(C,ue)|0,a=(a=a+Math.imul(C,le)|0)+Math.imul(P,ue)|0,i=i+Math.imul(P,le)|0,r=r+Math.imul(O,fe)|0,a=(a=a+Math.imul(O,pe)|0)+Math.imul(k,fe)|0,i=i+Math.imul(k,pe)|0;var Ce=(l+(r=r+Math.imul(E,de)|0)|0)+((8191&(a=(a=a+Math.imul(E,me)|0)+Math.imul(N,de)|0))<<13)|0;l=((i=i+Math.imul(N,me)|0)+(a>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(B,ne),a=(a=Math.imul(B,re))+Math.imul(z,ne)|0,i=Math.imul(z,re),r=r+Math.imul(D,ie)|0,a=(a=a+Math.imul(D,oe)|0)+Math.imul(j,ie)|0,i=i+Math.imul(j,oe)|0,r=r+Math.imul(T,ue)|0,a=(a=a+Math.imul(T,le)|0)+Math.imul(M,ue)|0,i=i+Math.imul(M,le)|0,r=r+Math.imul(C,fe)|0,a=(a=a+Math.imul(C,pe)|0)+Math.imul(P,fe)|0,i=i+Math.imul(P,pe)|0;var Pe=(l+(r=r+Math.imul(O,de)|0)|0)+((8191&(a=(a=a+Math.imul(O,me)|0)+Math.imul(k,de)|0))<<13)|0;l=((i=i+Math.imul(k,me)|0)+(a>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(B,ie),a=(a=Math.imul(B,oe))+Math.imul(z,ie)|0,i=Math.imul(z,oe),r=r+Math.imul(D,ue)|0,a=(a=a+Math.imul(D,le)|0)+Math.imul(j,ue)|0,i=i+Math.imul(j,le)|0,r=r+Math.imul(T,fe)|0,a=(a=a+Math.imul(T,pe)|0)+Math.imul(M,fe)|0,i=i+Math.imul(M,pe)|0;var Ae=(l+(r=r+Math.imul(C,de)|0)|0)+((8191&(a=(a=a+Math.imul(C,me)|0)+Math.imul(P,de)|0))<<13)|0;l=((i=i+Math.imul(P,me)|0)+(a>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(B,ue),a=(a=Math.imul(B,le))+Math.imul(z,ue)|0,i=Math.imul(z,le),r=r+Math.imul(D,fe)|0,a=(a=a+Math.imul(D,pe)|0)+Math.imul(j,fe)|0,i=i+Math.imul(j,pe)|0;var Te=(l+(r=r+Math.imul(T,de)|0)|0)+((8191&(a=(a=a+Math.imul(T,me)|0)+Math.imul(M,de)|0))<<13)|0;l=((i=i+Math.imul(M,me)|0)+(a>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(B,fe),a=(a=Math.imul(B,pe))+Math.imul(z,fe)|0,i=Math.imul(z,pe);var Me=(l+(r=r+Math.imul(D,de)|0)|0)+((8191&(a=(a=a+Math.imul(D,me)|0)+Math.imul(j,de)|0))<<13)|0;l=((i=i+Math.imul(j,me)|0)+(a>>>13)|0)+(Me>>>26)|0,Me&=67108863;var Re=(l+(r=Math.imul(B,de))|0)+((8191&(a=(a=Math.imul(B,me))+Math.imul(z,de)|0))<<13)|0;return l=((i=Math.imul(z,me))+(a>>>13)|0)+(Re>>>26)|0,Re&=67108863,u[0]=ge,u[1]=ye,u[2]=ve,u[3]=be,u[4]=we,u[5]=xe,u[6]=_e,u[7]=Ee,u[8]=Ne,u[9]=Se,u[10]=Oe,u[11]=ke,u[12]=Ie,u[13]=Ce,u[14]=Pe,u[15]=Ae,u[16]=Te,u[17]=Me,u[18]=Re,0!==l&&(u[19]=l,n.length++),n};function d(e,t,n){return(new m).mulp(e,t,n)}function m(e,t){this.x=e,this.y=t}Math.imul||(h=p),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?h(this,e,t):n<63?p(this,e,t):n<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,a=0,i=0;i>>26)|0)>>>26,o&=67108863}n.words[i]=s,r=o,o=a}return 0!==r?n.words[i]=r:n.length--,n.strip()}(this,e,t):d(this,e,t)},m.prototype.makeRBT=function(e){for(var t=new Array(e),n=i.prototype._countBits(e)-1,r=0;r>=1;return r},m.prototype.permute=function(e,t,n,r,a,i){for(var o=0;o>>=1)a++;return 1<>>=13,n[2*o+1]=8191&i,i>>>=13;for(o=2*t;o>=26,t+=a/67108864|0,t+=i>>>26,this.words[n]=67108863&i}return 0!==t&&(this.words[n]=t,this.length++),this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>a}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r=0);var t,n=e%26,a=(e-n)/26,i=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(t=0;t>>26-n}o&&(this.words[t]=o,this.length++)}if(0!==a){for(t=this.length-1;t>=0;t--)this.words[t+a]=this.words[t];for(t=0;t=0),a=t?(t-t%26)/26:0;var i=e%26,o=Math.min((e-i)/26,this.length),s=67108863^67108863>>>i<o)for(this.length-=o,l=0;l=0&&(0!==c||l>=a);l--){var f=0|this.words[l];this.words[l]=c<<26-i|f>>>i,c=f&s}return u&&0!==c&&(u.words[u.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,a=1<=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var a=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},i.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[a+n]=67108863&i}for(;a>26,this.words[a+n]=67108863&i;if(0===s)return this.strip();for(r(-1===s),s=0,a=0;a>26,this.words[a]=67108863&i;return this.negative=1,this.strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),a=e,o=0|a.words[a.length-1];0!=(n=26-this._countBits(o))&&(a=a.ushln(n),r.iushln(n),o=0|a.words[a.length-1]);var s,u=r.length-a.length;if("mod"!==t){(s=new i(null)).length=u+1,s.words=new Array(s.length);for(var l=0;l=0;f--){var p=67108864*(0|r.words[a.length+f])+(0|r.words[a.length+f-1]);for(p=Math.min(p/o|0,67108863),r._ishlnsubmul(a,p,f);0!==r.negative;)p--,r.negative=0,r._ishlnsubmul(a,1,f),r.isZero()||(r.negative^=1);s&&(s.words[f]=p)}return s&&s.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:s||null,mod:r}},i.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(a=s.div.neg()),"div"!==t&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(e)),{div:a,mod:o}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(e)),{div:s.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modn(e.words[0]))}:this._wordDiv(e,t);var a,o,s},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),a=e.andln(1),i=n.cmp(r);return i<0||1===a&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,a=this.length-1;a>=0;a--)n=(t*n+(0|this.words[a]))%e;return n},i.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var a=(0|this.words[n])+67108864*t;this.words[n]=a/e|0,t=a%e}return this.strip()},i.prototype.divn=function(e){return this.clone().idivn(e)},i.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new i(1),o=new i(0),s=new i(0),u=new i(1),l=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++l;for(var c=n.clone(),f=t.clone();!t.isZero();){for(var p=0,h=1;0==(t.words[0]&h)&&p<26;++p,h<<=1);if(p>0)for(t.iushrn(p);p-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(f)),a.iushrn(1),o.iushrn(1);for(var d=0,m=1;0==(n.words[0]&m)&&d<26;++d,m<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(c),u.isub(f)),s.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),a.isub(s),o.isub(u)):(n.isub(t),s.isub(a),u.isub(o))}return{a:s,b:u,gcd:n.iushln(l)}},i.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a,o=new i(1),s=new i(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var l=0,c=1;0==(t.words[0]&c)&&l<26;++l,c<<=1);if(l>0)for(t.iushrn(l);l-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);for(var f=0,p=1;0==(n.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(n.iushrn(f);f-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(n)>=0?(t.isub(n),o.isub(s)):(n.isub(t),s.isub(o))}return(a=0===t.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(e),a},i.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var a=t.cmp(n);if(a<0){var i=t;t=n,n=i}else if(0===a||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,a=1<>>26,s&=67108863,this.words[o]=s}return 0!==i&&(this.words[o]=i,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var a=0|this.words[0];t=a===e?0:ae.length)return 1;if(this.length=0;n--){var r=0|this.words[n],a=0|e.words[n];if(r!==a){ra&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new _(e)},i.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var g={k256:null,p224:null,p192:null,p25519:null};function y(e,t){this.name=e,this.p=new i(t,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function x(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(e){if("string"==typeof e){var t=i._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){_.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},y.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t0?n.isub(this.p):n.strip(),n},y.prototype.split=function(e,t){e.iushrn(this.n,0,t)},y.prototype.imulK=function(e){return e.imul(this.k)},a(v,y),v.prototype.split=function(e,t){for(var n=Math.min(e.length,9),r=0;r>>22,a=i}a>>>=22,e.words[r-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=a,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._prime=function(e){if(g[e])return g[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new b;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new x}return g[e]=t,t},_.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},_.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},_.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},_.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},_.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},_.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},_.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},_.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},_.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},_.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},_.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},_.prototype.isqr=function(e){return this.imul(e,e.clone())},_.prototype.sqr=function(e){return this.mul(e,e)},_.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new i(1)).iushrn(2);return this.pow(e,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),u=s.redNeg(),l=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,l).cmp(u);)c.redIAdd(u);for(var f=this.pow(c,a),p=this.pow(e,a.addn(1).iushrn(1)),h=this.pow(e,a),d=o;0!==h.cmp(s);){for(var m=h,g=0;0!==m.cmp(s);g++)m=m.redSqr();r(g=0;r--){for(var l=t.words[r],c=u-1;c>=0;c--){var f=l>>c&1;a!==n[0]&&(a=this.sqr(a)),0!==f||0!==o?(o<<=1,o|=f,(4==++s||0===r&&0===c)&&(a=this.mul(a,n[o]),s=0,o=0)):s=0}u=26}return a},_.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},_.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new E(e)},a(E,_),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=n.isub(r).iushrn(this.shift),i=a;return a.cmp(this.m)>=0?i=a.isub(this.m):a.cmpn(0)<0&&(i=a.iadd(this.m)),i._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=n.isub(r).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===e||e,this)}).call(this,n(436)(e))},function(e,t,n){"use strict";(function(e){ + */function i(e,t){function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]t?1:0}(e,t)}function R(e){if(null==e)return e;for(var t=[],n=0,r=e;n=0),E(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(function(e){return typeof e===t})}function z(e,t){return Object(r.od)(function(){return Object(r.Tc)(Object(r.dd)(Object(r.Pb)(e,e),t,!0))})}var B=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.getConfig=function(){return{}},t}(r.Ec.Serializable),F=function(e){function t(t){var n=e.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){var n=z(e,t.axis),a=Object(r.O)(n,0,t.maxValue);return Object(r.Ob)(e,Object(r.Ha)(a,Object(r.s)(y(c()),n)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(B);r.Ec.registerClass(F);var V=function(e){function t(t){var n=e.call(this)||this;return n.defaultAxis=0,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){return Object(r.Ha)(e,Object(r.s)(y(c()),z(e,t.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(B);r.Ec.registerClass(V);var U=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e){return Object(r.sc)(e)},t.className="NonNeg",t}(B);r.Ec.registerClass(U);var W=function(e){function t(t){var n=e.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=t.minValue?t.minValue:n.defaultMinValue,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.rate=null!=t.rate?t.rate:n.defaultRate,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return i(t,e),t.prototype.apply=function(e){var t=this;return Object(r.od)(function(){var n=z(e,t.axis),a=Object(r.s)(Object(r.Ob)(y(t.rate),Object(r.O)(n,t.minValue,t.maxValue)),Object(r.Ob)(y(1-t.rate),n));return Object(r.Ob)(e,Object(r.Ha)(a,Object(r.s)(y(c()),n)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(B);r.Ec.registerClass(W);var q={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function $(e){return P(e)}function G(e,t){return void 0===t&&(t={}),T(e,r.Ec.SerializationMap.getMap().classNameMap,t,"constraint")}function H(e){return null==e?null:"string"==typeof e?G({className:e in q?q[e]:e,config:{}}):e instanceof B?e:G(e)}var K=Object.freeze({maxNorm:function(e){return new F(e)},unitNorm:function(e){return new V(e)},nonNeg:function(){return new U},minMaxNorm:function(e){return new W(e)}}),X=new Map,Y=["channelsFirst","channelsLast"];function J(e){j(Y,"DataFormat",e)}var Z=["valid","same","causal"];function Q(e){j(Z,"PaddingMode",e)}var ee=["max","avg"],te=[],ne="/";function re(e,t){te.push(e);try{var n=t();return te.pop(),n}catch(e){throw te.pop(),e}}function ae(e){if(!se(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===te.length?"":te.join(ne)+ne)+e}function ie(e){if(!se(e))throw new Error("Not a valid tensor name: '"+e+"'");X.has(e)||X.set(e,0);var t=X.get(e);if(X.set(e,X.get(e)+1),t>0){var n=e+"_"+t;return X.set(n,1),n}return e}var oe=new RegExp(/^[A-Za-z][A-Za-z0-9\._\/]*$/);function se(e){return!!e.match(oe)}function ue(e){return e===parseInt(e.toString(),10)}function le(e,t,n){null==t&&(t=0),null==n&&(n=e.length);for(var r=1,a=t;a= 2 but got x shape = "+e.shape+" and y shape = "+t.shape);if(t.rank>=3&&(a=e.shape.slice(-1)[0])!==(s=t.shape.slice(-2)[0]))throw new x("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and y shape = "+t.shape);if(2===e.rank&&2===t.rank)return Object(r.Ab)(e,t);var n=e.shape.slice(),a=n.pop();e=e.reshape([-1,a]);var i=t.shape.slice(),o=i.pop(),s=i.pop(),u=i.concat([o]),l=Array.from({length:t.rank},function(e,n){return 0===n?t.rank-2:n<=t.rank-2?n-1:n});t=t.transpose(l).reshape([s,-1]);var c=n.concat(u);return Object(r.Ab)(e,t).reshape(c)}function Ee(e,t,n){return Object(r.od)(function(){return t=Array.isArray(t)?Object(r.hd)(t,"int32"):t.toInt(),Object(r.Xa)(e,t,n)})}function Ne(e){return Object(r.Pb)(e,e)}function Oe(e,t,n){return Object(r.od)(function(){if(null==n&&(n="channelsLast"),J(n),1!==t.rank&&t.rank!==e.rank)throw new w("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e.rank);var r,a=t.shape;if(5===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1,1])):e.add(t.reshape([1,a[3],a[0],a[1],a[2]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(4===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1])):e.add(t.reshape([1,a[2],a[0],a[1]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(3===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1])):e.add(t.reshape([1,a[1],a[0]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,a[0]])):e.add(t.reshape([1].concat(a))));else{if(!(e.rank<3))throw new w("Unsupported input rank by biasAdd: "+e.rank);r=e.add(t)}return r})}function ke(e,t,n,a){return Object(r.od)(function(){if(null!=n&&!r.yd.arraysEqual(e.shape,n))throw new x("Non-default noise shape is not implemented yet: "+JSON.stringify(n));if(null!=a)throw new x("seed is not implemented for dropout yet.");var i=Object(r.Zc)(Object(r.s)(Object(r.Sb)(t),Object(r.oc)(e.shape,0,1,"float32")));return i=Object(r.Ob)(Object(r.Ha)(y(1),Object(r.bd)(y(1),t)),i),Object(r.Ob)(e,i)})}function Ie(e,t,n){return void 0===n&&(n=!1),n?e():t()}var Ce=["fanIn","fanOut","fanAvg"],Ae=["normal","uniform"],Pe=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(r.Ec.Serializable),Te=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e,t){return Object(r.Hd)(e,t)},t.className="Zeros",t}(Pe);r.Ec.registerClass(Te);var Me=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.apply=function(e,t){return Object(r.Yb)(e,t)},t.className="Ones",t}(Pe);r.Ec.registerClass(Me);var Re=function(e){function t(t){var n=e.call(this)||this;if("object"!=typeof t)throw new w("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new w("config must have value set but got "+t);return n.value=t.value,n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){return Object(r.Ob)(Object(r.Bc)(n.value),Object(r.Yb)(e,t))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(Pe);r.Ec.registerClass(Re);var De=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){return Object(r.oc)(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(Pe);r.Ec.registerClass(De);var je=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x("randomNormal does not support dType "+t+".");return _e(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(Pe);r.Ec.registerClass(je);var Le=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x("truncatedNormal does not support dType "+t+".");return Object(r.vd)(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(Pe);r.Ec.registerClass(Le);var ze=function(e){function t(t){var n=e.call(this)||this;return n.gain=null!=t.gain?Object(r.Bc)(t.gain):y(1),n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){if(2!==e.length||e[0]!==e[1])throw new w("Identity matrix initializer can only be used for 2D square matrices.");return Object(r.Ob)(n.gain,Object(r.Sa)(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain.get()}},t.className="Identity",t}(Pe);r.Ec.registerClass(ze);var Be=function(e){function t(t){var n=e.call(this)||this;if(t.scale<0)throw new w("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=t.mode,function(e){j(Ce,"FanMode",e)}(n.mode),n.distribution=t.distribution,function(e){j(Ae,"Distribution",e)}(n.distribution),n.seed=t.seed,n}return i(t,e),t.prototype.apply=function(e,t){var n=function(e,t){var n,r;if(void 0===t&&(t="channelsLast"),J(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length))if("channelsFirst"===t){var a=le(e,2);n=e[1]*a,r=e[0]*a}else"channelsLast"===t&&(a=le(e,0,e.length-2),n=e[e.length-2]*a,r=e[e.length-1]*a);else{var i=le(e);n=Math.sqrt(i),r=Math.sqrt(i)}return[n,r]}(e),a=n[0],i=n[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,a):"fanOut"===this.mode?o/=Math.max(1,i):o/=Math.max(1,(a+i)/2),"normal"===this.distribution){var s=Math.sqrt(o);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new x(this.getClassName()+" does not support dType "+t+".");return Object(r.vd)(e,0,s,t,this.seed)}var u=Math.sqrt(3*o);return Object(r.oc)(e,-u,u,t)},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(Pe);r.Ec.registerClass(Be);var Fe=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return Be.className},t}(Be),Ve=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return Be.className},t}(Be),Ue=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return Be.className},t}(Be),We=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return i(t,e),t.prototype.getClassName=function(){return Be.className},t}(Be),qe=function(e){function t(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new x("Random seed is not implemented for Orthogonal Initializer yet.");return n}return i(t,e),t.prototype.apply=function(e,t){var n=this;return Object(r.od)(function(){if(2!==e.length)throw new x("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=_e(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),a=r.ob.gramSchmidt(t);return e[0]>e[1]&&(a=a.transpose()),Object(r.Ob)(y(n.gain),a)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(Pe);r.Ec.registerClass(qe);var $e={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Ge(e,t){return void 0===t&&(t={}),T(e,r.Ec.SerializationMap.getMap().classNameMap,t,"initializer")}function He(e){return P(e)}function Ke(e){if("string"==typeof e){var t=e in $e?$e[e]:e;return"GlorotUniform"===t?new Fe:"GlorotNormal"===t?new Ve:"HeNormal"===t?new Ue:"LeCunNormal"===t?new We:Ge({className:t,config:{}})}return e instanceof Pe?e:Ge(e)}var Xe=Object.freeze({zeros:function(){return new Te},ones:function(){return new Me},constant:function(e){return new Re(e)},randomUniform:function(e){return new De(e)},randomNormal:function(e){return new je(e)},truncatedNormal:function(e){return new Le(e)},identity:function(e){return new ze(e)},varianceScaling:function(e){return new Be(e)},glorotUniform:function(e){return new Fe(e)},glorotNormal:function(e){return new Ve(e)},heNormal:function(e){return new Ue(e)},leCunNormal:function(e){return new We(e)},orthogonal:function(e){return new qe(e)}});function Ye(e){return Array.isArray(e)&&Array.isArray(e[0])}function Je(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function Ze(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new w("Expected Tensor length to be 1; got "+e.length);t=e[0]}else t=e;return t}function Qe(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new w("Expected exactly 1 Shape; got "+e.length)}return e}function et(e){for(var t=0,n=0,r=e;n1)throw new v("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new v("Layer "+this.name+" is not connected, no input to return.");return O(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new v("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new v("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return O(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this._trainableWeights:[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=k(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=k(this.inputSpec);if(e.length!==t.length)throw new w("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var n=0;n=0?o[u]:o[o.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new w("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+o+".")}}if(null!=a.shape)for(var f=0;f0&&Array.isArray(d[0])?d.map(function(r,a){return new ot(g,r,n,k(e),t,n.name,a)}):new ot(g,d,n,k(e),t,n.name),n.addInboundNode(e,m,null,null,h,d,t),n._refCount++,null!=n.activityRegularizer)throw new x("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},t.prototype.warnOnIncompatibleInputShape=function(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(e)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var t=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)}),t&&console.warn("The shape of the input tensor ("+JSON.stringify(e)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new v("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,n=this.inboundNodes;te.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(n-this.batchStartMillis),this.batchDurationsMillis.length>=e.DECISION_BATCH_COUNT&&(a=this.batchDurationsMillis.reduce(function(e,t){return e+t})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=Math.round(e.THRESHOLD_MILLIS/a),this.autoYieldEveryBatches<1&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=r.yd.now(),this.lastYieldBatchCount=this.batchCount,[3,6];case 3:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,Object(r.Tb)()]:[3,6];case 4:return i.sent(),[4,this.resolveOneTensorInLogs(t)];case 5:i.sent(),this.lastYieldBatchCount=this.batchCount,i.label=6;case 6:return[3,9];case 7:return"batch"!==this.yieldEvery?[3,9]:[4,Object(r.Tb)()];case 8:i.sent(),i.label=9;case 9:return[2]}})})},e.prototype.maybeYieldOnEpoch=function(){return s(this,void 0,void 0,function(){return u(this,function(e){switch(e.label){case 0:return"epoch"!==this.yieldEvery?[3,2]:[4,Object(r.Tb)()];case 1:e.sent(),e.label=2;case 2:return[2]}})})},e.SKIP_FIRST_BATCHES=1,e.DECISION_BATCH_COUNT=2,e.THRESHOLD_MILLIS=16,e}(),yt=function(e){function t(t){var n=e.call(this)||this;return n.yieldEvery=t||"auto",n}return i(t,e),t.prototype.onTrainBegin=function(e){return s(this,void 0,void 0,function(){return u(this,function(e){return this.autoYielder=new gt(this.yieldEvery),[2]})})},t.prototype.onEpochBegin=function(e){return s(this,void 0,void 0,function(){return u(this,function(e){return this.seen=0,this.totals={},[2]})})},t.prototype.onBatchEnd=function(e,t){return s(this,void 0,void 0,function(){var e,n,a,i,o=this;return u(this,function(s){switch(s.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(t)];case 1:for(i in s.sent(),null==t&&(t={}),e=null==t.size?0:t.size,this.seen+=e,n=function(n){var i=t[n];if("number"==typeof i)a.totals.hasOwnProperty(n)||(a.totals[n]=0),a.totals[n]=a.totals[n]+i*e;else{var s=void 0;n in a.totals?s=a.totals[n]:a.totals[n]=y(0),a.totals[n]=Object(r.od)(function(){return Object(r.s)(o.totals[n],Object(r.Ob)(i,y(e)))}),null!=s&&s.dispose()}},a=this,t)n(i);return[2]}})})},t.prototype.onEpochEnd=function(e,t){return s(this,void 0,void 0,function(){var e,n,a,i,o,s=this;return u(this,function(u){switch(u.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(u.sent(),null!=t)for(e=function(e){if(null==n.totals[e])return"continue";"number"==typeof n.totals[e]?t[e]=n.totals[e]/n.seen:Object(r.od)(function(){t[e]=Object(r.Ob)(Object(r.Ha)(y(1),y(s.seen)),s.totals[e]),s.totals[e].dispose(),Object(r.ib)(t[e])})},n=this,a=0,i=this.params.metrics;a=0&&Number.isInteger(t),"Verbosity level is expected to be an integer >= 0, but got "+t),e.checkForDuplicate(n),null==e.constructors[t]&&(e.constructors[t]=[]),e.constructors[t].push(n)},e.checkForDuplicate=function(t){for(var n in e.constructors)e.constructors[+n].forEach(function(e){if(e===t)throw new w("Duplicate callback constructor.")})},e.clear=function(){e.constructors={}},e.createCallbacks=function(t){var n=[];for(var r in e.constructors){var a=+r;t>=a&&n.push.apply(n,e.constructors[a])}return n.map(function(e){return new e})},e}();function xt(e,t){return Object(r.od)(function(){var n=Object(r.dd)(Ne(e),t,!0),a=Object(r.Ob)(Object(r.Bc)(c()),Object(r.Zb)(e)),i=Object(r.Tc)(Object(r.Db)(n,a));return Object(r.Ha)(e,i)})}function _t(e,t){return Object(r.od)(function(){return Object(r.Fb)(Ne(Object(r.bd)(t,e)),-1)})}function St(e,t){return Object(r.od)(function(){return Object(r.Fb)(Object(r.p)(Object(r.bd)(t,e)),-1)})}function Et(e,t){return Object(r.od)(function(){var n=Object(r.bd)(e,t),a=Object(r.O)(Object(r.p)(e),c(),Number.MAX_VALUE),i=Object(r.p)(Object(r.Ha)(n,a));return Object(r.Ob)(y(100),Object(r.Fb)(i,-1))})}function Nt(e,t){return Object(r.od)(function(){var n=y(1),a=Object(r.O)(t,c(),Number.MAX_VALUE),i=Object(r.rb)(Object(r.s)(n,a)),o=Object(r.O)(e,c(),Number.MAX_VALUE),s=Object(r.rb)(Object(r.s)(n,o));return Object(r.Fb)(Ne(Object(r.bd)(i,s)),-1)})}function Ot(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.Db)(n,Object(r.bd)(a,Object(r.Ob)(e,t)));return Object(r.Fb)(Ne(i),-1)})}function kt(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.Db)(n,Object(r.bd)(a,Object(r.Ob)(e,t)));return Object(r.Fb)(i,-1)})}function It(e,t){return Object(r.od)(function(){var n=y(0),a=y(1),i=Object(r.dd)(Object(r.Ob)(e,t),-1),o=Object(r.Bb)(Object(r.Ob)(Object(r.bd)(a,e),t),-1);return Object(r.Db)(n,Object(r.s)(a,Object(r.bd)(o,i)))})}function Ct(e,t){return Object(r.od)(function(){var n=y(Math.log(2)),a=Object(r.bd)(t,e),i=Object(r.bd)(Object(r.s)(a,Object(r.Qc)(Object(r.Ob)(y(-2),a))),n);return Object(r.Fb)(i,-1)})}function At(e,t,n){return void 0===n&&(n=!1),Object(r.od)(function(){if(n)t=Object(r.Pc)(t);else{var a=Object(r.dd)(t,t.shape.length-1,!0);t=Object(r.Ha)(t,a)}return t=Object(r.O)(t,c(),1-c()),Object(r.Sb)(Object(r.dd)(Object(r.Ob)(e.toFloat(),Object(r.rb)(t)),t.shape.length-1))})}function Pt(e,t,n){return void 0===n&&(n=!1),Object(r.od)(function(){var a=Object(r.Ua)(function(e){var t=[le(e.shape)];return e.reshape(t)}(e)).toInt(),i=t.shape;return At(Object(r.Xb)(a,i[i.length-1]).reshape(i),t,n)})}function Tt(e,t){return Object(r.od)(function(){var n;return n=Object(r.O)(t,c(),1-c()),n=Object(r.rb)(Object(r.Ha)(n,Object(r.bd)(Object(r.Zb)(n),n))),Object(r.Fb)(function(e,t){return Object(r.od)(function(){var n=Object(r.Db)(t,Object(r.Id)(t)),a=Object(r.Ob)(t,e),i=Object(r.rb)(Object(r.s)(y(1),Object(r.Pa)(Object(r.Sb)(Object(r.p)(t)))));return Object(r.s)(Object(r.bd)(n,a),i)})}(e,n),-1)})}function Mt(e,t){return Object(r.od)(function(){var n=Object(r.O)(e,c(),1),a=Object(r.O)(t,c(),1);return Object(r.dd)(Object(r.Ob)(e,Object(r.rb)(Object(r.Ha)(n,a))),-1)})}function Rt(e,t){return Object(r.od)(function(){var n=Object(r.rb)(Object(r.s)(y(c()),t));return Object(r.Fb)(Object(r.bd)(t,Object(r.Ob)(e,n)),-1)})}function Dt(e,t){return Object(r.od)(function(){var n=xt(e,-1),a=xt(t,-1),i=Object(r.Ob)(n,a);return Object(r.Sb)(Object(r.dd)(i,-1))})}function jt(e){var t={meanSquaredError:_t,meanAbsoluteError:St,meanAbsolutePercentageError:Et,meanSquaredLogarithmicError:Nt,squaredHinge:Ot,hinge:kt,categoricalHinge:It,logcosh:Ct,categoricalCrossentropy:At,sparseCategoricalCrossentropy:Pt,binaryCrossentropy:Tt,kullbackLeiblerDivergence:Mt,poisson:Rt,cosineProximity:Dt};if("string"==typeof e){if(e in t)return t[e];var n="Unknown loss "+e;throw e.toLowerCase().includes("softmaxcrossentropy")&&(n="Unknown loss "+e+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new w(n)}return e}function Lt(e,t){return Object(r.od)(function(){var n=Object(r.Ob)(y(.5),Object(r.Zb)(t)),a=de(Object(r.bb)(t,n),e.dtype);return Object(r.Fb)(Object(r.Ma)(e,a),-1)})}function zt(e,t){return Object(r.od)(function(){return de(Object(r.Ma)(Object(r.x)(e,-1),Object(r.x)(t,-1)),"float32")})}function Bt(e,t){return Object(r.od)(function(){var n=y(1);return Object(r.vb)(e.equal(n),t.equal(n)).sum().cast("float32")})}function Ft(e,t){return Object(r.od)(function(){var n=y(0),a=Bt(e,t),i=function(e,t){return Object(r.od)(function(){var n=y(1),a=y(0);return Object(r.vb)(e.equal(a),t.equal(n)).sum().cast("float32")})}(e,t),o=a.add(i);return Object(r.Fd)(Object(r.bb)(o,n),a.div(o),n).cast("float32")})}function Vt(e,t){return Tt(e,t)}function Ut(e,t){throw new x}var Wt=_t,qt=_t,$t=St,Gt=St,Ht=Et,Kt=Et,Xt=At,Yt=Dt,Jt=Pt;function Zt(e,t,n){void 0===n&&(n=console.log);for(var r="",a=0;a0&&(r=r.slice(0,r.length-1)+" "),r=(r+=e[a]).slice(0,t[a]),r+=" ".repeat(t[a]-r.length);n(r)}function Qt(e,t,n){var r;try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}Zt([e.name+" ("+e.getClassName()+")",r,e.countParams().toString()],t,n)}function en(e,t,n,r){var a;try{a=JSON.stringify(e.outputShape)}catch(e){a="multiple"}for(var i=[],o=0,s=e.inboundNodes;o0&&-1===n.indexOf(u)))for(var l=0;l1 nodes"),E(0===l,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(l);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var p=0;p=0;)a.splice(a.indexOf(u),1);S.push(u)}},O=[],k=[],I=0,C=r.outputs;Ir?1:0});for(var K=0,X=H;K0)throw new w("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],t=0,n=this.layers;t0)throw new w(p.length+" of "+a+" weights are not set: "+p)}at(c)}(e,this.layers,a):function(e,t,n){void 0===n&&(n=!1);for(var a=e.keras_version,i=(e.backend,t.map(function(e){return e.name})),o={},s=0,u=t;s1)for(var s=0,u=o;s0){for(var h=[],d=0;d0&&e.apply(O(i),r)}function o(e){var r=e.name,i=tn(e,null!=t.customObjects?t.customObjects:{});n[r]=i;for(var o=0,s=e.inboundNodes;o0)i=!0;else if(pn(e)){for(var o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new w("Error when checking model "+a+" expected no data, but got "+e)}return[]}if(null==e)return t.map(function(e){return null});var s;if(pn(e)){e=e,s=[];for(var u=0,l=t;u1)throw new w("The model "+a+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e]}for(var f=0;f=0&&d!==m)throw new w("Error when checking "+a+": expected "+t[f]+" to have shape ["+n[f]+"], but got array with shape ["+p.shape+"].")}}return s}function dn(e,t){for(var n=[],r=0,a=null;r=e&&(a=e),n.push([r,a]),r=a;return n}function mn(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(function(e){return ge(e,t,n-t)}):ge(e,t,n-t)}function gn(e,t){return Object(r.od)(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return gn(e,t)}):Ee(e,"int32"===t.dtype?t:t.toInt())})}function yn(e,t,n,r,a){var i;if(void 0===r&&(r=!0),void 0===a&&(a=""),Array.isArray(e)){if(e.length!==t.length)throw new w("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+t.length+" Tensor(s), but instead got "+e.length+" Tensors(s).");i=e}else{if(t.length>1)throw new w("The model expects "+t.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");i=[e]}if(null!=n)for(var o=0;o0&&Number.isInteger(e),"batchSize is required to be a positive integer, but got "+e)}!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(on||(on={}));var bn=function(e){function t(t){var n=e.call(this,t)||this;return n.isTraining=!1,n}return i(t,e),t.prototype.summary=function(e,t,n){if(void 0===n&&(n=console.log),!this.built)throw new w("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");!function(e,t,n,r){void 0===r&&(r=console.log);var a,i=function(e){var t=!0,n=[],r=[];for(var a in e.nodesByDepth)n.push(e.nodesByDepth[a]);for(var i=0,o=n;i1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}r.push.apply(r,s)}if(t)for(var u=0,l=e.layers;u1&&(t.metricsTensors.push([n,e]),t.metricsNames.push(t.outputNames[e]+"_loss"))}});var h=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map(function(e){return[]});if(Array.isArray(e))return t.map(function(t){return e});if(null!=e){for(var n=[],r=0,a=t;r1&&(n=t.outputNames[e]+"_"+n),t.metricsNames.push(n),t.metricsTensors.push([r,e])}(e,r,l)},s=0,u=h[e];s0){var c=[];throw t.forEach(function(t,n){null==t&&c.push(e[n])}),new w("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return t},t.prototype.predictLoop=function(e,t,n){var a=this;return void 0===t&&(t=32),void 0===n&&(n=!1),Object(r.od)(function(){var i=a.checkNumSamples(e);if(n)throw new x("Verbose predictLoop() is not implemented yet.");for(var o=dn(i,t),s=[],u=function(t){var n=Object(r.od)(function(){var n=o[t][0],r=o[t][1],i=mn(e,n,r),s=[];if(Array.isArray(i))for(var u=0;u1)throw new w("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(i.length>1)throw new w("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(a.length>0&&i.length>0&&!r.yd.arraysEqual(a,i))throw new w("Input Tensors should have the same number of samples as target Tensors. Found "+a[0]+" input sample(s) and "+i[0]+" target sample(s).")}(e=hn(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=hn(t,this.feedOutputNames,i,!1,"target")),function(e,t,n){for(var r=[_t,Tt,At],a=0;a0&&e[0].shape[0]%a!=0)throw new w("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+a+". Found: "+e[0].shape[0]+" sample(s).");return[e,t,null]},t.prototype.fitLoop=function(e,t,n,a,i,o,l,c,f,p,h,d,m,g,y){return s(this,void 0,void 0,function(){var s,v,b,_,S,E,N,O,k=this;return u(this,function(I){switch(I.label){case 0:if(null==a&&(a=32),null==i&&(i=1),null==p&&(p=!0),null==d&&(d=0),s=!1,null!=c&&null!=f&&(s=!0),null!=g&&(s=!0,null==m))throw new w("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(v=this.checkNumSamples(t,a,m,"steps_per_epoch"))&&(b=he(0,v)),null==o&&(o=1),this.history=new vt,_=[new yt(y)].concat(wt.createCallbacks(o)),null!=l&&_.push.apply(_,l),_.push(this.history),(S=new mt(_)).setModel(this),S.setParams({epochs:i,initialEpoch:d,samples:v,steps:m,batchSize:a,verbose:o,doValidation:s,metrics:h}),[4,S.onTrainBegin()];case 1:I.sent(),this.stopTraining_=!1,E=function(i){var o,l,h,d,g;return u(this,function(y){switch(y.label){case 0:return[4,S.onEpochBegin(i)];case 1:if(y.sent(),o={},null==m)return[3,2];throw new x("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===p)throw new x("batch shuffling is not implemneted yet");p&&r.yd.shuffle(b),l=Object(r.hd)(b),h=dn(v,a),d=function(i){var p;return u(this,function(u){switch(u.label){case 0:return p={},[4,S.onBatchBegin(i,p)];case 1:return u.sent(),Object(r.od)(function(){var u=h[i][0],d=h[i][1],m=ge(l,u,d-u);p.batch=i,p.size=d-u;for(var g=gn(t,m),y=e(g),v=0;v1&&(a+="_"+N(e.slice(0,n),r)),t.push(a)}return t},t.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(t){return Object(r.od)(function(){for(var n,a=[],i=t.slice(0,e.inputs.length),o=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),s=[],u=0;u0){if(l=!0,2!==n.validationData.length)throw 3===n.validationData.length?new x("validationData including sample weights is not supported yet."):new w("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+n.validationData+" is invalid.");c=n.validationData[0],f=n.validationData[1],d=this.standardizeUserData(c,f,!0,a),c=d[0],f=d[1],p=c.concat(f)}else null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1?(l=!0,m=Math.floor(o[0].shape[0]*(1-n.validationSplit)),g=o[0].shape[0],c=mn(o,m,g),o=mn(o,0,m),f=mn(s,m,g),s=mn(s,0,m),h=!0,p=c.concat(f)):null!=n.validationSteps&&(l=!0);return y=o.concat(s),this.checkTrainableWeightsConsistency(),v=function(e){var t=e.slice(0,O.inputs.length),n=e.slice(O.inputs.length,O.inputs.length+O.outputs.length),a=[],i=O.collectedTrainableWeights.map(function(e){return e.read()});return[O.optimizer.minimize(function(){for(var e=[],i=0;i1)throw new w("Found more than one ("+n.length+") save handlers for URL '"+e+"'");e=n[0]}if(null==e.save)throw new w("Model.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,r.hb.encodeWeights(this.getNamedWeights(t))];case 1:return a=u.sent(),i=!1,o=null,s=this.toJSON(o,i),[2,e.save({modelTopology:s,weightData:a.data,weightSpecs:a.specs})]}})})},t.className="Model",t}(sn);r.Ec.registerClass(bn);var wn=function(e){function t(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n._updatable=!0,n.built=!1,n.name=null!=t.name?t.name:d("sequential_"),null!=t.layers)for(var r=0,a=t.layers;r0)&&(n=t.sourceLayer,r=t.nodeIndex),0===n.inboundNodes.length)return[t];var a=n.inboundNodes[r];if(0===a.inboundLayers.length)return a.inputTensors;for(var i=[],o=0;o1)throw new w("Found more than one ("+n.length+") load handlers for URL '"+e+"'");e=n[0]}return[2,function(e,t,n){return void 0===n&&(n=!0),s(this,void 0,void 0,function(){var t,a,i,o,s;return u(this,function(u){switch(u.label){case 0:if(null==e.load)throw new w("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(t=u.sent(),null!=(a=t.modelTopology).model_config&&(a=a.model_config),i=tn(function e(t,n){if(null===t)return null;if("string"==typeof t)return C(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var r=[],a=t.length,i=0;i 0 but got "+JSON.stringify(e.filters))},t}(nr),ar=function(e){function t(n){var r=e.call(this,2,n)||this;return t.verifyConfig(n),r}return i(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyConfig=function(e){if("number"!=typeof e.kernelSize&&!L(e.kernelSize,"number",1,2))throw new w("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(rr);r.Ec.registerClass(ar);var ir=function(e){function t(t){var n=e.call(this,t)||this;if(n.inputSpec=[new it({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new w("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return i(t,e),t.prototype.build=function(e){if(4!==(e=Qe(e)).length)throw new w("Input should have rank 4; Received input shape: "+JSON.stringify(e));var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new w("The channel dimension of the inputs should be defined. Found `None`.");var n,r=e[t],a=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new it({ndim:4,axes:(n={},n[t]=r,n)})],this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);if(4!==t.shape.length)throw new w("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var a,i,o=t.shape,s=o[0];"channelsFirst"===n.dataFormat?(a=2,i=3):(a=1,i=2);var u=o[a],l=o[i],c=n.kernelSize[0],f=n.kernelSize[1],p=n.strides[0],h=n.strides[1],d=[s,er(u,p,c,n.padding),er(l,h,f,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(t=Object(r.ud)(t,[0,2,3,1]));var m=Object(r.Y)(t,n.kernel.read(),d,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(m=Object(r.ud)(m,[0,3,1,2])),null!=n.bias&&(m=Oe(m,n.bias.read(),n.dataFormat)),null!=n.activation&&(m=n.activation.apply(m)),m})},t.prototype.computeOutputShape=function(e){var t,n,r,a=(e=Qe(e)).slice();"channelsFirst"===this.dataFormat?(t=1,n=2,r=3):(t=3,n=1,r=2);var i=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[t]=this.filters,a[n]=er(a[n],s,i,this.padding),a[r]=er(a[r],u,o,this.padding),a},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(ar);r.Ec.registerClass(ir);var or=function(e){function t(t){return e.call(this,2,t)||this}return i(t,e),t.className="SeparableConv2D",t}(function(e){function t(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new w("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new w("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new w("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=Ke(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Jn(n.depthwiseRegularizer),r.depthwiseConstraint=H(n.depthwiseConstraint),r.pointwiseInitializer=Ke(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Jn(n.pointwiseRegularizer),r.pointwiseConstraint=H(n.pointwiseConstraint),r}return i(t,e),t.prototype.build=function(e){if((e=Qe(e)).length1)throw new w("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var a=null==e[0]?null:e[0].slice(1),i=1;i1){var v=he(1,u).concat([0]);t.push(Object(r.ud)(h,v)),c=!0}else t.push(h)}var b=n.mergeFunction(t),w=b.rank;if(c)if(null==w){var x=b.shape;g=[m=x[x.length-1]].concat(x.slice(0,x.length-1)),b=Object(r.ud)(b.reshape([-1,m]),[1,0]).reshape(g)}else w>1&&(v=[w-1].concat(he(0,w-1)),b=Object(r.ud)(b,v));return b}return n.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var n=1;n1)throw new w("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return Object(r.od)(function(){return be(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new w("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,a=0,i=t.slice(1);a=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new w("Axis "+t+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new it({ndim:e.length,axes:(r={},r[t]=n,r)})];var r,a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var a=null!=t.training&&t.training,i=Ze(e),o=i.shape,s=o.length,u=he(0,s),l=n.axis>=0?n.axis:n.axis+s;u.splice(l,1);var c=S(1,s);c[l]=o[l];var f=u.slice();f.sort();var p=!r.yd.arraysEqual(f,he(0,s).slice(0,s-1));if(!a)return function(){if(p){var e=n.movingMean.read().reshape(c),t=n.movingVariance.read().reshape(c),r=n.center?n.beta.read().reshape(c):null,a=n.scale?n.gamma.read().reshape(c):null;return Or(i,e,t,r,a,n.epsilon)}return Or(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=function(e,t,n,a,i){return void 0===i&&(i=.001),r.yd.arraysEqual(a.slice().sort(),he(0,e.rank-1))?function(e,t,n,a,i){return void 0===i&&(i=.001),Object(r.od)(function(){var o=Object(r.Mb)(e,a),s=o.mean,u=o.variance;return[Or(e,s,u,n,t,i),s,u]})}(e,t,n,a,i):function(e,t,n,a,i){return void 0===i&&(i=.001),Object(r.od)(function(){for(var o=Object(r.Mb)(e,a),s=o.mean,u=o.variance,l=[],c=0,f=he(0,e.rank);c=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return function(e,t,n){return Object(r.od)(function(){if(4!==e.rank)throw new w("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new w("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new w("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var a;return a="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],Object(r.cc)(e,a)})}(Ze(e),n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ZeroPadding2D",t}(ct);function Cr(e,t,n,a,i,o){return Object(r.od)(function(){var s;J(i),j(ee,"PoolMode",o),Q(a),null==n&&(n=[1,1]),null==a&&(a="valid"),null==i&&(i="channelsLast"),null==o&&(o="max"),e=tr(e,i);var u="same"===a?"same":"valid";return s="max"===o?Object(r.Cb)(e,t,n,u):Object(r.E)(e,t,n,u),"channelsFirst"===i&&(s=Object(r.ud)(s,[0,3,1,2])),s})}r.Ec.registerClass(Ir);var Ar=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new w("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize}if(null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new w("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides}return n.padding=null==t.padding?"valid":t.padding,Q(n.padding),n.inputSpec=[new it({ndim:3})],n}return i(t,e),t.prototype.computeOutputShape=function(e){var t=Qn((e=Qe(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){n.invokeCallHook(e,t),e=me(Ze(e),2);var a=n.poolingFunction(Ze(e),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return Object(r.Xc)(a,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Pr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"max")},t.className="MaxPooling1D",t}(Ar);r.Ec.registerClass(Pr);var Tr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"avg")},t.className="AveragePooling1D",t}(Ar);r.Ec.registerClass(Tr);var Mr=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new w("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides];return n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,J(n.dataFormat),Q(n.padding),n.inputSpec=[new it({ndim:4})],n}return i(t,e),t.prototype.computeOutputShape=function(e){e=Qe(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=Qn(t,this.poolSize[0],this.padding,this.strides[0]),n=Qn(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return n.invokeCallHook(e,t),n.poolingFunction(Ze(e),n.poolSize,n.strides,n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Rr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"max")},t.className="MaxPooling2D",t}(Mr);r.Ec.registerClass(Rr);var Dr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return J(a),Q(r),Cr(e,t,n,r,a,"avg")},t.className="AveragePooling2D",t}(Mr);r.Ec.registerClass(Dr);var jr=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[new it({ndim:3})],n}return i(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,t){throw new x},t}(ct),Lr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.call=function(e,t){return Object(r.od)(function(){var t=Ze(e);return Object(r.Fb)(t,1)})},t.className="GlobalAveragePooling1D",t}(jr);r.Ec.registerClass(Lr);var zr=function(e){function t(t){return e.call(this,t)||this}return i(t,e),t.prototype.call=function(e,t){return Object(r.od)(function(){var t=Ze(e);return Object(r.Bb)(t,1)})},t.className="GlobalMaxPooling1D",t}(jr);r.Ec.registerClass(zr);var Br=function(e){function t(t){var n=e.call(this,t)||this;return n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,J(n.dataFormat),n.inputSpec=[new it({ndim:4})],n}return i(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new x},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(ct),Fr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);return"channelsLast"===n.dataFormat?Object(r.Fb)(t,[1,2]):Object(r.Fb)(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(Br);r.Ec.registerClass(Fr);var Vr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){var t=Ze(e);return"channelsLast"===n.dataFormat?Object(r.Bb)(t,[1,2]):Object(r.Bb)(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(Br);function Ur(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new w("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function Wr(e,t,n,a,i,o,s,u){void 0===a&&(a=!1),void 0===s&&(s=!1),void 0===u&&(u=!1);var l=t.shape.length;if(l<3)throw new w("Input should be at least 3D, but is "+l+"D.");var c,f,p=[1,0].concat(he(2,l));if(t=Object(r.ud)(t,p),null!=i)throw new x("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=o)throw new x("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),a&&(t=Object(r.uc)(t,0));for(var h=n,d=t.shape[0],m=function(n){var a=ge(t,n,1);a=a.reshape(a.shape.slice(1));var i=Object(r.od)(function(){return e(a,h)});if(f=i[0],u)if(0===n)c=f.expandDims(1);else{var o=Object(r.R)([c,f.expandDims(1)],1);c.dispose(),c=o}h=i[1]},g=0;g1?xe(n,[1,e]):n}):t.cell.stateSize>1?[xe(n,[1,t.cell.stateSize])]:[n]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="RNN",t}(ct);r.Ec.registerClass(qr);var $r=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t}(ct),Gr=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,n.activation=Fn(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=Ke(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Ke(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Ke(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Jn(t.kernelRegularizer),n.recurrentRegularizer=Jn(t.recurrentRegularizer),n.biasRegularizer=Jn(t.biasRegularizer),n.kernelConstraint=H(t.kernelConstraint),n.recurrentConstraint=H(t.recurrentConstraint),n.biasConstraint=H(t.biasConstraint),n.dropout=fe([1,pe([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=fe([1,pe([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return i(t,e),t.prototype.build=function(e){e=Qe(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){if(2!==(e=e).length)throw new w("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var a=e[1];e=e[0];var i,o=null!=t.training&&t.training;01){for(var o=[],s=0;s= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t)},t.prototype.computeOutputShape=function(e){var t=[(e=Qe(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))},t.prototype.call=function(e,t){var n=this;return Object(r.od)(function(){return Wr(function(e,r){return[Ze(n.layer.call(e,t)),[]]},e=Ze(e),[],!1,null,null,!1,!0)[1]})},t.className="TimeDistributed",t}(ea);r.Ec.registerClass(ta);var na=["sum","mul","concat","ave"],ra=function(e){function t(t){var n=e.call(this,t)||this,r=t.layer.getConfig();if(n.forwardLayer=tn({className:t.layer.getClassName(),config:r}),r.goBackwards=!0!==r.goBackwards,n.backwardLayer=tn({className:t.layer.getClassName(),config:r}),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,function(e){j(na,"BidirectionalMergeMode",e)}(t.mergeMode),n.mergeMode=t.mergeMode,t.weights)throw new x("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n.numConstants=null,n}return i(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))},t.prototype.computeOutputShape=function(e){var t,n,r,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(r=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):O(n)},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,a=null==n?null:n.constants;null==n&&(n={});var i=Ur(t,r,a,this.numConstants);if(t=i.inputs,r=i.initialState,a=i.constants,Array.isArray(t)&&(r=t.slice(1),t=t[0]),(null==r||0===r.length)&&null==a)return e.prototype.apply.call(this,t,n);var o=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new w("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,o.push.apply(o,r);var l=r.map(function(e){return new it({shape:e.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=a)throw new x("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof ot,f=0,p=o;f0?a(r(e),9007199254740991):0}},function(e,t){var n=e.exports={version:"2.6.1"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(4),a=n(293),i=n(52),o=Object.defineProperty;t.f=n(14)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),a)try{return o(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){e.exports=!n(8)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){(function(e){!function(e,t){"use strict";function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function a(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function i(e,t,n){if(i.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o=n(435).Buffer}catch(e){}function s(e,t,n){for(var r=0,a=Math.min(e.length,n),i=t;i=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return r}function u(e,t,n,r){for(var a=0,i=Math.min(e.length,n),o=t;o=49?s-49+10:s>=17?s-17+10:s}return a}i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var a=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&a++,16===t?this._parseHex(e,a):this._parseBase(e,t,a),"-"===e[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var a=0;a=0;a-=3)o=e[a]|e[a-1]<<8|e[a-2]<<16,this.words[i]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,i++);else if("le"===n)for(a=0,i=0;a>>26-s&67108863,(s+=24)>=26&&(s-=26,i++);return this.strip()},i.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)a=s(e,n,n+6),this.words[r]|=a<>>26-i&4194303,(i+=24)>=26&&(i-=26,r++);n+6!==t&&(a=s(e,t,n+6),this.words[r]|=a<>>26-i&4194303),this.strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,a=1;a<=67108863;a*=t)r++;r--,a=a/t|0;for(var i=e.length-n,o=i%r,s=Math.min(i,i-o)+n,l=0,c=n;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],c=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var a=0|e.words[0],i=0|t.words[0],o=a*i,s=67108863&o,u=o/67108864|0;n.words[0]=s;for(var l=1;l>>26,f=67108863&u,p=Math.min(l,t.length-1),h=Math.max(0,l-e.length+1);h<=p;h++){var d=l-h|0;c+=(o=(a=0|e.words[d])*(i=0|t.words[h])+f)/67108864|0,f=67108863&o}n.words[l]=0|f,u=0|c}return 0!==u?n.words[l]=0|u:n.length--,n.strip()}i.prototype.toString=function(e,t){var n;if(e=e||10,t=0|t||1,16===e||"hex"===e){n="";for(var a=0,i=0,o=0;o>>24-a&16777215)||o!==this.length-1?l[6-u.length]+u+n:u+n,(a+=2)>=26&&(a-=26,o--)}for(0!==i&&(n=i.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var p=c[e],h=f[e];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var m=d.modn(h).toString(e);n=(d=d.idivn(h)).isZero()?m+n:l[p-m.length]+m+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(e,t){return r(void 0!==o),this.toArrayLike(o,e,t)},i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,n){var a=this.byteLength(),i=n||Math.max(1,a);r(a<=i,"byte array longer than desired length"),r(i>0,"Requested array length <= 0"),this.strip();var o,s,u="le"===t,l=new e(i),c=this.clone();if(u){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),l[s]=o;for(;s=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},i.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;re.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var a=0;a0&&(this.words[a]=~this.words[a]&67108863>>26-n),this.strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,a=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,r=e):(n=e,r=this);for(var a=0,i=0;i>>26;for(;0!==a&&i>>26;if(this.length=n.length,0!==a)this.words[this.length]=a,this.length++;else if(n!==this)for(;ie.length?this.clone().iadd(e):e.clone().iadd(this)},i.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,a=this.cmp(e);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o>26,this.words[o]=67108863&t;for(;0!==i&&o>26,this.words[o]=67108863&t;if(0===i&&o>>13,h=0|o[1],d=8191&h,m=h>>>13,g=0|o[2],y=8191&g,v=g>>>13,b=0|o[3],w=8191&b,x=b>>>13,_=0|o[4],S=8191&_,E=_>>>13,N=0|o[5],O=8191&N,k=N>>>13,I=0|o[6],C=8191&I,A=I>>>13,P=0|o[7],T=8191&P,M=P>>>13,R=0|o[8],D=8191&R,j=R>>>13,L=0|o[9],z=8191&L,B=L>>>13,F=0|s[0],V=8191&F,U=F>>>13,W=0|s[1],q=8191&W,$=W>>>13,G=0|s[2],H=8191&G,K=G>>>13,X=0|s[3],Y=8191&X,J=X>>>13,Z=0|s[4],Q=8191&Z,ee=Z>>>13,te=0|s[5],ne=8191&te,re=te>>>13,ae=0|s[6],ie=8191&ae,oe=ae>>>13,se=0|s[7],ue=8191&se,le=se>>>13,ce=0|s[8],fe=8191&ce,pe=ce>>>13,he=0|s[9],de=8191&he,me=he>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(l+(r=Math.imul(f,V))|0)+((8191&(a=(a=Math.imul(f,U))+Math.imul(p,V)|0))<<13)|0;l=((i=Math.imul(p,U))+(a>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(d,V),a=(a=Math.imul(d,U))+Math.imul(m,V)|0,i=Math.imul(m,U);var ye=(l+(r=r+Math.imul(f,q)|0)|0)+((8191&(a=(a=a+Math.imul(f,$)|0)+Math.imul(p,q)|0))<<13)|0;l=((i=i+Math.imul(p,$)|0)+(a>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,V),a=(a=Math.imul(y,U))+Math.imul(v,V)|0,i=Math.imul(v,U),r=r+Math.imul(d,q)|0,a=(a=a+Math.imul(d,$)|0)+Math.imul(m,q)|0,i=i+Math.imul(m,$)|0;var ve=(l+(r=r+Math.imul(f,H)|0)|0)+((8191&(a=(a=a+Math.imul(f,K)|0)+Math.imul(p,H)|0))<<13)|0;l=((i=i+Math.imul(p,K)|0)+(a>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(w,V),a=(a=Math.imul(w,U))+Math.imul(x,V)|0,i=Math.imul(x,U),r=r+Math.imul(y,q)|0,a=(a=a+Math.imul(y,$)|0)+Math.imul(v,q)|0,i=i+Math.imul(v,$)|0,r=r+Math.imul(d,H)|0,a=(a=a+Math.imul(d,K)|0)+Math.imul(m,H)|0,i=i+Math.imul(m,K)|0;var be=(l+(r=r+Math.imul(f,Y)|0)|0)+((8191&(a=(a=a+Math.imul(f,J)|0)+Math.imul(p,Y)|0))<<13)|0;l=((i=i+Math.imul(p,J)|0)+(a>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(S,V),a=(a=Math.imul(S,U))+Math.imul(E,V)|0,i=Math.imul(E,U),r=r+Math.imul(w,q)|0,a=(a=a+Math.imul(w,$)|0)+Math.imul(x,q)|0,i=i+Math.imul(x,$)|0,r=r+Math.imul(y,H)|0,a=(a=a+Math.imul(y,K)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,K)|0,r=r+Math.imul(d,Y)|0,a=(a=a+Math.imul(d,J)|0)+Math.imul(m,Y)|0,i=i+Math.imul(m,J)|0;var we=(l+(r=r+Math.imul(f,Q)|0)|0)+((8191&(a=(a=a+Math.imul(f,ee)|0)+Math.imul(p,Q)|0))<<13)|0;l=((i=i+Math.imul(p,ee)|0)+(a>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(O,V),a=(a=Math.imul(O,U))+Math.imul(k,V)|0,i=Math.imul(k,U),r=r+Math.imul(S,q)|0,a=(a=a+Math.imul(S,$)|0)+Math.imul(E,q)|0,i=i+Math.imul(E,$)|0,r=r+Math.imul(w,H)|0,a=(a=a+Math.imul(w,K)|0)+Math.imul(x,H)|0,i=i+Math.imul(x,K)|0,r=r+Math.imul(y,Y)|0,a=(a=a+Math.imul(y,J)|0)+Math.imul(v,Y)|0,i=i+Math.imul(v,J)|0,r=r+Math.imul(d,Q)|0,a=(a=a+Math.imul(d,ee)|0)+Math.imul(m,Q)|0,i=i+Math.imul(m,ee)|0;var xe=(l+(r=r+Math.imul(f,ne)|0)|0)+((8191&(a=(a=a+Math.imul(f,re)|0)+Math.imul(p,ne)|0))<<13)|0;l=((i=i+Math.imul(p,re)|0)+(a>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(C,V),a=(a=Math.imul(C,U))+Math.imul(A,V)|0,i=Math.imul(A,U),r=r+Math.imul(O,q)|0,a=(a=a+Math.imul(O,$)|0)+Math.imul(k,q)|0,i=i+Math.imul(k,$)|0,r=r+Math.imul(S,H)|0,a=(a=a+Math.imul(S,K)|0)+Math.imul(E,H)|0,i=i+Math.imul(E,K)|0,r=r+Math.imul(w,Y)|0,a=(a=a+Math.imul(w,J)|0)+Math.imul(x,Y)|0,i=i+Math.imul(x,J)|0,r=r+Math.imul(y,Q)|0,a=(a=a+Math.imul(y,ee)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,ee)|0,r=r+Math.imul(d,ne)|0,a=(a=a+Math.imul(d,re)|0)+Math.imul(m,ne)|0,i=i+Math.imul(m,re)|0;var _e=(l+(r=r+Math.imul(f,ie)|0)|0)+((8191&(a=(a=a+Math.imul(f,oe)|0)+Math.imul(p,ie)|0))<<13)|0;l=((i=i+Math.imul(p,oe)|0)+(a>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(T,V),a=(a=Math.imul(T,U))+Math.imul(M,V)|0,i=Math.imul(M,U),r=r+Math.imul(C,q)|0,a=(a=a+Math.imul(C,$)|0)+Math.imul(A,q)|0,i=i+Math.imul(A,$)|0,r=r+Math.imul(O,H)|0,a=(a=a+Math.imul(O,K)|0)+Math.imul(k,H)|0,i=i+Math.imul(k,K)|0,r=r+Math.imul(S,Y)|0,a=(a=a+Math.imul(S,J)|0)+Math.imul(E,Y)|0,i=i+Math.imul(E,J)|0,r=r+Math.imul(w,Q)|0,a=(a=a+Math.imul(w,ee)|0)+Math.imul(x,Q)|0,i=i+Math.imul(x,ee)|0,r=r+Math.imul(y,ne)|0,a=(a=a+Math.imul(y,re)|0)+Math.imul(v,ne)|0,i=i+Math.imul(v,re)|0,r=r+Math.imul(d,ie)|0,a=(a=a+Math.imul(d,oe)|0)+Math.imul(m,ie)|0,i=i+Math.imul(m,oe)|0;var Se=(l+(r=r+Math.imul(f,ue)|0)|0)+((8191&(a=(a=a+Math.imul(f,le)|0)+Math.imul(p,ue)|0))<<13)|0;l=((i=i+Math.imul(p,le)|0)+(a>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(D,V),a=(a=Math.imul(D,U))+Math.imul(j,V)|0,i=Math.imul(j,U),r=r+Math.imul(T,q)|0,a=(a=a+Math.imul(T,$)|0)+Math.imul(M,q)|0,i=i+Math.imul(M,$)|0,r=r+Math.imul(C,H)|0,a=(a=a+Math.imul(C,K)|0)+Math.imul(A,H)|0,i=i+Math.imul(A,K)|0,r=r+Math.imul(O,Y)|0,a=(a=a+Math.imul(O,J)|0)+Math.imul(k,Y)|0,i=i+Math.imul(k,J)|0,r=r+Math.imul(S,Q)|0,a=(a=a+Math.imul(S,ee)|0)+Math.imul(E,Q)|0,i=i+Math.imul(E,ee)|0,r=r+Math.imul(w,ne)|0,a=(a=a+Math.imul(w,re)|0)+Math.imul(x,ne)|0,i=i+Math.imul(x,re)|0,r=r+Math.imul(y,ie)|0,a=(a=a+Math.imul(y,oe)|0)+Math.imul(v,ie)|0,i=i+Math.imul(v,oe)|0,r=r+Math.imul(d,ue)|0,a=(a=a+Math.imul(d,le)|0)+Math.imul(m,ue)|0,i=i+Math.imul(m,le)|0;var Ee=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(a=(a=a+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((i=i+Math.imul(p,pe)|0)+(a>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(z,V),a=(a=Math.imul(z,U))+Math.imul(B,V)|0,i=Math.imul(B,U),r=r+Math.imul(D,q)|0,a=(a=a+Math.imul(D,$)|0)+Math.imul(j,q)|0,i=i+Math.imul(j,$)|0,r=r+Math.imul(T,H)|0,a=(a=a+Math.imul(T,K)|0)+Math.imul(M,H)|0,i=i+Math.imul(M,K)|0,r=r+Math.imul(C,Y)|0,a=(a=a+Math.imul(C,J)|0)+Math.imul(A,Y)|0,i=i+Math.imul(A,J)|0,r=r+Math.imul(O,Q)|0,a=(a=a+Math.imul(O,ee)|0)+Math.imul(k,Q)|0,i=i+Math.imul(k,ee)|0,r=r+Math.imul(S,ne)|0,a=(a=a+Math.imul(S,re)|0)+Math.imul(E,ne)|0,i=i+Math.imul(E,re)|0,r=r+Math.imul(w,ie)|0,a=(a=a+Math.imul(w,oe)|0)+Math.imul(x,ie)|0,i=i+Math.imul(x,oe)|0,r=r+Math.imul(y,ue)|0,a=(a=a+Math.imul(y,le)|0)+Math.imul(v,ue)|0,i=i+Math.imul(v,le)|0,r=r+Math.imul(d,fe)|0,a=(a=a+Math.imul(d,pe)|0)+Math.imul(m,fe)|0,i=i+Math.imul(m,pe)|0;var Ne=(l+(r=r+Math.imul(f,de)|0)|0)+((8191&(a=(a=a+Math.imul(f,me)|0)+Math.imul(p,de)|0))<<13)|0;l=((i=i+Math.imul(p,me)|0)+(a>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(z,q),a=(a=Math.imul(z,$))+Math.imul(B,q)|0,i=Math.imul(B,$),r=r+Math.imul(D,H)|0,a=(a=a+Math.imul(D,K)|0)+Math.imul(j,H)|0,i=i+Math.imul(j,K)|0,r=r+Math.imul(T,Y)|0,a=(a=a+Math.imul(T,J)|0)+Math.imul(M,Y)|0,i=i+Math.imul(M,J)|0,r=r+Math.imul(C,Q)|0,a=(a=a+Math.imul(C,ee)|0)+Math.imul(A,Q)|0,i=i+Math.imul(A,ee)|0,r=r+Math.imul(O,ne)|0,a=(a=a+Math.imul(O,re)|0)+Math.imul(k,ne)|0,i=i+Math.imul(k,re)|0,r=r+Math.imul(S,ie)|0,a=(a=a+Math.imul(S,oe)|0)+Math.imul(E,ie)|0,i=i+Math.imul(E,oe)|0,r=r+Math.imul(w,ue)|0,a=(a=a+Math.imul(w,le)|0)+Math.imul(x,ue)|0,i=i+Math.imul(x,le)|0,r=r+Math.imul(y,fe)|0,a=(a=a+Math.imul(y,pe)|0)+Math.imul(v,fe)|0,i=i+Math.imul(v,pe)|0;var Oe=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(a=(a=a+Math.imul(d,me)|0)+Math.imul(m,de)|0))<<13)|0;l=((i=i+Math.imul(m,me)|0)+(a>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(z,H),a=(a=Math.imul(z,K))+Math.imul(B,H)|0,i=Math.imul(B,K),r=r+Math.imul(D,Y)|0,a=(a=a+Math.imul(D,J)|0)+Math.imul(j,Y)|0,i=i+Math.imul(j,J)|0,r=r+Math.imul(T,Q)|0,a=(a=a+Math.imul(T,ee)|0)+Math.imul(M,Q)|0,i=i+Math.imul(M,ee)|0,r=r+Math.imul(C,ne)|0,a=(a=a+Math.imul(C,re)|0)+Math.imul(A,ne)|0,i=i+Math.imul(A,re)|0,r=r+Math.imul(O,ie)|0,a=(a=a+Math.imul(O,oe)|0)+Math.imul(k,ie)|0,i=i+Math.imul(k,oe)|0,r=r+Math.imul(S,ue)|0,a=(a=a+Math.imul(S,le)|0)+Math.imul(E,ue)|0,i=i+Math.imul(E,le)|0,r=r+Math.imul(w,fe)|0,a=(a=a+Math.imul(w,pe)|0)+Math.imul(x,fe)|0,i=i+Math.imul(x,pe)|0;var ke=(l+(r=r+Math.imul(y,de)|0)|0)+((8191&(a=(a=a+Math.imul(y,me)|0)+Math.imul(v,de)|0))<<13)|0;l=((i=i+Math.imul(v,me)|0)+(a>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(z,Y),a=(a=Math.imul(z,J))+Math.imul(B,Y)|0,i=Math.imul(B,J),r=r+Math.imul(D,Q)|0,a=(a=a+Math.imul(D,ee)|0)+Math.imul(j,Q)|0,i=i+Math.imul(j,ee)|0,r=r+Math.imul(T,ne)|0,a=(a=a+Math.imul(T,re)|0)+Math.imul(M,ne)|0,i=i+Math.imul(M,re)|0,r=r+Math.imul(C,ie)|0,a=(a=a+Math.imul(C,oe)|0)+Math.imul(A,ie)|0,i=i+Math.imul(A,oe)|0,r=r+Math.imul(O,ue)|0,a=(a=a+Math.imul(O,le)|0)+Math.imul(k,ue)|0,i=i+Math.imul(k,le)|0,r=r+Math.imul(S,fe)|0,a=(a=a+Math.imul(S,pe)|0)+Math.imul(E,fe)|0,i=i+Math.imul(E,pe)|0;var Ie=(l+(r=r+Math.imul(w,de)|0)|0)+((8191&(a=(a=a+Math.imul(w,me)|0)+Math.imul(x,de)|0))<<13)|0;l=((i=i+Math.imul(x,me)|0)+(a>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(z,Q),a=(a=Math.imul(z,ee))+Math.imul(B,Q)|0,i=Math.imul(B,ee),r=r+Math.imul(D,ne)|0,a=(a=a+Math.imul(D,re)|0)+Math.imul(j,ne)|0,i=i+Math.imul(j,re)|0,r=r+Math.imul(T,ie)|0,a=(a=a+Math.imul(T,oe)|0)+Math.imul(M,ie)|0,i=i+Math.imul(M,oe)|0,r=r+Math.imul(C,ue)|0,a=(a=a+Math.imul(C,le)|0)+Math.imul(A,ue)|0,i=i+Math.imul(A,le)|0,r=r+Math.imul(O,fe)|0,a=(a=a+Math.imul(O,pe)|0)+Math.imul(k,fe)|0,i=i+Math.imul(k,pe)|0;var Ce=(l+(r=r+Math.imul(S,de)|0)|0)+((8191&(a=(a=a+Math.imul(S,me)|0)+Math.imul(E,de)|0))<<13)|0;l=((i=i+Math.imul(E,me)|0)+(a>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(z,ne),a=(a=Math.imul(z,re))+Math.imul(B,ne)|0,i=Math.imul(B,re),r=r+Math.imul(D,ie)|0,a=(a=a+Math.imul(D,oe)|0)+Math.imul(j,ie)|0,i=i+Math.imul(j,oe)|0,r=r+Math.imul(T,ue)|0,a=(a=a+Math.imul(T,le)|0)+Math.imul(M,ue)|0,i=i+Math.imul(M,le)|0,r=r+Math.imul(C,fe)|0,a=(a=a+Math.imul(C,pe)|0)+Math.imul(A,fe)|0,i=i+Math.imul(A,pe)|0;var Ae=(l+(r=r+Math.imul(O,de)|0)|0)+((8191&(a=(a=a+Math.imul(O,me)|0)+Math.imul(k,de)|0))<<13)|0;l=((i=i+Math.imul(k,me)|0)+(a>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(z,ie),a=(a=Math.imul(z,oe))+Math.imul(B,ie)|0,i=Math.imul(B,oe),r=r+Math.imul(D,ue)|0,a=(a=a+Math.imul(D,le)|0)+Math.imul(j,ue)|0,i=i+Math.imul(j,le)|0,r=r+Math.imul(T,fe)|0,a=(a=a+Math.imul(T,pe)|0)+Math.imul(M,fe)|0,i=i+Math.imul(M,pe)|0;var Pe=(l+(r=r+Math.imul(C,de)|0)|0)+((8191&(a=(a=a+Math.imul(C,me)|0)+Math.imul(A,de)|0))<<13)|0;l=((i=i+Math.imul(A,me)|0)+(a>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(z,ue),a=(a=Math.imul(z,le))+Math.imul(B,ue)|0,i=Math.imul(B,le),r=r+Math.imul(D,fe)|0,a=(a=a+Math.imul(D,pe)|0)+Math.imul(j,fe)|0,i=i+Math.imul(j,pe)|0;var Te=(l+(r=r+Math.imul(T,de)|0)|0)+((8191&(a=(a=a+Math.imul(T,me)|0)+Math.imul(M,de)|0))<<13)|0;l=((i=i+Math.imul(M,me)|0)+(a>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(z,fe),a=(a=Math.imul(z,pe))+Math.imul(B,fe)|0,i=Math.imul(B,pe);var Me=(l+(r=r+Math.imul(D,de)|0)|0)+((8191&(a=(a=a+Math.imul(D,me)|0)+Math.imul(j,de)|0))<<13)|0;l=((i=i+Math.imul(j,me)|0)+(a>>>13)|0)+(Me>>>26)|0,Me&=67108863;var Re=(l+(r=Math.imul(z,de))|0)+((8191&(a=(a=Math.imul(z,me))+Math.imul(B,de)|0))<<13)|0;return l=((i=Math.imul(B,me))+(a>>>13)|0)+(Re>>>26)|0,Re&=67108863,u[0]=ge,u[1]=ye,u[2]=ve,u[3]=be,u[4]=we,u[5]=xe,u[6]=_e,u[7]=Se,u[8]=Ee,u[9]=Ne,u[10]=Oe,u[11]=ke,u[12]=Ie,u[13]=Ce,u[14]=Ae,u[15]=Pe,u[16]=Te,u[17]=Me,u[18]=Re,0!==l&&(u[19]=l,n.length++),n};function d(e,t,n){return(new m).mulp(e,t,n)}function m(e,t){this.x=e,this.y=t}Math.imul||(h=p),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?h(this,e,t):n<63?p(this,e,t):n<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,a=0,i=0;i>>26)|0)>>>26,o&=67108863}n.words[i]=s,r=o,o=a}return 0!==r?n.words[i]=r:n.length--,n.strip()}(this,e,t):d(this,e,t)},m.prototype.makeRBT=function(e){for(var t=new Array(e),n=i.prototype._countBits(e)-1,r=0;r>=1;return r},m.prototype.permute=function(e,t,n,r,a,i){for(var o=0;o>>=1)a++;return 1<>>=13,n[2*o+1]=8191&i,i>>>=13;for(o=2*t;o>=26,t+=a/67108864|0,t+=i>>>26,this.words[n]=67108863&i}return 0!==t&&(this.words[n]=t,this.length++),this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>a}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r=0);var t,n=e%26,a=(e-n)/26,i=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(t=0;t>>26-n}o&&(this.words[t]=o,this.length++)}if(0!==a){for(t=this.length-1;t>=0;t--)this.words[t+a]=this.words[t];for(t=0;t=0),a=t?(t-t%26)/26:0;var i=e%26,o=Math.min((e-i)/26,this.length),s=67108863^67108863>>>i<o)for(this.length-=o,l=0;l=0&&(0!==c||l>=a);l--){var f=0|this.words[l];this.words[l]=c<<26-i|f>>>i,c=f&s}return u&&0!==c&&(u.words[u.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,a=1<=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var a=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},i.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[a+n]=67108863&i}for(;a>26,this.words[a+n]=67108863&i;if(0===s)return this.strip();for(r(-1===s),s=0,a=0;a>26,this.words[a]=67108863&i;return this.negative=1,this.strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),a=e,o=0|a.words[a.length-1];0!=(n=26-this._countBits(o))&&(a=a.ushln(n),r.iushln(n),o=0|a.words[a.length-1]);var s,u=r.length-a.length;if("mod"!==t){(s=new i(null)).length=u+1,s.words=new Array(s.length);for(var l=0;l=0;f--){var p=67108864*(0|r.words[a.length+f])+(0|r.words[a.length+f-1]);for(p=Math.min(p/o|0,67108863),r._ishlnsubmul(a,p,f);0!==r.negative;)p--,r.negative=0,r._ishlnsubmul(a,1,f),r.isZero()||(r.negative^=1);s&&(s.words[f]=p)}return s&&s.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:s||null,mod:r}},i.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(a=s.div.neg()),"div"!==t&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(e)),{div:a,mod:o}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(e)),{div:s.div,mod:o}):e.length>this.length||this.cmp(e)<0?{div:new i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modn(e.words[0]))}:this._wordDiv(e,t);var a,o,s},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),a=e.andln(1),i=n.cmp(r);return i<0||1===a&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,a=this.length-1;a>=0;a--)n=(t*n+(0|this.words[a]))%e;return n},i.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var a=(0|this.words[n])+67108864*t;this.words[n]=a/e|0,t=a%e}return this.strip()},i.prototype.divn=function(e){return this.clone().idivn(e)},i.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new i(1),o=new i(0),s=new i(0),u=new i(1),l=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++l;for(var c=n.clone(),f=t.clone();!t.isZero();){for(var p=0,h=1;0==(t.words[0]&h)&&p<26;++p,h<<=1);if(p>0)for(t.iushrn(p);p-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(f)),a.iushrn(1),o.iushrn(1);for(var d=0,m=1;0==(n.words[0]&m)&&d<26;++d,m<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(c),u.isub(f)),s.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),a.isub(s),o.isub(u)):(n.isub(t),s.isub(a),u.isub(o))}return{a:s,b:u,gcd:n.iushln(l)}},i.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a,o=new i(1),s=new i(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var l=0,c=1;0==(t.words[0]&c)&&l<26;++l,c<<=1);if(l>0)for(t.iushrn(l);l-- >0;)o.isOdd()&&o.iadd(u),o.iushrn(1);for(var f=0,p=1;0==(n.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(n.iushrn(f);f-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(n)>=0?(t.isub(n),o.isub(s)):(n.isub(t),s.isub(o))}return(a=0===t.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(e),a},i.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var a=t.cmp(n);if(a<0){var i=t;t=n,n=i}else if(0===a||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,a=1<>>26,s&=67108863,this.words[o]=s}return 0!==i&&(this.words[o]=i,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var a=0|this.words[0];t=a===e?0:ae.length)return 1;if(this.length=0;n--){var r=0|this.words[n],a=0|e.words[n];if(r!==a){ra&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new _(e)},i.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var g={k256:null,p224:null,p192:null,p25519:null};function y(e,t){this.name=e,this.p=new i(t,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function x(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(e){if("string"==typeof e){var t=i._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function S(e){_.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},y.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t0?n.isub(this.p):n.strip(),n},y.prototype.split=function(e,t){e.iushrn(this.n,0,t)},y.prototype.imulK=function(e){return e.imul(this.k)},a(v,y),v.prototype.split=function(e,t){for(var n=Math.min(e.length,9),r=0;r>>22,a=i}a>>>=22,e.words[r-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=a,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._prime=function(e){if(g[e])return g[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new b;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new x}return g[e]=t,t},_.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},_.prototype._verify2=function(e,t){r(0==(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},_.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},_.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},_.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},_.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},_.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},_.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},_.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},_.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},_.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},_.prototype.isqr=function(e){return this.imul(e,e.clone())},_.prototype.sqr=function(e){return this.mul(e,e)},_.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new i(1)).iushrn(2);return this.pow(e,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),u=s.redNeg(),l=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,l).cmp(u);)c.redIAdd(u);for(var f=this.pow(c,a),p=this.pow(e,a.addn(1).iushrn(1)),h=this.pow(e,a),d=o;0!==h.cmp(s);){for(var m=h,g=0;0!==m.cmp(s);g++)m=m.redSqr();r(g=0;r--){for(var l=t.words[r],c=u-1;c>=0;c--){var f=l>>c&1;a!==n[0]&&(a=this.sqr(a)),0!==f||0!==o?(o<<=1,o|=f,(4==++s||0===r&&0===c)&&(a=this.mul(a,n[o]),s=0,o=0)):s=0}u=26}return a},_.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},_.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new S(e)},a(S,_),S.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},S.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},S.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=n.isub(r).iushrn(this.shift),i=a;return a.cmp(this.m)>=0?i=a.isub(this.m):a.cmpn(0)<0&&(i=a.iadd(this.m)),i._forceRed(this)},S.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=n.isub(r).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},S.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===e||e,this)}).call(this,n(436)(e))},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(472),a=n(471),i=n(254);function o(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(o()=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function d(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 F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return V(e).length;default:if(r)return F(e).length;t=(""+t).toLowerCase(),r=!0}}function m(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:y(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):y(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,a){var i,o=1,s=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;o=2,s/=2,u/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(i=n;is&&(n=s-u),i=n;i>=0;i--){for(var f=!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 o=0;o>8,a=n%256,i.push(a),i.push(r);return i}(t,e.length-n),e,n,r)}function N(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a239?4:l>223?3:l>191?2:1;if(a+f<=n)switch(f){case 1:l<128&&(c=l);break;case 2:128==(192&(i=e[a+1]))&&(u=(31&l)<<6|63&i)>127&&(c=u);break;case 3:i=e[a+1],o=e[a+2],128==(192&i)&&128==(192&o)&&(u=(15&l)<<12|(63&i)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:i=e[a+1],o=e[a+2],s=e[a+3],128==(192&i)&&128==(192&o)&&128==(192&s)&&(u=(15&l)<<18|(63&i)<<12|(63&o)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,f=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=f}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);for(var n="",r=0;rthis.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 C(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return I(this,t,n);case"base64":return N(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(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(t>>>=0,n>>>=0,r>>>=0,a>>>=0,this===e)return 0;for(var i=a-r,o=n-t,s=Math.min(i,o),l=this.slice(r,a),c=e.slice(t,n),f=0;fa)&&(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 b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(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 k(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 T(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 M(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 R(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 j(e,t,n,r,i){return i||D(e,0,n,4),a.write(e,t,n,r,23,4),n+4}function L(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,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=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||A(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||A(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||A(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||A(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||A(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||A(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||A(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||A(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||A(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||A(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||A(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||A(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||A(e,4,this.length),a.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||A(e,4,this.length),a.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||A(e,8,this.length),a.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||A(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||T(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||T(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||T(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):M(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||T(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):M(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||T(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):R(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||T(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):R(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);T(this,e,t,n,a-1,-a)}var i=0,o=1,s=0;for(this[t]=255&e;++i>0)-s&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);T(this,e,t,n,a-1,-a)}var i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o>>0)-s&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||T(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||T(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):M(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||T(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):M(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||T(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):R(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||T(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):R(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return j(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return j(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return L(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(o+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 V(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(B,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function U(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(26))},function(e,t,n){var r=n(51);e.exports=function(e){return Object(r(e))}},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(n(61));t.default=function(e){return function(){var t=e.apply(this,arguments);return new r.default(function(e,n){return function a(i,o){try{var s=t[i](o),u=s.value}catch(e){return void n(e)}if(!s.done)return r.default.resolve(u).then(function(e){a("next",e)},function(e){a("throw",e)});e(u)}("next")})}}},function(e,t,n){e.exports=n(387)},function(e,t,n){var r=n(24),a=n(12),i=n(53),o=n(57),s=n(64),u=function(e,t,n){var l,c,f,p=e&u.F,h=e&u.G,d=e&u.S,m=e&u.P,g=e&u.B,y=e&u.W,v=h?a:a[t]||(a[t]={}),b=v.prototype,w=h?r:d?r[t]:(r[t]||{}).prototype;for(l in h&&(n=t),n)(c=!p&&w&&void 0!==w[l])&&s(v,l)||(f=c?w[l]:n[l],v[l]=h&&"function"!=typeof w[l]?n[l]:g&&c?i(f,r):y&&w[l]==f?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(f):m&&"function"==typeof f?i(Function.call,f):f,m&&((v.virtual||(v.virtual={}))[l]=f,e&u.R&&b&&!b[l]&&o(b,l,f)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e}}(n(373));t.default=function(){function e(e,t){for(var n=0;n"+a+""};e.exports=function(e,t){var n={};n[e]=t(s),r(r.P+r.F*a(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",n)}},function(e,t,n){var r=n(7),a=n(30),i=n(35),o=n(74)("src"),s=Function.toString,u=(""+s).split("toString");n(44).inspectSource=function(e){return s.call(e)},(e.exports=function(e,t,n,s){var l="function"==typeof n;l&&(i(n,"name")||a(n,"name",t)),e[t]!==n&&(l&&(i(n,o)||a(n,o,e[t]?""+e[t]:u.join(String(t)))),e===r?e[t]=n:s?e[t]?e[t]=n:a(e,t,n):(delete e[t],a(e,t,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[o]||s.call(this)})},function(e,t,n){var r=n(13),a=n(75);e.exports=n(14)?function(e,t,n){return r.f(e,t,a(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=n,n.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}},function(e,t,n){var r=n(35),a=n(17),i=n(196)("IE_PROTO"),o=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=a(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?o:null}},function(e,t,n){var r=n(105),a=n(75),i=n(34),o=n(52),s=n(35),u=n(293),l=Object.getOwnPropertyDescriptor;t.f=n(14)?l:function(e,t){if(e=i(e),t=o(t,!0),u)try{return l(e,t)}catch(e){}if(s(e,t))return a(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(106),a=n(51);e.exports=function(e){return r(a(e))}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){"use strict";t.__esModule=!0;var r=o(n(369)),a=o(n(367)),i="function"==typeof a.default&&"symbol"==typeof r.default?function(e){return typeof e}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof a.default&&"symbol"===i(r.default)?function(e){return void 0===e?"undefined":i(e)}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":void 0===e?"undefined":i(e)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return t&&e.then(function(e){return t(void 0,e),e}).catch(function(e){return t(e),e}),e}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){var r=n(48),a=n(256),i=n(170),o=Object.defineProperty;t.f=n(47)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),a)try{return o(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";var r=n(8);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null)})}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(25);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,a){return e.call(t,n,r,a)}}return function(){return e.apply(t,arguments)}}},function(e,t){var n=e.exports={version:"2.6.1"};"number"==typeof __e&&(__e=n)},function(e,t,n){"use strict";var r=n(31),a=n(5);function i(e,t){return 55296==(64512&e.charCodeAt(t))&&!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1))}function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function s(e){return 1===e.length?"0"+e:e}function u(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=a,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var n=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),a=0;a>6|192,n[r++]=63&o|128):i(e,a)?(o=65536+((1023&o)<<10)+(1023&e.charCodeAt(++a)),n[r++]=o>>18|240,n[r++]=o>>12&63|128,n[r++]=o>>6&63|128,n[r++]=63&o|128):(n[r++]=o>>12|224,n[r++]=o>>6&63|128,n[r++]=63&o|128)}else for(a=0;a>>0}return o},t.split32=function(e,t){for(var n=new Array(4*e.length),r=0,a=0;r>>24,n[a+1]=i>>>16&255,n[a+2]=i>>>8&255,n[a+3]=255&i):(n[a+3]=i>>>24,n[a+2]=i>>>16&255,n[a+1]=i>>>8&255,n[a]=255&i)}return n},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,n){return e+t+n>>>0},t.sum32_4=function(e,t,n,r){return e+t+n+r>>>0},t.sum32_5=function(e,t,n,r,a){return e+t+n+r+a>>>0},t.sum64=function(e,t,n,r){var a=e[t],i=r+e[t+1]>>>0,o=(i>>0,e[t+1]=i},t.sum64_hi=function(e,t,n,r){return(t+r>>>0>>0},t.sum64_lo=function(e,t,n,r){return t+r>>>0},t.sum64_4_hi=function(e,t,n,r,a,i,o,s){var u=0,l=t;return u+=(l=l+r>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,n,r,a,i,o,s){return t+r+i+s>>>0},t.sum64_5_hi=function(e,t,n,r,a,i,o,s,u,l){var c=0,f=t;return c+=(f=f+r>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,n,r,a,i,o,s,u,l){return t+r+i+s+l>>>0},t.rotr64_hi=function(e,t,n){return(t<<32-n|e>>>n)>>>0},t.rotr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0},t.shr64_hi=function(e,t,n){return e>>>n},t.shr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0}},function(e,t){var n,r,a=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(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:o}catch(e){r=o}}();var u,l=[],c=!1,f=-1;function p(){c&&u&&(c=!1,u.length?l=u.concat(l):f=-1,l.length&&h())}function h(){if(!c){var e=s(p);c=!0;for(var t=l.length;t;){for(u=l,l=[];++f1)for(var n=1;nx;x++)if((p||x in v)&&(g=b(m=v[x],x,y),e))if(n)_[x]=g;else if(g)switch(e){case 3:return!0;case 5:return m;case 6:return x;case 2:_.push(m)}else if(c)return!1;return f?-1:l||c?c:_}}},function(e,t,n){var r=n(2),a=n(44),i=n(8);e.exports=function(e,t){var n=(a.Object||{})[e]||Object[e],o={};o[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",o)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(9);e.exports=function(e,t){if(!r(e))return e;var n,a;if(t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;if("function"==typeof(n=e.valueOf)&&!r(a=n.call(e)))return a;if(!t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(102);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,a){return e.call(t,n,r,a)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(270),a=n(2),i=n(131)("metadata"),o=i.store||(i.store=new(n(267))),s=function(e,t,n){var a=o.get(e);if(!a){if(!n)return;o.set(e,a=new r)}var i=a.get(t);if(!i){if(!n)return;a.set(t,i=new r)}return i};e.exports={store:o,map:s,has:function(e,t,n){var r=s(t,n,!1);return void 0!==r&&r.has(e)},get:function(e,t,n){var r=s(t,n,!1);return void 0===r?void 0:r.get(e)},set:function(e,t,n,r){s(n,r,!0).set(e,t)},keys:function(e,t){var n=s(e,t,!1),r=[];return n&&n.forEach(function(e,t){r.push(t)}),r},key:function(e){return void 0===e||"symbol"==typeof e?e:String(e)},exp:function(e){a(a.S,"Reflect",e)}}},function(e,t,n){"use strict";if(n(14)){var r=n(59),a=n(7),i=n(8),o=n(2),s=n(120),u=n(172),l=n(43),c=n(68),f=n(75),p=n(30),h=n(66),d=n(41),m=n(11),g=n(265),y=n(72),v=n(52),b=n(35),w=n(85),x=n(9),_=n(17),E=n(183),N=n(71),S=n(32),O=n(70).f,k=n(181),I=n(74),C=n(10),P=n(49),A=n(130),T=n(103),M=n(178),R=n(83),D=n(125),j=n(69),L=n(179),B=n(276),z=n(13),F=n(33),V=z.f,U=F.f,W=a.RangeError,q=a.TypeError,$=a.Uint8Array,G=Array.prototype,H=u.ArrayBuffer,K=u.DataView,X=P(0),Y=P(2),J=P(3),Z=P(4),Q=P(5),ee=P(6),te=A(!0),ne=A(!1),re=M.values,ae=M.keys,ie=M.entries,oe=G.lastIndexOf,se=G.reduce,ue=G.reduceRight,le=G.join,ce=G.sort,fe=G.slice,pe=G.toString,he=G.toLocaleString,de=C("iterator"),me=C("toStringTag"),ge=I("typed_constructor"),ye=I("def_constructor"),ve=s.CONSTR,be=s.TYPED,we=s.VIEW,xe=P(1,function(e,t){return Oe(T(e,e[ye]),t)}),_e=i(function(){return 1===new $(new Uint16Array([1]).buffer)[0]}),Ee=!!$&&!!$.prototype.set&&i(function(){new $(1).set({})}),Ne=function(e,t){var n=d(e);if(n<0||n%t)throw W("Wrong offset!");return n},Se=function(e){if(x(e)&&be in e)return e;throw q(e+" is not a typed array!")},Oe=function(e,t){if(!(x(e)&&ge in e))throw q("It is not a typed array constructor!");return new e(t)},ke=function(e,t){return Ie(T(e,e[ye]),t)},Ie=function(e,t){for(var n=0,r=t.length,a=Oe(e,r);r>n;)a[n]=t[n++];return a},Ce=function(e,t,n){V(e,t,{get:function(){return this._d[n]}})},Pe=function(e){var t,n,r,a,i,o,s=_(e),u=arguments.length,c=u>1?arguments[1]:void 0,f=void 0!==c,p=k(s);if(void 0!=p&&!E(p)){for(o=p.call(s),r=[],t=0;!(i=o.next()).done;t++)r.push(i.value);s=r}for(f&&u>2&&(c=l(c,arguments[2],2)),t=0,n=m(s.length),a=Oe(this,n);n>t;t++)a[t]=f?c(s[t],t):s[t];return a},Ae=function(){for(var e=0,t=arguments.length,n=Oe(this,t);t>e;)n[e]=arguments[e++];return n},Te=!!$&&i(function(){he.call(new $(1))}),Me=function(){return he.apply(Te?fe.call(Se(this)):Se(this),arguments)},Re={copyWithin:function(e,t){return B.call(Se(this),e,t,arguments.length>2?arguments[2]:void 0)},every:function(e){return Z(Se(this),e,arguments.length>1?arguments[1]:void 0)},fill:function(e){return L.apply(Se(this),arguments)},filter:function(e){return ke(this,Y(Se(this),e,arguments.length>1?arguments[1]:void 0))},find:function(e){return Q(Se(this),e,arguments.length>1?arguments[1]:void 0)},findIndex:function(e){return ee(Se(this),e,arguments.length>1?arguments[1]:void 0)},forEach:function(e){X(Se(this),e,arguments.length>1?arguments[1]:void 0)},indexOf:function(e){return ne(Se(this),e,arguments.length>1?arguments[1]:void 0)},includes:function(e){return te(Se(this),e,arguments.length>1?arguments[1]:void 0)},join:function(e){return le.apply(Se(this),arguments)},lastIndexOf:function(e){return oe.apply(Se(this),arguments)},map:function(e){return xe(Se(this),e,arguments.length>1?arguments[1]:void 0)},reduce:function(e){return se.apply(Se(this),arguments)},reduceRight:function(e){return ue.apply(Se(this),arguments)},reverse:function(){for(var e,t=Se(this).length,n=Math.floor(t/2),r=0;r1?arguments[1]:void 0)},sort:function(e){return ce.call(Se(this),e)},subarray:function(e,t){var n=Se(this),r=n.length,a=y(e,r);return new(T(n,n[ye]))(n.buffer,n.byteOffset+a*n.BYTES_PER_ELEMENT,m((void 0===t?r:y(t,r))-a))}},De=function(e,t){return ke(this,fe.call(Se(this),e,t))},je=function(e){Se(this);var t=Ne(arguments[1],1),n=this.length,r=_(e),a=m(r.length),i=0;if(a+t>n)throw W("Wrong length!");for(;i255?255:255&r),a.v[h](n*t+a.o,r,_e)}(this,n,e)},enumerable:!0})};b?(d=n(function(e,n,r,a){c(e,d,l,"_d");var i,o,s,u,f=0,h=0;if(x(n)){if(!(n instanceof H||"ArrayBuffer"==(u=w(n))||"SharedArrayBuffer"==u))return be in n?Ie(d,n):Pe.call(d,n);i=n,h=Ne(r,t);var y=n.byteLength;if(void 0===a){if(y%t)throw W("Wrong length!");if((o=y-h)<0)throw W("Wrong length!")}else if((o=m(a)*t)+h>y)throw W("Wrong length!");s=o/t}else s=g(n),i=new H(o=s*t);for(p(e,"_d",{b:i,o:h,l:o,e:s,v:new K(i)});fb;b++)if((g=t?v(o(d=e[b])[0],d[1]):v(e[b]))===l||g===c)return g}else for(m=y.call(e);!(d=m.next()).done;)if((g=a(m,v,d.value,t))===l||g===c)return g}).BREAK=l,t.RETURN=c},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t,n){"use strict";var r=n(7),a=n(13),i=n(14),o=n(10)("species");e.exports=function(e){var t=r[e];i&&t&&!t[o]&&a.f(t,o,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(291),a=n(195).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,a)}},function(e,t,n){var r=n(4),a=n(290),i=n(195),o=n(196)("IE_PROTO"),s=function(){},u=function(){var e,t=n(198)("iframe"),r=i.length;for(t.style.display="none",n(194).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("