123 |
- /*! For license information please see whatIfService.min.js.LICENSE.txt */
- !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n=e();for(var r in n)("object"==typeof exports?exports:t)[r]=n[r]}}(self,(function(){return(()=>{var t={714:(t,e,n)=>{"use strict";n.r(e),n.d(e,{AdadeltaOptimizer:()=>vf,AdagradOptimizer:()=>yf,AdamOptimizer:()=>bf,AdamaxOptimizer:()=>xf,Add:()=>vr,AddN:()=>yr,BroadcastTo:()=>kr,Callback:()=>wb,CallbackList:()=>Km,CustomCallback:()=>Jm,DataStorage:()=>ii,Div:()=>br,ENV:()=>p,EarlyStopping:()=>Ib,Environment:()=>u,FromPixels:()=>Rr,FusedBatchNorm:()=>xr,GraphModel:()=>Ex,History:()=>Ym,Identity:()=>Er,InputSpec:()=>Fm,KernelBackend:()=>oi,LayerVariable:()=>Dm,LayersModel:()=>rv,MaxPoolWithArgmax:()=>Dr,MomentumOptimizer:()=>Cf,NonMaxSuppressionV5:()=>Sr,OneHot:()=>Ir,Optimizer:()=>gf,PadV2:()=>Tr,RMSPropOptimizer:()=>Nf,RNN:()=>Ky,Rank:()=>Ct,Reduction:()=>ep,SGDOptimizer:()=>wf,Sequential:()=>iv,Square:()=>Cr,SquaredDifference:()=>wr,SymbolicTensor:()=>Mm,Tensor:()=>wt,TensorBuffer:()=>vt,Tile:()=>Ar,Transpose:()=>Nr,Variable:()=>Et,abs:()=>zr,acos:()=>Lr,acosh:()=>Br,add:()=>Or,addN:()=>Eu,addStrict:()=>ga,all:()=>xc,any:()=>wc,argMax:()=>Cc,argMin:()=>Nc,asin:()=>Pr,asinh:()=>Wr,atan:()=>Vr,atan2:()=>va,atanh:()=>Ur,avgPool:()=>lc,avgPool3d:()=>hc,backend:()=>ln,backend_util:()=>Ni,basicLSTMCell:()=>Pc,batchNorm:()=>_u,batchNorm2d:()=>zu,batchNorm3d:()=>Pu,batchNorm4d:()=>Uu,batchNormalization:()=>Ou,batchNormalization2d:()=>Mu,batchNormalization3d:()=>Bu,batchNormalization4d:()=>Vu,batchToSpaceND:()=>er,booleanMaskAsync:()=>Ll,broadcastTo:()=>ju,browser:()=>lf,buffer:()=>Qn,callbacks:()=>Eb,cast:()=>nr,ceil:()=>jr,clipByValue:()=>Gr,clone:()=>Gu,complex:()=>En,concat:()=>Kn,concat1d:()=>Xn,concat2d:()=>Yn,concat3d:()=>Jn,concat4d:()=>$n,constraints:()=>md,conv1d:()=>Vl,conv2d:()=>Ul,conv2dTranspose:()=>Jl,conv3d:()=>jl,conv3dTranspose:()=>$l,cos:()=>qr,cosh:()=>Hr,cumsum:()=>rr,customGrad:()=>ti,data:()=>r,deprecationWarn:()=>He,depthToSpace:()=>ar,depthwiseConv2d:()=>Hl,deregisterOp:()=>Fb,diag:()=>Zc,disableDeprecationWarnings:()=>qe,dispose:()=>Ze,disposeVariables:()=>Ke,div:()=>_a,divNoNan:()=>$u,divStrict:()=>ya,dot:()=>Ql,dropout:()=>Qc,elu:()=>Dc,enableDebugMode:()=>Ge,enableProdMode:()=>je,engine:()=>Xe,env:()=>c,equal:()=>wl,equalStrict:()=>Cl,erf:()=>Kr,exp:()=>Xr,expandDims:()=>ir,expm1:()=>Yr,eye:()=>Qu,fft:()=>qc,fill:()=>Un,findBackend:()=>on,findBackendFactory:()=>sn,floor:()=>Jr,floorDiv:()=>ba,frame:()=>ap,fused:()=>Lp,gather:()=>Ml,gatherND:()=>$c,gather_util:()=>Ma,getBackend:()=>rn,getGradient:()=>m,getKernel:()=>d,getKernelsForBackend:()=>g,grad:()=>Ya,grads:()=>Ja,greater:()=>Nl,greaterEqual:()=>Sl,greaterEqualStrict:()=>kl,greaterStrict:()=>Il,hammingWindow:()=>rp,hannWindow:()=>np,ifft:()=>Hc,imag:()=>Tn,image:()=>Tp,inTopKAsync:()=>sp,initializers:()=>xm,input:()=>lv,io:()=>af,irfft:()=>Xc,isFinite:()=>ua,isInf:()=>sa,isNaN:()=>oa,keep:()=>Qe,layers:()=>vb,leakyRelu:()=>Oc,less:()=>El,lessEqual:()=>Al,lessEqualStrict:()=>Tl,lessStrict:()=>Rl,linalg:()=>Cp,linspace:()=>jn,loadGraphModel:()=>Ax,loadLayersModel:()=>uv,localResponseNormalization:()=>Lc,log:()=>$r,log1p:()=>Zr,logSigmoid:()=>Qr,logSoftmax:()=>ri,logSumExp:()=>Sc,logicalAnd:()=>qu,logicalNot:()=>Hu,logicalOr:()=>Ku,logicalXor:()=>Xu,losses:()=>vp,matMul:()=>Zl,math:()=>sf,max:()=>kc,maxPool:()=>uc,maxPool3d:()=>pc,maxPoolWithArgmax:()=>fc,maximum:()=>xa,maximumStrict:()=>wa,mean:()=>Ic,memory:()=>Ye,metrics:()=>yb,min:()=>Ec,minimum:()=>Ca,minimumStrict:()=>Na,mod:()=>Sa,modStrict:()=>ka,model:()=>ov,models:()=>bb,moments:()=>Ac,movingAverage:()=>Vc,mul:()=>Ia,mulStrict:()=>Ea,multiRNNCell:()=>Wc,multinomial:()=>tl,neg:()=>ta,nextFrame:()=>Ef,norm:()=>Bc,notEqual:()=>Dl,notEqualStrict:()=>Ol,oneHot:()=>el,ones:()=>Wn,onesLike:()=>qn,op:()=>In,outerProduct:()=>tc,pad:()=>nl,pad1d:()=>rl,pad2d:()=>al,pad3d:()=>il,pad4d:()=>ol,pool:()=>cc,pow:()=>Aa,powStrict:()=>Ta,prelu:()=>_c,print:()=>tr,prod:()=>Rc,profile:()=>Je,rand:()=>sl,randomGamma:()=>ml,randomNormal:()=>gl,randomUniform:()=>vl,range:()=>Gn,ready:()=>nn,real:()=>An,reciprocal:()=>ea,registerBackend:()=>un,registerCallbackConstructor:()=>cv,registerGradient:()=>y,registerKernel:()=>v,registerOp:()=>Ob,regularizers:()=>xb,relu:()=>Fc,relu6:()=>Mc,removeBackend:()=>an,reshape:()=>or,reverse:()=>ec,reverse1d:()=>nc,reverse2d:()=>rc,reverse3d:()=>ac,reverse4d:()=>ic,rfft:()=>Kc,round:()=>na,rsqrt:()=>ra,scalar:()=>On,scatterND:()=>Gc,scatter_util:()=>Wa,selu:()=>zc,separableConv2d:()=>Yl,sequential:()=>sv,serialization:()=>ff,setBackend:()=>en,setPlatform:()=>cn,setdiff1dAsync:()=>pr,sigmoid:()=>aa,sign:()=>ia,signal:()=>op,sin:()=>la,sinh:()=>ca,slice:()=>dc,slice1d:()=>mc,slice2d:()=>gc,slice3d:()=>vc,slice4d:()=>yc,slice_util:()=>Xa,softmax:()=>ni,softplus:()=>pa,spaceToBatchND:()=>sr,sparseToDense:()=>Jc,spectral:()=>Yc,split:()=>Zn,sqrt:()=>ha,square:()=>yl,squaredDifference:()=>bl,squaredDifferenceStrict:()=>Ra,squeeze:()=>ur,stack:()=>lr,step:()=>fa,stft:()=>ip,stridedSlice:()=>Uc,sub:()=>Da,subStrict:()=>Oa,sum:()=>Tc,sumOutType:()=>Rt,tan:()=>da,tanh:()=>ma,tensor:()=>Rn,tensor1d:()=>_n,tensor2d:()=>Fn,tensor3d:()=>Mn,tensor4d:()=>zn,tensor5d:()=>Ln,tensor6d:()=>Bn,tensor_util:()=>Mt,test_util:()=>pl,tidy:()=>$e,tile:()=>Zu,time:()=>tn,topk:()=>jc,train:()=>kf,transpose:()=>ai,truncatedNormal:()=>xl,unregisterGradient:()=>x,unregisterKernel:()=>b,unsortedSegmentSum:()=>zl,unstack:()=>cr,util:()=>pt,valueAndGrad:()=>$a,valueAndGrads:()=>Za,variable:()=>Pn,variableGrads:()=>Qa,version:()=>nC,version_converter:()=>Tx,version_core:()=>df,version_layers:()=>Tg,webgl:()=>mf,where:()=>Yu,whereAsync:()=>Ju,zeros:()=>Vn,zerosLike:()=>Hn});var r={};n.r(r),n.d(r,{CSVDataset:()=>Fw,Dataset:()=>ww,FileDataSource:()=>Xw,TextLineDataset:()=>Ew,URLDataSource:()=>Yw,array:()=>Nw,csv:()=>Jw,func:()=>$w,generator:()=>Zw,microphone:()=>tC,version_data:()=>eC,webcam:()=>Qw,zip:()=>Sw});var a=function(t,e){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function o(t,e,n,r){return new(n||(n=Promise))((function(a,i){function o(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(o,s)}u((r=r.apply(t,e||[])).next())}))}function s(t,e){var n,r,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=e.call(t,o)}catch(t){i=[6,t],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}var u=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},t.prototype.get=function(t){return t in this.flags||(this.flags[t]=this.evaluateFlag(t)),this.flags[t]},t.prototype.getNumber=function(t){return this.get(t)},t.prototype.getBool=function(t){return this.get(t)},t.prototype.getFlags=function(){return this.flags},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},t.prototype.setFlags=function(t){this.flags=Object.assign({},t)},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return l(n,e[0],e[1]),e.join("=")})),n);"tfjsflags"in r&&r.tfjsflags.split(",").forEach((function(e){var n=e.split(":"),r=n[0],a=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,a)}))}},t}();function l(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function c(){return p}var p=null,h=new Map,f=new Map;function d(t,e){var n=w(t,e);return h.get(n)}function m(t){return f.get(t)}function g(t){for(var e=h.entries(),n=[];;){var r=e.next(),a=r.done,i=r.value;if(a)break;var o=i[0],s=i[1];o.split("_")[0]===t&&n.push(s)}return n}function v(t){var e=t.kernelName,n=t.backendName,r=w(e,n);if(h.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");h.set(r,t)}function y(t){var e=t.kernelName;f.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),f.set(e,t)}function b(t,e){var n=w(t,e);if(!h.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");h.delete(n)}function x(t){if(!f.has(t))throw new Error("The gradient '"+t+"' for backend is not registered");f.delete(t)}function w(t,e){return e+"_"+t}function C(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function N(t,e,n){return Math.max(t,Math.min(e,n))}function S(t){return t%2==0?t:t+1}function k(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function I(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function E(t,e,n){void 0===n&&(n=""),I(D(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function A(t){I(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function T(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||q(t)&&!n)for(var r=0;r<t.length;++r)T(t[r],e,n);else e.push(t);return e}function R(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function D(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function O(t){return t%1==0}function _(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function F(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function M(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function z(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise((function(r,a){var i=0,o=function(){if(t())r();else{i++;var s=e(i);null!=n&&i>=n?a():setTimeout(o,s)}};o()}))}function L(t,e){for(var n=1,r=-1,a=0;a<t.length;++a)if(t[a]>=0)n*=t[a];else if(-1===t[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(t[a]<0)throw Error("Shapes can not be < 0. Found "+t[a]+" at dim "+a);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var i=t.slice();return i[r]=e/n,i}function B(t,e){var n=e.length;return I((t=null==t?e.map((function(t,e){return e})):[].concat(t)).every((function(t){return t>=-n&&t<n})),(function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t})),I(t.every((function(t){return O(t)})),(function(){return"All values in axis param must be integers but got axis "+t})),t.map((function(t){return t<0?n+t:t}))}function P(t,e){for(var n=[],r=[],a=null!=e&&Array.isArray(e)&&0===e.length,i=null==e||a?null:B(e,t).sort(),o=0,s=0;s<t.length;++s){if(null!=i){if(i[o]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==i[o]||i[o]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),i[o]<=s&&o++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function W(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function V(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function U(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function j(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function G(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function q(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function H(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function K(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function X(t){return"string"==typeof t||t instanceof String}function Y(t){return"boolean"==typeof t}function J(t){return"number"==typeof t}function $(t){return Array.isArray(t)?$(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":J(t)?"float32":X(t)?"string":Y(t)?"bool":"float32"}function Z(t){return!!(t&&t.constructor&&t.call&&t.apply)}function Q(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function tt(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function et(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=T(t)),n&&U(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),a=0;a<r.length;++a)0!==Math.round(t[a])&&(r[a]=1);return r}throw new Error("Unknown data type "+e)}function nt(t,e){if(0===t.length)return e[0];var n=t.reduce((function(t,e){return t*e}));if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var a=new Array;if(1===n.length)for(var i=n[0],o=0;o<i;o++)a[o]=r[e+o];else{i=n[0];var s=n.slice(1),u=s.reduce((function(t,e){return t*e}));for(o=0;o<i;o++)a[o]=t(e+o*u,s,r)}return a}(0,t,e)}function rt(t,e){for(var n=at(t,e),r=0;r<n.length;r++)n[r]=1;return n}function at(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function it(){return c().platform.now()}function ot(t){t.forEach((function(e){I(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function st(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.encode(t,e)}function ut(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.decode(t,e)}function lt(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],a=0;a<t.length-1;++a)r+=n[a]*t[a];return r}function ct(t,e,n){if(0===e)return[];if(1===e)return[t];for(var r=new Array(e),a=0;a<r.length-1;++a)r[a]=Math.floor(t/n[a]),t-=r[a]*n[a];return r[r.length-1]=t,r}var pt=Object.freeze({shuffle:C,clamp:N,nearestLargerEven:S,sum:k,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var a=Number(t[r])-Number(e[r]);n+=a*a}return n},assert:I,assertShapesMatch:E,assertNonNull:A,flatten:T,sizeFromShape:R,isScalarShape:function(t){return 0===t.length},arraysEqual:D,isInt:O,tanh:_,sizeToSquarishShape:F,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return C(e),e},rightPad:M,repeatedTry:z,inferFromImplicitShape:L,parseAxisParam:B,squeezeShape:P,getTypedArrayFromDType:W,getArrayFromDType:V,checkConversionForErrors:U,isValidDtype:j,hasEncodingLoss:G,isTypedArray:q,bytesPerElement:H,bytesFromStringArray:K,isString:X,isBoolean:Y,isNumber:J,inferDtype:$,isFunction:Z,nearestDivisor:Q,computeStrides:tt,toTypedArray:et,toNestedArray:nt,makeOnesTypedArray:rt,makeZerosTypedArray:at,now:it,assertNonNegativeIntegerDimensions:ot,fetch:function(t,e){return c().platform.fetch(t,e)},encodeString:st,decodeString:ut,locToIndex:lt,indexToLoc:ct}),ht=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new ft)}return t.prototype.profileKernel=function(t,e,n){var r,a=this,i=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var a=t[r];if(isNaN(a)||!isFinite(a))return console.warn("Found "+a+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),i.then((function(i){var o="";null!=i.getExtraProfileInfo&&(o=i.getExtraProfileInfo()),a.logger.logKernelProfile(t,n,r,i.kernelMs,e,o)}))}))})),r},t}(),ft=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,a,i){var o="number"==typeof r?M(r+"ms",9):r.error,s=M(t,25),u=e.rank,l=e.size,c=M(e.shape.toString(),14),p="";for(var h in a){var f=a[h].shape||e.shape,d=f.length;p+=h+": "+d+"D "+(d>0?f:"")+" "}console.log("%c"+s+"\t%c"+o+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+p+"\t%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();function dt(t,e,n){return M(Array.isArray(t)?parseFloat(t[0].toFixed(7))+" + "+parseFloat(t[1].toFixed(7))+"j":X(t)?"'"+t+"'":"bool"===n?mt(t):parseFloat(t.toFixed(7)).toString(),e)}function mt(t){return 0===t?"false":"true"}function gt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var vt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=R(t),null!=n){var a=n.length;I(a===this.size,(function(){return"Length of values '"+a+"' does not match the size inferred by the shape '"+r.size+"'."}))}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||V(e,this.size),this.strides=tt(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),I(n.length===this.rank,(function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"}));var a=this.locToIndex(n);this.values[a]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,a=t;r<a.length;r++){var i=a[r];if(i<0||i>=this.shape[n]){var o="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(o)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return yt().makeTensor(this.values,this.shape,this.dtype)},t}(),yt=null,bt=null,xt=null,wt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=R(t),this.strides=tt(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),I(1===this.size,(function(){return"The array must have only 1 element."})),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,a){return this.throwIfDisposed(),this.reshape([t,e,n,r,a])},t.prototype.asType=function(t){return this.throwIfDisposed(),bt.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,bt.buffer(this.shape,this.dtype,t)]}}))}))},t.prototype.bufferSync=function(){return bt.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,nt(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return nt(this.shape,this.dataSync())},t.prototype.data=function(){return o(this,void 0,void 0,(function(){var t,e;return s(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=yt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map((function(t){return ut(t)}))]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,t]}}))}))},t.prototype.dataSync=function(){this.throwIfDisposed();var t=yt().readSync(this.dataId);if("string"===this.dtype)try{return t.map((function(t){return ut(t)}))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},t.prototype.bytes=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,yt().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)]}}))}))},t.prototype.dispose=function(){this.isDisposed||(yt().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),bt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),bt.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),bt.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),bt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),bt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),bt.clone(this)},t.prototype.toString=function(t){return void 0===t&&(t=!1),function(t,e,n,r){var a=tt(e),i=function(t,e,n,r){var a=R(e),i=r[r.length-1],o=new Array(i).fill(0),s=e.length,u="complex64"===n?gt(t):t;if(s>1)for(var l=0;l<a/i;l++)for(var c=l*i,p=0;p<i;p++)o[p]=Math.max(o[p],dt(u[c+p],0,n).length);return o}(t,e,n,a),o=e.length,s=function t(e,n,r,a,i,o){void 0===o&&(o=!0);var s="complex64"===r?2:1,u=n[0],l=n.length;if(0===l)return"complex64"===r?[dt(gt(e)[0],0,r)]:"bool"===r?[mt(e[0])]:[e[0].toString()];if(1===l){if(u>20){var c=3*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice((u-3)*s,u*s));return"complex64"===r&&(p=gt(p),h=gt(h)),["["+p.map((function(t,e){return dt(t,i[e],r)})).join(", ")+", ..., "+h.map((function(t,e){return dt(t,i[u-3+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?gt(e):Array.from(e)).map((function(t,e){return dt(t,i[e],r)})).join(", ")+"]"]}var f=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>20){for(var v=0;v<3;v++){var y=(b=v*m)+m;g.push.apply(g,t(e.slice(b,y),f,r,d,i,!1))}for(g.push("..."),v=u-3;v<u;v++)y=(b=v*m)+m,g.push.apply(g,t(e.slice(b,y),f,r,d,i,v===u-1))}else for(v=0;v<u;v++){var b;y=(b=v*m)+m,g.push.apply(g,t(e.slice(b,y),f,r,d,i,v===u-1))}var x=2===l?",":"";for(g[0]="["+g[0]+x,v=1;v<g.length-1;v++)g[v]=" "+g[v]+x;var w=",\n";for(v=2;v<l;v++)w+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(o?"":w),g}(t,e,n,a,i),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+o),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map((function(t){return" "+t})).join("\n")),u.join("\n")}(this.dataSync(),this.shape,this.dtype,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),bt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),bt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),bt.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),bt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),bt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),bt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),bt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),bt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),bt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),bt.unstack(this,t)},t.prototype.batchNormalization=function(t,e,n,r,a){return void 0===n&&(n=.001),xt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,a,r,n)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),bt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),bt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),bt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),bt.cast(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),bt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),bt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),bt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),bt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),bt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),bt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),bt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),bt.mulStrict(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),bt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),bt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),bt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),bt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),bt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),bt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),bt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),bt.modStrict(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),bt.squaredDifferenceStrict(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),bt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),bt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),bt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),bt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),bt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),bt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),bt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),bt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),bt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),bt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),bt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),bt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),bt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),bt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),bt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),bt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),bt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),bt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),bt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),bt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),bt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),bt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),bt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),bt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),bt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),bt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),bt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),bt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),bt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),bt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),bt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),bt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),bt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),bt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),bt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),bt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),bt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),bt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),bt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),bt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),bt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),bt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),bt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),bt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),bt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),bt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),bt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),bt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),bt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),bt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),bt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),bt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),bt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),bt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),bt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),bt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),bt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),bt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),bt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),bt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),bt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),bt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),bt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),bt.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,a,i){return void 0===r&&(r="NWC"),void 0===a&&(a=1),this.throwIfDisposed(),bt.conv1d(this,t,e,n,r,a,i)},t.prototype.conv2d=function(t,e,n,r,a,i){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),bt.conv2d(this,t,e,n,r,a,i)},t.prototype.conv2dTranspose=function(t,e,n,r,a){return this.throwIfDisposed(),bt.conv2dTranspose(this,t,e,n,r,a)},t.prototype.depthwiseConv2D=function(t,e,n,r,a,i){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),bt.depthwiseConv2d(this,t,e,n,r,a,i)},t.prototype.separableConv2d=function(t,e,n,r,a,i){return void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC"),this.throwIfDisposed(),bt.separableConv2d(this,t,e,n,r,a,i)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),bt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),bt.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),bt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,a){return this.throwIfDisposed(),bt.pool(this,t,e,n,r,a)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),yt().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),bt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),bt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),bt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),bt.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,a,i,o,s){return void 0===r&&(r=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===s&&(s=0),this.throwIfDisposed(),bt.stridedSlice(this,t,e,n,r,a,i,o,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),bt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),bt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),bt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),bt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),bt.spectral.irfft(this)},t}();Object.defineProperty(wt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var Ct,Nt,St,kt,It,Et=function(t){function e(e,n,r,a){var i=t.call(this,e.shape,e.dtype,e.dataId,a)||this;return i.trainable=n,i.name=r,i}return i(e,t),e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!D(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");yt().disposeTensor(this),this.dataId=t.dataId,yt().incRef(this,null)},e.prototype.dispose=function(){yt().disposeVariable(this),this.isDisposedInternal=!0},e}(wt);Object.defineProperty(Et,Symbol.hasInstance,{value:function(t){return t instanceof wt&&null!=t.assign&&t.assign instanceof Function}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(Ct||(Ct={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(Nt||(Nt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(St||(St={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(kt||(kt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(It||(It={}));var At={float32:kt,int32:Nt,bool:St,complex64:It};function Tt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return At[t][e]}function Rt(t){return Tt(t,"int32")}function Dt(t,e){if(t.dtype===e.dtype)return[t,e];var n=Tt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Ot(t,e){I(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function _t(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof wt)n.push(e);else if(a=e,Array.isArray(a)||"object"==typeof a){var a,i=e;for(var o in i){var s=i[o];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}var Ft,Mt=Object.freeze({makeTypesMatch:Dt,assertTypesMatch:Ot,isTensorInList:function(t,e){return e.some((function(e){return e.id===t.id}))},getTensorsInContainer:_t}),zt=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),Lt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new zt}return t.prototype.ready=function(){return o(this,void 0,void 0,(function(){var t,e,n;return s(this,(function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then((function(){}))];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}}))}))},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory)},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},t.prototype.setBackend=function(t){return o(this,void 0,void 0,(function(){var e,n,r;return s(this,(function(a){switch(a.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=a.sent(),[3,3];case 2:r=n,a.label=3;case 3:if(!r)return[2,!1];a.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new ht(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;g(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;g(t).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])}))},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var a=++this.pendingBackendInitId,i=r.then((function(n){return!(a<e.pendingBackendInitId||(e.registry[t]=n,e.pendingBackendInit=null,0))})).catch((function(n){return!(a<e.pendingBackendInitId||(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),1))}));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority}))},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),a=r.success,i=r.asyncInit;if(i||a)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,a=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,a,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},t.prototype.tidy=function(t,e){var n,r=this,a=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");a=t}return this.scopedRun((function(){return r.startScope(a)}),(function(){return r.endScope(n)}),(function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n}))},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(function(t){return{x:function(){return t.toFloat()}}}),[],{}),e},t.prototype.runKernel=function(t,e,n,r,a){return this.runKernelFunc(null,e,null,t,n,r,a)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),a=0;n.forEach((function(t){a+="complex64"===t.dtype?3:1}));var i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-e-a-i;if(o>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+o+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,a,i,o){var s,u=this,l=[],c=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var p,h=this.state.numBytes,f=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,g=d(r,this.backendName);if(null!=g)p=function(){var t=u.backend.numDataIds();m=g.kernelFunc({inputs:e,attrs:a,backend:u.backend});var n=Array.isArray(m)?m:[m];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)}));if(c){var p=u.getTensorsForGradient(r,e,s);if(null==p){null==o&&(o=[]);var h=s.filter((function(t,e){return o[e]}));p=(i||[]).slice().concat(h)}l=u.saveTensorsForBackwardMode(p)}return s};else{var v=function(t){c&&(l=t.map((function(t){return u.keep(u.clone(t))})))};p=function(){var e=u.backend.numDataIds();m=u.tidy((function(){return t(u.backend,v)}));var n=Array.isArray(m)?m:[m];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n}}return this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return p()})):p()})),c&&this.addTapeNode(r,e,s,n,l,a),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-h,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-f,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(m)?s:s[0]},t.prototype.saveTensorsForBackwardMode=function(t){var e=this;return t.map((function(t){return e.keep(e.clone(t))}))},t.prototype.getTensorsForGradient=function(t,e,n){var r=m(t);if(null!=r){var a=r.inputsToSave||[],i=r.outputsToSave||[],o=void 0;r.saveAllInputs?(I(Array.isArray(e),(function(){return"saveAllInputs is true, expected inputs to be an array."})),o=Object.keys(e).map((function(t){return e[t]}))):o=a.map((function(t){return e[t]}));var s=n.filter((function(t,e){return i[e]}));return o.concat(s)}return null},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var a=t;"string"===n&&X(t[0])&&(a=t.map((function(t){return st(t)})));var i=r.write(a,e,n),o=new wt(e,n,i,this.nextTensorId());if(this.incRef(o,r),"string"===n){var s=this.state.tensorInfo.get(i),u=K(a);this.state.numBytes+=u-s.bytes,s.bytes=u}return o},t.prototype.makeTensorFromDataId=function(t,e,n,r){var a=new wt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(a,r),a},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var a=new Et(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*H(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Et||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return o(this,void 0,void 0,(function(){var e,n;return s(this,(function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(t){return t.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n,r,a,i){var o=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:a},u=m(t);null!=u&&(r=u.gradFunc),null!=r&&(s.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],a=at(r.size,r.dtype);return o.makeTensor(a,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],a,i)}),this.state.activeTape.push(s)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=_t(t),r=new Set(n.map((function(t){return t.id}))),a=0;a<this.state.activeScope.track.length;a++){var i=this.state.activeScope.track[a];i.kept||r.has(i.id)||i.dispose()}var o=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(t){t.kept||t.scopeId!==o.id||e.track(t)}))},t.prototype.gradients=function(t,e,n,r){var a=this;if(void 0===r&&(r=!1),I(e.length>0,(function(){return"gradients() received an empty list of xs."})),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var i=this.scopedRun((function(){return a.startTape()}),(function(){return a.endTape()}),(function(){return a.tidy("forward",t)}));I(i instanceof wt,(function(){return"The result y returned by f() must be a tensor."}));var o=function(t,e,n){for(var r={},a={},i=0;i<e.length;i++)r[e[i].id]=!0;for(i=0;i<t.length;i++){var o=(d=t[i]).inputs;for(var s in o){for(var u=o[s],l=!1,c=0;c<e.length;c++)if(r[u.id]){d.outputs.forEach((function(t){return r[t.id]=!0})),l=!0,a[d.id]=!0;break}if(l)break}}var p={};p[n.id]=!0;var h={};for(i=t.length-1;i>=0;i--)for(o=(d=t[i]).inputs,c=0;c<d.outputs.length;c++)if(p[d.outputs[c].id]){for(var s in o)p[o[s].id]=!0,h[d.id]=!0;break}var f=[];for(i=0;i<t.length;i++){var d;if(a[(d=t[i]).id]&&h[d.id]){var m={};for(var s in d.inputs){var g=d.inputs[s];r[g.id]&&(m[s]=g)}var v=Object.assign({},d);v.inputs=m,v.outputs=d.outputs,f.push(v)}}return f}(this.state.activeTape,e,i);if(!r&&0===o.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(function(){var t,r,s={};s[i.id]=null==n?(r=rt(R(t=i.shape),"float32"),Bt.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var a=e[r],i=[];if(a.outputs.forEach((function(e){var n=t[e.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+a.kernelName+".");var o=a.gradient(i),s=function(e){if(!(e in o))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(o)+".");var r=n((function(){return o[e]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var i=a.inputs[e];if(!D(r.shape,i.shape))throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+i.shape+"'");if(null==t[i.id])t[i.id]=r;else{var s=t[i.id];t[i.id]=s.add(r),s.dispose()}};for(var u in a.inputs)s(u)},a=e.length-1;a>=0;a--)r(a)}(s,o,(function(t){return a.tidy(t)}));var u=e.map((function(t){return s[t.id]}));return 0===a.state.gradientDepth&&(a.state.activeTape.forEach((function(t){for(var e=0,n=t.saved;e<n.length;e++)n[e].dispose()})),a.state.activeTape=null),{value:i,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return I(Z(t),(function(){return"The f passed in customGrad(f) must be a function."})),function(){for(var n,r=[],a=0;a<arguments.length;a++)r[a]=arguments[a];I(r.every((function(t){return t instanceof wt})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var i={};return r.forEach((function(t,e){i[e]=t})),e.runKernelFunc((function(e,a){return I((n=t.apply(void 0,r.concat([a]))).value instanceof wt,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),I(Z(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),i,(function(t,e){var a=n.gradFunc(t,e),i=Array.isArray(a)?a:[a];I(i.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),I(i.every((function(t){return t instanceof wt})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var o={};return i.forEach((function(t,e){o[e]=function(){return t}})),o}))}},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},t.prototype.time=function(t){return o(this,void 0,void 0,(function(){var e,n;return s(this,(function(r){switch(r.label){case 0:return e=it(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=it()-e,[2,n]}}))}))},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new zt,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}(),Bt=function(){var t=function(){if(null==Ft){var t=void 0;if("undefined"!=typeof window)t=window;else if(void 0!==n.g)t=n.g;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}Ft=t}return Ft}();if(null==t._tfengine){var e=new u(t);t._tfengine=new Lt(e)}return function(t){p=t}(t._tfengine.ENV),yt=function(){return t._tfengine},t._tfengine}();function Pt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Wt=c();Wt.registerFlag("DEBUG",(function(){return!1}),(function(t){t&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Wt.registerFlag("IS_BROWSER",(function(){return Pt()})),Wt.registerFlag("IS_NODE",(function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node})),Wt.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Wt.registerFlag("PROD",(function(){return!1})),Wt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Wt.getBool("DEBUG")})),Wt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Wt.registerFlag("IS_TEST",(function(){return!1}));var Vt,Ut,jt,Gt={},qt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ht(t,e){Gt[t]=e}function Kt(t){t in Gt||(Gt[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=function(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(t);return e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Gt[t]}),!1),1===t?e.getContext("webgl",qt)||e.getContext("experimental-webgl",qt):e.getContext("webgl2",qt)}(t));var e=Gt[t];return e.isContextLost()?(delete Gt[t],Kt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Gt[t])}function Xt(t,e){return[e,t]}function Yt(t){var e=R(t);return F(Math.ceil(e/4))}function Jt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function $t(t,e){var n,r,a,i,o,s,u,l,p,h=t;return 2===c().getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,a=h.RGBA16F,i=h.RGBA32F,o=h.RED,s=4,u=1,l=h.HALF_FLOAT,p=h.FLOAT):(n=t.RGBA,r=t.RGBA,a=t.RGBA,i=h.RGBA,o=t.RGBA,s=4,u=4,l=null!=e?e.HALF_FLOAT_OES:null,p=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:l,textureTypeFloat:p}}function Zt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+te(t,e))}(t),r}function Qt(t){return!!(c().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||5.96e-8<Math.abs(t)&&Math.abs(t)<65504)}function te(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function ee(t,e,n){return Se(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function ne(t,e,n){var r=Se(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Zt(t,e,(function(){return t.shaderSource(r,n)})),Zt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function re(t,e,n){var r=Se(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Zt(t,e,(function(){return t.shaderSource(r,n)})),Zt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=oe.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],a=t.split("\n"),i=a.length.toString().length+2,o=a.map((function(t,e){return M((e+1).toString(),i)+t})),s=0,u=0;u<o.length;u++)s=Math.max(o[u].length,s);var l=o.slice(0,r-1),c=o.slice(r-1,r),p=o.slice(r);console.log(l.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+M(c[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Vt||(Vt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Ut||(Ut={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(jt||(jt={}));var ae,ie,oe=/ERROR: [0-9]+:([0-9]+):/g;function se(t,e){return Se(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function ue(t,e,n){if(Zt(t,e,(function(){return t.linkProgram(n)})),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function le(t,e,n){if(Zt(t,e,(function(){return t.validateProgram(n)})),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function ce(t,e,n){var r=Se(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Zt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),Zt(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function pe(t,e,n){var r=Se(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Zt(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),Zt(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function he(t,e){return Se(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function fe(t,e){var n=c().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function de(t,e){return Se(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function me(t,e,n,r,a,i,o,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Zt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,a)})),Zt(t,e,(function(){return t.vertexAttribPointer(u,i,t.FLOAT,!1,o,s)})),Zt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function ge(t,e,n,r){ke(t,r),Zt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function ve(t,e,n,r){return Se(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function ye(t,e,n){return t.getUniformLocation(e,n)}function be(t,e,n,r,a,i){Zt(t,e,(function(){return ge(t,e,r,i)})),Zt(t,e,(function(){return t.uniform1i(a,i)}))}function xe(t,e,n,r){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Zt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function we(t,e,n){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Zt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ne(t,e))}function Ne(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function Se(t,e,n,r){var a=Zt(t,e,(function(){return n()}));if(null==a)throw new Error(r);return a}function ke(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Ie(t,e){return void 0===e&&(e=2),R(t.slice(0,t.length-e))}function Ee(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Ae(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ie(t)].concat(Ee(t))),e}function Te(t,e){var n;void 0===e&&(e=!1);var r=c().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map((function(e,n){return n>=t.length-2?S(t[n]):t[n]}))).length&&(t=[2,t[0]])),2!==t.length){var a=P(t);t=a.newShape}var i=R(t);if(t.length<=1&&i<=r)return[1,i];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var o=Ie(t),s=2,u=2;return t.length&&(s=(n=Ee(t))[0],u=n[1]),F(i=o*(s/2)*(u/2)).map((function(t){return 2*t}))}return F(i)}function Re(t){return t%2==0}function De(t,e){if(D(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(Re(n)&&Re(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Re(t[0])&&Re(e[0])}function Oe(t){if(null==ae){var e=Kt(t);ae=e.getParameter(e.MAX_TEXTURE_SIZE)}return ae}function _e(t){if(null==ie){var e=Kt(t);ie=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ie)}function Fe(t){if(0===t)return 0;var e=Kt(t);return Me(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Me(e,"EXT_disjoint_timer_query")?1:0}function Me(t,e){return null!=t.getExtension(e)}function ze(t){try{if(null!=Kt(t))return!0}catch(t){return!1}return!1}function Le(t){if(0===t)return!1;var e=Kt(t);if(1===t){if(!Me(e,"OES_texture_float"))return!1}else if(!Me(e,"EXT_color_buffer_float"))return!1;return Pe(e)}function Be(t){if(0===t)return!1;var e=Kt(t);if(1!==t){if(Me(e,"EXT_color_buffer_float"))return Pe(e);if(Me(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=$t(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var a=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,a),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(a),i}(e,n)}return!1}return!!Me(e,"OES_texture_float")&&!!Me(e,"WEBGL_color_buffer_float")&&Pe(e)}function Pe(t){var e=$t(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),a}function We(t){return 2===t&&null!=Kt(t).fenceSync}var Ve=Object.freeze({callAndCheck:Zt,canBeRepresented:Qt,getWebGLErrorMessage:te,getExtensionOrThrow:ee,createVertexShader:ne,createFragmentShader:re,createProgram:se,linkProgram:ue,validateProgram:le,createStaticVertexBuffer:ce,createStaticIndexBuffer:pe,getNumChannels:function(){return 2===c().getNumber("WEBGL_VERSION")?1:4},createTexture:he,validateTextureSize:fe,createFramebuffer:de,bindVertexBufferToProgramAttribute:me,bindTextureUnit:ge,unbindTextureUnit:function(t,e,n){ke(t,n),Zt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:ve,getProgramUniformLocation:ye,bindTextureToProgramUniformSampler:be,bindCanvasToFramebuffer:function(t,e){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Zt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Zt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:xe,unbindColorTextureFromFramebuffer:we,validateFramebuffer:Ce,getFramebufferErrorMessage:Ne,getBatchDim:Ie,getRowsCols:Ee,getShapeAs3D:Ae,getTextureShapeFromLogicalShape:Te,isReshapeFree:De,getWebGLMaxTextureSize:Oe,resetMaxTextureSize:function(){ae=null},resetMaxTexturesInShader:function(){ie=null},getMaxTexturesInShader:_e,getWebGLDisjointQueryTimerVersion:Fe,hasExtension:Me,isWebGLVersionEnabled:ze,isCapableOfRenderingToFloatTexture:Le,isDownloadFloatTextureEnabled:Be,isWebGLFenceEnabled:We}),Ue=c();function je(){c().set("PROD",!0)}function Ge(){c().set("DEBUG",!0)}function qe(){c().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function He(t){c().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ke(){Bt.disposeVariables()}function Xe(){return Bt}function Ye(){return Bt.memory()}function Je(t){return Bt.profile(t)}function $e(t,e){return Bt.tidy(t,e)}function Ze(t){_t(t).forEach((function(t){return t.dispose()}))}function Qe(t){return Bt.keep(t)}function tn(t){return Bt.time(t)}function en(t){return Bt.setBackend(t)}function nn(){return Bt.ready()}function rn(){return Bt.backendName}function an(t){Bt.removeBackend(t)}function on(t){return Bt.findBackend(t)}function sn(t){return Bt.findBackendFactory(t)}function un(t,e,n){return void 0===n&&(n=1),Bt.registerBackend(t,e,n)}function ln(){return Bt.backend}function cn(t,e){c().setPlatform(t,e)}function pn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];c().getBool("IS_TEST")||console.warn.apply(console,t)}function hn(t,e){var n=t;if(q(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||q(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&c().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||q(e)){I(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),I(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var a=n.slice(1),i=0;i<e.length;++i)t(e[i],a,r.concat(i))}else I(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}))}(t,r,[]),r}function fn(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function dn(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof wt)return fn(r,t.dtype,e,n),t;var a=$(t);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),fn(r,a,e,n),null==t||!q(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var i=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+i+"'")}var o=hn(t,a);q(t)||Array.isArray(t)||(t=[t]);var s="string"!==a?et(t,a,c().getBool("DEBUG")):T(t,[],!0);return Bt.makeTensor(s,o,a)}function mn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map((function(t,r){return dn(t,e+"["+r+"]",n)}),r)}function gn(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function vn(t,e,n){for(var r=t.length+e.length,a=[],i=0,o=0,s=0;s<r;s++)-1===n.indexOf(s)?a.push(t[i++]):a.push(e[o++]);return a}function yn(t,e){for(var n=[],r=t.length,a=0;a<r;a++)-1===e.indexOf(a)&&n.push(t[a]);return[n,e.map((function(e){return t[e]}))]}function bn(t,e){return vn(t,e.map((function(t){return 1})),e)}function xn(t,e,n){I(gn(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function wn(t,e){if(gn(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach((function(t){return n.push(t)})),n}function Cn(t){return t.map((function(t,e){return[e,t]})).sort((function(t,e){return t[1]-e[1]})).map((function(t){return t[0]}))}function Nn(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function Sn(t,e){var n=t[0].length;t.forEach((function(t,e){I(t.length===n,(function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"}))})),I(e>=0&&e<n,(function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."}));var r=t[0];t.forEach((function(t,a){for(var i=0;i<n;i++)I(i===e||t[i]===r[i],(function(){return"Error in concat"+n+"D: Shape of tensors["+a+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+a+"."}))}))}function kn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function In(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var a=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Bt.startScope(n);try{var a=r.apply(void 0,t);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Bt.endScope(a),a}catch(t){throw Bt.endScope(null),t}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}Ue.registerFlag("HAS_WEBGL",(function(){return Ue.getNumber("WEBGL_VERSION")>0})),Ue.registerFlag("WEBGL_VERSION",(function(){return ze(2)?2:ze(1)?1:0})),Ue.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Ue.get("WEBGL_VERSION")})),Ue.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Ue.registerFlag("WEBGL_PACK",(function(){return Ue.getBool("HAS_WEBGL")})),Ue.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_CLIP",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_REDUCE",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_CONV_IM2COL",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Oe(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return _e(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=Ue.getNumber("WEBGL_VERSION");return 0===t?0:Fe(t)})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Le(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Ue.getBool("WEBGL_FORCE_F16_TEXTURES")&&Ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Be(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return We(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),xt=He;var En=In({complex_:function(t,e){var n=dn(t,"real","complex"),r=dn(e,"imag","complex");return E(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Bt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),An=In({real_:function(t){var e=dn(t,"input","real");return Bt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),Tn=In({imag_:function(t){var e=dn(t,"input","imag");return Bt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function Rn(t,e,n){return Dn(t,e,hn(t,n),n)}function Dn(t,e,n,r){if(null==r&&(r=$(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!q(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){ot(e);var a=R(e),i=R(n);I(a===i,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+a+" values but has "+i}));for(var o=0;o<n.length;++o){var s=n[o],u=o!==n.length-1||s!==R(e.slice(o));I(n[o]===e[o]||!u,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return q(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?et(t,r,c().getBool("DEBUG")):T(t,[],!0),Bt.makeTensor(t,e,r)}function On(t,e){if((q(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&q(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Dn(t,[],[],e)}function _n(t,e){A(t);var n=hn(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Dn(t,null,n,e)}function Fn(t,e,n){if(A(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=hn(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Dn(t,e,r,n)}function Mn(t,e,n){if(A(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=hn(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Dn(t,e,r,n)}function zn(t,e,n){if(A(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=hn(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Dn(t,e,r,n)}function Ln(t,e,n){if(A(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=hn(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Dn(t,e,r,n)}function Bn(t,e,n){if(A(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=hn(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Dn(t,e=e||r,r,n)}function Pn(t,e,n,r){return void 0===e&&(e=!0),Bt.makeVariable(t,e,n,r)}function Wn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Wn(t,"float32"),r=Vn(t,"float32");return En(n,r)}var a=rt(R(t),e);return Bt.makeTensor(a,t,e)}function Vn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Vn(t,"float32"),r=Vn(t,"float32");return En(n,r)}var a=at(R(t),e);return Bt.makeTensor(a,t,e)}function Un(t,e,n){return Bt.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function jn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Bt.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})}function Gn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return Vn([0],r);var a=at(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),a[0]=t;for(var i=1;i<a.length;i++)a[i]=a[i-1]+n;return _n(a,r)}var qn=In({onesLike_:function(t){var e=dn(t,"x","onesLike");if("complex64"===e.dtype){var n=qn(An(e)),r=Hn(Tn(e));return En(n,r)}return Bt.runKernelFunc((function(t){return t.onesLike(e)}),{x:e},(function(t,e){return{x:function(){return Hn(t)}}}),"OnesLike")}}),Hn=In({zerosLike_:function(t){var e=dn(t,"x","zerosLike");return Bt.runKernelFunc((function(t){return t.zerosLike(e)}),{x:e},(function(t,e){return{x:function(){return Hn(t)}}}),"ZerosLike")}}),Kn=In({concat_:function(t,e){void 0===e&&(e=0),I(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=mn(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")})),e=B(e,n[0].shape)[0];var r=kn(n.map((function(t){return t.shape})),e);if(0===R(r))return Rn([],r);if(1===(n=n.filter((function(t){return t.size>0}))).length)return n[0];var a=n.map((function(t){return t.shape}));Sn(a,e);var i=n,o={axis:e};return Bt.runKernelFunc((function(t){return t.concat(n,e)}),i,(function(t){var n=a.map((function(t){return t[e]}));return Zn(t,n,e).map((function(t){return function(){return t}}))}),"Concat",o)}}),Xn=In({concat1d_:function(t){return Kn(t,0)}}),Yn=In({concat2d_:function(t,e){return Kn(t,e)}}),Jn=In({concat3d_:function(t,e){return Kn(t,e)}}),$n=In({concat4d_:function(t,e){return Kn(t,e)}}),Zn=In({split_:function(t,e,n){void 0===n&&(n=0);var r,a=dn(t,"x","split");return n=B(n,a.shape)[0],"number"==typeof e?(I(a.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(a.shape[n]/e)):(I(a.shape[n]===e.reduce((function(t,e){return t+e})),(function(){return"The sum of sizes must match the size of the axis dimension."})),r=e),Bt.runKernelFunc((function(t){return t.split(a,r,n)}),{$x:a},(function(t){return{$x:function(){return Kn(t,n)}}}))}});function Qn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",ot(t),new vt(t,e,n)}function tr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var er=In({batchToSpaceND_:function(t,e,n){var r=dn(t,"x","batchToSpaceND"),a=e.reduce((function(t,e){return t*e}));return I(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),I(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),I(r.shape[0]%a==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+a})),Bt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),nr=In({cast_:function(t,e){var n=dn(t,"x","cast");if(!j(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var r={dtype:e};return Bt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),rr=In({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=dn(t,"x","cumsum"),i=wn([e|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=Nn(1,a.rank)[0],u=Bt.runKernelFunc((function(t){return t.cumsum(o,s,n,r)}),{permutedX:o},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=i&&(u=u.transpose(i)),u}}),ar=In({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=dn(t,"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 I(a*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape})),I(i*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape})),I(o%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+o+" for depthToSpace with input shape "+r.shape})),Bt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),ir=In({expandDims_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","expandDims",null);I(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(I(-(n.rank+1)<=e,(function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"})),e=n.rank+e+1),r.splice(e,0,1),or(n,r)}}),or=In({reshape_:function(t,e){var n=dn(t,"x","reshape",null);e=L(e,n.size),I(n.size===R(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Bt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),sr=In({spaceToBatchND_:function(t,e,n){var r=dn(t,"x","spaceToBatchND");return I(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),I(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),I(r.shape.reduce((function(t,r,a){return a>0&&a<=e.length?t&&(r+n[a-1][0]+n[a-1][1])%e[a-1]==0:t}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()})),Bt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),ur=In({squeeze_:function(t,e){var n=dn(t,"x","squeeze");return or(n,P(n.shape,e).newShape)}}),lr=In({stack_:function(t,e){void 0===e&&(e=0);var n=mn(t,"tensors","stack");if(I(n.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),1===n.length)return n[0].expandDims(e);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;I(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){E(a,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){I(i===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var o=n.map((function(t){return t.expandDims(e)}));return Kn(o,e)}}),cr=In({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=dn(t,"x","unstack");I(e>=-n.shape.length&&e<n.shape.length,(function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"})),e<0&&(e+=n.shape.length);var r={axis:e};return Bt.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return lr(t,e)}}}),"Unpack",r)}}),pr=function(t,e){return o(this,void 0,void 0,(function(){var n,r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return n=dn(t,"x","setdiff1d"),r=dn(e,"y","setdiff1d"),I(n.dtype===r.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."})),I(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),I(1===r.rank,(function(){return"y should be 1D tensor, but got y ("+r.shape+")."})),[4,n.data()];case 1:return a=s.sent(),[4,r.data()];case 2:for(i=s.sent(),o=new Set(i),u=0,p=0;p<a.length;p++)o.has(a[p])||u++;for(l=new vt([u],n.dtype),c=new vt([u],"int32"),p=0,h=0;p<a.length;p++)o.has(a[p])||(l.values[h]=a[p],c.values[h]=p,h++);return[2,[l.toTensor(),c.toTensor()]]}}))}))};function hr(t,e,n,r){void 0===r&&(r=!0);var a=[];if(r)(a=a.concat(e.slice(0))).push(t[0]/n),a=a.concat(t.slice(1));else{a=a.concat(t[0]);for(var i=e.length,o=0;o<i;++o)a=a.concat([t[o+1]/e[o],e[o]]);a=a.concat(t.slice(i+1))}return a}function fr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var a=e+1;a<t;++a)a<=2*e?(r.push(a),r.push(a-(e+1))):r.push(a)}else{var i=[],o=[];for(a=1;a<t;++a)a>=2*e+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 dr(t,e,n,r){void 0===r&&(r=!0);var a=[];r?a.push(t[0]/n):a.push(t[0]*n);for(var i=1;i<t.length;++i)i<=e.length?r?a.push(e[i-1]*t[i]):a.push(t[i]/e[i-1]):a.push(t[i]);return a}function mr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function gr(t,e,n){for(var r=t.slice(0,1),a=0;a<n;++a)r.push(t[a+1]-e[a][0]-e[a][1]);return r}var vr="Add",yr="AddN",br="Div",xr="FusedBatchNorm",wr="SquaredDifference",Cr="Square",Nr="Transpose",Sr="NonMaxSuppressionV5",kr="BroadcastTo",Ir="OneHot",Er="Identity",Ar="Tile",Tr="PadV2",Rr="FromPixels",Dr="MaxPoolWithArgmax",Or=In({add_:function(t,e){var n,r=dn(t,"a","add"),a=dn(e,"b","add");n=Dt(r,a),r=n[0],a=n[1];var i={a:r,b:a};return Bt.runKernelFunc((function(t,e){var n=t.add(r,a);return e([r,a]),n}),i,null,vr)}});function _r(t,e){for(var n=t.length,r=[],a=0;a<n;a++){var i=n-1-a,o=t[i]||1;(e[e.length-1-a]||1)>1&&1===o&&r.unshift(i)}return r}function Fr(t,e){for(var n=[],r=0;r<e.length;r++){var a=t[t.length-r-1],i=e.length-r-1,o=e[i];(null==a||1===a&&o>1)&&n.unshift(i)}return n}function Mr(t,e){for(var n=[],r=Math.max(t.length,e.length),a=0;a<r;a++){var i=t[t.length-a-1];null==i&&(i=1);var o=e[e.length-a-1];if(null==o&&(o=1),1===i)n.unshift(o);else if(1===o)n.unshift(i);else{if(i!==o)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(i)}}return n}var zr=In({abs_:function(t){var e=dn(t,"x","abs");return"complex64"===e.dtype?Bt.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Bt.runKernelFunc((function(t,n){var r=t.abs(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().step(-1))}}}),"Abs")}}),Lr=In({acos_:function(t){var e=dn(t,"x","acos");return Bt.runKernelFunc((function(t,n){var r=t.acos(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(On(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Br=In({acosh_:function(t){var e=dn(t,"x","acosh");return Bt.runKernelFunc((function(t,n){var r=t.acosh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}}))}}),Pr=In({asin_:function(t){var e=dn(t,"x","asin");return Bt.runKernelFunc((function(t,n){var r=t.asin(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(On(1).sub(n.toFloat().square()).sqrt())}}}))}}),Wr=In({asinh_:function(t){var e=dn(t,"x","asinh");return Bt.runKernelFunc((function(t,n){var r=t.asinh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.divStrict(On(1).add(n.toFloat().square()).sqrt())}}}))}}),Vr=In({atan_:function(t){var e=dn(t,"x","atan");return Bt.runKernelFunc((function(t,n){var r=t.atan(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}}))}}),Ur=In({atanh_:function(t){var e=dn(t,"x","atanh");return Bt.runKernelFunc((function(t,n){var r=t.atanh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(On(1).sub(n.toFloat().square()))}}}))}}),jr=In({ceil_:function(t){var e=dn(t,"x","ceil");return Bt.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),Gr=In({clipByValue_:function(t,e,n){var r=dn(t,"x","clipByValue");I(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var a=[r],i={min:e,max:n};return Bt.runKernelFunc((function(t,a){var i=t.clip(r,e,n);return a([r]),i}),{x:r},(function(t,r){var a=r[0];return{x:function(){return t.where(a.greaterEqual(e).logicalAnd(a.lessEqual(n)),Hn(t))}}}),"ClipByValue",i,a)}}),qr=In({cos_:function(t){var e=dn(t,"x","cos"),n=[e];return Bt.runKernelFunc((function(t,n){var r=t.cos(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return n.toFloat().sin().neg().mul(t)}}}),"Cos",{},n)}}),Hr=In({cosh_:function(t){var e=dn(t,"x","cosh");return Bt.runKernelFunc((function(t,n){var r=t.cosh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}}))}}),Kr=In({erf_:function(t){var e=dn(t,"x","erf");return I("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Bt.runKernelFunc((function(t,n){var r=t.erf(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}}))}}),Xr=In({exp_:function(t){var e=dn(t,"x","exp");return Bt.runKernelFunc((function(t,n){var r=t.exp(e);return n([r]),r}),{x:e},(function(t,e){return{x:function(){return t.mulStrict(e[0])}}}),"Exp",{},[],[!0])}}),Yr=In({expm1_:function(t){var e=dn(t,"x","expm1");return Bt.runKernelFunc((function(t,n){var r=t.expm1(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}}))}}),Jr=In({floor_:function(t){var e=dn(t,"x","floor");return Bt.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),$r=In({log_:function(t){var e=dn(t,"x","log"),n=[e];return Bt.runKernelFunc((function(t,n){var r=t.log(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.div(n.toFloat())}}}),"Log",{},n)}}),Zr=In({log1p_:function(t){var e=dn(t,"x","log1p");return Bt.runKernelFunc((function(t,n){var r=t.log1p(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}}))}}),Qr=In({logSigmoid_:function(t){var e=dn(t,"x","logSigmoid");return Bt.runKernelFunc((function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}}))}}),ta=In({neg_:function(t){var e=dn(t,"x","neg"),n=[e];return Bt.runKernelFunc((function(t){return t.neg(e)}),{x:e},(function(t){return{x:function(){return t.neg()}}}),"Neg",{},n)}}),ea=In({reciprocal_:function(t){var e=dn(t,"x","reciprocal");return Bt.runKernelFunc((function(t,n){var r=t.reciprocal(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}}))}}),na=In({round_:function(t){var e=dn(t,"x","round");return Bt.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),ra=In({rsqrt_:function(t){var e=dn(t,"x","rsqrt"),n=[e];return Bt.runKernelFunc((function(t,n){var r=t.rsqrt(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}}),"Rsqrt",{},n)}}),aa=In({sigmoid_:function(t){var e=dn(t,"x","sigmoid");return Bt.runKernelFunc((function(t,n){var r=t.sigmoid(e);return n([r]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mul(n.mul(On(1).sub(n)))}}}),"Sigmoid")}}),ia=In({sign_:function(t){var e=dn(t,"x","sign");return Bt.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),oa=In({isNaN_:function(t){var e=dn(t,"x","isNaN");return Bt.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),sa=In({isInf_:function(t){var e=dn(t,"x","isInf");return Bt.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),ua=In({isFinite_:function(t){var e=dn(t,"x","isFinite");return Bt.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return Hn(t)}}}))}}),la=In({sin_:function(t){var e=dn(t,"x","sin"),n=[e];return Bt.runKernelFunc((function(t,n){var r=t.sin(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return n.toFloat().cos().mul(t)}}}),"Sin",{},n)}}),ca=In({sinh_:function(t){var e=dn(t,"x","sinh");return Bt.runKernelFunc((function(t,n){var r=t.sinh(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}}))}}),pa=In({softplus_:function(t){var e=dn(t,"x","softplus");return Bt.runKernelFunc((function(t,n){var r=t.softplus(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}}))}}),ha=In({sqrt_:function(t){var e=dn(t,"x","sqrt");return Bt.runKernelFunc((function(t,n){var r=t.sqrt(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}}))}}),fa=In({step_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","step");return Bt.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return Hn(t)}}}))}}),da=In({tan_:function(t){var e=dn(t,"x","tan");return Bt.runKernelFunc((function(t,n){var r=t.tan(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}}))}}),ma=In({tanh_:function(t){var e=dn(t,"x","tanh");return Bt.runKernelFunc((function(t,n){var r=t.tanh(e);return n([r]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return On(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}}),ga=In({addStrict_:function(t,e){var n=dn(t,"a","addStrict"),r=dn(e,"b","addStrict");return E(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),va=In({atan2_:function(t,e){var n,r=dn(t,"a","atan2"),a=dn(e,"b","atan2");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.atan2(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Or(n.square(),r.square()),a=t.mul(r.div(e)),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},$b:function(){var e=Or(n.square(),r.square()),a=ta(t.mul(n.div(e))),o=Fr(r.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(r.shape)}}}))}}),ya=In({divStrict_:function(t,e){var n=dn(t,"a","div"),r=dn(e,"b","div");return E(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),ba=In({floorDiv_:function(t,e){var n,r=dn(t,"a","floorDiv"),a=dn(e,"b","floorDiv");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.floorDiv(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),a=Fr(n.shape,i);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=Fr(r.shape,i);a.length>0&&(e=e.sum(a).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}}),"FloorDiv")}}),xa=In({maximum_:function(t,e){var n,r=dn(t,"a","maximum"),a=dn(e,"b","maximum");return n=Dt(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.maximum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.greaterEqual(r).toFloat())},b:function(){return t.mul(n.less(r).toFloat())}}}),"Maximum")}}),wa=In({maximumStrict_:function(t,e){var n=dn(t,"a","maximumStrict"),r=dn(e,"b","maximumStrict");return E(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Ca=In({minimum_:function(t,e){var n,r=dn(t,"a","minimum"),a=dn(e,"b","minimum");return n=Dt(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.minimum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.lessEqual(r).toFloat())},b:function(){return t.mul(n.greater(r).toFloat())}}}),"Minimum")}}),Na=In({minimumStrict_:function(t,e){var n=dn(t,"a","minimumStrict"),r=dn(e,"b","minimumStrict");return E(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Sa=In({mod_:function(t,e){var n,r=dn(t,"a","mod"),a=dn(e,"b","mod");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.mod(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Fr(n.shape,i);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),a=Fr(r.shape,i);return a.length>0?e.sum(a).reshape(r.shape):e}}}))}}),ka=In({modStrict_:function(t,e){var n=dn(t,"a","modStrict"),r=dn(e,"b","modStrict");return E(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Ia=In({mul_:function(t,e){var n,r=dn(t,"a","mul"),a=dn(e,"b","mul");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.multiply(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),a=Fr(n.shape,i);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=Fr(r.shape,i);return a.length>0?e.sum(a).reshape(r.shape):e}}}),"Mul")}}),Ea=In({mulStrict_:function(t,e){var n=dn(t,"a","mul"),r=dn(e,"b","mul");return E(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Aa=In({pow_:function(t,e){var n,r=dn(t,"base","pow"),a=dn(e,"exp","pow");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape),o=[r,a];return Bt.runKernelFunc((function(t,e){var n=t.pow(r,a);return e([r,a,n]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1],a=e[2];return{a:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(On(1))))),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},b:function(){var e=n.greater(0),o=n.log().where(e,Hn(n)),s=t.mul(a.mul(o)),u=Fr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},o,[!0])}}),Ta=In({powStrict_:function(t,e){return E(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Ra=In({squaredDifferenceStrict_:function(t,e){var n=dn(t,"a","squaredDifferenceStrict"),r=dn(e,"b","squaredDifferenceStrict");return E(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Da=In({sub_:function(t,e){var n,r=dn(t,"a","sub"),a=dn(e,"b","sub");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t){return t.subtract(r,a)}),{a:r,b:a},(function(t){return{a:function(){var e=t,n=Fr(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Fr(a.shape,i);return n.length>0&&(e=e.sum(n)),e.neg().reshape(a.shape)}}}),"Sub")}}),Oa=In({subStrict_:function(t,e){var n=dn(t,"a","subStrict"),r=dn(e,"b","subStrict");return E(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),_a=In({div_:function(t,e){var n,r=dn(t,"a","div"),a=dn(e,"b","div");if(n=Dt(r,a),r=n[0],a=n[1],"int32"===r.dtype&&"int32"===a.dtype)return ba(r,a);var i={a:r,b:a};return Bt.runKernelFunc((function(t,e){var n=t.realDivide(r,a);return e([r,a]),n}),i,null,br,{})}});function Fa(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],a=1,i=0;i<n.length-1;++i)a*=n[i];var o=t.shape,s=n.slice();s.pop();var u=1;for(i=r;i<t.rank;++i)u*=o[i],s.push(o[i]);var l=tt(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,a,u,l]}var Ma=Object.freeze({prepareAndValidate:Fa});function za(t){return t<=30?t:Q(t,Math.floor(Math.sqrt(t)))}function La(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,a=e.rank>1?e.rank-1:1,i="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+a+".";if(n.rank<a)throw new Error(i+" update.rank < "+a+". ");if(t.length<r+(n.rank-a))throw new Error(i+" Output shape length < "+(r+(n.rank-a)));if(n.rank!==a+t.length-r)throw new Error(i+" update.rank != "+(a+t.length-r));for(var o=0;o<a;++o)if(n.shape[o]!==e.shape[o])throw new Error(i+" updates.shape["+o+"] ("+n.shape[o]+") != indices.shape["+o+"] ("+e.shape[o]+").");for(o=0;o<n.rank-a;++o)if(n.shape[o+a]!==t[o+r])throw new Error(i+" updates.shape["+(o+a)+"] ("+n.shape[o+a]+") != shape["+(o+a)+"] ("+t[o+a]+")")}function Ba(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.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===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}La(n,e,t)}function Pa(t,e,n){for(var r=e.shape.length,a=r>1?e.shape[r-1]:1,i=n.length,o=1,s=a;s<i;++s)o*=n[s];var u=a<1?1:a;return{sliceRank:a,numUpdates:R(e.shape)/u,sliceSize:o,strides:tt(n.slice(0,a)).concat([1]),outputSize:R(n)}}var Wa=Object.freeze({validateUpdateShape:La,validateInput:Ba,calculateShapes:Pa});function Va(t,e,n){I(t.rank===e.length,(function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."})),I(t.rank===n.length,(function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."}));for(var r=function(r){I(e[r]+n[r]<=t.shape[r],(function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"}))},a=0;a<t.rank;++a)r(a)}function Ua(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function ja(t,e,n){for(var r=[],a=0;a<t.length;a++)r[a]=Math.ceil((e[a]-t[a])/n[a]);return r}function Ga(t,e,n,r,a){var i=e[a],o=n[a]||1;(t&1<<a||null==i)&&(i=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[a];return i<0&&(i+=s),N(0,i,s-1)}function qa(t,e,n,r,a){var i=e[a],o=n[a]||1;(t&1<<a||null==i)&&(i=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[a];return i<0&&(i+=s),o>0?N(0,i,s):N(-1,i,s-1)}function Ha(t,e,n){for(var r=n.length,a=0;a<n.length;a++)if(n[a]>1){r=a;break}for(a=r+1;a<n.length;a++)if(e[a]>0||n[a]!==t[a])return!1;return!0}function Ka(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}var Xa=Object.freeze({assertParamsValid:Va,maskToAxes:Ua,computeOutShape:ja,startForAxis:Ga,stopForAxis:qa,isSliceContinous:Ha,computeFlatOffset:Ka});function Ya(t){return I(Z(t),(function(){return"The f passed in grad(f) must be a function"})),function(e,n){var r=dn(e,"x","tf.grad",null),a=null!=n?dn(n,"dy","tf.grad"):null;return Bt.tidy((function(){var e=Bt.gradients((function(){return t(r)}),[r],a),n=e.value,i=e.grads;return null!=a&&E(n.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ei(i),i[0]}))}}function Ja(t){return I(Z(t),(function(){return"The f passed in grads(f) must be a function"})),function(e,n){I(Array.isArray(e),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=mn(e,"args","tf.grads",null),a=null!=n?dn(n,"dy","tf.grads"):null;return Bt.tidy((function(){var e=Bt.gradients((function(){return t.apply(void 0,r)}),r,a),n=e.value,i=e.grads;return null!=a&&E(n.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ei(i),i}))}}function $a(t){return I(Z(t),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(e,n){I(e instanceof wt,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),I(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=Bt.gradients((function(){return t(e)}),[e],n),a=r.grads,i=r.value;return ei(a),{grad:a[0],value:i}}}function Za(t){return I(Z(t),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(e,n){I(Array.isArray(e)&&e.every((function(t){return t instanceof wt})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),I(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=Bt.gradients((function(){return t.apply(void 0,e)}),e,n);return null!=n&&E(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ei(r.grads),r}}function Qa(t,e){I(Z(t),(function(){return"The f passed in variableGrads(f) must be a function"})),I(null==e||Array.isArray(e)&&e.every((function(t){return t instanceof Et})),(function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}));var n=null!=e;if(!n)for(var r in e=[],Bt.registeredVariables)e.push(Bt.registeredVariables[r]);var a=n?e.filter((function(t){return!t.trainable})):null,i=e.length;I((e=e.filter((function(t){return t.trainable}))).length>0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+i+" variables is trainable."}));var o=Bt.gradients(t,e,null,!0),s=o.value,u=o.grads;I(u.some((function(t){return null!=t})),(function(){return"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()."})),I(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var l={};return e.forEach((function(t,e){null!=u[e]&&(l[t.name]=u[e])})),null!=a&&a.forEach((function(t){return l[t.name]=null})),{value:s,grads:l}}function ti(t){return Bt.customGrad(t)}function ei(t){if(t.filter((function(t){return null==t})).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 ni=In({softmax_:function(t,e){void 0===e&&(e=-1);var n=dn(t,"logits","softmax","float32");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Bt.runKernelFunc((function(t,r){var a=t.softmax(n,e);return r([a]),a}),{logits:n},(function(t,n){var r=n[0],a=t.mul(r);return{logits:function(){return a.sub(a.sum([e],!0).mul(r))}}}),"Softmax",{dim:e},[],[!0])}}),ri=In({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=dn(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return ti((function(t,n){var r=t.max(e,!0),a=t.sub(r),i=a.toFloat().sub(a.exp().sum(e,!0).log());return n([i]),{value:i,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),ai=In({transpose_:function(t,e){var n=dn(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),I(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){I(t>=0&&t<n.rank,(function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e}))})),n.rank<=1)return n.clone();var r={perm:e};return Bt.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},null,"Transpose",r)}}),ii=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),oi=function(){function t(){}return t.prototype.time=function(t){return si("time")},t.prototype.read=function(t){return si("read")},t.prototype.readSync=function(t){return si("readSync")},t.prototype.numDataIds=function(){return si("numDataIds")},t.prototype.disposeData=function(t){return si("disposeData")},t.prototype.write=function(t,e,n){return si("write")},t.prototype.move=function(t,e,n,r){return si("move")},t.prototype.memory=function(){return si("memory")},t.prototype.floatPrecision=function(){return si("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return si("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,si("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return si("slice")},t.prototype.stridedSlice=function(t,e,n,r){return si("stridedSlice")},t.prototype.unstack=function(t,e){return si("unstack")},t.prototype.reverse=function(t,e){return si("reverse")},t.prototype.concat=function(t,e){return si("concat")},t.prototype.neg=function(t){return si("neg")},t.prototype.add=function(t,e){return si("add")},t.prototype.addN=function(t){return si("addN")},t.prototype.subtract=function(t,e){return si("subtract")},t.prototype.multiply=function(t,e){return si("multiply")},t.prototype.realDivide=function(t,e){return si("realDivide")},t.prototype.floorDiv=function(t,e){return si("floorDiv")},t.prototype.sum=function(t,e){return si("sum")},t.prototype.prod=function(t,e){return si("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return si("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return si("argMin")},t.prototype.argMax=function(t,e){return si("argMax")},t.prototype.equal=function(t,e){return si("equal")},t.prototype.notEqual=function(t,e){return si("notEqual")},t.prototype.less=function(t,e){return si("less")},t.prototype.lessEqual=function(t,e){return si("lessEqual")},t.prototype.greater=function(t,e){return si("greater")},t.prototype.greaterEqual=function(t,e){return si("greaterEqual")},t.prototype.logicalNot=function(t){return si("logicalNot")},t.prototype.logicalAnd=function(t,e){return si("logicalAnd")},t.prototype.logicalOr=function(t,e){return si("logicalOr")},t.prototype.where=function(t){return si("where")},t.prototype.select=function(t,e,n){return si("select")},t.prototype.topk=function(t,e,n){return si("topk")},t.prototype.min=function(t,e){return si("min")},t.prototype.minimum=function(t,e){return si("minimum")},t.prototype.mod=function(t,e){return si("mod")},t.prototype.max=function(t,e){return si("max")},t.prototype.maximum=function(t,e){return si("maximum")},t.prototype.all=function(t,e){return si("all")},t.prototype.any=function(t,e){return si("any")},t.prototype.squaredDifference=function(t,e){return si("squaredDifference")},t.prototype.ceil=function(t){return si("ceil")},t.prototype.floor=function(t){return si("floor")},t.prototype.round=function(t){return si("round")},t.prototype.sign=function(t){return si("sign")},t.prototype.isNaN=function(t){return si("isNaN")},t.prototype.isInf=function(t){return si("isInf")},t.prototype.isFinite=function(t){return si("isFinite")},t.prototype.pow=function(t,e){return si("pow")},t.prototype.exp=function(t){return si("exp")},t.prototype.expm1=function(t){return si("expm1")},t.prototype.softmax=function(t,e){return si("softmax")},t.prototype.log=function(t){return si("log")},t.prototype.log1p=function(t){return si("log1p")},t.prototype.sqrt=function(t){return si("sqrt")},t.prototype.rsqrt=function(t){return si("rsqrt")},t.prototype.square=function(t){return si("square")},t.prototype.reciprocal=function(t){return si("reciprocal")},t.prototype.relu=function(t){return si("relu")},t.prototype.relu6=function(t){return si("relu6")},t.prototype.prelu=function(t,e){return si("prelu")},t.prototype.elu=function(t){return si("elu")},t.prototype.eluDer=function(t,e){return si("eluDer")},t.prototype.selu=function(t){return si("selu")},t.prototype.int=function(t){return si("int")},t.prototype.clip=function(t,e,n){return si("clip")},t.prototype.abs=function(t){return si("abs")},t.prototype.complexAbs=function(t){return si("complexAbs")},t.prototype.sigmoid=function(t){return si("sigmoid")},t.prototype.softplus=function(t){return si("softplus")},t.prototype.sin=function(t){return si("sin")},t.prototype.cos=function(t){return si("cos")},t.prototype.tan=function(t){return si("tan")},t.prototype.asin=function(t){return si("asin")},t.prototype.acos=function(t){return si("acos")},t.prototype.atan=function(t){return si("atan")},t.prototype.atan2=function(t,e){return si("atan2")},t.prototype.sinh=function(t){return si("sinh")},t.prototype.cosh=function(t){return si("cosh")},t.prototype.tanh=function(t){return si("tanh")},t.prototype.asinh=function(t){return si("asinh")},t.prototype.acosh=function(t){return si("acosh")},t.prototype.atanh=function(t){return si("atanh")},t.prototype.erf=function(t){return si("erf")},t.prototype.step=function(t,e){return si("step")},t.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,si("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return si("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return si("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return si("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,si("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return si("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return si("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return si("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return si("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return si("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return si("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return si("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return si("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return si("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return si("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return si("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return si("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return si("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return si("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return si("reshape")},t.prototype.cast=function(t,e){return si("cast")},t.prototype.tile=function(t,e){return si("tile")},t.prototype.pad=function(t,e,n){return si("pad")},t.prototype.transpose=function(t,e){return si("transpose")},t.prototype.gather=function(t,e,n){return si("gather")},t.prototype.gatherND=function(t,e){return si("gatherND")},t.prototype.scatterND=function(t,e,n){return si("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return si("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return si("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return si("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return si("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return si("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return si("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,a,i){return si("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,a){return si("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,a,i,o){return si("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return si("multinomial")},t.prototype.oneHot=function(t,e,n,r){return si("oneHot")},t.prototype.cumsum=function(t,e,n,r){return si("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,a){return si("nonMaxSuppression")},t.prototype.fft=function(t){return si("fft")},t.prototype.ifft=function(t){return si("ifft")},t.prototype.complex=function(t,e){return si("complex")},t.prototype.real=function(t){return si("real")},t.prototype.imag=function(t){return si("imag")},t.prototype.cropAndResize=function(t,e,n,r,a,i){return si("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return si("depthToSpace")},t.prototype.split=function(t,e,n){return si("split")},t.prototype.sparseToDense=function(t,e,n,r){return si("sparseToDense")},t.prototype.diag=function(t){return si("diag")},t.prototype.fill=function(t,e,n){return si("fill")},t.prototype.onesLike=function(t){return si("onesLike")},t.prototype.zerosLike=function(t){return si("zerosLike")},t.prototype.linspace=function(t,e,n){return si("linspace")},t.prototype.dispose=function(){return si("dispose")},t}();function si(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function ui(t,e,n,r,a,i,o){void 0===o&&(o="channelsLast");var s,u=fi(e),l=u[0],c=u[1];if("channelsLast"===o)s=[l,c,t[3],t[3]];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);s=[l,c,t[1],t[1]]}return ci(t,s,n,r,a,i,!1,o)}function li(t,e,n,r,a,i,o){void 0===o&&(o="NDHWC");var s,u,l=di(e),c=l[0],p=l[1],h=l[2];if("NDHWC"===o)u="channelsLast",s=[c,p,h,t[4],t[4]];else{if("NCDHW"!==o)throw new Error("Unknown dataFormat "+o);u="channelsFirst",s=[c,p,h,t[1],t[1]]}return pi(t,s,n,r,a,!1,u,i)}function ci(t,e,n,r,a,i,o,s){void 0===o&&(o=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],p=u[2],h=u[3];if("channelsLast"===s)l=t[0],c=t[1],p=t[2],h=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=t[0],h=t[1],c=t[2],p=t[3]}var f,d=e[0],m=e[1],g=e[3],v=fi(n),y=v[0],b=v[1],x=fi(r),w=x[0],C=x[1],N=mi(d,w),S=mi(m,C),k=function(t,e,n,r,a,i,o,s){var u,l,c;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var p=function(t,e,n,r,a){null==r&&(r=hi(t,e,n));var i=t[1],o=gi((t[0]-e+2*r)/n+1,a);I(O(o),(function(){return"The output # of rows ("+o+") must be an integer. Change the stride and/or zero pad parameters"}));var s=gi((i-e+2*r)/n+1,a);return I(O(s),(function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"})),[o,s]}([e,n],i,r,t,s);l=p[0],c=p[1]}else if("same"===t){l=Math.ceil(e/r),c=Math.ceil(n/a);var h=Math.max(0,(l-1)*r+i-e),f=Math.max(0,(c-1)*a+o-n),d=Math.floor(h/2),m=h-d,g=Math.floor(f/2);u={top:d,bottom:m,left:g,right:f-g,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((e-i+1)/r),c=Math.ceil((n-o+1)/a)}return{padInfo:u,outHeight:l,outWidth:c}}(a,c,p,y,b,N,S,i),E=k.padInfo,A=k.outHeight,T=k.outWidth,R=o?g*h:g;return"channelsFirst"===s?f=[l,R,A,T]:"channelsLast"===s&&(f=[l,A,T,R]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:p,inChannels:h,outHeight:A,outWidth:T,outChannels:R,padInfo:E,strideHeight:y,strideWidth:b,filterHeight:d,filterWidth:m,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationHeight:w,dilationWidth:C,inShape:t,outShape:f,filterShape:e}}function pi(t,e,n,r,a,i,o,s){void 0===i&&(i=!1),void 0===o&&(o="channelsLast");var u=[-1,-1,-1,-1,-1],l=u[0],c=u[1],p=u[2],h=u[3],f=u[4];if("channelsLast"===o)l=t[0],c=t[1],p=t[2],h=t[3],f=t[4];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);l=t[0],f=t[1],c=t[2],p=t[3],h=t[4]}var d,m=e[0],g=e[1],v=e[2],y=e[4],b=di(n),x=b[0],w=b[1],C=b[2],N=di(r),S=N[0],k=N[1],E=N[2],A=mi(m,S),T=mi(g,k),R=mi(v,E),D=function(t,e,n,r,a,i,o,s,u,l,c){var p,h,f,d;if("number"==typeof t){p={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var m=function(t,e,n,r,a,i){null==a&&(a=hi(t,e,r));var o=t[1],s=t[2],u=gi((t[0]-e+2*a)/r+1,i);I(O(u),(function(){return"The output # of depths ("+u+") must be an integer. Change the stride and/or zero pad parameters"}));var l=gi((o-e+2*a)/r+1,i);I(O(l),(function(){return"The output # of rows ("+l+") must be an integer. Change the stride and/or zero pad parameters"}));var c=gi((s-e+2*a)/r+1,i);return I(O(c),(function(){return"The output # of columns ("+c+") must be an integer. Change the stride and/or zero pad parameters"})),[u,l,c,1]}([e,n,r,1],s,0,a,t,c);h=m[0],f=m[1],d=m[2]}else if("same"===t){var g=((h=Math.ceil(e/a))-1)*a+s-e,v=((f=Math.ceil(n/i))-1)*i+u-n,y=((d=Math.ceil(r/o))-1)*o+l-r,b=Math.floor(g/2),x=g-b,w=Math.floor(v/2),C=v-w,N=Math.floor(y/2);p={top:w,bottom:C,left:N,right:y-N,front:b,back:x,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((e-s+1)/a),f=Math.ceil((n-u+1)/i),d=Math.ceil((r-l+1)/o)}return{padInfo:p,outDepth:h,outHeight:f,outWidth:d}}(a,c,p,h,x,w,C,A,T,R,s),_=D.padInfo,F=D.outDepth,M=D.outHeight,z=D.outWidth,L=i?y*f:y;return"channelsFirst"===o?d=[l,L,F,M,z]:"channelsLast"===o&&(d=[l,F,M,z,L]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:p,inWidth:h,inChannels:f,outDepth:F,outHeight:M,outWidth:z,outChannels:L,padInfo:_,strideDepth:x,strideHeight:w,strideWidth:C,filterDepth:m,filterHeight:g,filterWidth:v,effectiveFilterDepth:A,effectiveFilterHeight:T,effectiveFilterWidth:R,dilationDepth:S,dilationHeight:k,dilationWidth:E,inShape:t,outShape:d,filterShape:e}}function hi(t,e,n,r){void 0===r&&(r=1);var a=mi(e,r);return Math.floor((t[0]*(n-1)-n+a)/2)}function fi(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function di(t){return"number"==typeof t?[t,t,t]:t}function mi(t,e){return e<=1?t:t+(t-1)*(e-1)}function gi(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function vi(t){var e=fi(t),n=e[0],r=e[1],a=e[2];return 1===n&&1===r&&1===a}function yi(t,e){return vi(t)||vi(e)}function bi(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function xi(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Vn(t.shape),a=t.toFloat(),i=n.complex(a,r);return r.dispose(),a.dispose(),i}if(!G(t.dtype,e))return Bt.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var o=n.real(t);return i=o.cast(e),o.dispose(),i}if("int32"===e)return n.int(t);if("bool"===e){var s=On(0,t.dtype);return i=n.notEqual(t,s),s.dispose(),i}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function wi(t,e){return Bt.makeTensorFromDataId(t.dataId,e,t.dtype)}function Ci(t,e,n){var r=(e-t)/(n-1),a=at(n,"float32");a[0]=t;for(var i=1;i<a.length;i++)a[i]=a[i-1]+r;return _n(a,"float32")}var Ni=Object.freeze({castTensor:xi,reshapeTensor:wi,linspaceImpl:Ci,upcastType:Tt,axesAreInnerMostDims:gn,combineLocations:vn,computeOutAndReduceShapes:yn,expandShapeToKeepDim:bn,assertAxesAreInnerMostDims:xn,getAxesPermutation:wn,getUndoAxesPermutation:Cn,getInnerMostAxes:Nn,getBroadcastDims:_r,getReductionAxes:Fr,assertAndGetBroadcastShape:Mr,assertParamsConsistent:Sn,computeOutShape:kn,computePool2DInfo:ui,computePool3DInfo:li,computeConv2DInfo:ci,computeConv3DInfo:pi,computeDefaultPad:hi,tupleValuesAreOne:vi,eitherStridesOrDilationsAreOne:yi,convertConv2DDataFormat:bi,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:za});function Si(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function ki(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Ii(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Ei(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Ai(t,e,n){var r=function(t,e,n){return function(t,e,n){for(var r=0,a=t.length,i=0,o=!1;r<a;){var s=n(e,t[i=r+(a-r>>>1)]);s>0?r=i+1:(a=i,o=!s)}return o?r:-r-1}(t,e,n||Ti)}(t,e,n),a=r<0?-(r+1):r;t.splice(a,0,e)}function Ti(t,e){return t>e?1:t<e?-1:0}function Ri(t,e,n,r,a){return Oi(t,e,n,r,a,0).selectedIndices}function Di(t,e,n,r,a,i){var o=Oi(t,e,n,r,a,i,!0);return o.numValidOutputs.dispose(),{selectedIndices:o.selectedIndices,selectedScores:o.selectedScores}}function Oi(t,e,n,r,a,i,o,s){void 0===o&&(o=!1),void 0===s&&(s=!1);for(var u=Array.from(e).map((function(t,e){return{score:t,boxIndex:e,suppressBeginIndex:0}})).filter((function(t){return t.score>a})).sort(Mi),l=i>0?-.5/i:0,c=[],p=[];c.length<n&&u.length>0;){var h=u.pop(),f=h.score,d=h.boxIndex,m=h.suppressBeginIndex;if(f<a)break;for(var g=!1,v=c.length-1;v>=m;--v){var y=_i(t,d,c[v]);if(y>=r){g=!0;break}if(h.score=h.score*Fi(r,l,y),h.score<=a)break}h.suppressBeginIndex=c.length,g||(h.score===f?(c.push(d),p.push(h.score)):h.score>a&&Ai(u,h,Mi))}var b=c.length;return s&&(c.fill(0,b),p.fill(0,b)),{selectedIndices:_n(c,"int32"),selectedScores:_n(p,"float32"),numValidOutputs:On(b,"int32")}}function _i(t,e,n){var r=t.subarray(4*e,4*e+4),a=t.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]),p=Math.max(a[0],a[2]),h=Math.max(a[1],a[3]),f=(s-i)*(u-o),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),v=Math.min(s,p),y=Math.min(u,h),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(f+d-b)}function Fi(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Mi(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function zi(t,e,n){var r=new Array(t.rank).fill(0),a=t.shape.slice();return e.map((function(e){a[n]=e;var i=t.slice(r,a);return r[n]+=e,i}))}function Li(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var a=Qn(n,t.dtype);for(r=0;r<a.values.length;++r){for(var i=a.indexToLoc(r),o=new Array(t.rank),s=0;s<o.length;s++)o[s]=i[s]%t.shape[s];var u=t.locToIndex(o);a.values[r]=t.values[u]}return a.toTensor()}function Bi(t,e,n,r,a){for(var i=e[e.length-1],o=[t.length/i,i],s=o[0],u=o[1],l=W(n,s*r),c=W("int32",s*r),p=0;p<s;p++){for(var h=p*u,f=t.subarray(h,h+u),d=[],m=0;m<f.length;m++)d.push({value:f[m],index:m});d.sort((function(t,e){return e.value-t.value}));var g=p*r,v=l.subarray(g,g+r),y=c.subarray(g,g+r);for(m=0;m<r;m++)v[m]=d[m].value,y[m]=d[m].index}var b=e.slice();return b[b.length-1]=r,[Rn(l,b,n),Rn(c,b,"int32")]}function Pi(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var a=Qn(t,"int32"),i=Qn([n.length,t.length],"int32");for(r=0;r<n.length;r++){var o=a.indexToLoc(n[r]),s=r*t.length;i.values.set(o,s)}return i.toTensor()}var Wi=function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((function(t,e){return"T"+e}));var n=[];this.variableNames.forEach((function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();")}));var r=this.variableNames.map((function(t){return"v"+t})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n float result = "+r+";\n setOutput(result);\n }\n "},Vi=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((function(t,e){return"T"+e}));var n=[];this.variableNames.forEach((function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")}));var r=this.variableNames.map((function(t){return"v"+t})).join(" + ");this.userCode="\n void main() {\n "+n.join("\n ")+"\n\n vec4 result = "+r+";\n setOutput(result);\n }\n "},Ui=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,a=t.batchSize,i=t.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===e?">":"<",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 "};function ji(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function Gi(t,e){return 1===e?[t]:ji(t,e)}function qi(){var t,e,n,r,a,i,o,s,u,l;return 2===c().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",a="texture",i="outputColor",o="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",a="texture2D",i="gl_FragColor",o="",s="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:a,output:i,defineOutput:o,defineSpecialNaN:s,defineSpecialInf:u,defineRound:l}}function Hi(t,e,n){void 0===n&&(n="index");var r=tt(e);return r.map((function(e,a){return"int "+t[a]+" = "+n+" / "+e+"; "+(a===r.length-1?"int "+t[a+1]+" = "+n+" - "+t[a]+" * "+e:"index -= "+t[a]+" * "+e)+";"})).join("")}function Ki(t){var e=tt(t).map((function(t){return t.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var Xi="\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";function Yi(t,e,n,r){var a=[];t.forEach((function(t){var e=R(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?a.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(a.push("uniform sampler2D "+t.name+";"),a.push("uniform int offset"+t.name+";"))}));var i,o,s=a.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?$i(t):Ji(t);var a=t.shapeInfo.logicalShape,i=e.logicalShape;return a.length<=i.length&&(r+=n?function(t,e){var n,r,a=t.name,i=a.charAt(0).toUpperCase()+a.slice(1),o="get"+i+"AtOutCoords",s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length,l=_r(t.shapeInfo.logicalShape,e.logicalShape),c=ao(u),p=u-s,h=["x","y","z","w","u","v"];n=0===s?"":u<2&&l.length>=1?"coords = 0;":l.map((function(t){return"coords."+h[t+p]+" = 0;"})).join("\n"),r=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+p]})).join(", ");var f="return outputValue;",d=1===R(t.shapeInfo.logicalShape),m=1===R(e.logicalShape);if(1!==s||d||m){if(d&&!m)f=1===u?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(l.length){var g=s-2,v=s-1;l.indexOf(g)>-1&&l.indexOf(v)>-1?f="return vec4(outputValue.x);":l.indexOf(g)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":l.indexOf(v)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+o+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+i+"("+r+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",i=e.texShape,o=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&D(o,i))return"\n float "+a+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=ao(u),c=_r(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+a+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map((function(t){return"coords."+h[t+p]+" = 0;"})).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+p]})).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)})).join("\n"),l=e.texShape,c=qi(),p=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(c),h=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+Zi+"\n "+Qi+"\n "+to+"\n "}(c);return e.isPacked?(i=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[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 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(D(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[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 "}(t,e);case 3:return n=t,r=e,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=(i=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+a[0]+", "+a[1]+"));\n int index = resTexRC.x * "+a[1]+" + resTexRC.y;\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+i+");\n int c = imod(index, "+i+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),a=r*Math.ceil(t[t.length-2]/2),i=a,o="",s="b, r, c",u=2;u<t.length-1;u++)o="\n int b"+u+" = index / "+(i*=t[t.length-u-1])+";\n index -= b"+u+" * "+i+";\n "+o,s="b"+u+", "+s;return"\n ivec"+t.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+o+"\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec"+t.length+"("+s+");\n }\n "}(t,e)}var n,r,a,i,o}(e.logicalShape,l),o=function(t){return"\n void setOutput(vec4 val) {\n "+t.output+" = val;\n }\n "}(c)):(i=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){return 1===e[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ":1===e[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n return resTexRC.x * "+e[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){return D(t,e)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ":1===t[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===t[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n int r = index / "+t[1]+";\n int c = index - r * "+t[1]+";\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=e,r=Hi(["r","c","d"],t),"\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 "+r+"\n return ivec3(r, c, d);\n }\n ";case 4:return function(t,e){var n=Hi(["r","c","d","d2"],t);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(t,e);case 5:return function(t,e){var n=Hi(["r","c","d","d2","d3"],t);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n "+e[1]+"));\n\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(t,e);case 6:return function(t,e){var n=Hi(["r","c","d","d2","d3","d4"],t);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,l),o=function(t){return"\n void setOutput(float val) {\n "+t.output+" = vec4(val, 0, 0, 0);\n }\n "}(c)),r&&(h+=eo),[h,p,o,s,i,u,n].join("\n")}function Ji(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,a=r[0],i=r[1];if(1===a&&1===i)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var o=t.shapeInfo.texShape;return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+o[0]+", "+o[1]+", "+no(e)+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n float "+n+"(int index) {\n "+ro(t)+"\n }\n ";var r=t.shapeInfo.texShape,a=r[0],i=r[1];if(1===i&&1===a)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var o=no(e);return 1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+o+") + 0.5) / "+a+".0);\n return sampleTexture("+e+", uv);\n }\n ":1===a?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+o+") + 0.5) / "+i+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+a+", "+i+", index + "+o+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t.shapeInfo.texShape;if(null!=a&&D(e,a)){var i=a[0];return"\n float "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a[1]+".0, "+i+".0);\n return sampleTexture("+n+", uv);\n }\n "}var o=P(e),s=o.newShape,u=o.keptDims,l=s;if(l.length<e.length)return"\n "+Ji(io(t,l))+"\n float "+r+"(int row, int col) {\n return "+r+"("+oo(["row","col"],u)+");\n }\n ";if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n "+ro(t)+"\n }\n ";var c=a[0],p=a[1],h=no(n);return 1===p?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+c+".0);\n return sampleTexture("+n+", uv);\n }\n ":1===c?"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+p+".0, 0.5);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+e[1]+" + col + "+h+";\n vec2 uv = uvFromFlat("+c+", "+p+", index);\n return sampleTexture("+n+", uv);\n }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e[1]*e[2],i=e[2],o=P(e),s=o.newShape,u=o.keptDims,l=s;if(l.length<e.length)return"\n "+Ji(io(t,l))+"\n float "+r+"(int row, int col, int depth) {\n return "+r+"("+oo(["row","col","depth"],u)+");\n }\n ";if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+a+", "+i+", 1)));\n "+ro(t)+"\n }\n ";var c=t.shapeInfo.texShape,p=c[0],h=c[1],f=t.shapeInfo.flatOffset;return h===a&&null==f?"\n float "+r+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+i+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+h+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":h===i&&null==f?"\n float "+r+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+h+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+a+" + col * "+i+" + depth + "+no(n)+";\n vec2 uv = uvFromFlat("+p+", "+h+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e[3],i=e[2]*a,o=e[1]*i,s=P(e),u=s.newShape,l=s.keptDims;if(u.length<e.length)return"\n "+Ji(io(t,u))+"\n float "+r+"(int row, int col, int depth, int depth2) {\n return "+r+"("+oo(["row","col","depth","depth2"],l)+");\n }\n ";if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+o+", "+i+", "+a+", 1)));\n "+ro(t)+"\n }\n ";var c=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,h=p[0],f=p[1];return f===o&&null==c?"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+i+", "+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+f+".0, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":f===a&&null==c?"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+e[1]*e[2]+", "+e[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+f+".0, "+h+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+o+" + col * "+i+" +\n depth * "+a+" + depth2;\n vec2 uv = uvFromFlat("+h+", "+f+", index + "+no(n)+");\n return sampleTexture("+n+", uv);\n }\n "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e[4],i=e[3]*a,o=e[2]*i,s=e[1]*o,u=P(e),l=u.newShape,c=u.keptDims;if(l.length<e.length)return"\n "+Ji(io(t,l))+"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n return "+r+"("+oo(["row","col","depth","depth2","depth3"],c)+");\n }\n ";if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+s+", "+o+", "+i+", "+a+")) +\n depth3;\n "+ro(t)+"\n }\n ";var p=t.shapeInfo.flatOffset,h=t.shapeInfo.texShape,f=h[0],d=h[1];return d===s&&null==p?"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+o+", "+i+", "+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ":d===a&&null==p?"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]+",\n "+e[2]*e[3]+", "+e[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+o+" + depth * "+i+" +\n depth2 * "+a+" + depth3 + "+no(n)+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=P(e),i=a.newShape,o=a.keptDims;if(i.length<e.length)return"\n "+Ji(io(t,i))+"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+r+"("+oo(["row","col","depth","depth2","depth3","depth4"],o)+");\n }\n ";var s=e[5],u=e[4]*s,l=e[3]*u,c=e[2]*l,p=e[1]*c;if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4("+p+", "+c+", "+l+", "+u+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+s+", 1)));\n "+ro(t)+"\n }\n ";var h=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,d=f[0],m=f[1];return m===p&&null==h?"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+c+", "+l+", "+u+", "+s+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ":m===s&&null==h?"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]*e[4]+",\n "+e[2]*e[3]*e[4]+",\n "+e[3]*e[4]+",\n "+e[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ":"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+p+" + col * "+c+" + depth * "+l+" +\n depth2 * "+u+" + depth3 * "+s+" + depth4 + "+no(n)+";\n vec2 uv = uvFromFlat("+d+", "+m+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function $i(t){var e;switch(t.shapeInfo.logicalShape.length){case 0:return"\n vec4 get"+(e=t.name).charAt(0).toUpperCase()+e.slice(1)+"() {\n return "+qi().texture2D+"("+e+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],i=qi();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+a[0]+", "+a[1]+", index);\n return "+i.texture2D+"("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t.shapeInfo.texShape,i=a[0],o=a[1],s=qi();if(null!=a&&D(e,a))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o+".0, "+i+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===e[0])return"\n "+$i(io(t,e.slice(1)))+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+oo(["b","row","col"],[1,2])+");\n }\n ";var o=i[0],s=i[1],u=Math.ceil(e[2]/2);return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+o+", "+s+", "+u*Math.ceil(e[1]/2)+", "+u+", b, row, col);\n return "+qi().texture2D+"("+n+", uv);\n }\n "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,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)],s=o[0],u=o[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f<n-1;f++)p="int b"+f+", "+p,h="b"+f+" * "+(c*=e[n-f-1])+" + "+h;return"\n vec4 "+a+"("+p+") {\n int index = "+h+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+qi().texture2D+"("+r+", uv);\n }\n "}(t)}}var Zi="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Qi="\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",to="\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",eo="\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 no(t){return"offset"+t}function ro(t){var e=t.name,n=R(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n for (int i = 0; i < "+n+"; i++) {\n if (i == index) {\n return "+e+"[i];\n }\n }\n "}function ao(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function io(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function oo(t,e){return e.map((function(e){return t[e]})).join(", ")}var so=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,I(t.length>2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var a=t[t.length-1],i=Math.ceil(a/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),r||this.variableNames.push("bestIndicesA");var o,s,u=this.outputShape,l=u.length,c=ao(l),p=Gi("coords",l);if(1===i){var h=ao(s=l+1);o="\n "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,o="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),d="."+f[s-1],m=f.map((function(t){return"int "+t})),g=Gi("sourceLocR",s-1).concat("inIdx.r"),v=Gi("sourceLocG",s-1).concat("inIdx.g"),y=Gi("sourceLocB",s-1).concat("inIdx.b"),b=Gi("sourceLocA",s-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+")));",C="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",N=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }\n "+N+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+o+"\n ivec4 srcIdx = ivec4(sourceLocR"+d+", sourceLocG"+d+",\n sourceLocB"+d+", sourceLocA"+d+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+x+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},uo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\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 >= "+t.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 >= "+t.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 "},lo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=p-1-t.padInfo.top,m=h-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+a+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},co=function(t,e,n,r,a,i){this.outputShape=[],this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="0.0";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=a&&(Mr(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+i+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},po=function(t,e,n,r,a,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="vec4(0.0)";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=a&&(Mr(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+o+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+i+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},ho=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},fo="return a + b;",mo="return a - b;",go="return a * b;",vo="return (a < 0.) ? b * a : a;",yo=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},bo="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",xo=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Mr(e,n);var a=this.outputShape.length,i="";if(r)if(0===a||1===R(this.outputShape))i="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(i="\n "+ao(a)+" coords = getOutputCoords();\n ",1===a)i+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var o=Gi("coords",a);i+="\n bool nextRowOutOfBounds =\n ("+o[a-2]+" + 1) >= "+this.outputShape[a-2]+";\n bool nextColOutOfBounds =\n ("+o[a-1]+" + 1) >= "+this.outputShape[a-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+i+"\n\n setOutput(result);\n }\n "},wo=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Co=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),No=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},So=function(t){this.outputShape=[],this.outputShape=kn(t,1),this.variableNames=t.map((function(t,e){return"T"+e}));var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var a=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+a+"));")}var i=e.length,o=e[e.length-1];r.push("else setOutput(getT"+i+"(yR, yC-"+o+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},ko=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=kn(t,e);var n=this.outputShape,r=n.length,a=ao(r),i=Gi("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map((function(t,e){return"T"+e}));var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var l=o[e],c=o.slice(-2),p=o.join(),h="if ("+l+" < "+s[0]+") {\n return getChannel(\n getT0("+p+"), vec2("+c.join()+"));\n }";for(u=1;u<s.length;u++){var f=s[u-1];h+="\n if ("+l+" < "+s[u]+" && "+l+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+Io(o,l,f)+"),\n vec2("+Io(c,l,f)+"));\n }"}var d=s.length,m=s[s.length-1];h+="\n return getChannel(\n getT"+d+"("+Io(o,l,m)+"),\n vec2("+Io(c,l,m)+"));",this.userCode="\n float getValue("+o.map((function(t){return"int "+t}))+") {\n "+h+"\n }\n\n void main() {\n "+a+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+i+"), 0., 0., 0.);\n\n "+i[r-1]+" = "+i[r-1]+" + 1;\n if ("+i[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+i+");\n }\n\n "+i[r-2]+" = "+i[r-2]+" + 1;\n if ("+i[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+i+");\n }\n\n "+i[r-1]+" = "+i[r-1]+" - 1;\n if ("+i[r-2]+" < "+n[r-2]+" &&\n "+i[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+i+");\n }\n setOutput(result);\n }\n "};function Io(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var Eo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,i="channelsLast"===t.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+i+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ao=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i="channelsLast"===t.dataFormat,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=i?1:2,l=i?2:3,c=i?3:1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - 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 < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 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 >= "+t.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 < "+t.outChannels+"; d2++) {\n\n if ("+i+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},To=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.padInfo.front,i=t.padInfo.top,o=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+a+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ro=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+a+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Do=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+i+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.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 "},Oo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i=e-1-t.padInfo.top,o=n-1-t.padInfo.left,s=t.outChannels/t.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 < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 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 >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+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 "},_o=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,m=d?1:2,g=d?2:3,v=d?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+h+") *\n getW(wR, wC, "+h+", d2);\n } else {\n dotProd +=\n getX(batch, "+h+", xR, xC) *\n getW(wR, wC, "+h+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2),\n getW(wR, wC, "+h+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1),\n getX(batch, xR, xC, "+h+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC),\n getX(batch, "+h+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+x+"\n "+b+"\n setOutput(result);\n }\n "},Fo=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+a+", "+i+", "+o+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Mo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.inHeight,i=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,f=t.filterWidth,d=t.outChannels/t.inChannels,m="",g="";n&&(m=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",g="result = activation(result);");var v=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+m+"\n\n const ivec2 strides = ivec2("+u+", "+l+");\n const ivec2 pads = ivec2("+o+", "+s+");\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 / "+d+";\n int q = d2 - d1 * "+d+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+h+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+a+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC++) {\n int xC = xCCorner + wC * "+p+";\n\n if (xC < 0 || xC >= "+i+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+v+"\n "+g+"\n setOutput(result);\n }\n "},zo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var a=t.inHeight,i=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,f=t.filterWidth,d=f,m="int xR; int xC; int xCOffset;",g=0;g<h;g++)for(var v=0;v<f;v++)m+="\n vec4 xTexelR"+g+"C"+2*v+" = vec4(0.);\n vec4 wR"+g+"C"+v+" = vec4(0.);\n vec4 xR"+g+"C"+v+" = vec4(0.);";for(g=0;g<h;g++)for(var y=0;y<d;y++){if(m+="\n xR = xRCorner + "+g*c+";\n xC = xCCorner + "+(v=2*y)*p+";\n ",1===l){if(v<f&&(m+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+i+") {\n xTexelR"+g+"C"+v+".zw = vec2(0.);\n }\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+i+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+i+") {\n previous.zw = vec2(0.);\n }\n\n xR"+g+"C"+v+" = vec4(previous.zw, xTexelR"+g+"C"+v+".xy);\n } else {\n xR"+g+"C"+v+" = vec4(0, 0, xTexelR"+g+"C"+v+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+a+" && xC >= 0 && xC < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = xTexelR"+g+"C"+v+";\n ",v+1<f)){var b=s%2==0?S(p):p;p%2==0&&s%2==1||p%2!=0&&s%2!=1?(m+="\n xCOffset = xC + "+s%2+" + "+b+";\n\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",p>1&&(m+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n "),m+="\n xR"+g+"C"+(v+1)+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".xy);\n "):m+="\n xCOffset = xC + "+b+";\n\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+g+"C"+(v+1)+" = xTexelR"+g+"C"+(v+2)+";\n "}}else v<f&&(m+="\n if(xR >= 0 && xR < "+a+") {\n ",s%2==1?(m+="\n xCOffset = xC + 1 - "+l+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".zw);\n ",v+1<f&&(m+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+l+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+g+"C"+(v+1)+" = vec4(xTexelR"+g+"C"+(v+2)+".xy, final.xy);\n ")):(m+="\n if(xC >= 0 && xC < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + "+l+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".xy, xTexelR"+g+"C"+(v+2)+".xy);\n ",v+1<f&&(m+="\n xR"+g+"C"+(v+1)+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".zw);\n ")),m+="}");v<f&&(m+="\n vec4 wTexelR"+g+"C"+v+" = getW("+g+", "+v+", d1, q);\n wR"+g+"C"+v+" = vec4(wTexelR"+g+"C"+v+".xz, wTexelR"+g+"C"+v+".xz);\n ",v+1<f&&(m+="\n vec4 wTexelR"+g+"C"+(v+1)+" = getW("+g+", "+(v+1)+", d1, q);\n wR"+g+"C"+(v+1)+" =\n vec4(wTexelR"+g+"C"+(v+1)+".xz, wTexelR"+g+"C"+(v+1)+".xz);"))}for(g=0;g<h;g++)for(v=0;v<f;v++)m+="dotProd += xR"+g+"C"+v+" * wR"+g+"C"+v+";";var x="",w="";n&&(x=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",w="result = activation(result);");var C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+x+"\n\n const ivec2 strides = ivec2("+u+", "+l+");\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n\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;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+m+"\n\n vec4 result = dotProd;\n "+C+"\n "+w+"\n setOutput(result);\n }\n "},Lo=function(t,e,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=t[0],o=t[1],s=t[2],u=t[3],l=e[0],c=n[0],p=n[1];this.outputShape=[l,c,p,u];var h="bilinear"===r?1:0,f=[o-1+".0",s-1+".0"],d=f[0],m=f[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],v=g[0],y=g[1],b=g[2],x=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=x[0],C=x[1],N=x[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+w+");\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 = "+y+";\n float width_scale = "+C+";\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 = "+N+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},Bo=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,a=t[t.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 "+ao(r)+" coords = getOutputCoords();\n int end = "+Po(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 && "+e+") {\n continue;\n }\n "+Po(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function Po(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var Wo=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=qi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Hi(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},Vo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=qi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Hi(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},Uo=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,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 / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),jo=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},Go=function(t){this.variableNames=["A"],this.outTexUsage=Ut.DOWNLOAD;var e=qi();this.outputShape=t,this.userCode="\n "+Xi+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},qo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ut.DOWNLOAD;var e=qi();this.outputShape=t,this.userCode="\n "+Xi+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},Ho=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=qi(),a=e[0],i=e[1];this.outputShape=t;var o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode="\n "+Ki(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+i+";\n int c = imod(flatIndex, "+i+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+a+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+o+", 0., 0., 0.);\n }\n "},Ko=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=qi(),a=e[0],i=e[1];this.outputShape=t;var o="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;o+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+i+";\n c = imod(flatIndex, "+i+");\n uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+a+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Ki(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+o+"\n\n "+r.output+" = "+s+";\n }\n "},Xo=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;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 "+t+"\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 "},Yo=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),Jo=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var a=ao(this.rank),i=function(t,e){var n=t.length;if(n>4)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<t.length;i++)i===e?a.push("int(getIndices("+r[i]+"))"):a.push(""+r[i]);return a.join()}(t,n);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n "},$o=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=ao(e.length),a=ao(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 "};function Zo(t,e){var n=qi();return ne(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Qo(t,e){return ce(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ts(t,e){return pe(t,e,new Uint16Array([0,1,2,2,1,3]))}function es(t,e,n,r,a,i,o){fe(n,r);var s=he(t,e),u=t.TEXTURE_2D;return Zt(t,e,(function(){return t.bindTexture(u,s)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Zt(t,e,(function(){return t.texImage2D(u,0,a,n,r,0,i,o,null)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function ns(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],a.internalFormatFloat,a.textureFormatFloat,t.FLOAT)}function rs(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],a.internalFormatHalfFloat,a.textureFormatFloat,a.textureTypeHalfFloat)}function as(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function is(t,e,n,r,a){var i=Jt(n,r);return es(t,e,i[0],i[1],a.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function os(t,e,n,r,a){var i=Jt(n,r);return es(t,e,i[0],i[1],a.internalFormatPackedHalfFloat,t.RGBA,a.textureTypeHalfFloat)}function ss(t,e,n,r){return Zt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),me(t,e,n,"clipSpacePos",r,3,20,0)&&me(t,e,n,"uv",r,2,20,12)}function us(t,e,n,r,a,i,o){var s,u,l;Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),i instanceof Uint8Array?(s=new Uint8Array(r*a*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*a*4),u=t.FLOAT,l=o.internalFormatPackedFloat),s.set(i),Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,a,0,t.RGBA,u,s)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function ls(t,e,n,r){Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function cs(t,e,n,r,a){var i=t.createBuffer();Zt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,i)}));var o=16*n*r;return Zt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,o,t.STREAM_READ)})),Zt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Zt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),i}function ps(t,e,n){var r=t,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}function hs(t,e,n,r,a){var i=Xt(n,r),o=i[0],s=i[1],u=new Uint8Array(n*r*4);return Zt(t,e,(function(){return t.readPixels(0,0,o,s,a.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function fs(t,e,n,r,a,i,o,s){var u=t,l=new Float32Array(function(t,e){var n=Jt(t,e);return n[0]*n[1]*4}(i,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function ds(t,e,n,r){var a=new Float32Array(n*r*4);return Zt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,a)})),a}var ms=Object.freeze({createVertexShader:Zo,createVertexBuffer:Qo,createIndexBuffer:ts,createFloat32MatrixTexture:ns,createFloat16MatrixTexture:rs,createUnsignedBytesMatrixTexture:as,createPackedMatrixTexture:is,createFloat16PackedMatrixTexture:os,bindVertexProgramAttributeStreams:ss,uploadDenseMatrixToTexture:us,uploadPixelDataToTexture:ls,createBufferFromOutputTexture:cs,downloadFloat32MatrixFromBuffer:ps,downloadByteEncodedFloatMatrixFromOutputTexture:hs,downloadPackedMatrixFromBuffer:fs,downloadMatrixFromPackedOutputTexture:ds}),gs=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=c().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ht(e,t)):this.gl=Kt(e);var n="WEBGL_color_buffer_float";if(1===c().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=ee(this.gl,this.debug,"OES_texture_float"),Me(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=ee(this.gl,this.debug,"OES_texture_half_float");else if(c().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Me(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=ee(this.gl,this.debug,"EXT_color_buffer_half_float");else if(c().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Me(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Me(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=Qo(this.gl,this.debug),this.indexBuffer=ts(this.gl,this.debug),this.framebuffer=de(this.gl,this.debug),this.textureConfig=$t(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return c().getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Zt(e,this.debug,(function(){return e.finish()})),Zt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Zt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Zt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Zt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Zt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),ns(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),rs(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),as(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),ls(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),us(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),os(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),is(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(we(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Zt(this.gl,this.debug,(function(){return e.gl.deleteTexture(t)}))},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return hs(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,a,i){return fs(this.gl,t,0,0,0,a,i,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return ps(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=cs(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(c().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=a.clientWaitSync(i,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},e=i}else c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return ds(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=re(e,this.debug,t),r=Zo(e,this.debug),a=se(e,this.debug);return Zt(e,this.debug,(function(){return e.attachShader(a,r)})),Zt(e,this.debug,(function(){return e.attachShader(a,n)})),ue(e,this.debug,a),this.debug&&le(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=ss(e,this.debug,this.program,this.vertexBuffer)),a},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Zt(this.gl,this.debug,(function(){return e.gl.deleteProgram(t)}))},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&le(this.gl,this.debug,this.program),Zt(this.gl,this.debug,(function(){return e.gl.useProgram(t)}))},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ve(this.gl,this.debug,t,e):ye(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return n.gl.getAttribLocation(t,e)}))},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),be(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Jt(e,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(t,a,i)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&le(this.gl,this.debug,this.program),Ce(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Zt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=ee(this.gl,this.debug,2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},t.prototype.endQuery=function(){if(2!==c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return o(this,void 0,void 0,(function(){var e=this;return s(this,(function(n){switch(n.label){case 0:return[4,z((function(){return e.disposed||e.isQueryAvailable(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(t,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(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise((function(n){e.addItemToPoll((function(){return t.isFencePassed()}),(function(){return n()}))}))},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length&&t[e]();++e);return e-1}(this.itemsToPoll.map((function(t){return t.isDoneFn}))),e=0;e<=t;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||z((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),xe(this.gl,this.debug,t,this.framebuffer),this.debug&&Ce(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(xe(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Ce(this.gl)):we(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;xe(r,this.debug,t,this.framebuffer),this.debug&&Ce(r),this.outputTexture=t,Zt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Zt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var a=this;this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return a.gl.scissor(t,e,n,r)}))},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function vs(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach((function(t,n){var r=t.logicalShape,a=e[n],i=a.shape;if(!D(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!t.isUniform||!a.isUniform){var o=t.texShape,s=a.isUniform?null:a.texData.texShape;if(!D(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}}))}var ys=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(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,p=n.dataFormat,h=s.left,f=s.top,d=a*r,m=qi(),g="channelsLast"===p,v=g?0:1,y=g?1:2,b="",x=0;x<=1;x++)for(var w=0;w<=1;w++)b+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+x+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+o+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+a+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+a+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*x+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*x+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},bs=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[];var i,o=e,s=t[3]-1;this.outputShape=t;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 "},xs=function(t,e,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,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 - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 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 "},ws=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var i,o=e,s=t[3]-1;this.outputShape=t;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.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+o+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+o+"; j <= "+o+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+i+";\n setOutput(result);\n }\n "},Cs=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,i=t.effectiveFilterWidth,o=a-1-t.padInfo.top,s=i-1-t.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) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.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 >= "+t.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 "},Ns=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,i=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+p+", "+h+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+a+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+o+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ss=function(t,e,n,r,a,i,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===i&&(i=null),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";i&&(f=o?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+i+"\n }":"vec4 activation(vec4 x) {\n "+i+"\n }",d="result = activation(result);");var m=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+h[0]+");\n result += ("+p[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+d+"\n\n setOutput(result);\n }\n "},ks=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,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 < "+(e-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("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Is=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],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 "},Es=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=Gi("rc",e),r=ao(e),a=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",a=t-2;a<t;a++)r+=n[a]+" >= "+e[a],a<t-1&&(r+="||");return r}(e,t,n),i=function(t,e,n,r){if(1===t)return"";var a=r.slice(-2);return"\n int r = "+a[0]+";\n int c = "+a[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),o=function(t,e){var n=t.length,r=function(t,e){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<t;o++)i=e[e.length-1-o]+","+i;n.push(i)}return n}(n,e);return 1===n?"getA(rc),\n rc + 1 >= "+t[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]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+a+") {\n setOutput(vec4(0));\n } else {\n "+i+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}},As=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));var r=t.length,a=ao(r),i=e.map((function(t){return t[0]})).join(","),o=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+a+" start = "+a+"("+i+");\n "+a+" end = "+a+"("+o+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+i+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Ts=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,a=ao(r),i=e.map((function(t){return t[0]})).join(","),o=e.map((function(e,n){return e[0]+t[n]})).join(","),s=Gi("rc",r),u=Gi("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[a+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d<m;d++)f+="\n "+p[d]+"\n if ("+h+") {\n result["+d+"] = float("+n+");\n } else {\n "+a+" source = rc - start;\n result["+d+"] = getChannel(getX("+u.join()+"), "+c+");\n }\n ";f+=1===r?"} ":"}}",this.userCode="\n const "+a+" start = "+a+"("+i+");\n const "+a+" end = "+a+"("+o+");\n\n void main() {\n "+a+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+f+"\n setOutput(result);\n }\n "},Rs=function(t,e,n,r,a){if(void 0===r&&(r=!1),void 0===a&&(a=!1),this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var i=t.filterWidth,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterHeight,p=t.effectiveFilterWidth,h=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;var d="avg"===e,m="((batch * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + d",g="(xR * "+t.inWidth+" + xC) * "+t.inChannels+" + d",v="0.0";if(d||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+h+", "+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 < "+c+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.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 = "+(r?a?m:g:"wR * "+p+" + wC")+";\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var b=4*Math.floor(i/4),x=i%4,w="\n if ("+d+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+h+", "+f+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.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("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+c+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n getValue(batch, xR, xC + 2 * "+l+", d),\n getValue(batch, xR, xC + 3 * "+l+", d)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n getValue(batch, xR, xC + 2 * "+l+", d),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n "}},Ds=function(t,e,n,r,a){if(void 0===r&&(r=!1),void 0===a&&(a=!1),this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var i=t.filterWidth,o=t.strideDepth,s=t.strideHeight,u=t.strideWidth,l=t.dilationDepth,c=t.dilationHeight,p=t.dilationWidth,h=t.effectiveFilterDepth,f=t.effectiveFilterHeight,d=t.effectiveFilterWidth,m=t.padInfo.front,g=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var y="avg"===e,b="0.0";if(y||(b="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+s+", "+u+");\n const ivec3 pads = ivec3("+m+", "+g+", "+v+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+h+";\n wD += "+l+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+f+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+";\n wC += "+p+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = "+(r?a?"(((batch * "+t.inDepth+" + xD) * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"((xD * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"wD * "+f+" * "+d+" +\n wR * "+d+" + wC")+";\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var x=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(x="avgValue / count");var w=4*Math.floor(i/4),C=i%4,N="\n if ("+y+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+s+", "+u+");\n const ivec3 pads = ivec3("+m+", "+g+", "+v+");\n const float initializationValue = "+b+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+b+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+h+";\n wD += "+l+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+f+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+w+"; wC += 4) {\n int xC = xCCorner + wC * "+p+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n getValue(batch, xD, xR, xC + 2 * "+p+", ch),\n getValue(batch, xD, xR, xC + 3 * "+p+", ch)\n );\n\n "+N+"\n }\n\n int xC = xCCorner + "+w+";\n if ("+(1===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+N+"\n } else if ("+(2===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n initializationValue,\n initializationValue\n );\n\n "+N+"\n } else if ("+(3===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n getValue(batch, xD, xR, xC + 2 * "+p+", ch),\n initializationValue\n );\n\n "+N+"\n }\n }\n setOutput("+x+");\n }\n }\n "}},Os=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,a=t.inSize,i=Math.ceil(a/n);this.outputShape=[r,i];var o="0.0",s="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",s="min"):"max"===e&&(o="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";a%n>0&&(f="\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 "+f+"\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 "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},_s=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;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 "+Hi(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Ki(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},Fs=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],i=r[2],o=t.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],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+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("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\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 "},Ms=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,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 "},zs=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+i+".0, "+o+".0,\n "+o+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Ls=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],i=r[2],o=t.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],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+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("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\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 "},Bs=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,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 "},Ps=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map((function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)})).join(","),a=ao(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("+t[0]+" - coord - 1));\n }\n "},Ws=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=Gi("rc",n),a=r[n-1]+" + 1 < "+this.outputShape[n-1],i=r[n-2]+" + 1 < "+this.outputShape[n-2],o=ao(n);function s(n){var r=t.map((function(r,a){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(a,n)}));return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+a+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+a+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+i+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+a+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},Vs=function(t,e,n,r,a,i,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=ao(a.length),u=ao(i.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>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 < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Us=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,a=t.inSize,i=t.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, segFilter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var p="";a%n>0&&(p="\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 "+p+"\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 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+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 segFilter = 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 segFilter = 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 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},js=function(t,e,n){var r,a;if(this.variableNames=["c","a","b"],this.outputShape=e,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<e.length;u++)s.push(""+i[u]),u<t&&o.push(""+i[u]);r=o.join(),a=s.join()}var l=ao(n);this.userCode="\n void main() {\n "+l+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "},Gs=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=ao(this.rank),r="uniform int start["+this.rank+"];",a=function(t){if(1===t)return"sourceLoc";if(t<=6)return qs.slice(0,t).map((function(t){return"sourceLoc."+t})).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map((function(t,e){return"sourceLoc."+qs[e]+" = start["+e+"] + coords."+qs[e]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+a+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),qs=["x","y","z","w","u","v"],Hs=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=ao(this.rank),n=Gi("coords",this.rank),r=Gi("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",i="getChannel(getSource("+r.join()+"), "+a+")",o="\n result.x = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+i+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+i+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map((function(t,e){return"start["+e+"]"})).join()+");":t.map((function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+"\n vec4 result = vec4(0.);\n "+o+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ks=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,a=ao(n.length),i=ao(n.length),o="";if(1===r)o="coords * strides + begin";else{var s=0;o=n.map((function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"})).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+o+"));\n }\n "},Xs=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,a=Ys(e,n),i=Js(t,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===jt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):a===jt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):a===jt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var a=Js(e,Ys(n,r),r);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],o=i.indexOf(t);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(o,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));for(var e in this.usedTextures)this.usedTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Ys(t,e){if(t===Ut.UPLOAD)return jt.PACKED_2X2_FLOAT32;if(t===Ut.RENDER||null==t)return function(t){return c().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?jt.PACKED_2X2_FLOAT32:jt.UNPACKED_FLOAT32:t?jt.PACKED_2X2_FLOAT16:jt.UNPACKED_FLOAT16}(e);if(t===Ut.DOWNLOAD||t===Ut.PIXELS)return jt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Js(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var $s=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var a=ao(this.rank),i=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a<t.length;a++)r.push("imod("+n[a]+", "+t[a]+")");return r.join()}(t);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n "},Zs=function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n float unaryOperation(float x) {\n "+e+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n "},Qs="if (isnan(x)) return x;",tu="return abs(x);",eu=Qs+"\n return (x < 0.0) ? 0.0 : x;\n",nu=Qs+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",ru="return (x >= 0.0) ? x : (exp(x) - 1.0);",au="return -x;",iu="return ceil(x);",ou="return floor(x);",su="return exp(x);",uu="return exp(x) - 1.0;",lu="return x;",cu="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",pu="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",hu="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",fu=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n "},du=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Gi("rc",e),r=ao(e),a=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),i=n.slice(-2),o=e<=1?"rc":"vec2("+i.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+a+");\n\n setOutput(getChannel(packedInput, "+o+"));\n }\n "},mu={};function gu(t,e){if(void 0===e&&(e=!1),"linear"===t)return"return x;";if("relu"===t)return e?cu:eu;if("elu"===t)return e?hu:ru;if("relu6"===t)return e?pu:nu;if("prelu"===t)return e?bo:vo;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var vu=function(t){function e(e){var n,r=t.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!c().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var a=Kt(c().getNumber("WEBGL_VERSION"));r.binaryCache=((n=c().getNumber("WEBGL_VERSION"))in mu||(mu[n]={}),mu[n]),r.gpgpu=new gs(a),r.canvas=a.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new Xs(r.gpgpu),r.numMBBeforeWarning=null==c().global.screen?1024:c().global.screen.height*c().global.screen.width*window.devicePixelRatio*600/1024/1024,r.texData=new ii(r,Bt),r}return i(e,t),e.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},e.prototype.write=function(t,e,n){if(c().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:Ut.UPLOAD}),r},e.prototype.move=function(t,e,n,r){if(c().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:Ut.UPLOAD})},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,a=e.complexTensors,i=e.slice,o=e.shape,s=e.isPacked;if(null!=i){var u;u=s?new fu(o,lu):new Zs(o,lu);var l=this.runWebGLProgram(u,[{dataId:t,shape:o,dtype:r}],r),c=this.readSync(l.dataId);return this.disposeData(l.dataId),c}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var p,h,f=null!=this.activeTimers;return f&&(p=it()),h="complex64"===r?Si(a.real.dataSync(),a.imag.dataSync()):this.getValuesFromTexture(t),f&&(this.downloadWaitMs+=it()-p),this.convertAndCacheOnCPU(t,h)},e.prototype.read=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a,i,o,u,l,p,h,f,d,m,g,v,y,b,x,w,C,N,S;return s(this,(function(s){switch(s.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise((function(t){return e.push(t)}))];if(n=this.texData.get(t),r=n.values,a=n.shape,i=n.slice,o=n.dtype,u=n.complexTensors,l=n.isPacked,null!=i)return p=l?new fu(a,lu):new Zs(a,lu),h=this.runWebGLProgram(p,[{dataId:t,shape:a,dtype:o}],o),f=this.read(h.dataId),this.disposeData(h.dataId),[2,f];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!c().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===c().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return d=null,"complex64"!==o&&c().get("WEBGL_BUFFER_SUPPORTED")&&(m=this.decode(t),g=this.texData.get(m.dataId),d=(S=this.gpgpu).createBufferFromTexture.apply(S,[g.texture].concat(Yt(a)))),this.pendingRead.set(t,[]),"complex64"===o?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:s.sent(),s.label=2;case 2:return"complex64"!==o?[3,4]:[4,Promise.all([u.real.data(),u.imag.data()])];case 3:return y=s.sent(),b=y[0],x=y[1],v=Si(b,x),[3,5];case 4:null==d?v=this.getValuesFromTexture(t):(w=R(a),v=this.gpgpu.downloadFloat32MatrixFromBuffer(d,w)),s.label=5;case 5:return null!=m&&this.disposeData(m.dataId),C=this.convertAndCacheOnCPU(t,v),N=this.pendingRead.get(t),this.pendingRead.delete(t),N.forEach((function(t){return t(C)})),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}}))}))},e.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!Qt(n)){if(c().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},e.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,a=n.dtype,i=n.isPacked,o=R(r);if(c().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var s=this.decode(t),u=this.texData.get(s.dataId),l=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[u.texture].concat(Yt(r))).subarray(0,o);return this.disposeData(s.dataId),l}var p=c().getBool("WEBGL_PACK")&&!0===i,h=p?Ae(r):r,f=p?new qo(h):new Go(h),d=this.runWebGLProgram(f,[{shape:h,dtype:a,dataId:t}],"float32"),m=this.texData.get(d.dataId),g=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,o);return this.disposeData(d.dataId),g},e.prototype.time=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a,i,o,u;return s(this,(function(s){switch(s.label){case 0:return e=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=T(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),i=T(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,r&&(this.programTimersStack=null),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(a)]:[3,2];case 1:return u=s.sent(),o.kernelMs=k(u),o.getExtraProfileInfo=function(){return u.map((function(t,e){return{name:i[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:o.kernelMs={error:"WebGL query timers are not supported in this environment."},s.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}}))}))},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:it(),endMs:null}},e.prototype.endTimer=function(t){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=it(),t)},e.prototype.getQueryTime=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,a=e.texShape,i=e.usage,o=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(a,r),this.textureManager.releaseTexture(n,a,i,o)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return c().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Bt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every((function(t){return null==n.texData.get(t.dataId).texture&&R(t.shape)<e}))},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.complex=function(t,e){var n=this.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Bt.keep(t.clone()),imag:Bt.keep(e.clone())},n},e.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===R(n))return Rn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,a=Ha(t.shape,e,n);if(r||!a){var i=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Hs(n):new Gs(n),o=i.getCustomSetupFunc(e);return this.compileAndRun(i,[t],null,o)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},e.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),a=this.makeOutput(n,t.dtype),i=this.texData.get(a.dataId);Object.assign(i,r),i.shape=n,i.dtype=t.dtype;var o=Ka(e,t.strides);r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(i.slice.origDataId)||1;return this.dataRefCount.set(i.slice.origDataId,s+1),a},e.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var a=ja(e,n,r);if(a.some((function(t){return 0===t})))return Rn([],a);var i=new Ks(e,r,a);return this.compileAndRun(i,[t])},e.prototype.reverse=function(t,e){var n=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ws(t.shape,e):new Ps(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map((function(t){return An(t)})),r=t.map((function(t){return Tn(t)}));return En(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>c().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(t.length/2),i=this.concat(t.slice(0,a),e),o=this.concat(t.slice(a),e);return this.concat([i,o],e)}if(c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var s=new ko(t.map((function(t){return t.shape})),e);return this.compileAndRun(s,t)}var u=kn(t.map((function(t){return t.shape})),e),l=t.map((function(t){return t.as2D(-1,R(t.shape.slice(e)))})),p=new So(l.map((function(t){return t.shape})));return this.compileAndRun(p,l).reshape(u)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,au,t.dtype);var e=new Zs(t.shape,au);return this.compileAndRun(e,[t])},e.prototype.batchMatMul=function(t,e,n,r){var a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],o=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===a||1===i)&&o>1e3){n&&(t=ai(t,[0,2,1])),r&&(e=ai(e,[0,2,1]));var u=1===i?t:t.as3D(s,o,1),l=1===i?2:1,c=1===i?e.as3D(s,1,o):e;return this.multiply(u,c).sum(l,!0)}var p=Tt(t.dtype,e.dtype),h=new Ss(t.shape,[s,a,i],n,r);return this.compileAndRun(h,[t,e],p)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,a=t.transposeB,i=t.bias,o=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=a?n.shape[1]:n.shape[2],c=e.shape[0],p=Tt(e.dtype,n.dtype),h=null!=i,f=null!=s,d=o?gu(o,!0):null,m=new Ss(e.shape,[c,u,l],r,a,h,d,f),g=[e,n];return i&&g.push(i),s&&g.push(s),this.compileAndRun(m,g,p)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),a=new ho("return areal * breal - aimag * bimag;",t.shape,e.shape),i=new ho("return areal * bimag + aimag * breal;",t.shape,e.shape),o=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,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([t,e]))return this.cpuBackend.multiply(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,go,t.dtype);var p=new yo(go,t.shape,e.shape);return this.compileAndRun(p,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,i){var o=[t,e,n],s=null;null!=i&&(s=i.shape,o.push(i));var u=null;if(null!=a&&(u=a.shape,o.push(a)),c().getBool("WEBGL_PACK_NORMALIZATION")){var l=new po(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,o)}var p=new co(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(p,o)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){var i=c().getBool("WEBGL_PACK_NORMALIZATION")?new ws(t.shape,e,n,r,a):new bs(t.shape,e,n,r,a);return this.compileAndRun(i,[t])},e.prototype.LRNGrad=function(t,e,n,r,a,i,o){var s=new xs(e.shape,r,a,i,o);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map((function(t){return ut(t)}));return Li(Qn(t.shape,t.dtype,n),e)}var r=new $s(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ts(t.shape,e,n):new As(t.shape,e,n);return this.compileAndRun(r,[t])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new Jo(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){I(t.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=hr(t.shape,e,r),i=fr(a.length,e.length),o=dr(t.shape,e,r),s=mr(n,e.length),u=gr(o,n,e.length);return ai(t.reshape(a),i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){I(t.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=[[0,0]];a.push.apply(a,n);for(var i=1+e.length;i<t.shape.length;++i)a.push([0,0]);var o=t.pad(a),s=hr(o.shape,e,r,!1),u=fr(s.length,e.length,!1),l=dr(o.shape,e,r,!1);return ai(o.reshape(s),u).reshape(l)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],a=t.shape[1],i=za(a),o=new Os({windowSize:i,inSize:a,batchSize:r},e),s=this.compileAndRun(o,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},e.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],a=t.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=za(a),o=new Ui({windowSize:i,inSize:a,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(o,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,a=za(r[r.length-1]),i=new so(r,a,e,null==n),o=null==n?[t]:[t,n],s=this.compileAndRun(i,o,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){xn("sum",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a),o=Rt(t.dtype);return this.reduce(i,"sum",o).reshape(r)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a),o=Rt(t.dtype);return this.reduce(i,"prod",o).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,a=wn([r],t.rank),i=t;null!=a&&(i=ai(t,a),r=Nn(1,t.rank)[0]);var o=function(t,e,n){for(var r=[],a=t.length,i=0;i<a;i++)i!==e?r.push(t[i]):r.push(n);return r}(i.shape,r,n),s=R([i.shape[r]]),u=i.as2D(-1,s),l=Rt(t.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",e,l,n).reshape(o);return null!=a&&(c=ai(c,Cn(a))),c},e.prototype.segOpCompute=function(t,e,n,r,a){var i=t.shape[0],o=t.shape[1],s=function(t,e){var n,r=!1;for(t<=30?(n=t,r=!0):n=Q(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=Q(t,n+1);return n}(o,a),u=new Us({windowSize:s,inSize:o,batchSize:i,numSegments:a},e),l=this.compileAndRun(u,[t,n],r);return l.shape[1]===a?l:(n=Gn(0,a).tile([o/s]),this.segOpCompute(l,e,n,r,a))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(xn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!c().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var a=yn(t.shape,r),i=a[0],o=R(a[1]),s=t.as2D(-1,o);return this.argReduce(s,n).reshape(i)}return this.argReducePacked(t,n)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var a=new Bo(t.shape,n,r);return this.compileAndRun(a,[t])},e.prototype.equal=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new yo("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new yo("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new yo("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new yo("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new yo("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new yo("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new Zs(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new yo("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new yo("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var r=new js(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],Tt(e.dtype,n.dtype))},e.prototype.where=function(t){pn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return Pi(t.shape,e)},e.prototype.topk=function(t,e,n){return Bi(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){xn("min",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);xn("max",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){xn("all",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(t,e){xn("any",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.floorDiv=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new yo("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,fo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Tt(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,fo,n);var r=new yo(fo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new fu(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,a){void 0===a&&(a=!1);var i=new xo(n,t.shape,e.shape,a);return this.compileAndRun(i,[t,e],r)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,a=this.texData.get(t.dataId),i=this.texData.get(e.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=r.makeComplexComponentTensorInfo(t,i),u=r.makeComplexComponentTensorInfo(e,o),l=new yo(n,t.shape,e.shape);return r.compileAndRun(l,[s,u],Tt(i.dtype,o.dtype))})),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>c().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var a=t.map((function(t){return t.dtype})).reduce((function(t,e){return Tt(t,e)})),i=t.map((function(t){return t.shape})),o=c().getBool("WEBGL_PACK")?new Vi(t[0].shape,i):new Wi(t[0].shape,i);return this.compileAndRun(o,t,a)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,mo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Tt(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,mo,t.dtype);var r=new yo(mo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=Tt(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,iu,t.dtype);var e=new Zs(t.shape,iu);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ou,t.dtype);var e=new Zs(t.shape,ou);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new Zs(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new Zs(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new Zs(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new Zs(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new Zs(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,su,t.dtype);var e=new Zs(t.shape,su);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,uu,t.dtype);var e=new Zs(t.shape,uu);return this.compileAndRun(e,[t])},e.prototype.softmax=function(t,e){var n=B([e],t.shape),r=this.max(t,n),a=bn(r.shape,n),i=this.subtract(t,r.reshape(a)),o=this.exp(i),s=this.sum(o,n).reshape(a);return _a(o,s)},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new Zs(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new Zs(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Zs(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Zs(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Zs(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=c().getBool("WEBGL_PACK")?new fu(t.shape,cu):new Zs(t.shape,eu),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=c().getBool("WEBGL_PACK")?new fu(t.shape,pu):new Zs(t.shape,nu),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo(bo,t.shape,e.shape):new yo(vo,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,hu,t.dtype);var e=new Zs(t.shape,ru);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new yo("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new Zs(t.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(e,[t])},e.prototype.int=function(t){var e=new Zs(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,a=(r=c().getBool("WEBGL_PACK_CLIP")?new Co(t.shape):new wo(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,a)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,tu,t.dtype);var e=new Zs(t.shape,tu);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new No(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Zs(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Zs(t.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(e,[t])},e.prototype.sin=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Zs(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Zs(t.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;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Zs(t.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 sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new Zs(t.shape,function(t){return void 0===t&&(t=0),Qs+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,r,a,i){var o=t.shape,s=this.texData.get(t.dataId),u=n.inChannels,l=o[0]*o[1]*o[2],p=n.outChannels,h="channelsLast"===n.dataFormat,f=(1===l||1===p)&&u>1e3,d=o[2]%2!=0&&!!s.isPacked;if(f||!c().getBool("WEBGL_LAZILY_UNPACK")||!c().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!d){var m=h?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],g=this.reshape(t,[1,m,n.inChannels]),v=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:v,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:i}),n.outShape)}var y=h?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),b={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},x=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,I(De(s.shape,b.shape),(function(){return"packed reshape "+s.shape+" to "+b.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),C=this.fusedBatchMatMul({a:b,b:w,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:i}),N=this.texData.get(C.dataId);return I(N.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=x,N.shape=n.outShape,Bt.makeTensorFromDataId(C.dataId,n.outShape,C.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,a,i){var o=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,p="channelsLast"===n.dataFormat,h=o*s*u,f=c*l,d=[h,f],m=t.squeeze([0]),g=e.reshape([1,h,-1]),v=new ys(d,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,d[0],d[1]]),b=null!=r,x=null!=i,w=a?gu(a,!0):null,C=new Ss(y.shape,[1,f,n.outChannels],!0,!1,b,w,x),N=[y,g];r&&N.push(r),x&&N.push(i);var S=this.compileAndRun(C,N);return p?S.reshape([1,c,l,n.outChannels]):S.reshape([1,n.outChannels,c,l])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,i=t.activation,o=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,a,i,o);if(c().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,a,i,o);var s=null!=a,u=null!=o,l=i?gu(i,!1):null,p=new _o(r,s,l,u),h=[e,n];return a&&h.push(a),o&&h.push(o),this.compileAndRun(p,h)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(c().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new _o(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Ao(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Eo(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,a=t.convInfo,i=t.bias,o=t.activation,s=t.preluActivationWeights,u=c().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels==1,l=o?gu(o,u):null,p=[n,r],h=null!=i,f=null!=s;return h&&p.push(i),f&&p.push(s),u?(e=new zo(a,h,l,f),this.compileAndRun(e,p)):(e=new Mo(a,h,l,f),this.compileAndRun(e,p))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return c().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new zo(n),this.compileAndRun(r,[t,e])):(r=new Mo(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Oo(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Do(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Fo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new Ro(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new To(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Rs(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Rs(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var a=new Rs(r,"max",!0),i=this.compileAndRun(a,[e]),o=new Cs(r),s=this.compileAndRun(o,[t,i],e.dtype);return i.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new uo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return xi(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),a=0,i=0;i<t.rank;i++)i!==e&&(r[a++]=t.shape[i]);var o=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(i=0;i<u.length;i++)o[e]=i,u[i]=this.slice(t,o,s).reshape(r);return u},e.prototype.avgPool3d=function(t,e){var n=new Ds(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new lo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new Ds(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,r){var a=new Ds(r,"max",!0),i=this.compileAndRun(a,[e]),o=new Ns(r),s=this.compileAndRun(o,[t,i],e.dtype);return i.dispose(),s},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!De(t.shape,e)&&(null===n.texture||!De(n.shape,e))){var r=this.packedReshape(t,e);return Bt.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return wi(t,e)},e.prototype.resizeBilinear=function(t,e,n,r){var a=c().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new zs(t.shape,e,n,r):new Ms(t.shape,e,n,r);return this.compileAndRun(a,[t],"float32")},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new Fs(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var a=new Bs(t.shape,e,n,r);return this.compileAndRun(a,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Ls(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var a=e?t:ni(t),i=a.shape[0],o=a.shape[1],s=new ks(i,o,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],"int32",u)},e.prototype.oneHot=function(t,e,n,r){var a=new Is(t.size,e,n,r);return this.compileAndRun(a,[t])},e.prototype.diag=function(t){var e=new jo(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,a){return pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Ri(t.dataSync(),e.dataSync(),n,r,a)},e.prototype.cropAndResize=function(t,e,n,r,a,i){var o=new Lo(t.shape,e.shape,r,a,i);return this.compileAndRun(o,[t,e,n],"float32")},e.prototype.depthToSpace=function(t,e,n){I(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));var r=t.shape[0],a="NHWC"===n?t.shape[1]:t.shape[2],i="NHWC"===n?t.shape[2]:t.shape[3],o="NHWC"===n?t.shape[3]:t.shape[1],s=a*e,u=i*e,l=o/(e*e),c=new Uo("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return zi(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=Pa(0,t,n),a=r.sliceRank,i=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=t.reshape([i,a]),p=e.reshape([i,o]);if(0===u)return wi(Rn([]),n);var h=On(0),f=new Vs(i,a,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var a=Pa(0,t,n),i=a.sliceRank,o=a.numUpdates,s=a.strides,u=a.outputSize,l=new Vs(o,i,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new Xo("return real * expR - imag * expI;",t.shape,e),a=new Xo("return real * expI + imag * expR;",t.shape,e),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],o=this.compileAndRun(r,i),s=this.compileAndRun(a,i),u=this.complex(o,s).as2D(t.shape[0],t.shape[1]);return o.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],a=Fa(t,e),i=a[0],o=a[1],s=a[2],u=a[3],l=e.reshape([o,r]),c=t.reshape([t.size/s,s]),p=new $o(r,u,[o,s]);return this.compileAndRun(p,[c,l]).reshape(i)},e.prototype.fill=function(t,e,n){if("string"===(n=n||$(e))){var r=V(n,R(t));return r.fill(e),Bt.makeTensor(r,t,n,this)}var a=new Yo(t,e),i=a.getCustomSetupFunc(e);return this.compileAndRun(a,[],n,i)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Ci(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Bt.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new du(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new Es(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[Ie(t.shape)].concat(Ee(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},a=[Ie(e)].concat(Ee(e)),i=new _s(a,n),o=this.runWebGLProgram(i,[r],t.dtype,null,!0);return{dataId:o.dataId,shape:e,dtype:o.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,a=n.shape,i=n.dtype,o=Ae(a);return e=r?new Vo(o):new Wo(o),{dtype:i,shape:a,dataId:this.runWebGLProgram(e,[{shape:o,dtype:i,dataId:t}],i,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,a){var i=this;void 0===a&&(a=!1);var o=this.makeTensorInfo(t.outputShape,n),s=this.texData.get(o.dataId);if(t.packedOutput&&(s.isPacked=!0),t.outPackingScheme===Vt.DENSE){var u=Yt(t.outputShape);s.texShape=u.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(s.usage=t.outTexUsage),0===R(o.shape))return s.values=W(o.dtype,0),o;var l=[],p=e.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 n=i.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&R(e.shape)<=c().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?i.unpackTensor(e):i.packTensor(e),l.push(e),n=i.texData.get(e.dataId);else if(n.isPacked&&!De(n.shape,e.shape)){var r=e,a=e.shape;e.shape=n.shape,e=i.packedReshape(e,a),l.push(e),n=i.texData.get(e.dataId),r.shape=a}return i.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);var h,f={shape:o.shape,texData:s,isUniform:!1},d=function(t,e,n){var r="";e.concat(n).forEach((function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e}));var a=t.userCode;return t.constructor.name+"_"+r+"_"+a}(t,p,f),m=this.getAndSaveBinary(d,(function(){return function(t,e,n,r){var a=e.userCode,i=n.map((function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}})),o=i.map((function(t){return t.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=Yi(i,s,a,e.packedInputs),l=t.createProgram(u),p=null,h=t.getUniformLocation(l,"NAN",!1);1===c().getNumber("WEBGL_VERSION")&&(p=t.getUniformLocation(l,"INFINITY",!1));for(var f={},d=0;d<e.variableNames.length;d++){var m=e.variableNames[d];f[m]=t.getUniformLocation(l,m,!1),f["offset"+m]=t.getUniformLocation(l,"offset"+m,!1)}return{program:e,source:u,webGLProgram:l,uniformLocations:f,inShapeInfos:o,outShapeInfo:s,infLoc:p,nanLoc:h}}(i.gpgpu,t,p,f)})),g=null!=this.activeTimers;if(g&&(h=this.startTimer()),function(t,e,n,r,a){vs(e.inShapeInfos,n),vs([e.outShapeInfo],[r]);var i=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(i,o[0],o[1]):t.setOutputMatrixTexture(i,o[0],o[1]),t.setProgram(e.webGLProgram),1===c().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach((function(n,r){var a=e.program.variableNames[r],i=e.uniformLocations[a],o=e.uniformLocations["offset"+a];if(null!=i)if(n.isUniform)if(R(n.shape)<2)t.gl.uniform1f(i,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(i,s)}else null!=n.texData.slice&&null!=o&&t.gl.uniform1i(o,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,i,r)})),null!=a&&a(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,m,p,f,r),l.forEach((function(t){return i.disposeData(t.dataId)})),g&&(h=this.endTimer(h),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(h)})),!c().getBool("WEBGL_LAZILY_UNPACK")&&s.isPacked&&!1===a){var v=this.unpackTensor(o);return this.disposeData(o.dataId),v}return o},e.prototype.compileAndRun=function(t,e,n,r,a){void 0===a&&(a=!1),n=n||e[0].dtype;var i=this.runWebGLProgram(t,e,n,r,a);return Bt.makeTensorFromDataId(i.dataId,i.shape,i.dtype)},e.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){var t=this;this.disposed||(c().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((function(e){t.gpgpu.deleteProgram(t.binaryCache[e].webGLProgram),delete t.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},e.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=$e((function(){if(!c().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=c().getBool("DEBUG");c().set("DEBUG",!1);var n=t.abs(On(1e-8)).dataSync()[0];if(c().set("DEBUG",e),n>0)return 32}return 16}))),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,a=n.dtype,i=n.values,o=n.texture,s=n.usage,u=n.isPacked;if(null==o){var l,c=null!=this.activeTimers;c&&(l=it());var p=n.texShape;if(null==p&&(p=Te(r,u),n.texShape=p),null!=i){var h=Ae(r),f=void 0,d=p[1],m=p[0],g=i instanceof Uint8Array;u?(d=(e=Jt(p[0],p[1]))[0],m=e[1],f=new Ko(h,[m,d],g)):f=new Ho(h,[m,d],g);var v=this.makeTensorInfo([m,d],a);this.texData.get(v.dataId).usage=g?Ut.PIXELS:Ut.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),d,m,i);var y=this.runWebGLProgram(f,[v],a,null,!0),b=this.texData.get(y.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(v.dataId),this.texData.delete(y.dataId),n.values=null,c&&(this.uploadWaitMs+=it()-l)}else{var x=this.acquireTexture(p,s,a,u);n.texture=x}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},e.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+a+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*H(e)},e}(oi);function yu(t,e){return t(e={exports:{}},e.exports),e.exports}Pt()&&Bt.registerBackend("webgl",(function(){return new vu}),2),"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self&&self;var bu=yu((function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function a(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new r(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)})),xu=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function a(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)})),wu=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function a(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)})),Cu=yu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,a=e.i;return t=r[a],n=(t^=t>>>7)^t<<24,n^=(t=r[a+1&7])^t>>>10,n^=(t=r[a+3&7])^t>>>3,n^=(t=r[a+4&7])^t<<7,t=r[a+7&7],n^=(t^=t<<13)^t<<9,r[a]=n,e.i=a+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function a(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)})),Nu=yu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,a=e.X,i=e.i;return e.w=r=r+1640531527|0,n=a[i+34&127],t=a[i=i+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=a[i]=n^t,e.i=i,n+(r^r>>>16)|0},function(t,e){var n,r,a,i,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),a=0,i=-32;i<u;++i)e&&(r^=e.charCodeAt((i+32)%e.length)),0===i&&(o=r),r^=r<<10,r^=r>>>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&(e&&e.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;t.w=o,t.X=s,t.i=a}(e,t)}function a(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)})),Su=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,a=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^a,e.a=a-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function a(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)})),ku=yu((function(t){!function(e,r){var a,i=this,o=256,s="random",u=r.pow(o,6),l=r.pow(2,52),c=2*l,p=255;function h(t,n,p){var h=[],v=m(function t(e,n){var r,a=[],i=typeof e;if(n&&"object"==i)for(r in e)try{a.push(t(e[r],n-1))}catch(t){}return a.length?a:"string"==i?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return a&&(t=a.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(e)]}}():t,3),h),y=new f(h),b=function(){for(var t=y.g(6),e=u,n=0;t<l;)t=(t+n)*o,e*=o,n=y.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,m(g(y.S),e),(n.pass||p||function(t,e,n,a){return a&&(a.S&&d(a,y),t.state=function(){return d(y,{})}),n?(r[s]=t,e):t})(b,v,"global"in n?n.global:this==r,n.state)}function f(t){var e,n=t.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);a<o;)s[a]=a++;for(a=0;a<o;a++)s[a]=s[i=p&i+t[a%n]+(e=s[a])],s[i]=e;(r.g=function(t){for(var e,n=0,a=r.i,i=r.j,s=r.S;t--;)e=s[a=p&a+1],n=n*o+s[p&(s[a]=s[i=p&i+e])+(s[i]=e)];return r.i=a,r.j=i,n})(o)}function d(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function m(t,e){for(var n,r=t+"",a=0;a<r.length;)e[p&a]=p&(n^=19*e[p&a])+r.charCodeAt(a++);return g(e)}function g(t){return String.fromCharCode.apply(0,t)}if(r["seed"+s]=h,m(r.random(),e),t.exports){t.exports=h;try{a=n(906)}catch(t){}}}([],Math)}));ku.alea=bu,ku.xor128=xu,ku.xorwow=wu,ku.xorshift7=Cu,ku.xor4096=Nu,ku.tychei=Su;var Iu=ku.alea,Eu=In({addN_:function(t){I(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),I(t.length>=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length}));var e=t.map((function(t,e){return dn(t,"tensors"+e,"addN")})),n=e[0];e.forEach((function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),e.forEach((function(t){if(!D(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Bt.runKernelFunc((function(t,n){return t.addN(e)}),r,null,"AddN")}});function Au(){He("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}function Tu(t){return 0===t.rank||1===t.rank?t.as4D(1,1,1,t.size):2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function Ru(t,e,n,r,a,i){null==i&&(i=.001);var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(l.rank===c.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),I(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),I(null==o||l.rank===o.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}));var p={x:u,scale:o,offset:s,mean:l,variance:c},h={varianceEpsilon:i};return Bt.runKernelFunc((function(t,e){var n=Tu(u),r=t.batchNormalization(n,Du(l),Du(c),i,Du(o),Du(s));return e([u,l,c,o]),r}),p,null,"FusedBatchNorm",h).reshape(u.shape)}function Du(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}var Ou=In({batchNormalization_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Ru(t,e,n,i,a,r)}}),_u=In({batchNorm_:Ru});function Fu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(2===l.rank||1===l.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."})),I(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(2===o.rank||1===o.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Mu=In({batchNormalization2d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Fu(t,e,n,i,a,r)}}),zu=In({batchNorm2d_:Fu});function Lu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(3===l.rank||1===l.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."})),I(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(3===o.rank||1===o.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Bu=In({batchNormalization3d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Lu(t,e,n,i,a,r)}}),Pu=In({batchNorm3d_:Lu});function Wu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),I(4===l.rank||1===l.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."})),I(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(4===o.rank||1===o.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Vu=In({batchNormalization4d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Wu(t,e,n,i,a,r)}}),Uu=In({batchNorm4d_:Wu}),ju=In({broadcastTo_:function(t,e){var n=dn(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.length<n.rank)throw new Error("broadcastTo(): shape.length="+e.length+" < input.rank="+n.rank+".");if(e.length>n.rank){for(var a=n.shape.slice();a.length<e.length;)a.unshift(1);n=n.reshape(a)}for(var i=n.shape,o=Array.from(e),s=e.length-1;s>=0;s--)if(i[s]===e[s])o[s]=1;else if(1!==n.shape[s])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var u=o.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));if(0===u.length)return n.clone();var l={x:n},c={shape:e,inputShape:i};return Bt.runKernelFunc((function(t){return t.tile(n,o)}),l,(function(t){return{x:function(){return t.sum(u,!0)}}}),kr,c)}}),Gu=In({clone_:function(t){var e=dn(t,"x","clone",null);return Bt.runKernelFunc((function(){return Bt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{x:e},null,Er)}}),qu=In({logicalAnd_:function(t,e){var n=dn(t,"a","logicalAnd","bool"),r=dn(e,"b","logicalAnd","bool");return Mr(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Hu=In({logicalNot_:function(t){var e=dn(t,"x","logicalNot","bool");return Bt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),Ku=In({logicalOr_:function(t,e){var n=dn(t,"a","logicalOr","bool"),r=dn(e,"b","logicalOr","bool");return Mr(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),Xu=In({logicalXor_:function(t,e){var n=dn(t,"a","logicalXor","bool"),r=dn(e,"b","logicalXor","bool");return Mr(n.shape,r.shape),Ku(t,e).logicalAnd(qu(t,e).logicalNot())}}),Yu=In({where_:function(t,e,n){var r=dn(e,"a","where"),a=dn(n,"b","where"),i=dn(t,"condition","where","bool");return E(r.shape,a.shape,"Error in where: "),1===i.rank?I(i.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):E(i.shape,a.shape,"Error in where: "),Bt.runKernelFunc((function(t,e){var n=t.select(i,r,a);return e([i]),n}),{$condition:i,$a:r,$b:a},(function(t,e){var n=e[0];return{$condition:function(){return Hn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),Ju=function(t){return o(this,void 0,void 0,(function(){var e,n,r;return s(this,(function(a){switch(a.label){case 0:return[4,(e=dn(t,"condition","whereAsync","bool")).data()];case 1:return n=a.sent(),r=Pi(e.shape,n),t!==e&&e.dispose(),[2,r]}}))}))},$u=In({divNoNan_:function(t,e){var n,r=dn(t,"a","div"),a=dn(e,"b","div");r=(n=Dt(r,a))[0],a=n[1];var i=_a(r,a),o=Hn(i),s=a.equal(o);return Yu(s,o,i)}}),Zu=In({tile_:function(t,e){var n=dn(t,"x","tile",null);I(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],a={x:n},i={reps:e};return Bt.runKernelFunc((function(t,r){var a=t.tile(n,e);return r([n]),a}),a,null,Ar,i,r)}}),Qu=In({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var a=Qn([t,e],r),i=t<=e?t:e,o=0;o<i;++o)a.set(1,o,o);var s=a.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return Zu(ir(s,0),[n[0],1,1]);if(2===n.length)return Zu(ir(ir(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return Zu(ir(ir(ir(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),tl=In({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var a=dn(t,"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=Bt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===o?u.as1D():u}}),el=In({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var a=dn(t,"indices","oneHot","int32"),i=a.shape.concat([e]),o={indices:a=a.flatten()},s={depth:e,onValue:n,offValue:r};return Bt.runKernelFunc((function(t,i){return i([a]),t.oneHot(a,e,n,r)}),o,null,Ir,s).reshape(i)}}),nl=In({pad_:function(t,e,n){void 0===n&&(n=0);var r=dn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a={paddings:e,constantValue:n},i={x:r};return Bt.runKernelFunc((function(t,a){return a([r]),t.pad(r,e,n)}),i,null,Tr,a)}}),rl=In({pad1d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),nl(t,[e],n)}}),al=In({pad2d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),il=In({pad3d_:function(t,e,n){return void 0===n&&(n=0),I(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),ol=In({pad4d_:function(t,e,n){return void 0===n&&(n=0),I(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),sl=In({rand_:function(t,e,n){var r=R(t),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<r;i++)a[i]=e();return Bt.makeTensor(a,t,n)}});function ul(){return 32===Bt.backend.floatPrecision()?.001:.1}function ll(t,e,n){var r=!0;if((q(t)||q(e))&&(r=!1),q(t)&&q(e)&&(r=!0),r){var a=t.constructor.name,i=e.constructor.name;if(a!==i)throw new Error("Arrays are of different type. Actual: "+a+". Expected: "+i)}if(Array.isArray(t)&&Array.isArray(e)){var o=hn(t),s=hn(e);if(!D(o,s))throw new Error("Arrays have different shapes. Actual: ["+o+"]. Expected: ["+s+"]")}var u=q(t)?t:T(t),l=q(e)?e:T(e);if(u.length!==l.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+l.length+".\nActual: "+u+".\nExpected: "+l+".");for(var c=0;c<l.length;++c){var p=u[c],h=l[c];if(!n(p,h))throw new Error("Arrays differ: actual["+c+"] = "+p+", expected["+c+"] = "+h+".\nActual: "+u+".\nExpected: "+l+".")}}function cl(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var pl=Object.freeze({TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(t,e,n){return null==n&&(n=ul()),ll(t,e,(function(t,e){return cl(t,e,n)}))},testEpsilon:ul,expectPromiseToFail:function(t,e){t().then((function(){return e.fail()}),(function(){return e()}))},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return X(t)||X(t[0])||X(e)||X(e[0])?ll(t,n,(function(t,e){return t==e})):ll(t,e,(function(t,e){return cl(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=ul()),!cl(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),hl=function(){function t(t,e,n,r,a){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var i=a||Math.random();this.random=Iu(i.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var a=void 0,i=void 0,o=void 0;do{o=(a=2*this.random()-1)*a+(i=2*this.random()-1)*i}while(o>=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),fl=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var a=r||Math.random();this.randu=Iu(a.toString()),this.randn=new hl(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,a,i;;){do{r=this.randn.nextValue(),i=1+this.c*r}while(i<=0);if(i*=i*i,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-i+Math.log(i)),(a=this.randu())<e||Math.log(a)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),dl=function(){function t(t,e,n,r){var a=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==a.dtype||"float32"===a.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=Iu(r)}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}(),ml=In({randomGamma_:function(t,e,n,r,a){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var i=new fl(e,n,r,a),o=Qn(t,r),s=0;s<o.values.length;s++)o.values[s]=i.nextValue();return o.toTensor()}}),gl=In({randomNormal_:function(t,e,n,r,a){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var i=new hl(e,n,r,!1,a),o=Qn(t,r),s=0;s<o.values.length;s++)o.values[s]=i.nextValue();return o.toTensor()}}),vl=In({randomUniform_:function(t,e,n,r,a){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var i=Qn(t,r),o=new dl(e,n,null,a),s=0;s<i.values.length;s++)i.values[s]=o.nextValue();return i.toTensor()}}),yl=In({square_:function(t){var e=dn(t,"x","square"),n=[e];return Bt.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}}),bl=In({squaredDifference_:function(t,e){var n,r=dn(t,"a","squaredDifference"),a=dn(e,"b","squaredDifference");n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape);var i={a:r,b:a},o=[r,a];return Bt.runKernelFunc((function(t,e){var n=t.squaredDifference(r,a);return e([r,a]),n}),i,(function(t,e){var n=e[0],r=e[1],a=On(2);return{a:function(){return t.mul(n.sub(r).mul(a))},b:function(){return t.mul(r.sub(n).mul(a))}}}),wr,{},o,[])}}),xl=In({truncatedNormal_:function(t,e,n,r,a){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");for(var i=new hl(e,n,r,!0,a),o=Qn(t,r),s=0;s<o.values.length;s++)o.values[s]=i.nextValue();return o.toTensor()}}),wl=In({equal_:function(t,e){var n,r=dn(t,"a","equal"),a=dn(e,"b","equal");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t){return t.equal(r,a)}),{$a:r,$b:a})}}),Cl=In({equalStrict_:function(t,e){var n=dn(t,"a","equalStrict"),r=dn(e,"b","equalStrict");return E(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),Nl=In({greater_:function(t,e){var n,r=dn(t,"a","greater"),a=dn(e,"b","greater");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t){return t.greater(r,a)}),{a:r,b:a},null,"Greater")}}),Sl=In({greaterEqual_:function(t,e){var n,r=dn(t,"a","greaterEqual"),a=dn(e,"b","greaterEqual");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.greaterEqual(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return Hn(n)},b:function(){return Hn(r)}}}),"GreaterEqual")}}),kl=In({greaterEqualStrict_:function(t,e){var n=dn(t,"a","greaterEqualStrict"),r=dn(e,"b","greaterEqualStrict");return E(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),Il=In({greaterStrict_:function(t,e){var n=dn(t,"a","greaterStrict"),r=dn(e,"b","greaterStrict");return E(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),El=In({less_:function(t,e){var n,r=dn(t,"a","less"),a=dn(e,"b","less");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t){return t.less(r,a)}),{a:r,b:a},null,"Less")}}),Al=In({lessEqual_:function(t,e){var n,r=dn(t,"a","lessEqual"),a=dn(e,"b","lessEqual");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.lessEqual(r,a);return e([r,a]),n}),{a:r,b:a},null,"LessEqual")}}),Tl=In({lessEqualStrict_:function(t,e){var n=dn(t,"a","lessEqualStrict"),r=dn(e,"b","lessEqualStrict");return E(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),Rl=In({lessStrict_:function(t,e){var n=dn(t,"a","lessStrict"),r=dn(e,"b","lessStrict");return E(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Dl=In({notEqual_:function(t,e){var n,r=dn(t,"a","notEqual"),a=dn(e,"b","notEqual");return n=Dt(r,a),r=n[0],a=n[1],Mr(r.shape,a.shape),Bt.runKernelFunc((function(t){return t.notEqual(r,a)}),{a:r,b:a},null,"NotEqual")}}),Ol=In({notEqualStrict_:function(t,e){var n=dn(t,"a","notEqualStrict"),r=dn(e,"b","notEqualStrict");return E(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function _l(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Fl(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var Ml=In({gather_:function(t,e,n){void 0===n&&(n=0);var r=dn(t,"x","gather"),a=dn(e,"indices","gather","int32");n=B(n,r.shape)[0];var i=function(t,e,n){for(var r=t.shape[n],a=[],i=1,o=1,s=0;s<n;s++)a.push(t.shape[s]),i*=t.shape[s];for(s=0;s<e.rank;s++)a.push(e.shape[s]);for(s=n+1;s<t.rank;s++)a.push(t.shape[s]),o*=t.shape[s];return{batchSize:i,sliceSize:o,dimSize:r,outputShape:a}}(r,a,n);return Bt.runKernelFunc((function(t,e){var i=t.gather(r,a.flatten(),n);return e([a]),i}),{x:r,indices:a},(function(t,e){var a=e[0];return{x:function(){var e=r.shape,i=a.size,o=e.slice(0,n),s=o.length,u=e.slice(n,e.length).slice(1),l=u.length,c=_l(0,s),p=_l(s+1,s+1+l),h=Fl([o,[i],u]),f=t.reshape(h),d=a.reshape([i]),m=Fl([[s],c,p]),g=f.transpose(m),v=zl(g,d,r.shape[n]),y=Cn(m);return v.transpose(y)},indices:function(){return a}}}),"Gather",{axis:n}).reshape(i.outputShape)}}),zl=In({unsortedSegmentSum_:function(t,e,n){var r=dn(t,"x","unsortedSegmentSum"),a=dn(e,"segmentIds","unsortedSegmentSum","int32");return I(O(n),(function(){return"numSegments must be of dtype int"})),Bt.runKernelFunc((function(t,e){var i=t.unsortedSegmentSum(r,a,n);return e([a]),i}),{$x:r},(function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=xa(e,Hn(e)),r=Ml(t,n),a=Sl(e,On(0,"int32")),i=r.rank-a.rank,o=0;o<i;++o)a=ir(a,o+1);a=qu(a,Wn(r.shape,"bool"));var s=Hn(r);return Yu(a,r,s)}(t,n)}}}))}}),Ll=function(t,e,n){return o(this,void 0,void 0,(function(){var r,a,i,o,u,l,c,p,h,f,d,m,g;return s(this,(function(s){switch(s.label){case 0:for(r=dn(t,"tensor","boolMask"),a=dn(e,"mask","boolMask","bool"),i=null==n?0:n,o=a.rank,u=r.shape,I(o>0,(function(){return"mask cannot be scalar"})),E(u.slice(i,i+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=i;c<i+o;c++)l*=u[c];return p=u.slice(0,i).concat([l],u.slice(i+o)),h=r.reshape(p),f=a.reshape([-1]),[4,Ju(f)];case 1:return d=s.sent(),m=d.squeeze([1]),g=Ml(h,m,i),t!==r&&r.dispose(),e!==a&&a.dispose(),m.dispose(),h.dispose(),f.dispose(),d.dispose(),[2,g]}}))}))};function Bl(t,e,n,r,a,i,o){void 0===i&&(i="NHWC"),I(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var s=t,u=e,l=!1;3===e.rank&&(l=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),I(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),I(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),I(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var c="NHWC"===i?s[3]:s[1],p="NHWC"===i?u.shape[3]:u.shape[1];I(c===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+c+") must match input depth for filter "+n.shape[2]+"."})),I(p===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+p+") must match output depth for filter "+n.shape[3]+"."})),null!=o&&I(O(a),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."}));var h=bi(i),f=ci(s,n.shape,r,1,a,o,!1,h),d=Bt.runKernelFunc((function(t,e){var r=t.conv2dDerInput(u,n,f);return e([n,u]),r}),{dy4D:u,filter:n},(function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return Ul(t,n,r,a,i,1,o)},filter:function(){return Gl(t,s,n.shape,r,a,i,o)}}}));return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function Pl(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],a=e[2];return 1===n&&1===r&&1===a}function Wl(t,e,n,r,a){I(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var i=t,o=e,s=!1;4===e.rank&&(s=!0,o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),i=[1,t[0],t[1],t[2],t[3]]);var u=i[4],l=o.shape[4];I(5===i.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+i.length+"."})),I(5===o.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+o.rank})),I(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),I(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),I(l===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[4]+"."}));var c=pi(i,n.shape,r,1,a),p=Bt.runKernelFunc((function(t){return t.conv3dDerInput(o,n,c)}),{dy5D:o});return s?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}var Vl=In({conv1d_:function(t,e,n,r,a,i,o){void 0===a&&(a="NWC"),void 0===i&&(i=1);var s=dn(t,"x","conv1d"),u=dn(e,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),I(3===l.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."})),I(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=o&&I(O(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."})),I(l.shape[2]===u.shape[1],(function(){return"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."})),I(yi(n,i),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+i+"'"})),I("NWC"===a,(function(){return"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported."}));var p=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),h=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),f=Ul(h,p,[1,n],r,"NHWC",[1,i],o);return c?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),Ul=In({conv2d_:function(t,e,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=dn(t,"x","conv2d"),u=dn(e,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),I(4===l.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."})),I(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=o&&I(O(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var p="NHWC"===a?l.shape[3]:l.shape[1];I(p===u.shape[2],(function(){return"Error in conv2d: depth of input ("+p+") must match input depth for filter "+u.shape[2]+"."})),I(yi(n,i),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}));var h=bi(a),f=ci(l.shape,u.shape,n,i,r,o,!1,h),d=[u,l],m=Bt.runKernelFunc((function(t,e){var n=t.conv2d(l,u,f);return e([u,l]),n}),{x:l,filter:u},(function(t,e){var o=e,s=o[0],u=o[1];return I(vi(i),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+i+"'"})),{x:function(){return ql(u.shape,t,s,n,r,a)},filter:function(){return Gl(u,t,s.shape,n,r,a)}}}),"Conv2D",f,d);return c?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),jl=In({conv3d_:function(t,e,n,r,a,i){void 0===a&&(a="NDHWC"),void 0===i&&(i=[1,1,1]);var o=dn(t,"x","conv3d"),s=dn(e,"filter","conv3d"),u=o,l=!1;4===o.rank&&(l=!0,u=o.as5D(1,o.shape[0],o.shape[1],o.shape[2],o.shape[3])),I(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),I(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),I(u.shape[4]===s.shape[3],(function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."})),I(function(t,e){return Pl(t)||Pl(e)}(n,i),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),I("NDHWC"===a,(function(){return"Error in conv3d: got dataFormat of "+a+" but only NDHWC is currently supported."}));var c=pi(u.shape,s.shape,n,i,r),p=Bt.runKernelFunc((function(t,e){var n=t.conv3d(u,s,c);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){I(Pl(i),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+i+"'"}));var a=e[0],o=e[1];return{x:function(){return Wl(a.shape,t,o,n,r)},$filter:function(){return function(t,e,n,r,a){var i=t;4===t.rank&&(i=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var o=e;4===o.rank&&(o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),I(5===i.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+i.shape+"."})),I(5===o.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+o.shape+"."})),I(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),I(i.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+i.shape[4]+") must match input depth in filter ("+n[3]+"."})),I(o.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+o.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=pi(i.shape,n,r,1,a);return Bt.runKernelFunc((function(t){return t.conv3dDerFilter(i,o,s)}),{x5D:i,dy5D:o})}(a,t,o.shape,n,r)}}}));return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),Gl=In({conv2dDerFilter_:function(t,e,n,r,a,i,o){void 0===i&&(i="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),I(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),I(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),I(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var l="NHWC"===i?s.shape[3]:s.shape[1],c="NHWC"===i?u.shape[3]:u.shape[1];I(l===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+l+") must match input depth in filter ("+n[2]+"."})),I(c===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+c+") must match output depth for filter ("+n[3]+")."})),null!=o&&I(O(a),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."}));var p=bi(i),h=ci(s.shape,n,r,1,a,o,!1,p);return Bt.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,h)}),{x4D:s,dy4D:u})}}),ql=In({conv2dDerInput_:Bl}),Hl=In({depthwiseConv2d_:function(t,e,n,r,a,i,o){void 0===a&&(a="NHWC"),void 0===i&&(i=[1,1]);var s=dn(t,"x","depthwiseConv2d"),u=dn(e,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),I(4===l.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."})),I(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),I(l.shape[3]===u.shape[2],(function(){return"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]),I(yi(n,i),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&I(O(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var p=ci(l.shape,u.shape,n,i,r,o,!0),h=[l,u],f=Bt.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(l,u,p);return e([l,u]),n}),{x:l,filter:u},(function(t,e){I(vi(i),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+i+"'"}));var n=e[0],r=e[1];return{x:function(){return Kl(n.shape,t,r,p)},filter:function(){return Xl(n,t,r.shape,p)}}}),"DepthwiseConv2dNative",p,h);return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),Kl=In({depthwiseConv2dDerInput_:function(t,e,n,r){var a=e,i=!1;3===e.rank&&(i=!0,a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=Bt.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(a,n,r)}),{dy4D:a});return i?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}}),Xl=In({depthwiseConv2dDerFilter_:function(t,e,n,r){var a=t;3===t.rank&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=e;return 3===i.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Bt.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(a,i,r)}),{x4D:a,dy4D:i})}}),Yl=In({separableConv2d_:function(t,e,n,r,a,i,o){void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC");var s=dn(t,"x","separableConv2d"),u=dn(e,"depthwiseFilter","separableConv2d"),l=dn(n,"pointwiseFilter","separableConv2d"),c=s,p=!1;if(3===s.rank&&(p=!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");I(4===c.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."})),I(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),I(4===l.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),I(1===l.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."})),I(1===l.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+"."}));var h=u.shape[2],f=u.shape[3];I(l.shape[2]===h*f,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+h*f+", but got "+l.shape[2]+"."}));var d=Hl(c,u,r,a,o,i),m=Ul(d,l,1,"valid",o);return p?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Jl=In({conv2dTranspose_:function(t,e,n,r,a,i){return Bl(n,dn(t,"x","conv2dTranspose"),dn(e,"filter","conv2dTranspose"),r,a,"NHWC",i)}}),$l=In({conv3dTranspose_:function(t,e,n,r,a){return Wl(n,dn(t,"x","conv3dTranspose"),dn(e,"filter","conv3dTranspose"),r,a)}}),Zl=In({matMul_:function(t,e,n,r){var a;void 0===n&&(n=!1),void 0===r&&(r=!1);var i=dn(t,"a","matMul"),o=dn(e,"b","matMul");a=Dt(i,o),i=a[0],o=a[1];var s=n?i.shape[i.rank-2]:i.shape[i.rank-1],u=r?o.shape[o.rank-1]:o.shape[o.rank-2],l=n?i.shape[i.rank-1]:i.shape[i.rank-2],c=r?o.shape[o.rank-2]:o.shape[o.rank-1],p=i.shape.slice(0,-2),h=o.shape.slice(0,-2),f=R(p),d=R(h);I(i.rank>=2&&o.rank>=2&&i.rank===o.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+i.rank+" and "+o.rank+"."})),I(D(p,h),(function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+i.shape+" and "+o.shape+" must match."})),I(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+i.shape+" and "+o.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var m=i.shape.slice(0,-2).concat([l,c]),g=n?i.as3D(f,s,l):i.as3D(f,l,s),v=r?o.as3D(d,c,u):o.as3D(d,u,c),y={transposeA:n,transposeB:r};return Bt.runKernelFunc((function(t,e){var a=t.batchMatMul(g,v,n,r);return e([g,v]),a}),{a:g,b:v},(function(t,e){var a=e,i=a[0],o=a[1];return n||r?!n&&r?{a:function(){return t.matMul(o,!1,!1)},b:function(){return t.matMul(i,!0,!1)}}:n&&!r?{a:function(){return o.matMul(t,!1,!0)},b:function(){return i.matMul(t,!1,!1)}}:{a:function(){return o.matMul(t,!0,!0)},b:function(){return t.matMul(i,!0,!0)}}:{a:function(){return t.matMul(o,!1,!0)},b:function(){return i.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(m)}}),Ql=In({dot_:function(t,e){var n=dn(t,"t1","dot"),r=dn(e,"t2","dot");I(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(function(){return"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 I(a===i,(function(){return"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]))}}),tc=In({outerProduct_:function(t,e){var n=dn(t,"v1","outerProduct"),r=dn(e,"v2","outerProduct");return I(1===n.rank&&1===r.rank,(function(){return"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))}}),ec=In({reverse_:function(t,e){var n=dn(t,"x","reverse");if(0===n.rank)return n.clone();var r=B(e,n.shape);return Bt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),nc=In({reverse1d_:function(t){var e=dn(t,"x","reverse");return I(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),ec(e,0)}}),rc=In({reverse2d_:function(t,e){var n=dn(t,"x","reverse");return I(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),ec(n,e)}}),ac=In({reverse3d_:function(t,e){var n=dn(t,"x","reverse");return I(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),ec(n,e)}}),ic=In({reverse4d_:function(t,e){var n=dn(t,"x","reverse");return I(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),ec(n,e)}});function oc(t,e,n,r,a,i){var o=dn(t,"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]),I(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),I(yi(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=i&&I(O(a),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var l=ui(s.shape,e,n,r,a,i);if(1===l.filterWidth&&1===l.filterHeight&&D(l.inShape,l.outShape))return o.clone();var c=[s],p=Bt.runKernelFunc((function(t,e){var n=t.maxPool(s,l);return e([s,n]),n}),{x:s},(function(t,i){var o=i[0],s=i[1];return{x:function(){return function(t,e,n,r,a,i,o,s){var u=dn(t,"dy","maxPoolBackprop"),l=dn(e,"input","maxPoolBackprop"),c=dn(n,"output","maxPoolBackprop");I(l.rank===u.rank,(function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"})),null==i&&(i=[1,1]),I(yi(a,i),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"})),I(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),I(4===l.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}));var p=ui(l.shape,r,a,i,o,void 0);return Bt.runKernelFunc((function(t){return t.maxPoolBackprop(u,l,c,p)}),{$dy:u,$input:l})}(t,o,s,e,n,r,a)}}}),"MaxPool",l,c);return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function sc(t,e,n,r,a,i){var o=dn(t,"x","avgPool","float32");null==r&&(r=[1,1]),I(yi(n,r),(function(){return"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])),I(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=i&&I(O(a),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var l=ui(s.shape,e,n,r,a,i);if(1===l.filterWidth&&1===l.filterHeight&&D(l.inShape,l.outShape))return o.clone();var c=Bt.runKernelFunc((function(t){return t.avgPool(s,l)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,a,i){var o=dn(t,"dy","avgPoolBackprop"),s=dn(e,"input","avgPoolBackprop");I(s.rank===o.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"})),null==a&&(a=[1,1]),I(yi(r,a),(function(){return"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])),I(4===l.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."})),I(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var p=ui(u.shape,n,r,a,i),h=Bt.runKernelFunc((function(t){return t.avgPoolBackprop(l,u,p)}),{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,a)}}}),"AvgPool",l);return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var uc=In({maxPool_:function(t,e,n,r,a){return oc(t,e,n,1,r,a)}}),lc=In({avgPool_:function(t,e,n,r,a){return sc(t,e,n,1,r,a)}}),cc=In({pool_:function(t,e,n,r,a,i){null==a&&(a=[1,1]),null==i&&(i=1),0===r&&(r="valid");var o=dn(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(yi(i,a),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}));var l,c=ui(s.shape,e,i,a,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map((function(t,n){return t+(t-1)*(e[n]-1)})).map((function(t){return t-1})),r=n.map((function(t){return Math.floor(t/2)})),a=n.map((function(t,e){return t-r[e]}));return n.map((function(t,e){return[r[e],a[e]]}))}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],f=function(t,e,n){var r=n.map((function(t){return t[0]})),a=n.map((function(t){return t[1]})),i=t.concat(r,a),o=e.map((function(t,e){return(t-i[e]%t)%t})),s=a.map((function(t,e){return t+o[e]}));return[e.map((function(t,e){return[r[e],s[e]]})),e.map((function(t,e){return[0,o[e]]}))]}([c.inHeight,c.inWidth],p,l),d=f[0],m=f[1],g=h?r:"valid",v=h?s:sr(s,p,d),y=("avg"===n?function(){return sc(v,e,i,1,g)}:function(){return oc(v,e,i,1,g)})(),b=h?y:er(y,p,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),pc=In({maxPool3d_:function(t,e,n,r,a,i,o){void 0===i&&(i="NDHWC");var s=dn(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),I(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(yi(n,o),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=a&&I(O(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var c=li(u.shape,e,n,o,r,a,i),p=Bt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n}),{x:u},(function(t,i){var s=i[0],u=i[1];return{x:function(){return function(t,e,n,r,a,i,o,s){var u=dn(t,"dy","maxPool3dBackprop"),l=dn(e,"input","maxPool3dBackprop"),c=dn(n,"output","maxPool3dBackprop"),p=u,h=l,f=c,d=!1;4===l.rank&&(d=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),I(5===p.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."})),I(5===h.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+h.rank+"."})),I(5===f.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+f.rank+"."})),null==i&&(i=[1,1,1]),I(yi(a,i),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"})),null!=s&&I(O(o),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."}));var m=li(h.shape,r,a,i,o,s),g=Bt.runKernelFunc((function(t){return t.maxPool3dBackprop(p,h,f,m)}),{dy5D:p,input5D:h});return d?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(t,s,u,e,n,o,r,a)}}}));return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),hc=In({avgPool3d_:function(t,e,n,r,a,i,o){void 0===i&&(i="NDHWC");var s=dn(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),I(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(yi(n,o),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=a&&I(O(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var c=li(u.shape,e,n,o,r,a,i),p=Bt.runKernelFunc((function(t){return t.avgPool3d(u,c)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,a,i,o){var s=dn(t,"dy","avgPool3dBackprop"),u=dn(e,"input","avgPool3dBackprop"),l=s,c=u,p=!1;4===u.rank&&(p=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),I(5===l.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."})),I(5===c.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."})),null==a&&(a=[1,1,1]),I(yi(r,a),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'"})),null!=o&&I(O(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."}));var h=li(c.shape,n,r,a,i,o),f=Bt.runKernelFunc((function(t){return t.avgPool3dBackprop(l,c,h)}),{dy5D:l,input5D:c});return p?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}(t,u,e,n,o,r,a)}}}));return p=p.cast(u.dtype),l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),fc=In({maxPoolWithArgmax_:function(t,e,n,r,a){void 0===a&&(a=!1);var i=dn(t,"x","maxPoolWithArgmax"),o={filterSize:e,strides:n,pad:r,includeBatchInIndex:a},s=Bt.runKernel("MaxPoolWithArgmax",{x:i},o);return{result:s[0],indexes:s[1]}}}),dc=In({slice_:function(t,e,n){var r,a,i=dn(t,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(i.rank-1).fill(0)):e.length<i.rank?e.concat(new Array(i.rank-e.length).fill(0)):e.slice()).forEach((function(t){I(-1!==t,(function(){return"slice() does not support negative begin indexing."}))})),a=(a=null==n?new Array(i.rank).fill(-1):"number"==typeof n?[n].concat(new Array(i.rank-1).fill(-1)):n.length<i.rank?n.concat(new Array(i.rank-n.length).fill(-1)):n).map((function(t,e){return t>=0?t:(I(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),i.shape[e]-r[e])})),Va(i,r,a);var o=i.shape,s={begin:r,size:a};return Bt.runKernelFunc((function(t){return t.slice(i,r,a)}),{x:i},(function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],o[n]-r[n]-a[n]]);return{x:function(){return nl(t,e)}}}),"Slice",s)}}),mc=In({slice1d_:function(t,e,n){var r=dn(t,"x","slice1d");return I(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),dc(r,[e],[n])}}),gc=In({slice2d_:function(t,e,n){var r=dn(t,"x","slice2d");return I(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),dc(r,e,n)}}),vc=In({slice3d_:function(t,e,n){var r=dn(t,"x","slice3d");return I(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),dc(r,e,n)}}),yc=In({slice4d_:function(t,e,n){var r=dn(t,"x","slice4d");return I(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),dc(r,e,n)}});function bc(t,e,n,r,a){return e.rank<n.rank&&(e=e.reshape(bn(e.shape,r))),t.rank<n.rank&&(t=t.reshape(bn(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==a?r:r.transpose(a)}}}var xc=In({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","all","bool"),a=B(e,r.shape),i=a,o=wn(i,r.rank);null!=o&&(r=r.transpose(o),i=Nn(i.length,r.rank));var s=Bt.runKernelFunc((function(t){return t.all(r,i)}),{$x:r});if(n){var u=bn(s.shape,a);return s.reshape(u)}return s}}),wc=In({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","any","bool"),a=B(e,r.shape),i=a,o=wn(i,r.rank);null!=o&&(r=r.transpose(o),i=Nn(i.length,r.rank));var s=Bt.runKernelFunc((function(t){return t.any(r,i)}),{$x:r});if(n){var u=bn(s.shape,a);return s.reshape(u)}return s}}),Cc=In({argMax_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","argMax");null==e&&(e=0);var r=B(e,n.shape),a=wn(r,n.rank);null!=a&&(n=n.transpose(a),r=Nn(r.length,n.rank));var i={axis:r[0]},o=[n];return Bt.runKernelFunc((function(t,e){var a=t.argMax(n,r[0]);return e([n]),a}),{x:n},(function(t,e){var n=e[0];return{x:function(){return Hn(n)}}}),"ArgMax",i,o)}}),Nc=In({argMin_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","argMin");null==e&&(e=0);var r=B(e,n.shape),a=wn(r,n.rank);return null!=a&&(n=n.transpose(a),r=Nn(r.length,n.rank)),Bt.runKernelFunc((function(t,e){var a=t.argMin(n,r[0]);return e([n]),a}),{$x:n},(function(t,e){var n=e[0];return{$x:function(){return Hn(n)}}}))}}),Sc=In({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","logSumExp"),a=B(e,r.shape),i=r.max(a,!0),o=r.sub(i).exp().sum(a).log(),s=i.reshape(o.shape).add(o);if(n){var u=bn(s.shape,a);return s.reshape(u)}return s}}),kc=In({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","max"),a=r,i=B(e,r.shape),o=i,s=wn(o,r.rank);null!=s&&(r=r.transpose(s),o=Nn(o.length,r.rank));var u=[r],l=Bt.runKernelFunc((function(t,e){var n=t.max(r,o);return e([a,n]),n}),{x:r},(function(t,e){return bc(t,e[1],e[0],i,s)}),"Max",{axes:o},u,[!0]);if(n){var c=bn(l.shape,i);l=l.reshape(c)}return l}}),Ic=In({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","mean"),a=B(e,r.shape),i=R(yn(r.shape,a)[1]);return ti((function(t){var r=On(i);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return a.forEach((function(t){n[t]=1})),e.reshape(n).mul(Wn(t.shape,"float32")).div(i)}}}))(r)}}),Ec=In({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","min"),a=r,i=B(e,r.shape),o=i,s=wn(o,r.rank);null!=s&&(r=r.transpose(s),o=Nn(o.length,r.rank));var u=[r],l=Bt.runKernelFunc((function(t,e){var n=t.min(r,o);return e([a,n]),n}),{x:r},(function(t,e){return bc(t,e[1],e[0],i,s)}),"Min",{axes:o},u,[!0]);if(n){var c=bn(l.shape,i);l=l.reshape(c)}return l}}),Ac=In({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=B(e,(t=dn(t,"x","moments")).shape),a=t.mean(r,n),i=a.shape;n||(i=bn(a.shape,r));var o=t.toFloat().sub(a.reshape(i)).square();return{mean:a,variance:o.mean(r,n)}}}),Tc=In({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var a=B(e,r.shape);return ti((function(t){var e=wn(a,t.rank),r=a,i=t;null!=e&&(i=t.transpose(e),r=Nn(r.length,t.rank));var o=function(e){var n=t.shape.slice();return a.forEach((function(t){n[t]=1})),e.reshape(n).mul(Wn(t.shape,"float32"))},s={axes:r},u=Bt.runKernelFunc((function(t){return t.sum(i,r)}),{x:i},(function(t){return{x:function(){return o(t)}}}),"Sum",s);if(n){var l=bn(u.shape,a);u=u.reshape(l)}return{value:u,gradFunc:o}}))(r)}}),Rc=In({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var a=B(e,r.shape),i=wn(a,r.rank),o=a,s=r;null!=i&&(s=r.transpose(i),o=Nn(o.length,r.rank));var u=Bt.runKernelFunc((function(t){return t.prod(s,o)}),{permutedX:s});if(n){var l=bn(u.shape,a);u=u.reshape(l)}return u}}),Dc=In({elu_:function(t){var e=dn(t,"x","elu");return Bt.runKernelFunc((function(t,n){var r=t.elu(e);return n([r]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){return Bt.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),Oc=In({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=dn(t,"x","leakyRelu");return xa(On(e).mul(n),n)}}),_c=In({prelu_:function(t,e){var n=dn(t,"x","prelu"),r=dn(e,"alpha","prelu");return Bt.runKernelFunc((function(t,e){var a=t.prelu(n,r);return e([n,r]),a}),{x:n,alpha:r},(function(t,e){var n=e[0],r=e[1],a=n.greater(0);return{x:function(){return Yu(a,t,t.mul(r))},alpha:function(){var e=Yu(a,Hn(t),t.mul(n)),i=Fr(r.shape,t.shape);return i.length>0&&(e=e.sum(i)),e.reshape(r.shape)}}}),"Prelu")}}),Fc=In({relu_:function(t){var e=dn(t,"x","relu");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((function(t,n){var r=t.relu(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mulStrict(n.step().toFloat())}}}),"Relu")}}),Mc=In({relu6_:function(t){var e=dn(t,"x","relu6");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),zc=In({selu_:function(t){var e=dn(t,"x","selu");return Bt.runKernelFunc((function(t,n){var r=t.selu(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){var e=n.greater(On(0)),r=On(1.7580993408473768),a=On(1.0507009873554805),i=t.mul(a),o=t.mul(r).mul(n.toFloat().exp());return Yu(e,i,o)}}}))}}),Lc=In({localResponseNormalization_:function(t,e,n,r,a){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===a&&(a=.5);var i=dn(t,"x","localResponseNormalization");I(4===i.rank||3===i.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+i.rank+"."})),I(O(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));var u=Bt.runKernelFunc((function(t,i){var s=t.localResponseNormalization4D(o,e,n,r,a);return i([o,s]),s}),{x4D:o},(function(t,i){var o=i[0],s=i[1];return{x4D:function(){return Bt.runKernelFunc((function(i){return i.LRNGrad(t,o,s,e,n,r,a)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Bc=In({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var a=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(On(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=dn(t,"x","norm"),e,n),i=a.shape;if(r){var o=B(n,t.shape);i=bn(a.shape,o)}return a.reshape(i)}}),Pc=In({basicLSTMCell_:function(t,e,n,r,a,i){var o=dn(t,"forgetBias","basicLSTMCell"),s=dn(e,"lstmKernel","basicLSTMCell"),u=dn(n,"lstmBias","basicLSTMCell"),l=dn(r,"data","basicLSTMCell"),c=dn(a,"c","basicLSTMCell"),p=dn(i,"h","basicLSTMCell"),h=l.concat(p,1).matMul(s).add(u),f=h.shape[0],d=h.shape[1]/4,m=[f,d],g=h.slice([0,0],m),v=h.slice([0,d],m),y=h.slice([0,2*d],m),b=h.slice([0,3*d],m),x=g.sigmoid().mulStrict(v.tanh()).addStrict(c.mulStrict(o.add(y).sigmoid())),w=x.tanh().mulStrict(b.sigmoid());return[x,w]}}),Wc=In({multiRNNCell_:function(t,e,n,r){for(var a=dn(e,"data","multiRNNCell"),i=mn(n,"c","multiRNNCell"),o=mn(r,"h","multiRNNCell"),s=a,u=[],l=0;l<t.length;l++){var c=t[l](s,i[l],o[l]);u.push(c[0]),u.push(c[1]),s=c[1]}var p=[],h=[];for(l=0;l<u.length;l+=2)p.push(u[l]),h.push(u[l+1]);return[p,h]}}),Vc=In({movingAverage_:function(t,e,n,r,a){void 0===a&&(a=!0);var i=dn(t,"v","movingAverage"),o=dn(e,"x","movingAverage"),s=dn(n,"decay","movingAverage");Ot(i,o),I(D(i.shape,o.shape),(function(){return"Shape mismatch in v and x"}));var u=On(1),l=u.sub(s),c=o.sub(i).mul(l);if(a){I(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var p=dn(r,"step","movingAverage");c=c.div(u.sub(Aa(s,p)))}return i.add(c)}}),Uc=In({stridedSlice_:function(t,e,n,r,a,i,o,s,u){if(void 0===a&&(a=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==o)throw new Error("ellipsis mask is not yet supported");var l=dn(t,"x","stridedSlice"),c=Ua(s),p=l.shape.slice();c.forEach((function(t){e[t]=0,n[t]=1,p.splice(t,0,1)})),l=l.reshape(p);for(var h=0;h<l.rank;h++)e[h]=Ga(a,e,r,l.shape,h),n[h]=qa(i,n,r,l.shape,h),r[h]=r[h]||1;var f=Ua(u);f.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var d=ja(e,n,r),m=d.filter((function(t,e){return-1===f.indexOf(e)}));return r.every((function(t){return 1===t}))?dc(l,e,d).reshape(m):Bt.runKernelFunc((function(t){return t.stridedSlice(l,e,n,r)}),{$x:l}).reshape(m)}}),jc=In({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=dn(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var a=r.shape[r.shape.length-1];if(e>a)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+e);var i=Bt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:i[0],indices:i[1]}}}),Gc=In({scatterND_:function(t,e,n){var r=dn(t,"indices","scatterND","int32"),a=dn(e,"updates","scatterND");return Ba(a,r,n),Bt.runKernelFunc((function(t){return t.scatterND(r,a,n)}),{indices:r,updates:a},null,"ScatterNd",{shape:n})}}),qc=In({fft_:function(t){I("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),Hc=In({ifft_:function(t){I("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),Kc=In({rfft_:function(t,e){I("float32"===t.dtype,(function(){return"The dtype for rfft() must be real value but got "+t.dtype}));var n,r=t.shape[t.shape.length-1],a=t.size/r;if(null!=e&&e<r){var i=t.shape.map((function(t){return 0})),o=t.shape.map((function(t){return t}));o[t.shape.length-1]=e,n=t.slice(i,o),r=e}else if(null!=e&&e>r){var s=t.shape.map((function(t){return t}));s[t.shape.length-1]=e-r,n=t.concat(Vn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=En(n,u).as2D(a,r),c=qc(l),p=Math.floor(r/2)+1,h=An(c),f=Tn(c),d=h.split([p,r-p],h.shape.length-1),m=f.split([p,r-p],f.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=p,En(d[0],m[0]).reshape(g)}}),Xc=In({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),a=Hc(r);return An(a)}var i=[n,2*(e-1)],o=An(t).as2D(n,e),s=Tn(t).as2D(n,e),u=o.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(On(-1)),c=o.concat(u,1),p=s.concat(l,1);return r=En(c,p).as2D(i[0],i[1]),a=Hc(r),An(a)}}),Yc=Object.freeze({fft:qc,ifft:Hc,rfft:Kc,irfft:Xc}),Jc=In({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var a=dn(t,"sparseIndices","sparseToDense","int32"),i=dn(e,"sparseValues","sparseToDense"),o=dn(r,"defaultValue","sparseToDense",i.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var a=t.rank>0?t.shape[0]:1,i=t.rank>1?t.shape[1]:1;if(n.length!==i)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+i+".");var o=e.size;if(0!==e.rank&&(1!==e.rank||o!==a))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+a+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,i,n,o),Bt.runKernelFunc((function(t){return t.sparseToDense(a,i,n,o)}),{$sparseIndices:a,$sparseValues:i,$defaultValue:o})}}),$c=In({gatherND_:function(t,e){var n=dn(e,"indices","gatherND","int32"),r=dn(t,"x","gatherND");return Bt.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}}),Zc=In({diag_:function(t){var e=dn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Bt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}}),Qc=In({dropout_:function(t,e,n,r){var a=dn(t,"x","dropout");if(I("float32"===a.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+a.dtype+" tensor instead."})),I(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof wt?a.clone():a;var i=function(t,e){if(null==e)return t.shape.slice();if(D(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(a,n),o=1-e,s=vl(i,0,1,"float32",r).add(o).floor().div(o);return a.mul(s)}});function tp(t,e,n){for(var r=1-t%2,a=new Float32Array(t),i=0;i<t;++i){var o=2*Math.PI*i/(t+r-1);a[i]=e-n*Math.cos(o)}return _n(a,"float32")}var ep,np=In({hannWindow_:function(t){return tp(t,.5,.5)}}),rp=In({hammingWindow_:function(t){return tp(t,.54,.46)}}),ap=In({frame_:function(t,e,n,r,a){void 0===r&&(r=!1),void 0===a&&(a=0);for(var i=0,o=[];i+e<=t.size;)o.push(dc(t,i,e)),i+=n;if(r)for(;i<t.size;){var s=i+e-t.size,u=Kn([dc(t,i,e-s),Un([s],a)]);o.push(u),i+=n}return 0===o.length?Fn([],[0,e]):Kn(o).as2D(o.length,e)}}),ip=In({stft_:function(t,e,n,r,a){var i;void 0===a&&(a=np),null==r&&(i=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(i)/Math.log(2)))));for(var o=ap(t,e,n),s=Ia(o,a(e)),u=[],l=0;l<o.shape[0];l++)u.push(Kc(s.slice([l,0],[1,e]),r));return Kn(u)}}),op=Object.freeze({hannWindow:np,hammingWindow:rp,frame:ap,stft:ip}),sp=function(t,e,n){return void 0===n&&(n=1),o(this,void 0,void 0,(function(){var r,a,i,o,u,l,c,p,h,f,d,m,g,v;return s(this,(function(s){switch(s.label){case 0:return r=dn(t,"predictions","inTopK"),a=dn(e,"targets","inTopK"),I(r.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),I(r.rank-1===a.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank})),E(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=r.shape[r.shape.length-1],I(n>0&&n<=i,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+n})),[4,r.data()];case 1:return o=s.sent(),[4,a.data()];case 2:for(u=s.sent(),l=[o.length/i,i],p=l[1],h=W("bool",c=l[0]),f=0;f<c;f++){for(d=f*p,m=o.subarray(d,d+p),g=[],v=0;v<m.length;v++)g.push({value:m[v],index:v});for(g.sort((function(t,e){return e.value-t.value})),h[f]=0,v=0;v<n;v++)if(g[v].index===u[f]){h[f]=1;break}}return t!==r&&r.dispose(),e!==a&&a.dispose(),[2,Rn(h,a.shape,"bool")]}}))}))};!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(ep||(ep={}));var up=In({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=ep.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","absoluteDifference"),i=dn(e,"predictions","absoluteDifference"),o=null;null!=n&&(o=dn(n,"weights","absoluteDifference")),E(a.shape,i.shape,"Error in absoluteDifference: ");var s=a.sub(i).abs();return lp(s,o,r)}}),lp=In({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=ep.SUM_BY_NONZERO_WEIGHTS);var r=dn(t,"losses","computeWeightedLoss"),a=null;null!=e&&(a=dn(e,"weights","computeWeightedLoss"));var i=null==a?r:r.mul(a);if(n===ep.NONE)return i;if(n===ep.SUM)return i.sum();if(n===ep.MEAN){if(null==a)return i.mean();var o=r.size/a.size,s=i.sum().div(a.sum());return o>1?s.div(On(o)):s}if(n===ep.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(On(r.size));var u=a.mul(Wn(r.shape)).notEqual(On(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),cp=In({cosineDistance_:function(t,e,n,r,a){void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","cosineDistance"),o=dn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=dn(r,"weights","cosineDistance")),E(i.shape,o.shape,"Error in cosineDistance: ");var u=On(1).sub(i.mul(o).sum(n,!0));return lp(u,s,a)}}),pp=In({hingeLoss_:function(t,e,n,r){void 0===r&&(r=ep.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","hingeLoss"),i=dn(e,"predictions","hingeLoss"),o=null;null!=n&&(o=dn(n,"weights","hingeLoss")),E(a.shape,i.shape,"Error in hingeLoss: ");var s=On(1);a=On(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return lp(u,o,r)}}),hp=In({huberLoss_:function(t,e,n,r,a){void 0===r&&(r=1),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","huberLoss"),o=dn(e,"predictions","huberLoss"),s=null;null!=n&&(s=dn(n,"weights","huberLoss")),E(i.shape,o.shape,"Error in huberLoss: ");var u=On(r),l=o.sub(i).abs(),c=Ca(l,u),p=l.sub(c),h=On(.5).mul(c.square()).add(u.mul(p));return lp(h,s,a)}}),fp=In({logLoss_:function(t,e,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","logLoss"),o=dn(e,"predictions","logLoss"),s=null;null!=n&&(s=dn(n,"weights","logLoss")),E(i.shape,o.shape,"Error in logLoss: ");var u=On(1),l=On(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return lp(c,s,a)}}),dp=In({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=ep.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","meanSquaredError"),i=dn(e,"predictions","meanSquaredError"),o=null;null!=n&&(o=dn(n,"weights","meanSquaredError")),E(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return lp(s,o,r)}}),mp=In({sigmoidCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"multiClassLabels","sigmoidCrossEntropy"),o=dn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","sigmoidCrossEntropy")),E(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=On(r),l=On(1),c=On(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var p=function(t,e){var n=dn(t,"labels","sigmoidCrossEntropyWithLogits"),r=dn(e,"logits","sigmoidCrossEntropyWithLogits");E(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 lp(p,s,a)}}),gp=In({softmaxCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"onehotLabels","softmaxCrossEntropy"),o=dn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","softmaxCrossEntropy")),E(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=On(r),l=On(1),c=On(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var p=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return ti((function(t,e,r){var a=e.logSumExp([n],!0),i=e.toFloat().sub(a);return r([t,i]),{value:i.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],a=e[1],i=bn(t.shape,[n]);return[t.reshape(i).mul(r.toFloat().sub(a.exp())),t.reshape(i).mul(a.exp().sub(r.toFloat()))]}}}))(t,e)}(i,o);return lp(p,s,a)}}),vp=Object.freeze({get Reduction(){return ep},absoluteDifference:up,computeWeightedLoss:lp,cosineDistance:cp,hingeLoss:pp,huberLoss:hp,logLoss:fp,meanSquaredError:dp,sigmoidCrossEntropy:mp,softmaxCrossEntropy:gp});function yp(t,e){return void 0===e&&(e=!1),Bt.tidy((function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],a=Qu(n),i=t.clone(),o=Fn([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(t){var e,u=i,l=s,c=a;e=Bt.tidy((function(){var e=i.slice([t,t],[n-t,1]),u=e.norm(),l=i.slice([t,t],[1,1]),c=Fn([[-1]]).where(l.greater(0),Fn([[1]])),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?o.clone():o.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=i.slice([t,0],[n-t,r]),m=f.mul(s),g=s.transpose();if(0===t)i=d.sub(m.matMul(g.matMul(d)));else{var v=d.sub(m.matMul(g.matMul(d)));i=i.slice([0,0],[t,r]).concat(v,0)}var y=m.transpose(),b=a.slice([0,t],[n,a.shape[1]-t]);if(0===t)a=b.sub(b.matMul(s).matMul(y));else{var x=b.sub(b.matMul(s).matMul(y));a=a.slice([0,0],[n,t]).concat(x,1)}return[s,i,a]})),s=e[0],i=e[1],a=e[2],Ze([u,l,c])},c=0;c<u;++c)l(c);return!e&&n>r&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]}))}var bp=In({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=dn(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var a=r.shape,i=r.shape.slice(-2),o=i[0],s=i[1];if(!(e<=o))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+o+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=o),n<0&&(n=s);var u=Gn(0,o,1,"int32").reshape([-1,1]),l=Gn(0,s,1,"int32"),c=Da(u,l),p=qu(c.lessEqual(On(+e,"int32")),c.greaterEqual(On(-n,"int32"))),h=Vn([o,s],r.dtype);return lr(cr(r.reshape([-1,o,s])).map((function(t){return Yu(p,t,h)}))).reshape(a)}}),xp=In({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,I(null!=t&&t.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var n=t[0].shape[0],r=function(e){I(t[e].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"}))},a=1;a<t.length;++a)r(a)}else e=!0,t=Zn(t,t.shape[0],0).map((function(t){return ur(t,[0])}));I(t.length<=t[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."}));var i=[],o=t,s=function(t){i.push(Bt.tidy((function(){var e=o[t];if(t>0)for(var n=0;n<t;++n){var r=Tc(i[n].mulStrict(e)).mul(i[n]);e=e.sub(r)}return e.div(Bc(e,"euclidean"))})))};for(a=0;a<t.length;++a)s(a);return e?lr(i,0):i}}),wp=In({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return yp(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=cr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),a=[],i=[];return r.forEach((function(t){var n=yp(t,e),r=n[0],o=n[1];a.push(r),i.push(o)})),[lr(a,0).reshape(t.shape),lr(i,0).reshape(t.shape)]}}),Cp=Object.freeze({bandPart:bp,gramSchmidt:xp,qr:wp});function Np(t,e,n,r,a,i){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==i&&(i=0);var o=t.shape[0];return n=Math.min(n,o),I(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),I(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),I(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),I(1===e.rank,(function(){return"scores must be a 1D tensor"})),I(e.shape[0]===o,(function(){return"scores has incompatible shape with boxes. Expected "+o+", but was "+e.shape[0]})),I(0<=i&&i<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+i+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:i}}var Sp=In({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeBilinear");I(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));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=e[0],s=e[1],u=Bt.runKernelFunc((function(t,e){return e([a]),t.resizeBilinear(a,o,s,n)}),{x:a},(function(t,e){return{x:function(){return Bt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:o,newWidth:s});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),kp=In({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeNearestNeighbor");I(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),I("float32"===r.dtype||"int32"===r.dtype,(function(){return"`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=e[0],s=e[1],u=Bt.runKernelFunc((function(t,e){return e([a]),t.resizeNearestNeighbor(a,o,s,n)}),{batchImages:a},(function(t,e){return{batchImages:function(){return Bt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ip=In({nonMaxSuppression_:function(t,e,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=dn(t,"boxes","nonMaxSuppression"),o=dn(e,"scores","nonMaxSuppression"),s=Np(i,o,n,r,a);n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:a};return Bt.runKernelFunc((function(t){return t.nonMaxSuppression(i,o,n,r,a)}),{boxes:i,scores:o},null,"NonMaxSuppressionV3",u)}}),Ep=In({nonMaxSuppressionWithScore_:function(t,e,n,r,a,i){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===i&&(i=0);var o=dn(t,"boxes","nonMaxSuppression"),s=dn(e,"scores","nonMaxSuppression"),u=Np(o,s,n,r,a,i),l={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:i=u.softNmsSigma},c=Bt.runKernel("NonMaxSuppressionV5",{boxes:o,scores:s},l);return{selectedIndices:c[0],selectedScores:c[1]}}}),Ap=In({cropAndResize_:function(t,e,n,r,a,i){var o=dn(t,"image","cropAndResize"),s=dn(e,"boxes","cropAndResize","float32"),u=dn(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return I(4===o.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."})),I(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."})),I(1===u.rank&&u.shape[0]===l,(function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."})),I(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),I(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),I("bilinear"===a||"nearest"===a,(function(){return"method must be bilinear or nearest, but was "+a})),Bt.runKernelFunc((function(t,e){return t.cropAndResize(o,s,u,r,a,i)}),{images:o,boxes:s,boxInd:u},null,"CropAndResize",{method:a,extrapolationValue:i,cropSize:r})}}),Tp=Object.freeze({resizeBilinear:Sp,resizeNearestNeighbor:kp,nonMaxSuppression:Ip,nonMaxSuppressionAsync:function(t,e,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),o(this,void 0,void 0,(function(){var i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return i=dn(t,"boxes","nonMaxSuppressionAsync"),o=dn(e,"scores","nonMaxSuppressionAsync"),u=Np(i,o,n,r,a),n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,[4,Promise.all([i.data(),o.data()])];case 1:return l=s.sent(),c=l[0],p=l[1],h=Ri(c,p,n,r,a),i!==t&&i.dispose(),o!==e&&o.dispose(),[2,h]}}))}))},nonMaxSuppressionWithScore:Ep,nonMaxSuppressionWithScoreAsync:function(t,e,n,r,a,i){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===i&&(i=0),o(this,void 0,void 0,(function(){var o,u,l,c,p,h,f;return s(this,(function(s){switch(s.label){case 0:return o=dn(t,"boxes","nonMaxSuppressionAsync"),u=dn(e,"scores","nonMaxSuppressionAsync"),l=Np(o,u,n,r,a,i),n=l.maxOutputSize,r=l.iouThreshold,a=l.scoreThreshold,i=l.softNmsSigma,[4,Promise.all([o.data(),u.data()])];case 1:return c=s.sent(),p=c[0],h=c[1],f=Di(p,h,n,r,a,i),o!==t&&o.dispose(),u!==e&&u.dispose(),[2,f]}}))}))},cropAndResize:Ap}),Rp=function(t,e){return!(t>0)||"linear"===e},Dp=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},Op=function(t,e){var n=e,r=Fr(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},_p=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Fc(t);if("elu"===e)return Dc(t);if("relu6"===e)return Mc(t);if("prelu"===e)return _c(t,n);throw new Error("Unknown fused activation "+e+".")},Fp=In({fusedMatMul_:function(t){var e,n=t.a,r=t.b,a=t.transposeA,i=void 0!==a&&a,o=t.transposeB,s=void 0!==o&&o,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights;if(!1===Rp(Bt.state.gradientDepth,c)){var h=Zl(n,r,i,s);return null!=u&&(h=Or(h,u)),_p(h,c,p)}var f=dn(n,"a","fused matMul"),d=dn(r,"b","fused matMul");e=Dt(f,d),f=e[0],d=e[1];var m=i?f.shape[f.rank-2]:f.shape[f.rank-1],g=s?d.shape[d.rank-1]:d.shape[d.rank-2],v=i?f.shape[f.rank-1]:f.shape[f.rank-2],y=s?d.shape[d.rank-2]:d.shape[d.rank-1],b=f.shape.slice(0,-2),x=d.shape.slice(0,-2),w=R(b),C=R(x);I(f.rank>=2&&d.rank>=2&&f.rank===d.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+f.rank+" and "+d.rank+"."})),I(D(b,x),(function(){return"Error in fused matMul: outer dimensions ("+b+") and ("+x+") of Tensors with shapes "+f.shape+" and "+d.shape+" must match."})),I(m===g,(function(){return"Error in fused matMul: inner shapes ("+m+") and ("+g+") of Tensors with shapes "+f.shape+" and "+d.shape+" and transposeA="+i+" and transposeB="+s+" must match."}));var N,S,k=f.shape.slice(0,-2).concat([v,y]),E=i?f.as3D(w,m,v):f.as3D(w,v,m),A=s?d.as3D(C,y,g):d.as3D(C,g,y);null!=u&&Mr(k,(N=Dt(N=dn(u,"bias","fused matMul"),f)[0]).shape),null!=p&&(S=dn(p,"prelu weights","fused matMul"));var T={a:E,b:A};null!=u&&(T.bias=N),null!=p&&(T.preluActivationWeights=S);var O=[E,A];return Bt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:E,b:A,transposeA:i,transposeB:s,bias:N,activation:c,preluActivationWeights:S});return e([E,A,n]),n}),T,(function(t,e){var n=e[0],r=e[1],a=e[2],o=Dp(t,a,c),l={};return null!=u&&(l={bias:function(){return Op(N,o)}}),i||s?!i&&s?Object.assign({a:function(){return o.matMul(r,!1,!1)},b:function(){return o.matMul(n,!0,!1)}},l):i&&!s?Object.assign({a:function(){return r.matMul(o,!1,!0)},b:function(){return n.matMul(o,!1,!1)}},l):Object.assign({a:function(){return r.matMul(o,!0,!0)},b:function(){return o.matMul(n,!0,!0)}},l):Object.assign({a:function(){return o.matMul(r,!1,!0)},b:function(){return n.matMul(o,!0,!1)}},l)}),"_FusedMatMul",{transposeA:i,transposeB:s,activation:c},O,[!0]).reshape(k)}}),Mp=In({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,i=t.dataFormat,o=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,f=t.preluActivationWeights;if(h=h||"linear",!1===Rp(Bt.state.gradientDepth,h)){var d=Ul(e,n,r,a,o,u,l);return null!=c&&(d=Or(d,c)),_p(d,h,f)}var m=dn(e,"x","conv2d"),g=dn(n,"filter","conv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),I(4===v.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."})),I(4===g.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."})),null!=l&&I(O(a),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+a+"."})),I(v.shape[3]===g.shape[2],(function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+g.shape[2]+"."})),I(yi(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),I("NHWC"===o,(function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported."}));var b,x,w=ci(v.shape,g.shape,r,u,a,l);null!=c&&(b=Dt(b=dn(c,"bias","fused conv2d"),m)[0],Mr(w.outShape,b.shape)),null!=f&&(x=dn(f,"prelu weights","fused conv2d"));var C={x:v,filter:g};null!=c&&(C.bias=b),null!=f&&(C.preluActivationWeights=x);var N=[g,v],S=Bt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:v,filter:g,convInfo:w,bias:b,activation:h,preluActivationWeights:x});return e([g,v,n]),n}),C,(function(t,e){var n=e,i=n[0],o=n[1],s=n[2],l=Dp(t,s,h);I(vi(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var p={};return null!=c&&(p={bias:function(){return Op(b,l)}}),Object.assign({x:function(){return ql(o.shape,l,i,r,a)},filter:function(){return Gl(o,l,i.shape,r,a)}},p)}),"FusedConv2D",{convInfo:w,activation:h},N,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),zp=In({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,i=t.dataFormat,o=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,f=t.preluActivationWeights;if(!1===Rp(Bt.state.gradientDepth,h)){var d=Hl(e,n,r,a,o,u,l);return null!=c&&(d=Or(d,c)),_p(d,h,f)}var m=dn(e,"x","depthwiseConv2d"),g=dn(n,"filter","depthwiseConv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),I(4===v.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+v.rank+"."})),I(4===g.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+g.rank+"."})),I(v.shape[3]===g.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+v.shape[3]+") must match the inChannels dimension in filter "+g.shape[2]+"."})),null==u&&(u=[1,1]),I(yi(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=l&&I(O(a),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+l+" but got pad "+a+"."}));var b,x,w=ci(v.shape,g.shape,r,u,a,l,!0);null!=c&&(b=Dt(b=dn(c,"bias","fused conv2d"),m)[0],Mr(w.outShape,b.shape)),null!=f&&(x=dn(f,"prelu weights","fused depthwiseConv2d"));var C={x:v,filter:g};null!=c&&(C.bias=b),null!=f&&(C.preluActivationWeights=x);var N=[g,v],S=Bt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:v,filter:g,convInfo:w,bias:b,activation:h,preluActivationWeights:x});return e([g,v,n]),n}),C,(function(t,e){I(vi(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],a=e[2],i=Dp(t,a,h),o={};return null!=c&&(o={bias:function(){return Op(b,i)}}),Object.assign({x:function(){return Kl(r.shape,i,n,w)},filter:function(){return Xl(r,i,n.shape,w)}},o)}),"FusedDepthwiseConv2D",{convInfo:w,activation:h},N,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),Lp=Object.freeze({matMul:Fp,conv2d:Mp,depthwiseConv2d:zp}),Bp=Object.freeze({image:Tp,linalg:Cp,losses:vp,spectral:Yc,fused:Lp,signal:op,add:Or,addN:Eu,batchNorm:_u,batchNormalization:Ou,batchNorm2d:zu,batchNormalization2d:Mu,batchNorm3d:Pu,batchNormalization3d:Bu,batchNorm4d:Uu,batchNormalization4d:Vu,broadcastTo:ju,clone:Gu,div:_a,divNoNan:$u,eye:Qu,multinomial:tl,oneHot:el,pad:nl,pad1d:rl,pad2d:al,pad3d:il,pad4d:ol,rand:sl,randomGamma:ml,randomNormal:gl,randomUniform:vl,square:yl,squaredDifference:bl,tile:Zu,truncatedNormal:xl,conv1d:Vl,conv2d:Ul,conv3d:jl,depthwiseConv2d:Hl,separableConv2d:Yl,conv2dTranspose:Jl,conv3dTranspose:$l,op:In,booleanMaskAsync:Ll,complex:En,real:An,imag:Tn,concat:Kn,concat1d:Xn,concat2d:Yn,concat3d:Jn,concat4d:$n,split:Zn,matMul:Zl,dot:Ql,outerProduct:tc,reverse:ec,reverse1d:nc,reverse2d:rc,reverse3d:ac,reverse4d:ic,maxPool:uc,avgPool:lc,pool:cc,maxPool3d:pc,avgPool3d:hc,maxPoolWithArgmax:fc,slice:dc,slice1d:mc,slice2d:gc,slice3d:vc,slice4d:yc,abs:zr,acos:Lr,acosh:Br,asin:Pr,asinh:Wr,atan:Vr,atanh:Ur,ceil:jr,clipByValue:Gr,cos:qr,cosh:Hr,erf:Kr,exp:Xr,expm1:Yr,floor:Jr,log:$r,log1p:Zr,logSigmoid:Qr,neg:ta,reciprocal:ea,round:na,rsqrt:ra,sigmoid:aa,sign:ia,isNaN:oa,isInf:sa,isFinite:ua,sin:la,sinh:ca,softplus:pa,sqrt:ha,step:fa,tan:da,tanh:ma,all:xc,any:wc,argMax:Cc,argMin:Nc,logSumExp:Sc,max:kc,mean:Ic,min:Ec,moments:Ac,sum:Tc,prod:Rc,equal:wl,equalStrict:Cl,greater:Nl,greaterEqual:Sl,greaterEqualStrict:kl,greaterStrict:Il,less:El,lessEqual:Al,lessEqualStrict:Tl,lessStrict:Rl,notEqual:Dl,notEqualStrict:Ol,addStrict:ga,atan2:va,divStrict:ya,floorDiv:ba,maximum:xa,maximumStrict:wa,minimum:Ca,minimumStrict:Na,mod:Sa,modStrict:ka,mul:Ia,mulStrict:Ea,pow:Aa,powStrict:Ta,squaredDifferenceStrict:Ra,sub:Da,subStrict:Oa,elu:Dc,leakyRelu:Oc,prelu:_c,relu:Fc,relu6:Mc,selu:zc,logicalAnd:qu,logicalNot:Hu,logicalOr:Ku,logicalXor:Xu,where:Yu,whereAsync:Ju,buffer:Qn,print:tr,batchToSpaceND:er,cast:nr,cumsum:rr,depthToSpace:ar,expandDims:ir,reshape:or,spaceToBatchND:sr,squeeze:ur,stack:lr,unstack:cr,setdiff1dAsync:pr,fill:Un,linspace:jn,ones:Wn,range:Gn,scalar:On,tensor:Rn,tensor1d:_n,tensor2d:Fn,tensor3d:Mn,tensor4d:zn,tensor5d:Ln,tensor6d:Bn,variable:Pn,zeros:Vn,onesLike:qn,zerosLike:Hn,transpose:ai,softmax:ni,logSoftmax:ri,localResponseNormalization:Lc,norm:Bc,gather:Ml,unsortedSegmentSum:zl,basicLSTMCell:Pc,multiRNNCell:Wc,movingAverage:Vc,stridedSlice:Uc,topk:jc,scatterND:Gc,fft:qc,ifft:Hc,rfft:Kc,irfft:Xc,sparseToDense:Jc,gatherND:$c,diag:Zc,dropout:Qc,hannWindow:np,hammingWindow:rp,frame:ap,stft:ip,inTopKAsync:sp});function Pp(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&I("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function Wp(t,e,n,r,a,i){for(var o=a.strideHeight,s=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,p=a.effectiveFilterWidth,h=a.padInfo.top,f=a.padInfo.left,d="max"===i?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Qn(a.outShape,n),g=m.values,v=a.outShape[1]*a.outShape[2]*a.outShape[3],y=a.outShape[2]*a.outShape[3],b=a.outShape[3],x=0;x<a.batchSize;++x)for(var w=x*v,C=x*r[0],N=0;N<a.inChannels;++N)for(var S=0;S<a.outHeight;++S)for(var k=S*o-h,I=Math.max(0,k),E=Math.min(a.inHeight,c+k),A=w+S*y,T=0;T<a.outWidth;++T){for(var R=T*s-f,D=Math.max(0,R),O=Math.min(a.inWidth,p+R),_=d,F=0,M=0,z=I;z<E;z+=u){for(var L=C+z*r[1],B=D;B<O;B+=l){var P=t[L+B*r[2]+N];"max"===i&&P>_?_=P:"avg"===i&&(F+=P,M++)}if(isNaN(_))break}g[A+T*b+N]="avg"===i?F/M:_}return m}function Vp(t,e,n,r,a,i){void 0===a&&(a=!1),void 0===i&&(i=!1);for(var o=Qn(r.outShape,"int32"),s=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterHeight,h=r.effectiveFilterWidth,f=r.padInfo.top,d=r.padInfo.left,m=Qn(e,n,t),g=0;g<r.batchSize;++g)for(var v=0;v<r.inChannels;++v)for(var y=0;y<r.outHeight;++y){for(var b=y*s-f,x=b;x<0;)x+=l;for(var w=Math.min(r.inHeight,p+b),C=0;C<r.outWidth;++C){for(var N=C*u-d,S=N;S<0;)S+=c;for(var k=Math.min(r.inWidth,h+N),I=Number.NEGATIVE_INFINITY,E=-1,A=x;A<w;A+=l)for(var T=A-b,R=S;R<k;R+=c){var D=R-N,O=m.get(g,A,R,v);O>I&&(I=O,E=a?i?((g*r.inHeight+A)*r.inWidth+R)*r.inChannels+v:(A*r.inWidth+R)*r.inChannels+v:T*h+D)}o.set(E,g,y,C,v)}}return o}function Up(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var jp=function(t){function e(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new ii(e,Bt),e}return i(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,c().get("IS_NODE")&&pn("\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============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},e.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},e.prototype.numDataIds=function(){return this.data.numDataIds()},e.prototype.read=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){return[2,this.readSync(t)]}))}))},e.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Si(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},e.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map((function(t){return ut(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qn(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Bt.makeTensorFromDataId(r,e,n,this)},e.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},e.prototype.time=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){return e=it(),t(),[2,{kernelMs:it()-e}]}))}))},e.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},e.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Bt.keep(t.clone()),imag:Bt.keep(e.clone())},n},e.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(Pp(t,"slice"),Ha(t.shape,e,n)){var r=Ka(e,t.strides),a=R(n);return Rn(this.readSync(t.dataId).subarray(r,r+a),n,t.dtype)}for(var i=Qn(n,t.dtype),o=this.bufferSync(t),s=0;s<i.size;++s){var u=i.indexToLoc(s).map((function(t,n){return t+e[n]}));i.values[s]=o.get.apply(o,u)}return i.toTensor()},e.prototype.stridedSlice=function(t,e,n,r){Pp(t,"stridedSlice");var a=ja(e,n,r);if(a.some((function(t){return 0===t})))return Rn([],a);for(var i=Qn(a,t.dtype),o=this.bufferSync(t),s=0;s<i.size;s++){for(var u=i.indexToLoc(s),l=new Array(u.length),c=0;c<l.length;c++)l[c]=u[c]*r[c]+e[c];i.set.apply(i,[o.get.apply(o,l)].concat(u))}return i.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=Qn([t.size,t.size],t.dtype),r=n.values,a=0;a<e.length;a++)r[a*t.size+a]=e[a];return n.toTensor()},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),a=0,i=0;i<t.rank;i++)i!==e&&(r[a++]=t.shape[i]);var o=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(i=0;i<u.length;i++)o[e]=i,u[i]=this.slice(t,o,s).reshape(r);return u},e.prototype.reverse=function(t,e){Pp(t,"reverse");for(var n=Qn(t.shape,t.dtype),r=this.bufferSync(t),a=function(a){var i=n.indexToLoc(a),o=i.slice();e.forEach((function(e){return o[e]=t.shape[e]-1-o[e]})),n.set.apply(n,[r.get.apply(r,o)].concat(i))},i=0;i<n.size;i++)a(i);return n.toTensor()},e.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map((function(t){return An(t)})),a=t.map((function(t){return Tn(t)}));return En(this.concat(r,e),this.concat(a,e))}var i=t.map((function(t){var n=R(t.shape.slice(e));return t.as2D(-1,n)})),o=kn(i.map((function(t){return t.shape})),1),s=Qn(o,t[0].dtype).values;if(1===i[0].shape[0]){var u=0;i.forEach((function(t){s.set(n.readSync(t.dataId),u),u+=t.size}))}else{var l=0;i.forEach((function(t){for(var e=n.readSync(t.dataId),r=0,a=0;a<t.shape[0];++a)for(var i=a*o[1]+l,u=0;u<t.shape[1];++u)s[i+u]=e[r++];l+=t.shape[1]}))}var c=kn(t.map((function(t){return t.shape})),e);return Rn(s,c,t[0].dtype)},e.prototype.neg=function(t){return Pp(t,"neg"),this.multiply(On(-1),t)},e.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t+n,imag:e+r}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t+e}))},e.prototype.addN=function(t){var e=this;Pp(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=Qn(t[0].shape,t[0].dtype),a=r.values,i=0;i<t.length;i++)for(var o=n[i],s=0;s<a.length;s++)a[s]+=o[s];return r.toTensor()},e.prototype.softmax=function(t,e){var n=B([e],t.shape),r=this.max(t,n),a=bn(r.shape,n),i=this.subtract(t,r.reshape(a)),o=this.exp(i),s=this.sum(o,n).reshape(a);return _a(o,s)},e.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t-n,imag:e-r}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t-e}))},e.prototype.pow=function(t,e){return Pp([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.pow(t,e)}))},e.prototype.batchMatMul=function(t,e,n,r){Pp([t,e],"matMul");for(var a=n?t.shape[1]:t.shape[2],i=n?t.shape[2]:t.shape[1],o=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],p=c[0],h=c[1],f=c[2],d=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],m=d[0],g=d[1],v=d[2],y=i*o,b=Qn([s,i,o],t.dtype),x=b.values,w=this.blockSize,C=0;C<s;C++)for(var N=0;N<i;N+=w)for(var S=0;S<o;S+=w)for(var k=0;k<a;k+=w)for(var I=Math.min(N+w,i),E=Math.min(S+w,o),A=Math.min(k+w,a),T=N;T<I;T++)for(var R=S;R<E;R++){for(var D=0,O=k;O<A;O++)D+=u[C*p+T*h+O*f]*l[O*m+R*g+C*v];x[C*y+(T*o+R)]+=D}return b.toTensor()},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,a=t.transposeB,i=t.bias,o=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,a);return i&&(u=this.add(u,i)),o&&(u=Up(this,u,o,s)),u},e.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t*e}))},e.prototype.floorDiv=function(t,e){return Pp([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},e.prototype.sum=function(t,e){Pp(t,"sum"),xn("sum",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,Tt(t.dtype,"int32")),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=0,h=0;h<o;++h)p+=u[c+h];s[l]=p}return i},e.prototype.prod=function(t,e){Pp(t,"sum");for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,Tt(t.dtype,"int32")),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=1,h=0;h<o;++h)p*=u[c+h];s[l]=p}return i},e.prototype.unsortedSegmentSum=function(t,e,n){Pp(t,"unsortedSegmentSum");for(var r=[],a=t.rank-e.rank,i=0;i<a;++i)e=e.expandDims(i+1);for(i=0;i<n;++i){var o=On(i,"int32"),s=wl(o,e).asType("float32").mul(t).sum(0);r.push(s)}return lr(r)},e.prototype.argMin=function(t,e){Pp(t,"argMin");var n=[e];xn("argMin",n,t.rank);for(var r=yn(t.shape,n),a=r[0],i=r[1],o=Vn(a,"int32"),s=R(i),u=this.readSync(o.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var m=l[p+d];m<h&&(h=m,f=d)}u[c]=f}return o},e.prototype.argMax=function(t,e){Pp(t,"argMax");var n=[e];xn("argMax",n,t.rank);for(var r=yn(t.shape,n),a=r[0],i=r[1],o=Vn(a,"int32"),s=R(i),u=this.readSync(o.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var m=l[p+d];m>h&&(h=m,f=d)}u[c]=f}return o},e.prototype.cumsum=function(t,e,n,r){if(Pp(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var a=Tt(t.dtype,"int32"),i=Vn(t.shape,a),o=this.readSync(i.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;c<s.length;c+=u)for(var p=0;p<u;p++){var h=l(c,p);if(0===p)o[h]=n?0:s[h];else{var f=l(c,p-1);o[h]=n?s[f]+o[f]:s[h]+o[f]}}return i},e.prototype.equal=function(t,e){return Pp([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},e.prototype.notEqual=function(t,e){return Pp([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},e.prototype.less=function(t,e){return Pp([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},e.prototype.lessEqual=function(t,e){return Pp([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},e.prototype.greater=function(t,e){return Pp([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},e.prototype.greaterEqual=function(t,e){return Pp([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},e.prototype.logicalNot=function(t){Pp(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return this.makeOutput(n,t.shape,"bool")},e.prototype.logicalAnd=function(t,e){return Pp([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},e.prototype.logicalOr=function(t,e){return Pp([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},e.prototype.select=function(t,e,n){Pp([t,e,n],"select");for(var r=this.readSync(t.dataId),a=this.readSync(e.dataId),i=this.readSync(n.dataId),o=Vn(e.shape,Tt(e.dtype,n.dtype)),s=this.readSync(o.dataId),u=0,l=0===t.rank||t.rank>1||1===e.rank?1:R(e.shape.slice(1)),c=0;c<r.length;c++)for(var p=0;p<l;p++)1===r[c]?s[u++]=a[c]:s[u++]=i[c];return o},e.prototype.where=function(t){Pp([t],"where");var e=this.readSync(t.dataId);return Pi(t.shape,e)},e.prototype.topk=function(t,e,n){return Pp(t,"topk"),Bi(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){Pp(t,"min"),xn("min",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];f<p&&(p=f)}s[l]=p}return i},e.prototype.minimum=function(t,e){return Pp([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},e.prototype.mod=function(t,e){return Pp([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e}))},e.prototype.max=function(t,e){Pp(t,"max"),xn("max",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];f>p&&(p=f)}s[l]=p}return i},e.prototype.maximum=function(t,e){return Pp([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},e.prototype.all=function(t,e){Pp(t,"all"),xn("all",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];p=p&&f}s[l]=p}return i},e.prototype.any=function(t,e){Pp(t,"any"),xn("any",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];p=p||f}s[l]=p}return i},e.prototype.squaredDifference=function(t,e){return Pp([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},e.prototype.ceil=function(t){Pp(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.floor=function(t){Pp(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.sign=function(t){Pp(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){Pp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isInf=function(t){Pp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isFinite=function(t){Pp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.round=function(t){Pp(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=Math.floor(e[r]);e[r]-a<.5?n[r]=Math.floor(e[r]):e[r]-a>.5?n[r]=Math.ceil(e[r]):n[r]=a%2==0?a:a+1}return this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){Pp(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.expm1=function(t){Pp(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.log=function(t){Pp(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.log(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.log1p=function(t){Pp(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.log1p(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.sqrt=function(t){Pp(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=Math.sqrt(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.rsqrt=function(t){Pp(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var a=e[r];n[r]=1/Math.sqrt(a)}return this.makeOutput(n,t.shape,"float32")},e.prototype.reciprocal=function(t){Pp(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return this.makeOutput(n,t.shape,"float32")},e.prototype.linear=function(t){return t},e.prototype.relu=function(t){Pp(t,"relu");for(var e=Vn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),a=0;a<r.length;++a)n[a]=Math.max(0,r[a]);return e},e.prototype.relu6=function(t){Pp(t,"relu");for(var e=Vn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),a=0;a<r.length;++a)n[a]=Math.min(Math.max(0,r[a]),6);return e},e.prototype.prelu=function(t,e){return Pp([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},e.prototype.elu=function(t){Pp(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=n[r];e[r]=a>=0?a:Math.exp(a)-1}return this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){Pp([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),a=this.readSync(t.dataId),i=0;i<r.length;++i){var o=r[i];n[i]=o>=1?a[i]:a[i]*(o+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){Pp(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=n[r];e[r]=a>=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return this.makeOutput(e,t.shape,"float32")},e.prototype.clip=function(t,e,n){Pp(t,"clip");for(var r=new Float32Array(t.size),a=this.readSync(t.dataId),i=0;i<a.length;++i){var o=a[i];r[i]=o>n?n:o<e?e:o}return this.makeOutput(r,t.shape,"float32")},e.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var a=n[2*r],i=n[2*r+1];e[r]=Math.hypot(a,i)}return this.makeOutput(e,t.shape,"float32")},e.prototype.int=function(t){Pp(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return this.makeOutput(e,t.shape,"int32")},e.prototype.sigmoid=function(t){Pp(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(e,t.shape,"float32")},e.prototype.softplus=function(t){Pp(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),a=0;a<r.length;++a){var i,o=r[a]>-e,s=r[a]<e,u=Math.exp(r[a]);i=s?u:o?r[a]:Math.log(1+u),n[a]=i}return this.makeOutput(n,t.shape,"float32")},e.prototype.sin=function(t){Pp(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cos=function(t){Pp(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tan=function(t){Pp(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asin=function(t){Pp(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acos=function(t){Pp(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan=function(t){Pp(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan2=function(t,e){return Pp([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},e.prototype.sinh=function(t){Pp(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cosh=function(t){Pp(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tanh=function(t){Pp(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=_(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asinh=function(t){Pp(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acosh=function(t){Pp(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atanh=function(t){Pp(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.erf=function(t){Pp(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var a=Math.sign(n[r]),i=Math.abs(n[r]),o=1/(1+.3275911*i);e[r]=a*(1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-i*i))}return this.makeOutput(e,t.shape,"float32")},e.prototype.step=function(t,e){void 0===e&&(e=0),Pp(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];isNaN(i)?n[a]=NaN:n[a]=i>0?1:e}return this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,i=t.activation,o=t.preluActivationWeights,s=this.conv2d(e,n,r);return a&&(s=this.add(s,a)),i&&(s=Up(this,s,i,o)),s},e.prototype.conv2d=function(t,e,n){Pp([t,e],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Qn(n.outShape,t.dtype),p=t.strides[0],h=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],m=c.strides[0],g=l?c.strides[1]:c.strides[2],v=l?c.strides[2]:1,y=l?1:c.strides[1],b=this.readSync(t.dataId),x=this.readSync(e.dataId),w=c.values,C=0;C<n.batchSize;++C)for(var N=C*p,S=C*m,k=0;k<n.outHeight;++k)for(var I=S+k*g,E=k*n.strideHeight-u,A=0;A<r;A++){var T=E+A*i;if(!(T<0||T>=n.inHeight))for(var R=A*e.strides[0],D=N+T*h,O=0;O<n.outWidth;++O)for(var _=I+O*v,F=O*n.strideWidth-s,M=0;M<a;M++){var z=F+M*o;if(!(z<0||z>=n.inWidth))for(var L=D+z*f,B=R+M*e.strides[1],P=0;P<n.inChannels;++P){for(var W=b[L+P*d],V=0;V<n.outChannels;++V)w[_+V*y]+=W*x[B+V];B+=n.outChannels}}}return c.toTensor()},e.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,a=n.filterHeight,i=n.filterWidth,o=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,l=n.padInfo.front,c=n.padInfo.left,p=n.padInfo.top,h=Qn(n.outShape,t.dtype),f=this.readSync(t.dataId),d=this.readSync(e.dataId),m=h.values,g=0;g<n.batchSize;++g)for(var v=g*t.strides[0],y=g*h.strides[0],b=0;b<n.outDepth;++b)for(var x=y+b*h.strides[1],w=b*n.strideDepth-l,C=0;C<r;C++){var N=w+C*o;if(!(N<0||N>=n.inDepth))for(var S=C*e.strides[0],k=v+N*t.strides[1],I=0;I<n.outHeight;++I)for(var E=x+I*h.strides[2],A=I*n.strideHeight-p,T=0;T<a;T++){var R=A+T*s;if(!(R<0||R>=n.inHeight))for(var D=S+T*e.strides[1],O=k+R*t.strides[2],_=0;_<n.outWidth;++_)for(var F=E+_*n.outChannels,M=_*n.strideWidth-c,z=0;z<i;z++){var L=M+z*u;if(!(L<0||L>=n.inWidth))for(var B=D+z*e.strides[2],P=O+L*n.inChannels,W=B,V=0;V<n.inChannels;++V){for(var U=f[P+V],j=0;j<n.outChannels;++j)m[F+j]+=U*d[W+j];W+=n.outChannels}}}}return h.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){Pp([t,e],"conv2dDerInput");for(var r=Qn(n.inShape,"float32"),a=r.values,i=this.readSync(t.dataId),o=this.readSync(e.dataId),s=e.strides,u=s[0],l=s[1],c=s[2],p=n.batchSize,h=n.filterHeight,f=n.filterWidth,d=n.inChannels,m=n.inHeight,g=n.inWidth,v=n.outChannels,y=n.outHeight,b=n.outWidth,x=n.strideHeight,w=n.strideWidth,C=n.dataFormat,N=h-1-n.padInfo.top,S=f-1-n.padInfo.left,k="channelsLast"===C,I=r.strides[0],E=k?r.strides[1]:r.strides[2],A=k?r.strides[2]:1,T=k?1:r.strides[1],R=t.strides[0],D=k?t.strides[1]:t.strides[2],O=k?t.strides[2]:1,_=k?1:t.strides[1],F=0;F<p;++F)for(var M=0;M<d;++M)for(var z=0;z<m;++z)for(var L=z-N,B=Math.max(0,Math.ceil(L/x)),P=Math.min(y,(h+L)/x),W=0;W<g;++W){for(var V=W-S,U=Math.max(0,Math.ceil(V/w)),j=Math.min(b,(f+V)/w),G=0,q=B;q<P;++q)for(var H=q*x-L,K=U;K<j;++K)for(var X=R*F+D*q+O*K,Y=u*(h-1-H)+l*(f-1-(K*w-V))+c*M,J=0;J<v;++J)G+=i[X+_*J]*o[Y+J];a[I*F+E*z+A*W+T*M]=G}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=Qn(n.inShape,"float32"),a=r.values,i=r.strides,o=i[0],s=i[1],u=i[2],l=i[3],c=this.readSync(t.dataId),p=t.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=this.readSync(e.dataId),v=e.strides,y=v[0],b=v[1],x=v[2],w=v[3],C=n.batchSize,N=n.filterDepth,S=n.filterHeight,k=n.filterWidth,I=n.inChannels,E=n.inDepth,A=n.inHeight,T=n.inWidth,R=n.outChannels,D=n.outDepth,O=n.outHeight,_=n.outWidth,F=n.strideDepth,M=n.strideHeight,z=n.strideWidth,L=N-1-n.padInfo.front,B=S-1-n.padInfo.top,P=k-1-n.padInfo.left,W=0;W<C;++W)for(var V=0;V<I;++V)for(var U=0;U<E;++U)for(var j=U-L,G=Math.max(0,Math.ceil(j/F)),q=Math.min(D,(N+j)/F),H=0;H<A;++H)for(var K=H-B,X=Math.max(0,Math.ceil(K/M)),Y=Math.min(O,(S+K)/M),J=0;J<T;++J){for(var $=J-P,Z=Math.max(0,Math.ceil($/z)),Q=Math.min(_,(k+$)/z),tt=0,et=G;et<q;++et)for(var nt=et*F-j,rt=X;rt<Y;++rt)for(var at=rt*M-K,it=Z;it<Q;++it)for(var ot=h*W+f*et+d*rt+m*it,st=y*(N-1-nt)+b*(S-1-at)+x*(k-1-(it*z-$))+w*V,ut=0;ut<R;++ut)tt+=c[ot+ut]*g[st+ut];a[o*W+s*U+u*H+l*J+V]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){Pp([t,e],"conv2dDerFilter");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s="channelsLast"===n.dataFormat,u=Qn(n.filterShape,"float32"),l=n.padInfo.left,c=n.padInfo.top,p=this.bufferSync(t),h=this.bufferSync(e),f=0;f<i;++f)for(var d=Math.max(0,Math.ceil((c-f)/r)),m=Math.min(n.outHeight,(n.inHeight+c-f)/r),g=0;g<o;++g)for(var v=Math.max(0,Math.ceil((l-g)/a)),y=Math.min(n.outWidth,(n.inWidth+l-g)/a),b=0;b<n.inChannels;++b)for(var x=0;x<n.outChannels;++x){for(var w=0,C=0;C<n.batchSize;++C)for(var N=d;N<m;++N)for(var S=f+N*r-c,k=v;k<y;++k){var I=g+k*a-l;w+=s?p.get(C,S,I,b)*h.get(C,N,k,x):p.get(C,b,S,I)*h.get(C,x,N,k)}u.set(w,f,g,b,x)}return u.toTensor()},e.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,a=n.strideHeight,i=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=Qn(n.filterShape,"float32"),c=l.values,p=l.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=this.readSync(e.dataId),v=e.strides,y=v[0],b=v[1],x=v[2],w=v[3],C=this.readSync(t.dataId),N=t.strides,S=N[0],k=N[1],I=N[2],E=N[3],A=n.padInfo.front,T=n.padInfo.left,R=n.padInfo.top,D=0;D<o;++D)for(var O=Math.max(0,Math.ceil((A-D)/r)),_=Math.min(n.outDepth,(n.inDepth+A-D)/r),F=D*h,M=0;M<s;++M)for(var z=Math.max(0,Math.ceil((R-M)/a)),L=Math.min(n.outHeight,(n.inHeight+R-M)/a),B=M*f+F,P=0;P<u;++P)for(var W=Math.max(0,Math.ceil((T-P)/i)),V=Math.min(n.outWidth,(n.inWidth+T-P)/i),U=P*d+B,j=0;j<n.inChannels;++j)for(var G=j*m+U,q=0;q<n.outChannels;++q){for(var H=0,K=0;K<n.batchSize;++K)for(var X=K*S,Y=K*y,J=O;J<_;++J)for(var $=(D+J*r-A)*k+X,Z=J*b+Y,Q=z;Q<L;++Q)for(var tt=(M+Q*a-R)*I+$,et=Q*x+Z,nt=W;nt<V;++nt){var rt=nt*w+et;H+=C[(P+nt*i-T)*E+tt+j]*g[rt+q]}c[G+q]=H}return l.toTensor()},e.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,i=t.activation,o=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return a&&(s=this.add(s,a)),i&&(s=Up(this,s,i,o)),s},e.prototype.depthwiseConv2D=function(t,e,n){Pp([t,e],"depthwiseConv2D");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=n.outChannels/n.inChannels,c=Qn(n.outShape,t.dtype),p=this.readSync(t.dataId),h=this.readSync(e.dataId),f=c.values,d=0;d<n.batchSize;++d)for(var m=d*t.strides[0],g=d*c.strides[0],v=0;v<n.outHeight;++v)for(var y=g+v*c.strides[1],b=v*n.strideHeight-s,x=0;x<r;++x){var w=b+x*i;if(!(w<0||w>=n.inHeight))for(var C=x*e.strides[0],N=m+w*t.strides[1],S=0;S<n.outWidth;++S)for(var k=y+S*c.strides[2],I=S*n.strideWidth-u,E=0;E<a;++E){var A=I+E*o;if(!(A<0||A>=n.inWidth))for(var T=C+E*e.strides[1],R=N+A*n.inChannels,D=k,O=T,_=0;_<n.inChannels;++_){for(var F=p[R+_],M=0;M<l;++M)f[D+M]+=F*h[O+M];D+=l,O+=l}}}return c.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){Pp([t,e],"depthwiseConv2DDerInput");for(var r=Qn(n.inShape,"float32"),a=r.values,i=r.strides,o=i[0],s=i[1],u=i[2],l=this.readSync(t.dataId),c=t.strides,p=c[0],h=c[1],f=c[2],d=this.readSync(e.dataId),m=e.strides,g=m[0],v=m[1],y=m[2],b=n.batchSize,x=n.filterHeight,w=n.filterWidth,C=n.inChannels,N=n.inHeight,S=n.inWidth,k=n.outChannels,I=n.outHeight,E=n.outWidth,A=n.strideHeight,T=n.strideWidth,R=x-1-n.padInfo.top,D=w-1-n.padInfo.left,O=k/C,_=0;_<b;++_)for(var F=0;F<C;++F)for(var M=0;M<N;++M)for(var z=M-R,L=Math.max(0,Math.ceil(z/A)),B=Math.min(I,(x+z)/A),P=0;P<S;++P){for(var W=P-D,V=Math.max(0,Math.ceil(W/T)),U=Math.min(E,(w+W)/T),j=0,G=L;G<B;++G)for(var q=G*A-z,H=V;H<U;++H)for(var K=p*_+h*G+f*H,X=g*(x-1-q)+v*(w-1-(H*T-W))+y*F,Y=0;Y<O;++Y)j+=l[K+(F*O+Y)]*d[X+Y];a[o*_+s*M+u*P+F]=j}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){Pp([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=Qn(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=n.outChannels/n.inChannels,p=this.bufferSync(t),h=this.bufferSync(e),f=0;f<i;++f)for(var d=Math.max(0,Math.ceil((l-f)/r)),m=Math.min(n.outHeight,(n.inHeight+l-f)/r),g=0;g<o;++g)for(var v=Math.max(0,Math.ceil((u-g)/a)),y=Math.min(n.outWidth,(n.inWidth+u-g)/a),b=0;b<n.outChannels;++b){for(var x=Math.trunc(b/c),w=b%c,C=0,N=0;N<n.batchSize;++N)for(var S=d;S<m;++S)for(var k=f+S*r-l,I=v;I<y;++I){var E=g+I*a-u;C+=p.get(N,k,E,x)*h.get(N,S,I,b)}s.set(C,f,g,x,w)}return s.toTensor()},e.prototype.tile=function(t,e){return Pp(t,"tile"),Li(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){Pp(t,"pad");var r=e.map((function(e,n){return e[0]+t.shape[n]+e[1]})),a=e.map((function(t){return t[0]})),i=this.bufferSync(t),o=Qn(r,t.dtype);0!==n&&o.values.fill(n);for(var s=0;s<t.size;s++){var u=i.indexToLoc(s),l=u.map((function(t,e){return t+a[e]}));o.set.apply(o,[i.get.apply(i,u)].concat(l))}return o.toTensor()},e.prototype.gather=function(t,e,n){Pp([t,e],"gather");var r=t.shape.slice(),a=this.readSync(e.dataId);r[n]=a.length;for(var i=Qn(r,t.dtype),o=this.bufferSync(t),s=0;s<i.size;++s){var u=i.indexToLoc(s),l=u.slice();l[n]=a[u[n]];var c=o.locToIndex(l);i.values[s]=o.values[c]}return i.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){Pp([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),a=hr(t.shape,e,r),i=fr(a.length,e.length),o=dr(t.shape,e,r),s=mr(n,e.length),u=gr(o,n,e.length);return ai(t.reshape(a),i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){Pp([t],"spaceToBatchND");var r=e.reduce((function(t,e){return t*e})),a=[[0,0]];a.push.apply(a,n);for(var i=1+e.length;i<t.shape.length;++i)a.push([0,0]);var o=t.pad(a),s=hr(o.shape,e,r,!1),u=fr(s.length,e.length,!1),l=dr(o.shape,e,r,!1);return ai(o.reshape(s),u).reshape(l)},e.prototype.maxPool=function(t,e){return Pp(t,"maxPool"),Wp(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"max").toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){Pp([e,n],"maxPoolBackprop");for(var a=this.readSync(e.dataId),i=Qn(r.outShape,e.dtype,Vp(a,e.shape,e.dtype,r).values),o=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,l=r.dilationWidth,c=r.effectiveFilterHeight,p=r.effectiveFilterWidth,h=p-1-r.padInfo.left,f=c-1-r.padInfo.top,d=Qn(e.shape,"float32"),m=this.bufferSync(t),g=0;g<r.batchSize;++g)for(var v=0;v<r.inChannels;++v)for(var y=0;y<r.inHeight;++y)for(var b=0;b<r.inWidth;++b){for(var x=y-f,w=b-h,C=0,N=0;N<c;N+=u){var S=(x+N)/o;if(!(S<0||S>=r.outHeight||Math.floor(S)!==S))for(var k=0;k<p;k+=l){var I=(w+k)/s;if(!(I<0||I>=r.outWidth||Math.floor(I)!==I)){var E=c*p-1-i.get(g,S,I,v)===N*p+k?1:0;0!==E&&(C+=m.get(g,S,I,v)*E)}}}d.set(C,g,y,b,v)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){Pp([t,e],"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,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Qn(e.shape,"float32"),d=1/(i*o),m=this.bufferSync(t),g=0;g<n.batchSize;++g)for(var v=0;v<n.inChannels;++v)for(var y=0;y<n.inHeight;++y)for(var b=0;b<n.inWidth;++b){for(var x=y-h,w=b-p,C=0,N=0;N<l;N+=s){var S=(x+N)/r;if(!(S<0||S>=n.outHeight||Math.floor(S)!==S))for(var k=0;k<c;k+=u){var I=(w+k)/a;I<0||I>=n.outWidth||Math.floor(I)!==I||(C+=m.get(g,S,I,v))}}f.set(C*d,g,y,b,v)}return f.toTensor()},e.prototype.pool3d=function(t,e,n){Pp(t,"pool3d");for(var r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),v=Qn(e.outShape,t.dtype),y=v.values,b=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],x=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],N=0;N<e.batchSize;++N)for(var S=N*b,k=N*t.strides[0],I=0;I<e.inChannels;++I)for(var E=0;E<e.outDepth;++E){for(var A=E*r-h,T=A;T<0;)T+=o;for(var R=Math.min(e.inDepth,l+A),D=S+E*x,O=0;O<e.outHeight;++O){for(var _=O*a-f,F=_;F<0;)F+=s;for(var M=Math.min(e.inHeight,c+_),z=D+O*w,L=0;L<e.outWidth;++L){for(var B=L*i-d,P=B;P<0;)P+=u;for(var W=Math.min(e.inWidth,p+B),V=z+L*C,U=m,j=0,G=0,q=T;q<R;q+=o){for(var H=k+q*t.strides[1],K=F;K<M;K+=s){for(var X=H+K*t.strides[2],Y=P;Y<W;Y+=u){var J=g[X+Y*t.strides[3]+I];if("max"===n&&J>U?U=J:"avg"===n&&(j+=J,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[V+I]="avg"===n?j/G:U}}}return v.toTensor()},e.prototype.avgPool3d=function(t,e){return Pp(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){Pp([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,a=n.strideHeight,i=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=h-1-n.padInfo.front,g=d-1-n.padInfo.left,v=f-1-n.padInfo.top,y=Qn(e.shape,"float32"),b=1/(o*s*u),x=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var N=0;N<n.inDepth;++N)for(var S=0;S<n.inHeight;++S)for(var k=0;k<n.inWidth;++k){for(var I=N-m,E=S-v,A=k-g,T=0,R=0;R<h;R+=l){var D=(I+R)/r;if(!(D<0||D>=n.outDepth||Math.floor(D)!==D))for(var O=0;O<f;O+=c){var _=(E+O)/a;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var F=0;F<d;F+=p){var M=(A+F)/i;M<0||M>=n.outWidth||Math.floor(M)!==M||(T+=x.get(w,D,_,M,C))}}}y.set(T*b,w,N,S,k,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return Pp(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Qn(e.outShape,"int32"),r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m=this.bufferSync(t),g=0;g<e.batchSize;++g)for(var v=0;v<e.inChannels;++v)for(var y=0;y<e.outDepth;++y){for(var b=y*r-h,x=b;x<0;)x+=o;for(var w=Math.min(e.inDepth,l+b),C=0;C<e.outHeight;++C){for(var N=C*a-f,S=N;S<0;)S+=s;for(var k=Math.min(e.inHeight,c+N),I=0;I<e.outWidth;++I){for(var E=I*i-d,A=E;A<0;)A+=u;for(var T=Math.min(e.inWidth,p+E),R=Number.NEGATIVE_INFINITY,D=-1,O=x;O<w;O+=o)for(var _=O-b,F=S;F<k;F+=s)for(var M=F-N,z=A;z<T;z+=u){var L=z-E,B=m.get(g,O,F,z,v);B>=R&&(R=B,D=_*c*p+M*c+L)}n.set(D,g,y,C,I,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){Pp([e,n],"maxPool3dBackprop");for(var a=this.maxPool3dPositions(e,r),i=r.strideDepth,o=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=p-1-r.padInfo.front,m=f-1-r.padInfo.left,g=h-1-r.padInfo.top,v=Qn(e.shape,"float32"),y=this.bufferSync(a),b=this.bufferSync(t),x=0;x<r.batchSize;++x)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var N=0;N<r.inHeight;++N)for(var S=0;S<r.inWidth;++S){for(var k=C-d,I=N-g,E=S-m,A=0,T=0;T<p;T+=u){var R=(k+T)/i;if(!(R<0||R>=r.outDepth||Math.floor(R)!==R))for(var D=0;D<h;D+=l){var O=(I+D)/o;if(!(O<0||O>=r.outHeight||Math.floor(O)!==O))for(var _=0;_<f;_+=c){var F=(E+_)/s;if(!(F<0||F>=r.outWidth||Math.floor(F)!==F)){var M=p*h*f-1-y.get(x,R,O,F,w)===T*h*f+D*f+_?1:0;0!==M&&(A+=b.get(x,R,O,F,w)*M)}}}}v.set(A,x,C,N,S,w)}return v.toTensor()},e.prototype.cast=function(t,e){return xi(t,e,this)},e.prototype.reshape=function(t,e){return wi(t,e)},e.prototype.avgPool=function(t,e){return Pp(t,"avgPool"),Pp(t,"maxPool"),Wp(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"avg").toTensor().toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){Pp(t,"resizeBilinear");for(var a=t.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=this.readSync(t.dataId),c=new Float32Array(R([i,e,n,u])),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g<i;g++)for(var v=0;v<e;v++)for(var y=d*v,b=Math.floor(y),x=y-b,w=Math.min(o-1,Math.ceil(y)),C=g*t.strides[0]+b*t.strides[1],N=g*t.strides[0]+w*t.strides[1],S=0;S<n;S++)for(var k=m*S,I=Math.floor(k),E=k-I,A=Math.min(s-1,Math.ceil(k)),T=C+I*t.strides[2],D=N+I*t.strides[2],O=C+A*t.strides[2],_=N+A*t.strides[2],F=0;F<u;F++){var M=l[T+F],z=l[D+F],L=M+(l[O+F]-M)*E,B=L+(z+(l[_+F]-z)*E-L)*x;c[f++]=B}return Rn(c,[i,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){Pp([t,e],"resizeBilinearBackprop");for(var r=e.shape,a=r[0],i=r[1],o=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(a*i*o*s),h=[n&&l>1?i-1:i,n&&c>1?o-1:o],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=this.readSync(t.dataId),v=0,y=0;y<a;y++)for(var b=y*e.strides[0],x=0;x<l;x++)for(var w=x*d,C=Math.floor(w),N=Math.min(Math.ceil(w),i-1),S=b+C*e.strides[1],k=b+N*e.strides[1],I=w-C,E=1-I,A=0;A<c;A++)for(var T=A*m,R=Math.floor(T),D=Math.min(Math.ceil(T),o-1),O=T-R,_=1-O,F=S+R*e.strides[2],M=S+D*e.strides[2],z=k+R*e.strides[2],L=k+D*e.strides[2],B=E*_,P=E*O,W=I*_,V=I*O,U=0;U<s;U++){var j=g[v++];p[F+U]+=j*B,p[M+U]+=j*P,p[z+U]+=j*W,p[L+U]+=j*V}return zn(p,[a,o,i,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){Pp(t,"resizeNearestNeighbor");for(var a=t.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=this.readSync(t.dataId),c=new Float32Array(i*e*n*u),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g<i;g++)for(var v=g*t.strides[0],y=0;y<e;y++)for(var b=f*y,x=v+Math.min(o-1,r?Math.round(b):Math.floor(b))*t.strides[1],w=0;w<n;w++)for(var C=d*w,N=x+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],S=0;S<u;S++){var k=l[N+S];c[m++]=k}return Rn(c,[i,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){Pp([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,a=r[0],i=r[1],o=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(a*i*o*s),h=this.readSync(t.dataId),f=[n&&l>1?i-1:i,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w<a;w++)for(var C=w*e.strides[0],N=0;N<i;N++)for(var S=C+N*e.strides[1],k=Math.floor(N*v),I=Math.floor(k-b/2),E=0;E<o;E++)for(var A=S+E*e.strides[2],T=Math.floor(E*y),R=Math.floor(T-x/2),D=0;D<s;D++){for(var O=0,_=0;_<b;_++){var F=_+I;if(!(F<0||F>=l)){var M=C+F*t.strides[1],z=F*m;if(N===Math.min(i-1,n?Math.round(z):Math.floor(z)))for(var L=0;L<x;L++){var B=L+R;if(!(B<0||B>=c)){var P=M+B*t.strides[2],W=B*g;E===Math.min(o-1,n?Math.round(W):Math.floor(W))&&(O+=h[P+D])}}}}p[A+D]=O}return zn(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,i){Pp([t,e,n,a,i],"batchNorm");for(var o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=a?this.readSync(a.dataId):new Float32Array([1]),c=i?this.readSync(i.dataId):new Float32Array([0]),p=new Float32Array(o.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x<o.length;++x)p[x]=c[g++]+(o[x]-s[v++])*l[y++]/Math.sqrt(u[b++]+r),g>=h&&(g=0),v>=m&&(v=0),y>=f&&(y=0),b>=d&&(b=0);return zn(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){Pp(t,"localResponseNormalization4D");var i=t.shape[3],o=i-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%i,r=t-n+Math.max(0,n-e),a=t-n+Math.min(n+e,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var p=0;p<u;p++){var h=c(p),f=s[p]*Math.pow(n+r*h,-a);l[p]=f}return zn(l,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,a,i,o){Pp(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=this.readSync(n.dataId),p=new Float32Array(t.size),h=t.size,f=0;f<h;f++){for(var d=f%s,m=f-d+Math.max(0,d-r),g=f-d+Math.min(s,d+r+1),v=0,y=m;y<g;y++)v+=Math.pow(l[y],2);for(v=i*v+a,y=m;y<g;y++){var b=-2*i*o*l[y]*c[f]/v;f===y&&(b+=Math.pow(v,-o)),b*=u[f],p[y]+=b}}return zn(p,t.shape)},e.prototype.multinomial=function(t,e,n,r){Pp(t,"multinomial");for(var a=e?t:ni(t),i=a.shape[0],o=a.shape[1],s=Vn([i,n],"int32"),u=this.readSync(s.dataId),l=this.readSync(a.dataId),c=0;c<i;++c){var p=c*o,h=new Float32Array(o-1);h[0]=l[p];for(var f=1;f<h.length;++f)h[f]=h[f-1]+l[p+f];for(var d=Iu(r.toString()),m=c*n,g=0;g<n;++g){var v=d();u[m+g]=h.length;for(var y=0;y<h.length;y++)if(v<h[y]){u[m+g]=y;break}}}return s},e.prototype.oneHot=function(t,e,n,r){Pp(t,"oneHot");var a=new Float32Array(t.size*e);a.fill(r);for(var i=this.readSync(t.dataId),o=0;o<t.size;++o)i[o]>=0&&i[o]<e&&(a[o*e+i[o]]=n);return Fn(a,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,a){return Pp(t,"nonMaxSuppression"),Ri(this.readSync(t.dataId),this.readSync(e.dataId),n,r,a)},e.prototype.fft=function(t){return this.fftBatch(t,!1)},e.prototype.ifft=function(t){return this.fftBatch(t,!0)},e.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],a=Qn(t.shape,"float32"),i=Qn(t.shape,"float32"),o=An(t).as2D(n,r),s=Tn(t).as2D(n,r),u=0;u<n;u++)for(var l=o.slice([u,0],[1,r]),c=s.slice([u,0],[1,r]),p=En(l,c),h=this.readSync(this.fftImpl(p,e).dataId),f=0;f<r;f++){var d=ki(h,f);a.values[u*r+f]=d.real,i.values[u*r+f]=d.imag}return En(a.toTensor(),i.toTensor()).as2D(n,r)},e.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var a=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(a=En(An(a).div(On(r)),Tn(a).div(On(r)))),a}var i=this.readSync(t.dataId),o=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(i,r,e));return En(o.real,o.imag).as2D(t.shape[0],t.shape[1])},e.prototype.isExponentOf2=function(t){return 0==(t&t-1)},e.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),a=e/2,i=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),a=0;a<t.length;a+=4)n[Math.floor(a/4)]=t[a],r[Math.floor(a/4)]=t[a+1];return{real:n,imag:r}}(r),o=En(i.real,i.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),a=2;a<t.length;a+=4)n[Math.floor(a/4)]=t[a],r[Math.floor(a/4)]=t[a+1];return{real:n,imag:r}}(r),u=En(s.real,s.imag).as1D();o=this.fftRadix2(o,a,n),u=this.fftRadix2(u,a,n);var l=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),a=0;a<Math.ceil(t/2);a++){var i=(e?2:-2)*Math.PI*(a/t);n[a]=Math.cos(i),r[a]=Math.sin(i)}return{real:n,imag:r}}(e,n),c=En(l.real,l.imag).mul(u),p=o.add(c),h=o.sub(c),f=An(p).concat(An(h)),d=Tn(p).concat(Tn(h));return En(f,d).as1D()},e.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),a=0;a<e;a++){for(var i=0,o=0,s=0;s<e;s++){var u=Ei(a*s,e,n),l=ki(t,s);i+=l.real*u.real-l.imag*u.imag,o+=l.real*u.imag+l.imag*u.real}n&&(i/=e,o/=e),Ii(r,i,o,a)}return r},e.prototype.depthToSpace=function(t,e,n){I("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),I(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],a=t.shape[1],i=t.shape[2],o=t.shape[3],s=a*e,u=i*e,l=o/(e*e),c=this.readSync(t.dataId),p=new Float32Array(r*s*u*l),h=0,f=0;f<r;++f)for(var d=0;d<s;++d)for(var m=Math.floor(d/e),g=d%e,v=0;v<u;++v)for(var y=Math.floor(v/e),b=(g*e+v%e)*l,x=0;x<l;++x){var w=x+b+o*(y+i*(m+a*f));p[h++]=c[w]}return zn(p,[r,s,u,l])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var a=Mr(t.shape,e.shape),i=Qn(a,n),o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=_r(t.shape,a),l=_r(e.shape,a),c=i.values;if(u.length+l.length===0)for(var p=0;p<c.length;++p)c[p]=r(o[p%o.length],s[p%s.length]);else{var h=this.bufferSync(t),f=this.bufferSync(e),d=function(n){var a=i.indexToLoc(n),p=a.slice(-t.rank);u.forEach((function(t){return p[t]=0}));var d=h.locToIndex(p),m=a.slice(-e.rank);l.forEach((function(t){return m[t]=0}));var g=f.locToIndex(m);c[n]=r(o[d],s[g])};for(p=0;p<c.length;++p)d(p)}return i.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Mr(t.shape,e.shape),a=Qn(r,"float32"),i=Qn(r,"float32"),o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=_r(t.shape,r),l=_r(e.shape,r),c=a.values,p=i.values;if(u.length+l.length===0)for(var h=0;h<c.length;h++){var f=h%o.length,d=h%s.length,m=n(o[2*f],o[2*f+1],s[2*d],s[2*d+1]);c[h]=m.real,p[h]=m.imag}else{var g=this.bufferSync(this.data.get(t.dataId).complexTensors.real),v=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var i=a.indexToLoc(r),h=i.slice(-t.rank);u.forEach((function(t){return h[t]=0}));var f=g.locToIndex(h),d=i.slice(-e.rank);l.forEach((function(t){return d[t]=0}));var m=v.locToIndex(d),y=n(o[2*f],o[2*f+1],s[2*m],s[2*m+1]);c[r]=y.real,p[r]=y.imag};for(h=0;h<c.length;h++)y(h)}return this.complex(a.toTensor(),i.toTensor())},e.prototype.split=function(t,e,n){return zi(t,e,n)},e.prototype.dispose=function(){},e.prototype.floatPrecision=function(){return 32},e.prototype.epsilon=function(){return 1e-7},e.prototype.cropAndResize=function(t,e,n,r,a,i){for(var o=t.shape,s=o[0],u=o[1],l=o[2],c=o[3],p=e.shape[0],h=r[0],f=r[1],d=Qn([p,h,f,c],"float32"),m=this.readSync(e.dataId),g=this.readSync(n.dataId),v=this.readSync(t.dataId),y=t.strides,b=d.strides,x=0;x<p;x++){var w=4*x,C=m[w],N=m[w+1],S=m[w+2],k=m[w+3],I=g[x];if(!(I>=s))for(var E=h>1?(S-C)*(u-1)/(h-1):0,A=f>1?(k-N)*(l-1)/(f-1):0,T=0;T<h;T++){var R=h>1?C*(u-1)+T*E:.5*(C+S)*(u-1);if(R<0||R>u-1)for(var D=0;D<f;D++)for(var O=0;O<c;O++){var _=O+D*b[2]+T*b[1]+x*b[0];d.values[_]=i}else if("bilinear"===a){var F=Math.floor(R),M=Math.ceil(R),z=R-F;for(D=0;D<f;D++)if((q=f>1?N*(l-1)+D*A:.5*(N+k)*(l-1))<0||q>l-1)for(O=0;O<c;O++)_=O+D*b[2]+T*b[1]+x*b[0],d.values[_]=i;else{var L=Math.floor(q),B=Math.ceil(q),P=q-L;for(O=0;O<c;O++){var W=v[_=O+L*y[2]+F*y[1]+I*y[0]],V=v[_=O+B*y[2]+F*y[1]+I*y[0]],U=v[_=O+L*y[2]+M*y[1]+I*y[0]],j=W+(V-W)*P,G=U+(v[_=O+B*y[2]+M*y[1]+I*y[0]]-U)*P;_=O+D*b[2]+T*b[1]+x*b[0],d.values[_]=j+(G-j)*z}}}else for(D=0;D<f;++D){var q;if((q=f>1?N*(l-1)+D*A:.5*(N+k)*(l-1))<0||q>l-1)for(O=0;O<c;O++)_=O+D*b[2]+T*b[1]+x*b[0],d.values[_]=i;else{var H=Math.round(q),K=Math.round(R);for(O=0;O<c;O++){var X=O+H*y[2]+K*y[1]+I*y[0],Y=O+D*b[2]+T*b[1]+x*b[0];d.values[Y]=v[X]}}}}}return d.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var a=Pa(0,t,n),i=a.sliceRank,o=a.numUpdates,s=a.sliceSize,u=a.strides,l=a.outputSize;return this.scatter(t,e,n,l,s,o,i,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],a=Fa(t,e),i=a[0],o=a[1],s=a[2],u=a[3];if(0===o)return Rn([],i,t.dtype);for(var l=new vt([o,s],t.dtype),c=this.readSync(e.dataId),p=this.readSync(t.dataId),h=0;h<o;h++){for(var f=[],d=0,m=0;m<r;m++){var g=c[h*r+m];d+=g*u[m],f.push(g)}if(d<0||d>=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var v=0;v<s;v++)l.values[h*s+v]=p[d*s+v]}return l.toTensor().reshape(i)},e.prototype.scatterND=function(t,e,n){var r=Pa(0,t,n),a=r.sliceRank,i=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=On(0);return this.scatter(t,e,n,u,o,i,a,s,l,!0)},e.prototype.fill=function(t,e,n){var r=V(n=n||$(e),R(t));return r.fill(e),Bt.makeTensor(r,t,n,this)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){var e=V(t.dtype,R(t.shape));return this.makeOutput(e,t.shape,t.dtype)},e.prototype.linspace=function(t,e,n){return Ci(t,e,n)},e.prototype.scatter=function(t,e,n,r,a,i,o,s,u,l){var c=[r/a,a],p=this.readSync(t.dataId),h=this.readSync(e.dataId);if(0===r)return Rn([],n,e.dtype);var f=new vt(c,e.dtype);f.values.fill(this.readSync(u.dataId)[0]);for(var d=0;d<i;d++){for(var m=[],g=0,v=0;v<o;v++){var y=p[d*o+v];m.push(y),g+=y*s[v]}if(g<0||g>=r/a)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b<a;b++)l?f.values[g*a+b]+=h[d*a+b]:f.values[g*a+b]=0===e.rank?h[0]:h[d*a+b]}return f.toTensor().reshape(n)},e}(oi);function Gp(t,e){return{kernelName:t,backendName:"cpu",kernelFunc:function(n){var r=n.inputs,a=n.backend,i=r,o=i.a,s=i.b,u=a;Pp([o,s],t);var l=u.data.get(o.dataId).values,c=u.data.get(s.dataId).values,p=e(o.shape,s.shape,l,c,o.dtype),h=p[0],f=p[1];return{dataId:u.write(h,f,o.dtype),shape:f,dtype:o.dtype}}}}function qp(t){return function(e,n,r,a,i){var o=Mr(e,n),s=o.length,u=tt(o),l=W(i,R(o)),c=e.length,p=n.length,h=tt(e),f=tt(n),d=_r(e,o),m=_r(n,o);if(d.length+m.length===0)for(var g=0;g<l.length;++g)l[g]=t(r[g%r.length],a[g%a.length]);else{var v=function(e){var n=ct(e,s,u),i=n.slice(-c);d.forEach((function(t){return i[t]=0}));var o=lt(i,c,h),g=n.slice(-p);m.forEach((function(t){return g[t]=0}));var v=lt(g,p,f);l[e]=t(r[o],a[v])};for(g=0;g<l.length;++g)v(g)}return[l,o]}}Bt.registerBackend("cpu",(function(){return new jp}),1);var Hp=qp((function(t,e){return t/e})),Kp=Gp(br,Hp),Xp={kernelName:"MaxPoolWithArgmax",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,a=e.x,i=n,o=i.filterSize,s=i.strides,u=i.pad,l=i.includeBatchInIndex,c=r;Pp(a,"MaxPoolWithArgmax");var p=c.data.get(a.dataId).values,h=ui(a.shape,o,s,[1,1],u),f=function(t,e,n,r,a){var i=Wp(t,0,n,tt(e),a,"max"),o=Vp(t,e,n,a,!0,r);return[i.values,o.values]}(p,a.shape,a.dtype,l,h),d=f[0],m=f[1],g=c.write(d,h.outShape,a.dtype),v=c.write(m,h.outShape,a.dtype);return[{dataId:g,shape:h.outShape,dtype:a.dtype},{dataId:v,shape:h.outShape,dtype:"int32"}]}},Yp={kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,a=e,i=a.boxes,o=a.scores,s=r,u=s.maxOutputSize,l=s.iouThreshold,c=s.scoreThreshold,p=s.softNmsSigma,h=n;Pp(i,"NonMaxSuppressionWithScore");var f=Di(h.data.get(i.dataId).values,h.data.get(o.dataId).values,u,l,c,p);return[f.selectedIndices,f.selectedScores]}},Jp={kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,a=n;Pp(r,"square");for(var i=a.data.get(r.dataId).values,o=new Float32Array(i.length),s=0;s<i.length;++s){var u=i[s];o[s]=u*u}return{dataId:a.write(o,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},$p=qp((function(t,e){var n=t-e;return n*n}));function Zp(t,e,n,r,a){for(var i=R(e),o=e.length,s=tt(e),u=tt(a),l=W(n,R(a)),c=0;c<i;++c){for(var p=ct(c,o,s),h=new Array(p.length),f=0;f<h.length;f++)h[f]=p[r[f]];l[lt(h,o,u)]=t[c]}return l}for(var Qp=0,th=[Yp,Jp,Gp(wr,$p),Kp,{kernelName:"Transpose",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,a=e.x,i=n.perm,o=r;Pp(a,"transpose");for(var s=a.shape.length,u=new Array(s),l=0;l<u.length;l++)u[l]=a.shape[i[l]];var c=Zp(o.data.get(a.dataId).values,a.shape,a.dtype,i,u);return{dataId:o.write(c,u,a.dtype),shape:u,dtype:a.dtype}}},Xp];Qp<th.length;Qp++)v(th[Qp]);for(var eh,nh=function(t){this.variableNames=["A"];var e=qi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},rh=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=qi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "},ah=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var a=ao(this.rank),i=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),a=0;a<t.length;a++)r[t[a]]=n[a];return r.join()}(e);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n "},ih=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var a=ao(this.rank),i=ji("rc",this.rank),o=new Array(this.rank);for(r=0;r<e.length;r++)o[e[r]]=i[r];var s="vec2("+o.slice(-2).join()+")",u="++"+i[this.rank-1]+" < "+n[this.rank-1],l="getChannel(getA("+o.join()+"), "+s+")";this.userCode="\n void main() {\n "+a+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = "+l+";\n if("+u+") {\n result[1] = "+l+";\n }\n --"+i[this.rank-1]+";\n if(++"+i[this.rank-2]+" < "+n[this.rank-2]+") {\n result[2] = "+l+";\n if("+u+") {\n result[3] = "+l+";\n }\n }\n setOutput(result);\n }\n "},oh=0,sh=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,a=e.pixels,i=r.numChannels,o="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,u=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],l=u[0],p=u[1],h=[p,l],f=[p,l,i];(s||o)&&(null==eh&&(eh=document.createElement("canvas").getContext("2d")),eh.canvas.width=l,eh.canvas.height=p,eh.drawImage(a,0,0,l,p),a=eh.canvas);var d=n.makeTensorInfo(h,"int32");n.texData.get(d.dataId).usage=Ut.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),a);var m=c().getBool("WEBGL_PACK")?new rh(f):new nh(f),g=n.runWebGLProgram(m,[d],"int32");return n.disposeData(d.dataId),g}},{kernelName:br,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e;return function(t,e,n){var r=new yo("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return c().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&(r=new xo("\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",t.shape,e.shape,!0)),n.runWebGLProgram(r,[t,e],"float32")}(r.a,r.b,n)}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;pn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var a=e,i=a.boxes,o=a.scores,s=r,u=s.maxOutputSize,l=s.iouThreshold,c=s.scoreThreshold,p=s.softNmsSigma,h=n,f=Di(h.readSync(i.dataId),h.readSync(o.dataId),u,l,c,p);return[f.selectedIndices,f.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,a=n,i=new Zs(r.shape,"return x * x;");return a.runWebGLProgram(i,[r],r.dtype)}},{kernelName:wr,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,a=r.a,i=r.b,o=n,s=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("return (a - b) * (a - b);",a.shape,i.shape):new yo("return (a - b) * (a - b);",a.shape,i.shape);return o.compileAndRun(s,[a,i])}},{kernelName:"Transpose",backendName:"webgl",kernelFunc:function(t){for(var e,n=t.inputs,r=t.attrs,a=t.backend,i=n.x,o=r.perm,s=a,u=i.shape.length,l=new Array(u),p=0;p<l.length;p++)l[p]=i.shape[o[p]];if(s.shouldExecuteOnCPU([i])){var h=Zp(s.texData.get(i.dataId).values,i.shape,i.dtype,o,l);e=s.makeTensorInfo(l,i.dtype),s.texData.get(e.dataId).values=h}else e=function(t,e,n){var r=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ih(t.shape,e):new ah(t.shape,e);return n.runWebGLProgram(r,[t],t.dtype)}(i,o,s);return e}},{kernelName:"MaxPoolWithArgmax",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,a=e.x,i=n,o=i.filterSize,s=i.strides,u=i.pad,l=i.includeBatchInIndex,c=r;I(4===a.shape.length,(function(){return"Error in maxPool: input must be rank 4 but got rank "+a.shape.length+"."}));var p=[1,1];I(yi(s,p),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+s+" and dilations '"+p+"'"}));var h=ui(a.shape,o,s,p,u),f=function(t,e,n,r){var a=new Rs(n,"max",!1),i=r.runWebGLProgram(a,[t],"float32");return a=new Rs(n,"max",!0,!0,e),[i,r.runWebGLProgram(a,[t],"float32")]}(a,l,h,c);return[f[0],f[1]]}}];oh<sh.length;oh++)v(sh[oh]);for(var uh=0,lh=[{kernelName:vr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],a=Mr(n.shape,r.shape);return{a:function(){var e=t,r=Fr(n.shape,a);return r.length>0&&(e=e.sum(r)),e.reshape(n.shape)},b:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)}}}},{kernelName:"AddN",saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}},{kernelName:kr,gradFunc:function(t,e,n){for(var r=n,a=r.inputShape,i=r.shape,o=Array.from(i),s=a.length-1;s>=0;s--)if(a[s]===i[s])o[s]=1;else if(1!==a[s])throw new Error("broadcastTo(): ["+a+"] cannot be broadcast to ["+i+"].");var u=[];for(s=0;s<o.length;s++)o[s]>1&&u.push(s);return{x:function(){return t.sum(u,!0)}}}},{kernelName:br,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],a=Mr(n.shape,r.shape);return{a:function(){var e=_a(t,r.toFloat()),i=Fr(n.shape,a);return i.length>0?Tc(e,i).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=Tc(e,i).reshape(r.shape));var o=yl(r);return ta(_a(e,o.toFloat()))}}}},{kernelName:"FusedBatchNorm",inputsToSave:["x","mean","variance","scale"],gradFunc:function(t,e,n){var r=n.varianceEpsilon,a=e[0],i=e[1],o=e[2],s=e[3],u=Tu(a),l=null==s?On(1):s,c=Fr(i.shape,u.shape),p=[];if(1===i.rank){for(var h=0;h<u.shape.length-1;++h)p.push(u.shape[h]);p.push(1)}var f=Da(a,i),d=Ia(t,l),m=ra(Or(o,On(r))),g=Ia(Ia(Ia(m,m),m),On(-.5));return{x:function(){return 1===i.rank?or(Ia(Ia(t,Zu(m.as4D(1,1,1,i.shape[0]),p)),l),a.shape):or(Ia(Ia(t,m),l),a.shape)},mean:function(){var t=Ia(Ia(m,On(-1)),d);return 1===i.rank&&(t=Tc(t,c)),or(t,i.shape)},variance:function(){var t=Ia(Ia(g,f),d);return 1===i.rank&&(t=Tc(t,c)),or(t,i.shape)},scale:function(){var e=Ia(f,m),n=Ia(t,e);return 1===i.rank&&(n=Tc(n,c)),or(n,i.shape)},offset:function(){var e=t;return 1===i.rank&&(e=Tc(e,c)),or(e,i.shape)}}}},{kernelName:Er,gradFunc:function(t){return{x:function(){return t.toFloat()}}}},{kernelName:Ir,inputsToSave:["indices"],gradFunc:function(t,e){var n=e[0];return{indices:function(){return Vn(n.shape,"float32")}}}},{kernelName:Tr,inputsToSave:["x"],gradFunc:function(t,e,n){var r=e[0],a=n.paddings.map((function(t){return t[0]}));return{x:function(){return t.slice(a,r.shape)}}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}},{kernelName:wr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],a=On(2);return{a:function(){return Ia(t,Ia(a,Da(n,r)))},b:function(){return Ia(t,Ia(a,Da(r,n)))}}}},{kernelName:Ar,inputsToSave:["x"],gradFunc:function(t,e,n){var r=e[0],a=n.reps;return{x:function(){var e=Hn(r);if(1===r.rank)for(var n=0;n<a[0];++n)e=e.add(t.slice([n*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(n=0;n<a[0];++n)for(var i=0;i<a[1];++i)e=e.add(t.slice([n*r.shape[0],i*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(n=0;n<a[0];++n)for(i=0;i<a[1];++i)for(var o=0;o<a[2];++o)e=e.add(t.slice([n*r.shape[0],i*r.shape[1],o*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(n=0;n<a[0];++n)for(i=0;i<a[1];++i)for(o=0;o<a[2];++o)for(var s=0;s<a[3];++s)e=e.add(t.slice([n*r.shape[0],i*r.shape[1],o*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return e}}}},{kernelName:"Transpose",gradFunc:function(t,e,n){var r=Cn(n.perm);return{x:function(){return ai(t,r)}}}}];uh<lh.length;uh++)y(lh[uh]);var ch=function(){function t(){}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();c().get("IS_BROWSER")&&c().setPlatform("browser",new ch);var ph,hh=function(){function t(){this.util=n(758),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=c().global.fetch?c().global.fetch(t,e):(null==ph&&(ph=n(352)),ph(t,e))},t.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},t}();c().get("IS_NODE")&&c().setPlatform("node",new hh);var fh={float32:4,int32:4,uint16:2,uint8:1,bool:1};function dh(t,e){for(var n={},r=0,a=function(e){var a=e.name,i=e.dtype,o=e.shape,s=R(o),u=void 0;if("quantization"in e){var l=e.quantization;if("uint8"!==l.dtype&&"uint16"!==l.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+l.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var c=fh[l.dtype],p=t.slice(r,r+s*c),h="uint8"===l.dtype?new Uint8Array(p):new Uint16Array(p);if("float32"===i)u=Float32Array.from(h,(function(t){return t*l.scale+l.min}));else{if("int32"!==i)throw new Error("Unsupported dtype in weight '"+a+"': "+i);u=Int32Array.from(h,(function(t){return Math.round(t*l.scale+l.min)}))}r+=s*c}else if("string"===i){var f=R(e.shape);u=[];for(var d=0;d<f;d++){var m=new Uint32Array(t.slice(r,r+4))[0];r+=4;var g=new Uint8Array(t.slice(r,r+m));u.push(g),r+=m}}else{var v=fh[i];if(p=t.slice(r,r+s*v),"float32"===i)u=new Float32Array(p);else if("int32"===i)u=new Int32Array(p);else{if("bool"!==i)throw new Error("Unsupported dtype in weight '"+a+"': "+i);u=new Uint8Array(p)}r+=s*v}n[a]=Rn(u,o,i)},i=0,o=e;i<o.length;i++)a(o[i]);return n}function mh(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach((function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)}));var r=new Uint8Array(e),a=0;return n.forEach((function(t){r.set(new Uint8Array(t.buffer),a),a+=t.byteLength})),r.buffer}var gh="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function vh(t){return gh?Buffer.byteLength(t):new Blob([t]).size}function yh(t){var e=0;t.forEach((function(t){e+=t.byteLength}));var n=new Uint8Array(e),r=0;return t.forEach((function(t){n.set(new Uint8Array(t),r),r+=t.byteLength})),n.buffer}function bh(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function xh(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:vh(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:vh(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var wh=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var a=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach((function(t){var n=t(e,r);null!==n&&a.push(n)})),a},t}(),Ch="://",Nh=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){I(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(Ch)&&(e=e.slice(0,e.indexOf(Ch))),I(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();I(null==r.managers[e],(function(){return"A model store manager is already registered for scheme '"+e+"'."})),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Sh(t){if(-1===t.indexOf(Ch))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Nh.getSchemes().join(","));return{scheme:t.split(Ch)[0],path:t.split(Ch)[1]}}function kh(t,e,n){return void 0===n&&(n=!1),o(this,void 0,void 0,(function(){var r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return I(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),I((r=wh.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),I(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."})),a=r[0],I((i=wh.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),I(i.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."})),o=i[0],u=Sh(t).scheme,l=Sh(t).path,c=u===Sh(t).scheme,[4,a.load()];case 1:return p=s.sent(),n&&c?[4,Nh.getManager(u).removeModel(l)]:[3,3];case 2:s.sent(),s.label=3;case 3:return[4,o.save(p)];case 4:return h=s.sent(),!n||c?[3,6]:[4,Nh.getManager(u).removeModel(l)];case 5:s.sent(),s.label=6;case 6:return[2,h.modelArtifactsInfo]}}))}))}var Ih="models_store",Eh="model_info_store";function Ah(){if(!c().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Th(t){var e=t.result;e.createObjectStore(Ih,{keyPath:"modelPath"}),e.createObjectStore(Eh,{keyPath:"modelPath"})}var Rh=function(){function t(t){if(this.indexedDB=Ah(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]}))}))},t.prototype.load=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,this.databaseAction(this.modelPath)]}))}))},t.prototype.databaseAction=function(t,e){var n=this;return new Promise((function(t,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return Th(a)},a.onsuccess=function(){var i=a.result;if(null==e){var o=i.transaction(Ih,"readonly"),s=o.objectStore(Ih).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."));t(s.result.modelArtifacts)},s.onerror=function(t){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=xh(e),c=i.transaction(Eh,"readwrite"),p=c.objectStore(Eh),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var a=(u=i.transaction(Ih,"readwrite")).objectStore(Ih).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});a.onsuccess=function(){return t({modelArtifactsInfo:l})},a.onerror=function(t){var e=(p=c.objectStore(Eh)).delete(n.modelPath);e.onsuccess=function(){return i.close(),r(a.error)},e.onerror=function(t){return i.close(),r(a.error)}}},h.onerror=function(t){return i.close(),r(h.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(t){return r(a.error)}}))},t.URL_SCHEME="indexeddb://",t}(),Dh=function(t){return c().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Rh.URL_SCHEME)?(e=t.slice(Rh.URL_SCHEME.length),new Rh(e)):null;var e};wh.registerSaveRouter(Dh),wh.registerLoadRouter(Dh);var Oh=function(){function t(){this.indexedDB=Ah()}return t.prototype.listModels=function(){return o(this,void 0,void 0,(function(){var t=this;return s(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Th(r)},r.onsuccess=function(){var t=r.result,a=t.transaction(Eh,"readonly"),i=a.objectStore(Eh).getAll();i.onsuccess=function(){for(var t={},n=0,r=i.result;n<r.length;n++){var a=r[n];t[a.modelPath]=a.modelArtifactsInfo}e(t)},i.onerror=function(e){return t.close(),n(i.error)},a.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}}))]}))}))},t.prototype.removeModel=function(t){return o(this,void 0,void 0,(function(){var e=this;return s(this,(function(n){var r;return t=(r=t).startsWith(Rh.URL_SCHEME)?r.slice(Rh.URL_SCHEME.length):r,[2,new Promise((function(n,r){var a=e.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return Th(a)},a.onsuccess=function(){var e,i=a.result,o=i.transaction(Eh,"readwrite"),s=o.objectStore(Eh),u=s.get(t);u.onsuccess=function(){if(null==u.result)return i.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var a=s.delete(t),o=function(){var a=(e=i.transaction(Ih,"readwrite")).objectStore(Ih).delete(t);a.onsuccess=function(){return n(u.result.modelArtifactsInfo)},a.onerror=function(t){return r(u.error)}};a.onsuccess=o,a.onerror=function(t){return o(),i.close(),r(u.error)}},u.onerror=function(t){return i.close(),r(u.error)},o.oncomplete=function(){null==e?i.close():e.oncomplete=function(){return i.close()}}},a.onerror=function(t){return r(a.error)}}))]}))}))},t}();if(c().getBool("IS_BROWSER"))try{Nh.registerManager(Rh.URL_SCHEME,new Oh)}catch(a){}var _h="/",Fh="tensorflowjs_models",Mh="info",zh="model_topology",Lh="weight_specs",Bh="weight_data",Ph="model_metadata";function Wh(t){return{info:[Fh,t,Mh].join(_h),topology:[Fh,t,zh].join(_h),weightSpecs:[Fh,t,Lh].join(_h),weightData:[Fh,t,Bh].join(_h),modelMetadata:[Fh,t,Ph].join(_h)}}function Vh(t){var e=t.split(_h);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(_h)}var Uh=function(){function t(t){if(!c().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=Wh(this.modelPath)}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){var e,n,r;return s(this,(function(a){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=xh(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(t){if(gh)return Buffer.from(t).toString("base64");for(var e=new Uint8Array(t),n="",r=0,a=e.length;r<a;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[2,{modelArtifactsInfo:r}]}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".")}return[2]}))}))},t.prototype.load=function(){return o(this,void 0,void 0,(function(){var t,e,n,r,a,i,o;return s(this,(function(s){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=r,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),null==(o=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(gh){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),a=0;a<n.length;++a)r.set([n.charCodeAt(a)],a);return r.buffer}(o),[2,e]}))}))},t.URL_SCHEME="localstorage://",t}(),jh=function(t){return c().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Uh.URL_SCHEME)?(e=t.slice(Uh.URL_SCHEME.length),new Uh(e)):null;var e};wh.registerSaveRouter(jh),wh.registerLoadRouter(jh);var Gh=function(){function t(){I(c().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),I("undefined"==typeof window||void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return t.prototype.listModels=function(){return o(this,void 0,void 0,(function(){var t,e,n,r,a,i;return s(this,(function(o){for(t={},e=Fh+_h,n=_h+Mh,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(i=Vh(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]}))}))},t.prototype.removeModel=function(t){return o(this,void 0,void 0,(function(){var e,n;return s(this,(function(r){var a;if(t=(a=t).startsWith(Uh.URL_SCHEME)?a.slice(Uh.URL_SCHEME.length):a,e=Wh(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]}))}))},t}();if(c().getBool("IS_BROWSER"))try{Nh.registerManager(Uh.URL_SCHEME,new Gh)}catch(a){}function qh(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var Hh=function(){function t(e){if(!c().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelTopologyFileName=e+".json",this.weightDataFileName=e+".weights.bin"}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a,i,o;return s(this,(function(s){switch(s.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,qh((function(){return i.dispatchEvent(new MouseEvent("click"))}))];case 2:return s.sent(),null==t.weightData?[3,4]:((o=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,o.href=e,[4,qh((function(){return o.dispatchEvent(new MouseEvent("click"))}))]);case 3:s.sent(),s.label=4;case 4:return[2,{modelArtifactsInfo:xh(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),Kh=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return o(this,void 0,void 0,(function(){var t,e,n=this;return s(this,(function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(r,a){var i=new FileReader;i.onload=function(i){var o=JSON.parse(i.target.result),s=o.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=o.weightsManifest;if(null!=u){var l;try{l=n.checkManifestAndWeightFiles(u,e)}catch(t){return void a(t)}var c=[],p=[],h=[];u.forEach((function(t){t.paths.forEach((function(t){p.push(t),h.push(null)})),c.push.apply(c,t.weights)})),u.forEach((function(t){t.paths.forEach((function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,a=p.indexOf(t);h[a]=n,-1===h.indexOf(null)&&r({modelTopology:s,weightSpecs:c,weightData:yh(h),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},e.onerror=function(e){return a("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(l[t])}))}))}else a(new Error("weightManifest field is missing from file "+t.name))}else a(new Error("modelTopology field is missing from file "+t.name))},i.onerror=function(e){return a("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},i.readAsText(t)}))]}))}))},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map((function(t){return bh(t.name)})),a={},i=0,o=t;i<o.length;i++)o[i].paths.forEach((function(t){var i=bh(t);if(-1!==n.indexOf(i))throw new Error("Duplicate file basename found in weights manifest: '"+i+"'");if(n.push(i),-1===r.indexOf(i))throw new Error("Weight file with basename '"+i+"' is not provided.");a[t]=e[r.indexOf(i)]}));if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return a},t}();function Xh(t,e,n,r){!function(t){I(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){I(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),I(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),I(e>=t,(function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e}))}(n=null==n?0:n,r=null==r?1:r);var a=0;return Promise.all(t.map((function(i){return i.then((function(i){var o=n+ ++a/t.length*(r-n);return e(o),i})),i})))}function Yh(t,e){return o(this,void 0,void 0,(function(){var n,r,a,i,o,u,l,p,h;return s(this,(function(s){switch(s.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?c().platform.fetch:e.fetchFunc,r=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return o=s.sent(),[3,4];case 2:return[4,Xh(r,e.onProgress,a,i)];case 3:o=s.sent(),s.label=4;case 4:return u=o.map((function(t){return t.arrayBuffer()})),l=.5,p=1,null!=e.onProgress?[3,6]:[4,Promise.all(u)];case 5:return h=s.sent(),[3,8];case 6:return[4,Xh(u,e.onProgress,l,p)];case 7:h=s.sent(),s.label=8;case 8:return[2,h]}}))}))}function Jh(t){var e=this;return function(n,r,a){return void 0===r&&(r=""),o(e,void 0,void 0,(function(){var e,i,o,u,l,c,p,h,f,d;return s(this,(function(s){switch(s.label){case 0:if(e=n.map((function(){return!1})),i={},o=null!=a?a.map((function(){return!1})):[],u=[],n.forEach((function(t,n){var r=0;t.weights.forEach((function(t){var s="quantization"in t?t.quantization.dtype:t.dtype,l=fh[s]*R(t.shape),c=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:l})};null!=a?a.forEach((function(e,n){e===t.name&&(c(),o[n]=!0)})):c(),u.push(t.name),r+=l}))})),!o.every((function(t){return t})))throw l=a.filter((function(t,e){return!o[e]})),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),p=[],c.forEach((function(t){n[t].paths.forEach((function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)}))})),[4,t(p)];case 1:return h=s.sent(),f={},d=0,c.forEach((function(t){for(var e=n[t].paths.length,r=0,a=0;a<e;a++)r+=h[d+a].byteLength;for(var o=new ArrayBuffer(r),s=new Uint8Array(o),u=0,l=0;l<e;l++){var c=new Uint8Array(h[d+l]);s.set(c,u),u+=c.byteLength}i[t].forEach((function(t){var e=dh(o.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)f[n]=e[n]})),d+=e})),[2,f]}}))}))}}wh.registerSaveRouter((function(t){return c().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Hh.URL_SCHEME)?function(t){return void 0===t&&(t="model"),new Hh(t)}(t.slice(Hh.URL_SCHEME.length)):null}));var $h=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(I("function"==typeof e.fetchFunc,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=e.fetchFunc):this.fetch=c().platform.fetch,I(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&I(2===t.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."})),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a;return s(this,(function(i){switch(i.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:xh(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return o(this,void 0,void 0,(function(){var t,e,n,r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=s.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");s.label=2;case 2:return s.trys.push([2,4,,5]),[4,t.json()];case 3:return e=s.sent(),[3,5];case 4:throw s.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,o=e.convertedBy,u=e.format,l=e.userDefinedMetadata,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:h=s.sent(),c=h[0],p=h[1],s.label=7;case 7:return[2,{modelTopology:r,weightSpecs:c,weightData:p,userDefinedMetadata:l,generatedBy:i,convertedBy:o,format:u}]}}))}))},t.prototype.loadWeights=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],i=this.weightPathPrefix||r,o=[],u=0,l=t;u<l.length;u++)c=l[u],o.push.apply(o,c.weights);return p=[],t.forEach((function(t){t.paths.forEach((function(t){p.push(i+t+a)}))})),[4,Yh(p,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return h=s.sent(),[2,[o,yh(h)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function Zh(t){return null!=t.match($h.URL_SCHEME_REGEX)}var Qh=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every((function(t){return Zh(t)})):Zh(t))?tf(t,{onProgress:e}):null};function tf(t,e){return new $h(t,e)}wh.registerSaveRouter(Qh),wh.registerLoadRouter(Qh);var ef,nf=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,this.modelArtifacts]}))}))},t}(),rf=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){return[2,this.saveHandler(t)]}))}))},t}(),af=Object.freeze({browserFiles:function(t){return new Kh(t)},browserHTTPRequest:function(t,e){return tf(t,e)},concatenateArrayBuffers:yh,decodeWeights:dh,encodeWeights:function(t,e){return o(this,void 0,void 0,(function(){var n,r,a,i,u,l=this;return s(this,(function(c){switch(c.label){case 0:for(n=[],r=[],a=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t),i=function(i){var u=a[i],c=Array.isArray(t)?t[i].tensor:t[u];if("float32"!==c.dtype&&"int32"!==c.dtype&&"bool"!==c.dtype&&"string"!==c.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+c.dtype);var p={name:u,shape:c.shape,dtype:c.dtype};if("string"===c.dtype){var h=new Promise((function(t){return o(l,void 0,void 0,(function(){var e,n,r,a,i,o,u;return s(this,(function(s){switch(s.label){case 0:return[4,c.bytes()];case 1:for(e=s.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+4*e.length,r=new Uint8Array(n),a=0,i=0;i<e.length;i++)o=e[i],u=new Uint8Array(new Uint32Array([o.length]).buffer),r.set(u,a),a+=4,r.set(o,a),a+=o.length;return t(r),[2]}}))}))}));r.push(h)}else r.push(c.data());null!=e&&(p.group=e),n.push(p)},u=0;u<a.length;++u)i(u);return[4,Promise.all(r)];case 1:return[2,{data:mh(c.sent()),specs:n}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new nf(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new nf({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new nf({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return wh.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:xh,getSaveHandlers:function(t){return wh.getSaveHandlers(t)},http:tf,isHTTPScheme:Zh,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),o(this,void 0,void 0,(function(){return s(this,(function(a){return[2,Jh((function(t){return Yh(t,{requestInit:r})}))(t,e,n)]}))}))},registerLoadRouter:function(t){return wh.registerLoadRouter(t)},registerSaveRouter:function(t){return wh.registerSaveRouter(t)},weightsLoaderFactory:Jh,withSaveHandler:function(t){return new rf(t)},copyModel:function(t,e){return o(this,void 0,void 0,(function(){return s(this,(function(n){return[2,kh(t,e,!1)]}))}))},listModels:function(){return o(this,void 0,void 0,(function(){var t,e,n,r,a,i,o;return s(this,(function(s){switch(s.label){case 0:t=Nh.getSchemes(),e={},n=0,r=t,s.label=1;case 1:return n<r.length?(a=r[n],[4,Nh.getManager(a).listModels()]):[3,4];case 2:for(o in i=s.sent())e[a+Ch+o]=i[o];s.label=3;case 3:return n++,[3,1];case 4:return[2,e]}}))}))},moveModel:function(t,e){return o(this,void 0,void 0,(function(){return s(this,(function(n){return[2,kh(t,e,!0)]}))}))},removeModel:function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){return e=Sh(t),[2,Nh.getManager(e.scheme).removeModel(e.path)]}))}))}}),of=In({confusionMatrix_:function(t,e,n){var r=dn(t,"labels","confusionMatrix"),a=dn(e,"predictions","confusionMatrix");I(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),I(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),I(1===a.rank,(function(){return"Expected the rank of predictions to be 1, but got "+a.rank})),I(r.shape[0]===a.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+a.shape[0]+". Labels and predictions should have the same number of elements."})),I(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var i=el(r.asType("int32"),n),o=el(a.asType("int32"),n);return i.transpose().matMul(o).asType("int32")}}),sf=Object.freeze({confusionMatrix:of}),uf=In({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,a=!1,i=!1,o=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)i=!0;else{if(null==t.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);o=!0}if(a&&a&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(null!=d("FromPixels",Bt.backendName))return Bt.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,l=a?[t.videoWidth,t.videoHeight]:[t.width,t.height],c=l[0],p=l[1];if(o?s=t.getContext("2d").getImageData(0,0,c,p).data:r||n?s=t.data:(i||a)&&(null==ef&&(ef=document.createElement("canvas").getContext("2d")),ef.canvas.width=c,ef.canvas.height=p,ef.drawImage(t,0,0,c,p),s=ef.getImageData(0,0,c,p).data),4===e)u=new Int32Array(s);else{var h=c*p;u=new Int32Array(h*e);for(var f=0;f<h;f++)for(var m=0;m<e;++m)u[f*e+m]=s[4*f+m]}return Mn(u,[p,c,e],"int32")}}),lf=Object.freeze({toPixels:function(t,e){return o(this,void 0,void 0,(function(){var n,r,a,i,o,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,S,k;return s(this,(function(s){switch(s.label){case 0:if(n=dn(t,"img","toPixels"),t instanceof wt||(n=n.toInt()),2!==n.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[4,n.data()];case 1:return u=s.sent(),l=n.min(),c=n.max(),[4,Promise.all([l.data(),c.data()])];case 2:if(p=s.sent(),h=p[0],f=p[1],d=h[0],m=f[0],l.dispose(),c.dispose(),"float32"===n.dtype){if(d<0||m>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+m+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||m>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+m+"].")}for(g="float32"===n.dtype?255:1,v=new Uint8ClampedArray(i*a*4),y=0;y<a*i;++y)b=void 0,x=void 0,w=void 0,C=void 0,1===o?(b=u[y]*g,x=u[y]*g,w=u[y]*g,C=255):3===o?(b=u[3*y]*g,x=u[3*y+1]*g,w=u[3*y+2]*g,C=255):4===o&&(b=u[4*y]*g,x=u[4*y+1]*g,w=u[4*y+2]*g,C=u[4*y+3]*g),v[0+(N=4*y)]=Math.round(b),v[N+1]=Math.round(x),v[N+2]=Math.round(w),v[N+3]=Math.round(C);return null!=e&&(e.width=i,e.height=a,S=e.getContext("2d"),k=new ImageData(v,i,a),S.putImageData(k,0,0)),n!==t&&n.dispose(),[2,v]}}))}))},fromPixels:uf}),cf=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),pf=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function hf(t){I(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),I("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),I(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),pf.register(t)}var ff=Object.freeze({Serializable:cf,SerializationMap:pf,registerClass:hf}),df="1.7.4",mf=Object.freeze({gpgpu_util:ms,webgl_util:Ve,forceHalfFloat:function(){c().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:vu,setWebGLContext:Ht,GPGPUContext:gs}),gf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),a=r.value,i=r.grads;if(null!=n){var o=n.map((function(t){return{name:t.name,tensor:i[t.name]}}));this.applyGradients(o)}else this.applyGradients(i);return Ze(i),e?a:(a.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return Qa(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Ze(this.iterations_)},e.prototype.saveIterations=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:On(this.iterations_,"int32")}]}))}))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},e.prototype.extractIterations=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}}))}))},e}(cf);Object.defineProperty(gf,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var vf=function(t){function e(e,n,r){void 0===r&&(r=null);var a=t.call(this)||this;return a.learningRate=e,a.rho=n,a.epsilon=r,a.accumulatedGrads=[],a.accumulatedUpdates=[],null==r&&(a.epsilon=Bt.backend.epsilon()),a}return i(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Bt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:$e((function(){return Hn(a).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:$e((function(){return Hn(a).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var o=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;$e((function(){var t=o.mul(e.rho).add(i.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(o.add(e.epsilon).sqrt()).mul(i),r=s.mul(e.rho).add(n.square().mul(1-e.rho));o.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(a);a.assign(u)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Ze(this.accumulatedGrads.map((function(t){return t.variable}))),Ze(this.accumulatedUpdates.map((function(t){return t.variable}))))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedUpdates=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="Adadelta",e}(gf);hf(vf);var yf=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return i(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Bt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:$e((function(){return Un(a.shape,e.initialAccumulatorValue).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var o=e.accumulatedGrads[r].variable;$e((function(){var t=o.add(i.square());o.assign(t);var n=i.div(t.add(Bt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(a);a.assign(n)}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Ze(this.accumulatedGrads.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(gf);hf(yf);var bf=function(t){function e(e,n,r,a){void 0===a&&(a=null);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],$e((function(){i.accBeta1=On(n).variable(),i.accBeta2=On(r).variable()})),null==a&&(i.epsilon=Bt.backend.epsilon()),i}return i(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);$e((function(){var r=Da(1,e.accBeta1),a=Da(1,e.accBeta2);n.forEach((function(n,i){var o=Bt.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:$e((function(){return Hn(o).variable(!1)}))}),null==e.accumulatedSecondMoment[i]&&(e.accumulatedSecondMoment[i]={originalName:n+"/v",variable:$e((function(){return Hn(o).variable(!1)}))});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,l=e.accumulatedSecondMoment[i].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=l.mul(e.beta2).add(s.square().mul(1-e.beta2)),h=c.div(r),f=p.div(a);u.assign(c),l.assign(p);var d=h.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(o);o.assign(d)}})),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))})),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Ze(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&Ze(this.accumulatedSecondMoment.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){var e,n=this;return s(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),$e((function(){n.accBeta1.assign(Aa(n.beta1,n.iterations_+1)),n.accBeta2.assign(Aa(n.beta2,n.iterations_+1))})),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedSecondMoment=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(gf);hf(bf);var xf=function(t){function e(e,n,r,a,i){void 0===a&&(a=null),void 0===i&&(i=0);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],$e((function(){o.iteration=On(0).variable(),o.accBeta1=On(n).variable()})),null==a&&(o.epsilon=Bt.backend.epsilon()),o}return i(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);$e((function(){var r=Da(1,e.accBeta1),a=_a(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,i){var o=Bt.registeredVariables[n];null==e.accumulatedFirstMoment[i]&&(e.accumulatedFirstMoment[i]={originalName:n+"/m",variable:Hn(o).variable(!1)}),null==e.accumulatedWeightedInfNorm[i]&&(e.accumulatedWeightedInfNorm[i]={originalName:n+"/v",variable:Hn(o).variable(!1)});var s=Array.isArray(t)?t[i].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[i].variable,l=e.accumulatedWeightedInfNorm[i].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=l.mul(e.beta2),h=s.abs(),f=p.maximum(h);u.assign(c),l.assign(f);var d=a.div(r).mul(c.div(f.add(e.epsilon))).add(o);o.assign(d)}})),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))})),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Ze(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&Ze(this.accumulatedWeightedInfNorm.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(t){throw new Error("setWeights() is not implemented for Adamax yet.")}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(gf);hf(xf);var wf=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return i(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=Bt.registeredVariables[n];$e((function(){var t=e.c.mul(a).add(i);i.assign(t)}))}})),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Qe(On(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(gf);hf(wf);var Cf=function(t){function e(e,n,r){void 0===r&&(r=!1);var a=t.call(this,e)||this;return a.learningRate=e,a.momentum=n,a.useNesterov=r,a.accumulations=[],a.m=On(a.momentum),a}return i(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Bt.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:$e((function(){return Hn(a).variable(!1)}))});var i=e.accumulations[r].variable,o=Array.isArray(t)?t[r].tensor:t[n];null!=o&&$e((function(){var t,n=e.m.mul(i).add(o);t=e.useNesterov?e.c.mul(o.add(n.mul(e.m))).add(a):e.c.mul(n).add(a),i.assign(n),a.assign(t)}))})),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Ze(this.accumulations.map((function(t){return t.variable})))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="Momentum",e}(wf);hf(Cf);var Nf=function(t){function e(e,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=t.call(this)||this;if(o.learningRate=e,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=i,null==a&&(o.epsilon=Bt.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.");return o}return i(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t)).forEach((function(n,r){var a=Bt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:$e((function(){return Hn(a).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:$e((function(){return Hn(a).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:$e((function(){return Hn(a).variable(!1)}))});var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var o=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;$e((function(){var t=o.mul(e.decay).add(i.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(i.mul(1-e.decay)),l=s.mul(e.momentum).add(i.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));o.assign(t),n.assign(u),s.assign(l);var c=a.sub(l);a.assign(c)}else{var p=o.mul(e.decay).add(i.square().mul(1-e.decay));l=s.mul(e.momentum).add(i.mul(e.learningRate).div(p.add(e.epsilon).sqrt())),o.assign(p),s.assign(l),c=a.sub(l),a.assign(c)}}))}})),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Ze(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&Ze(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&Ze(this.accumulatedMoments.map((function(t){return t.variable})))},e.prototype.getWeights=function(){return o(this,void 0,void 0,(function(){var t;return s(this,(function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map((function(t){return{name:t.originalName,tensor:t.variable}})))]}}))}))},e.prototype.setWeights=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.accumulatedMoments=t.slice(e,2*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}))),[2]}}))}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(gf);hf(Nf);var Sf=function(){function t(){}return t.sgd=function(t){return new wf(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Cf(t,e,n)},t.rmsprop=function(t,e,n,r,a){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===a&&(a=!1),new Nf(t,e,n,r,a)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new bf(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new vf(t,e,n)},t.adamax=function(t,e,n,r,a){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===a&&(a=0),new xf(t,e,n,r,a)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new yf(t,e)},t}(),kf={sgd:Sf.sgd,momentum:Sf.momentum,adadelta:Sf.adadelta,adagrad:Sf.adagrad,rmsprop:Sf.rmsprop,adamax:Sf.adamax,adam:Sf.adam},If="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function Ef(){return new Promise((function(t){return If((function(){return t()}))}))}wt.prototype.add=function(t){return Or(this,t)},wt.prototype.broadcastTo=function(t){return ju(this,t)},wt.prototype.div=function(t){return _a(this,t)},wt.prototype.divNoNan=function(t){return $u(this,t)},wt.prototype.squaredDifference=function(t){return bl(this,t)},wt.prototype.tile=function(t){return Zu(this,t)},wt.prototype.oneHot=function(t,e,n){return void 0===e&&(e=1),void 0===n&&(n=0),el(this,t,e,n)},wt.prototype.transpose=function(t){return ai(this,t)},wt.prototype.pad=function(t,e){return nl(this,t,e)},wt.prototype.batchNorm=function(t,e,n,r,a){return _u(this,t,e,n,r,a)},bt=Bp;var Af=function(t,e){return(Af=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function Tf(t,e){function n(){this.constructor=t}Af(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var Rf,Df=function(){return(Df=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t}).apply(this,arguments)};function Of(t,e,n,r){return new(n||(n=Promise))((function(a,i){function o(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(o,s)}u((r=r.apply(t,e||[])).next())}))}function _f(t,e){var n,r,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=e.call(t,o)}catch(t){i=[6,t],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function Ff(){return null==Rf&&(Rf=ln().epsilon()),Rf}var Mf=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Tf(e,t),e}(Error),zf=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Tf(e,t),e}(Error),Lf=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Tf(e,t),e}(Error),Bf=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Tf(e,t),e}(Error),Pf=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Tf(e,t),e}(Error);function Wf(t,e){if(Array.isArray(t)){for(var n=[],r=0;r<e;r++)n=n.concat(t);return n}return(n=new Array(e)).fill(t),n}function Vf(t,e){if(!t)throw new Pf(e)}function Uf(t,e){for(var n=0,r=0,a=t;r<a.length;r++)a[r]===e&&n++;return n}function jf(t){return 1===t.length?t[0]:t}function Gf(t){return Array.isArray(t)?t:[t]}function qf(t){var e=t.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==e[0]?e:"private"+e}function Hf(t){return t.length<=1||-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,(function(t,e){return e.toUpperCase()}))}!function(t){Tf((function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}),t)}(Error);var Kf={};function Xf(t){if(null==t)return null;var e={};return e.className=t.getClassName(),e.config=t.getConfig(),e}function Yf(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))t.forEach((function(t){return Yf(t)}));else for(var e=0,n=Object.keys(t);e<n.length;e++){var r=n[e],a=t[r];null!=a&&"object"==typeof a&&(Array.isArray(a)||"ndarray"!==a.type||"number"!=typeof a.value?Yf(a):t[r]=a.value)}}function Jf(t,e,n,r,a){var i,o,s;if(void 0===e&&(e={}),void 0===n&&(n={}),void 0===r&&(r="object"),void 0===a&&(a=!1),"string"==typeof t){var u=t,l=void 0;if(u in n)l=n[u];else if(u in Kf)l=Kf[u];else if(null==(l=e[u]))throw new Lf("Unknown "+r+": "+t+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return l}var c=t;if(null==c.className||null==c.config)throw new Lf(r+": Improper config format: "+JSON.stringify(c)+".\n'className' and 'config' must set.");var p=c.className,h=void 0,f=void 0;if(p in n?(h=(i=n[p])[0],f=i[1]):p in Kf?(h=(o=Kf.className)[0],f=o[1]):p in e&&(h=(s=e[p])[0],f=s[1]),null==h)throw new Lf("Unknown "+r+": "+p+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=f){for(var d={},m=0,g=Object.keys(Kf);m<g.length;m++)d[C=g[m]]=Kf[C];for(var v=0,y=Object.keys(n);v<y.length;v++)d[C=y[v]]=n[C];c.config.customObjects=d;for(var b=Df({},Kf),x=0,w=Object.keys(n);x<w.length;x++){var C=w[x];Kf[C]=n[C]}Yf(c.config);var N=f(h,c.config,n,a);return Kf=Df({},b),N}b=Df({},Kf);for(var S=0,k=Object.keys(n);S<k.length;S++)C=k[S],Kf[C]=n[C];return N=new h(c.config),Kf=Df({},b),N}function $f(t,e){return-1*function(t,e){return t<e?-1:t>e?1:0}(t,e)}function Zf(t){if(null==t)return t;for(var e=[],n=0,r=t;n<r.length;n++){var a=r[n];-1===e.indexOf(a)&&e.push(a)}return e}function Qf(t){if(null==t)throw new Lf("Invalid value in obj: "+JSON.stringify(t));for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function td(t,e,n){if(null!=n&&t.indexOf(n)<0)throw new Lf(n+" is not a valid "+e+". Valid values are "+t+" or null/undefined.")}function ed(t,e,n,r){return void 0===n&&(n=0),void 0===r&&(r=1/0),Vf(n>=0),Vf(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every((function(t){return typeof t===e}))}function nd(t,e){Array.isArray(t)?(pt.assert(t.length>0,(function(){return e+" is unexpectedly an empty array."})),t.forEach((function(t,n){return nd(t,"element "+(n+1)+" of "+e)}))):pt.assert(Number.isInteger(t)&&t>0,(function(){return"Expected "+e+" to be a positive integer, but got "+rd(t)+"."}))}function rd(t){return null===t?"null":Array.isArray(t)?"["+t.map((function(t){return rd(t)})).join(",")+"]":"string"==typeof t?'"'+t+'"':""+t}function ad(t){return"relu"===t?"relu":"linear"===t?"linear":"elu"===t?"elu":null}function id(t,e){return $e((function(){return ha(Tc(Ea(t,t),e,!0))}))}var od=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.getConfig=function(){return{}},e}(ff.Serializable),sd=function(t){function e(e){var n=t.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Tf(e,t),e.prototype.apply=function(t){var e=this;return $e((function(){var n=id(t,e.axis),r=Gr(n,0,e.maxValue);return Ia(t,_a(r,Or(Ff(),n)))}))},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(od);ff.registerClass(sd);var ud=function(t){function e(e){var n=t.call(this)||this;return n.defaultAxis=0,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Tf(e,t),e.prototype.apply=function(t){var e=this;return $e((function(){return _a(t,Or(Ff(),id(t,e.axis)))}))},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(od);ff.registerClass(ud);var ld=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return Fc(t)},e.className="NonNeg",e}(od);ff.registerClass(ld);var cd=function(t){function e(e){var n=t.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=e.minValue?e.minValue:n.defaultMinValue,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.rate=null!=e.rate?e.rate:n.defaultRate,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Tf(e,t),e.prototype.apply=function(t){var e=this;return $e((function(){var n=id(t,e.axis),r=Or(Ia(e.rate,Gr(n,e.minValue,e.maxValue)),Ia(1-e.rate,n));return Ia(t,_a(r,Or(Ff(),n)))}))},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(od);ff.registerClass(cd);var pd={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function hd(t){return Xf(t)}function fd(t,e){return void 0===e&&(e={}),Jf(t,ff.SerializationMap.getMap().classNameMap,e,"constraint")}function dd(t){return null==t?null:"string"==typeof t?fd({className:t in pd?pd[t]:t,config:{}}):t instanceof od?t:fd(t)}var md=Object.freeze({maxNorm:function(t){return new sd(t)},unitNorm:function(t){return new ud(t)},nonNeg:function(){return new ld},minMaxNorm:function(t){return new cd(t)}}),gd=["channelsFirst","channelsLast"],vd=["valid","same","causal"],yd=["max","avg"],bd=["sum","mul","concat","ave"],xd=new Map;function wd(t){td(gd,"DataFormat",t)}function Cd(t){td(vd,"PaddingMode",t)}function Nd(t){td(yd,"PoolMode",t)}var Sd=[];function kd(t,e){Sd.push(t);try{var n=e();return Sd.pop(),n}catch(t){throw Sd.pop(),t}}function Id(t){if(!Td(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===Sd.length?"":Sd.join("/")+"/")+t}function Ed(t){if(!Td(t))throw new Error("Not a valid tensor name: '"+t+"'");xd.has(t)||xd.set(t,0);var e=xd.get(t);if(xd.set(t,xd.get(t)+1),e>0){var n=t+"_"+e;return xd.set(n,1),n}return t}var Ad=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Td(t){return!!t.match(Ad)}function Rd(t){return t===parseInt(t.toString(),10)}function Dd(t,e,n){null==e&&(e=0),null==n&&(n=t.length);for(var r=1,a=e;a<n;++a)r*=t[a];return r}function Od(t){return _n(t=Array.isArray(t)?new Float32Array(t):t)}function _d(t){return Ec(Od(t)).dataSync()[0]}function Fd(t){return kc(Od(t)).dataSync()[0]}function Md(t,e){if(e<t)throw new Lf("end ("+e+") < begin ("+t+") is forbidden.");for(var n=[],r=t;r<e;++r)n.push(r);return n}function zd(t,e){return t.asType(e)}function Ld(t,e){void 0===e&&(e=-1);var n=t.shape.slice();return e<0&&(e=n.length+e+1),n.splice(e,0,1),t.reshape(n)}function Bd(t,e,n){return $e((function(){switch(t.rank){case 1:return mc(t,e,n);case 2:return gc(t,[e,0],[n,t.shape[1]]);case 3:return vc(t,[e,0,0],[n,t.shape[1],t.shape[2]]);case 4:return yc(t,[e,0,0,0],[n,t.shape[1],t.shape[2],t.shape[3]]);case 5:return dc(t,[e,0,0,0,0],[n,t.shape[1],t.shape[2],t.shape[3],t.shape[4]]);case 6:return dc(t,[e,0,0,0,0,0],[n,t.shape[1],t.shape[2],t.shape[3],t.shape[4],t.shape[5]]);default:throw new Lf("sliceAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}}))}function Pd(t,e,n){return $e((function(){switch(t.rank){case 1:return mc(t,e,n);case 2:return gc(t,[0,e],[t.shape[0],n]);case 3:return vc(t,[0,0,e],[t.shape[0],t.shape[1],n]);case 4:return yc(t,[0,0,0,e],[t.shape[0],t.shape[1],t.shape[2],n]);default:throw new Lf("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}}))}function Wd(t,e,n,r){return $e((function(){switch(t.rank){case 1:return mc(t,e,n);case 2:switch(r){case 1:return Bd(t,e,n);case 2:return Pd(t,e,n);default:throw new Lf("The axis is not within the rank of the tensor "+r)}case 3:switch(r){case 1:return Bd(t,e,n);case 2:return vc(t,[0,e,0],[t.shape[0],n,t.shape[2]]);case 3:return Pd(t,e,n);default:throw new Lf("The axis is not within the rank of the tensor "+r)}case 4:switch(r){case 1:return Bd(t,e,n);case 2:return yc(t,[0,e,0,0],[t.shape[0],n,t.shape[2],t.shape[3]]);case 3:return yc(t,[0,0,e,0],[t.shape[0],t.shape[1],n,t.shape[3]]);case 4:return Pd(t,e,n);default:throw new Lf("The axis is not within the rank of the tensor "+r)}default:throw new Lf("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}}))}function Vd(t,e){var n;return void 0===e&&(e=-1),e<0&&(e=0!==(n=t[0].rank)?n:0),e===t[0].rank&&(e=-1),Kn(t,e)}function Ud(t,e){switch(t.rank){case 1:return Xn([t,e]);case 2:return Yn([t,e],0);case 3:return Jn([t,e],0);case 4:return $n([t,e],0);default:throw new Lf("concatAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}}function jd(t,e){if(Array.isArray(e)||(e=[e]),t.rank!==e.length)throw new Lf("The length of input n ("+e.length+") does not match the number of dimensions in input x ("+t.rank+")");return Zu(t,e)}function Gd(t,e,n,r,a){return void 0===e&&(e=0),void 0===n&&(n=1),gl(t,e,n,r,a)}function qd(t,e,n,r){if(t.rank<2||e.rank<2)throw new Bf("dot requires both inputs to be rank >= 2 but got x shape = "+t.shape+" and y shape = "+e.shape);if(e.rank>=3&&t.shape.slice(-1)[0]!==(c=e.shape.slice(-2)[0]))throw new Bf("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+t.shape+" and y shape = "+e.shape);if(2===t.rank&&2===e.rank){var a=!1,i=!1;return Lp.matMul({a:t,b:e,transposeA:a,transposeB:i,bias:r?Xd(t.rank,r,"channelsLast"):null,activation:n})}var o=t.shape.slice(),s=o.pop();t=t.reshape([-1,s]);var u=e.shape.slice(),l=u.pop(),c=u.pop(),p=u.concat([l]),h=Array.from({length:e.rank},(function(t,n){return 0===n?e.rank-2:n<=e.rank-2?n-1:n}));e=e.transpose(h).reshape([c,-1]);var f=o.concat(p);return a=!1,i=!1,Lp.matMul({a:t,b:e,transposeA:a,transposeB:i,bias:r?Xd(t.rank,r,"channelsLast"):null,activation:n}).reshape(f)}function Hd(t,e,n){return $e((function(){return e=Array.isArray(e)?_n(e,"int32"):e.toInt(),Ml(t,e,n)}))}function Kd(t){return Ea(t,t)}function Xd(t,e,n){var r=e.shape;if(1!==e.rank&&e.rank!==t)throw new Lf("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+t);if(5===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1,1]):e.reshape([1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,1,r[0]]):e.reshape([1].concat(r))}else if(4===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1]):e.reshape([1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,r[0]]):e.reshape([1].concat(r))}else if(3===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1]):e.reshape([1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,r[0]]):e.reshape([1].concat(r))}else if(t<3)return e;throw new Lf("Unsupported input rank by biasAdd: "+e.rank)}function Yd(t,e,n){return $e((function(){return null==n&&(n="channelsLast"),wd(n),t.add(Xd(t.rank,e,n))}))}function Jd(t,e,n,r){return $e((function(){return Qc(t,e,n,r)}))}function $d(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Zd=["fanIn","fanOut","fanAvg"],Qd=["normal","uniform","truncatedNormal"],tm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(ff.Serializable),em=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){return Vn(t,e)},e.className="Zeros",e}(tm);ff.registerClass(em);var nm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){return Wn(t,e)},e.className="Ones",e}(tm);ff.registerClass(nm);var rm=function(t){function e(e){var n=t.call(this)||this;if("object"!=typeof e)throw new Lf("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new Lf("config must have value set but got "+e);return n.value=e.value,n}return Tf(e,t),e.prototype.apply=function(t,e){var n=this;return $e((function(){return Ia(On(n.value),Wn(t,e))}))},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(tm);ff.registerClass(rm);var am=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=e.minval||n.DEFAULT_MINVAL,n.maxval=e.maxval||n.DEFAULT_MAXVAL,n.seed=e.seed,n}return Tf(e,t),e.prototype.apply=function(t,e){return vl(t,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(tm);ff.registerClass(am);var im=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return Tf(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Bf("randomNormal does not support dType "+e+".");return Gd(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="RandomNormal",e}(tm);ff.registerClass(im);var om=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return Tf(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Bf("truncatedNormal does not support dType "+e+".");return xl(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="TruncatedNormal",e}(tm);ff.registerClass(om);var sm=function(t){function e(e){var n=t.call(this)||this;return n.gain=null!=e.gain?e.gain:1,n}return Tf(e,t),e.prototype.apply=function(t,e){var n=this;return $e((function(){if(2!==t.length||t[0]!==t[1])throw new Lf("Identity matrix initializer can only be used for 2D square matrices.");return Ia(n.gain,Qu(t[0]))}))},e.prototype.getConfig=function(){return{gain:this.gain}},e.className="Identity",e}(tm);ff.registerClass(sm);var um=function(t){function e(e){var n=t.call(this)||this;if(e.scale<0)throw new Lf("scale must be a positive float. Got: "+e.scale);return n.scale=null==e.scale?1:e.scale,n.mode=null==e.mode?"fanIn":e.mode,function(t){td(Zd,"FanMode",t)}(n.mode),n.distribution=null==e.distribution?"normal":e.distribution,function(t){td(Qd,"Distribution",t)}(n.distribution),n.seed=e.seed,n}return Tf(e,t),e.prototype.apply=function(t,e){var n=function(t,e){var n,r;if(void 0===e&&(e="channelsLast"),wd(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var a=Dd(t,2);n=t[1]*a,r=t[0]*a}else"channelsLast"===e&&(a=Dd(t,0,t.length-2),n=t[t.length-2]*a,r=t[t.length-1]*a);else{var i=Dd(t);n=Math.sqrt(i),r=Math.sqrt(i)}return[n,r]}(t),r=n[0],a=n[1],i=this.scale;if("fanIn"===this.mode?i/=Math.max(1,r):"fanOut"===this.mode?i/=Math.max(1,a):i/=Math.max(1,(r+a)/2),"normal"===this.distribution){var o=Math.sqrt(i);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Bf(this.getClassName()+" does not support dType "+e+".");return xl(t,0,o,e,this.seed)}var s=Math.sqrt(3*i);return vl(t,-s,s,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(tm);ff.registerClass(um);var lm=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="GlorotUniform",e}(um);ff.registerClass(lm);var cm=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="GlorotNormal",e}(um);ff.registerClass(cm);var pm=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="HeNormal",e}(um);ff.registerClass(pm);var hm=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="HeUniform",e}(um);ff.registerClass(hm);var fm=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="LeCunNormal",e}(um);ff.registerClass(fm);var dm=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Tf(e,t),e.prototype.getClassName=function(){return um.className},e.className="LeCunNormal",e}(um);ff.registerClass(dm);var mm=function(t){function e(e){var n=t.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==e.gain?n.DEFAULT_GAIN:e.gain,n.seed=e.seed,null!=n.seed)throw new Bf("Random seed is not implemented for Orthogonal Initializer yet.");return n}return Tf(e,t),e.prototype.apply=function(t,e){var n=this;return $e((function(){if(2!==t.length)throw new Bf("The Orthogonal Initializer does not support non-2D shapes yet.");t[0]*t[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+t[0]*t[1]+") elements: Slowness may result.");var e=Gd(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32"),r=Cp.gramSchmidt(e);return t[0]>t[1]&&(r=r.transpose()),Ia(n.gain,r)}))},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(tm);ff.registerClass(mm);var gm={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function vm(t,e){return void 0===e&&(e={}),Jf(t,ff.SerializationMap.getMap().classNameMap,e,"initializer")}function ym(t){return Xf(t)}function bm(t){if("string"==typeof t){var e=t in gm?gm[t]:t;if("GlorotNormal"===e)return new cm;if("GlorotUniform"===e)return new lm;if("HeNormal"===e)return new pm;if("HeUniform"===e)return new hm;if("LeCunNormal"===e)return new fm;if("LeCunUniform"===e)return new dm;var n={};return n.className=e,n.config={},vm(n)}return t instanceof tm?t:vm(t)}var xm=Object.freeze({zeros:function(){return new em},ones:function(){return new nm},constant:function(t){return new rm(t)},randomUniform:function(t){return new am(t)},randomNormal:function(t){return new im(t)},truncatedNormal:function(t){return new om(t)},identity:function(t){return new sm(t)},varianceScaling:function(t){return new um(t)},glorotUniform:function(t){return new lm(t)},glorotNormal:function(t){return new cm(t)},heNormal:function(t){return new pm(t)},heUniform:function(t){return new hm(t)},leCunNormal:function(t){return new fm(t)},leCunUniform:function(t){return new dm(t)},orthogonal:function(t){return new mm(t)}}),wm=0;function Cm(){return wm++}var Nm={};function Sm(t){return void 0===t&&(t=""),t in Nm||(Nm[t]=0),Nm[t]+=1,t+Nm[t].toString()}function km(t){return Array.isArray(t)&&Array.isArray(t[0])}function Im(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function Em(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new Lf("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function Am(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new Lf("Expected exactly 1 Shape; got "+t.length)}return t}function Tm(t){for(var e=0,n=0,r=t;n<r.length;n++){var a=r[n];0===a.shape.length?e+=1:e+=a.shape.reduce((function(t,e){return t*e}))}return e}var Rm="Variable",Dm=function(){function t(t,e,n,r,a){void 0===e&&(e="float32"),void 0===n&&(n=Rm),void 0===r&&(r=!0),void 0===a&&(a=null),this.dtype=null==e?"float32":e,this.shape=t.shape,this.id=Cm(),n=null==n?Rm:n,this.originalName=Id(n),this.name=Ed(this.originalName),this.trainable_=r,this.constraint=a,this.val=Pn(t,this.trainable_,this.name,this.dtype)}return t.prototype.read=function(){return this.assertNotDisposed(),this.val},t.prototype.write=function(t){return this.assertNotDisposed(),function(t,e){if(t.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(e.shape))}(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},t.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},t.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.trainable_=t,this.val.trainable=t},enumerable:!0,configurable:!0}),t}();function Om(t){return t.map((function(t){return t.read()}))}function _m(t){t.forEach((function(t){t[0].write(t[1])}))}var Fm=function(t){this.dtype=t.dtype,this.shape=t.shape,null!=t.shape?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}},Mm=function(t,e,n,r,a,i,o){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=r,this.callArgs=a,this.outputTensorIndex=o,this.id=Cm(),null!=i&&(this.originalName=Id(i),this.name=Ed(this.originalName)),this.rank=e.length},zm=0,Lm=function(){function t(t,e){this.callArgs=e,this.id=zm++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(var n=0,r=t.inboundLayers;n<r.length;n++){var a=r[n];null!=a&&a.outboundNodes.push(this)}t.outboundLayer.inboundNodes.push(this)}return t.prototype.getConfig=function(){for(var t=[],e=0,n=this.inboundLayers;e<n.length;e++){var r=n[e];null!=r?t.push(r.name):t.push(null)}return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}},t}(),Bm=0,Pm=function(t){function e(e){var n=t.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=Bm++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=e.name;if(!r){var a=n.getClassName();r=qf(a)+"_"+Sm(a)}if(n.name=r,n.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){var i=void 0;if(null!=e.batchInputShape)i=e.batchInputShape;else if(null!=e.inputShape){var o=null;null!=e.batchSize&&(o=e.batchSize),i=[o].concat(e.inputShape)}n.batchInputShape=i;var s=e.dtype;null==s&&(s=e.inputDType),null==s&&(s="float32"),n.dtype=s}return null!=e.weights?n.initialWeights=e.weights:n.initialWeights=null,n._refCount=null,n.fastWeightInitDuringBuild=!1,n}return Tf(e,t),e.nodeKey=function(t,e){return t.name+"_ib-"+e.toString()},e.prototype.getNodeAtIndex=function(t,e){if(0===this.inboundNodes.length)throw new zf("The layer has never been called and thus has no defined "+e+".");if(this.inboundNodes.length<=t)throw new Lf("Asked to get "+e+" at node "+t+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[t]},e.prototype.getInputAt=function(t){return jf(this.getNodeAtIndex(t,"input").inputTensors)},e.prototype.getOutputAt=function(t){return jf(this.getNodeAtIndex(t,"output").outputTensors)},Object.defineProperty(e.prototype,"input",{get:function(){if(this.inboundNodes.length>1)throw new Mf("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 Mf("Layer "+this.name+" is not connected, no input to return.");return jf(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new Mf("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new Mf("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return jf(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),e.prototype.calculateLosses=function(){return this.losses.map((function(t){return t()}))},Object.defineProperty(e.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this._trainableWeights.forEach((function(e){return e.trainable=t})),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter((function(t){return t.trainable})):[]},set:function(t){this._trainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter((function(t){return!t.trainable})).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(t){this._nonTrainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},e.prototype.assertInputCompatibility=function(t){if(t=Gf(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=Gf(this.inputSpec);if(t.length!==e.length)throw new Lf("Layer "+this.name+" expects "+e.length+" inputs, but it received "+t.length+" input tensors. Input received: "+t);for(var n=0;n<t.length;n++){var r=t[n],a=e[n];if(null!=a){var i=r.rank;if(null!=a.ndim&&i!==a.ndim)throw new Lf("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+a.ndim+", found ndim="+i);if(null!=a.maxNDim&&i>a.maxNDim)throw new Lf("Input "+n+" is incompatible with layer "+this.name+": expected max_ndim="+a.maxNDim+", found ndim="+i);if(null!=a.minNDim&&i<a.minNDim)throw new Lf("Input "+n+" is incompatible with layer "+this.name+": expected min_ndim="+a.minNDim+", found ndim="+i+".");if(null!=a.dtype&&r.dtype!==a.dtype)throw new Lf("Input "+n+" is incompatible with layer "+this.name+" : expected dtype="+a.dtype+", found dtype="+r.dtype+".");if(a.axes){var o=r.shape;for(var s in a.axes){var u=Number(s),l=a.axes[s],c=u>=0?o[u]:o[o.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new Lf("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 p=0;p<a.shape.length;++p){var h=a.shape[p],f=r.shape[p];if(null!=h&&null!=f&&h!==f)throw new Lf("Input "+n+" is incompatible with layer "+this.name+": expected shape="+a.shape+", found shape="+r.shape+".")}}}}},e.prototype.call=function(t,e){return t},e.prototype.invokeCallHook=function(t,e){null!=this._callHook&&this._callHook(t,e)},e.prototype.setCallHook=function(t){this._callHook=t},e.prototype.clearCallHook=function(){this._callHook=null},e.prototype.apply=function(t,e){var n=this;e=e||{},this.assertNotDisposed();for(var r=Gf(t),a=!0,i=0,o=r;i<o.length;i++)if(!(o[i]instanceof Mm)){a=!1;break}for(var s=!0,u=0,l=r;u<l.length;u++)if(l[u]instanceof Mm){s=!1;break}if(a===s)throw new Lf("Arguments to apply() must be all SymbolicTensors or all Tensors");return kd(this.name,(function(){if(!n.built){n.assertInputCompatibility(t);for(var a=[],i=0,o=Gf(t);i<o.length;i++){var u=o[i];a.push(u.shape)}n.build(jf(a)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights),null===n._refCount&&s&&(n._refCount=1)}if(n.assertInputCompatibility(t),s){for(var l=[],c=0,p=Gf(m=n.call(t,e));c<p.length;c++){var h=p[c];-1!==r.indexOf(h)&&(h=h.clone()),l.push(h)}if(m=jf(l),null!=n.activityRegularizer)throw new Bf("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m}var f=function(t){for(var e=[],n=0,r=t=Gf(t);n<r.length;n++){var a=r[n];e.push(a.shape)}return jf(e)}(t),d=n.computeOutputShape(f),m=void 0,g="float32";if(n.warnOnIncompatibleInputShape(Array.isArray(t)?f[0]:f),m=null!=d&&d.length>0&&Array.isArray(d[0])?d.map((function(r,a){return new Mm(g,r,n,Gf(t),e,n.name,a)})):new Mm(g,d,n,Gf(t),e,n.name),n.addInboundNode(t,m,null,null,f,d,e),n._refCount++,null!=n.activityRegularizer)throw new Bf("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m}))},e.prototype.warnOnIncompatibleInputShape=function(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(t)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach((function(n,r){null!=n&&null!=t[r]&&t[r]!==n&&(e=!0)})),e&&console.warn("The shape of the input tensor ("+JSON.stringify(t)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(e.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Mf("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var t=[],e=0,n=this.inboundNodes;e<n.length;e++){var r=n[e],a=JSON.stringify(r.outputShapes);-1===t.indexOf(a)&&t.push(a)}if(1===t.length){var i=this.inboundNodes[0].outputShapes;return Array.isArray(i)&&Array.isArray(i[0])&&1===i.length?i[0]:i}throw new Mf("The layer "+this.name+' has multiple inbound nodes with different output shapes. Hence the notion of "outut shape" is ill-defined for the layer.')},enumerable:!0,configurable:!0}),e.prototype.countParams=function(){if(!this.built)throw new zf("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return Tm(this.weights)},e.prototype.build=function(t){this.built=!0},e.prototype.getWeights=function(t){return void 0===t&&(t=!1),Om(t?this.trainableWeights:this.weights)},e.prototype.setWeights=function(t){var e=this;$e((function(){var n=e.weights;if(n.length!==t.length)throw new Lf('You called setWeights(weights) on layer "'+e.name+'" with a weight list of length '+t.length+", but the layer was expecting "+n.length+" weights. Provided weights: "+t+"...");if(0!==n.length){for(var r=[],a=Om(n),i=0;i<a.length;++i){var o=a[i],s=n[i],u=t[i];if(!pt.arraysEqual(o.shape,u.shape))throw new Lf("Layer weight shape "+o.shape+" not compatible with provided weight shape "+u.shape);r.push([s,u])}_m(r)}}))},e.prototype.addWeight=function(t,e,n,r,a,i,o){if(-1!==this._addedWeightNames.indexOf(t))throw new Lf("Duplicate weight name "+t+" for layer "+this.name);this._addedWeightNames.push(t),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=bm("zeros"));var s=r.apply(e,n),u=new Dm(s,n,t,i,o);return s.dispose(),null!=a&&this.addLoss((function(){return a.apply(u.read())})),null==i&&(i=!0),i?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u},e.prototype.setFastWeightInitDuringBuild=function(t){this.fastWeightInitDuringBuild=t},e.prototype.addLoss=function(t){var e;null==t||Array.isArray(t)&&0===t.length||(t=Gf(t),void 0!==this._losses&&null!==this._losses&&(e=this.losses).push.apply(e,t))},e.prototype.computeOutputShape=function(t){return t},e.prototype.computeMask=function(t,e){var n=this;if(!this.supportsMasking){if(null!=e){if(!Array.isArray(e))throw new TypeError("Layer "+this.name+" does not support masking, but was passed an inputMask.");e.forEach((function(t){if(null!=t)throw new TypeError("Layer "+n.name+" does not support masking, but was passed an inputMask.")}))}return null}return e},e.prototype.addInboundNode=function(t,e,n,r,a,i,o){void 0===o&&(o=null);var s=Gf(t);e=Gf(e),n=Gf(n),r=Gf(r),a=Im(a),i=Im(i);for(var u=[],l=[],c=[],p=0,h=s;p<h.length;p++){var f=h[p];u.push(f.sourceLayer),l.push(f.nodeIndex),c.push(f.tensorIndex)}new Lm({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:s,outputTensors:e,inputMasks:n,outputMasks:r,inputShapes:a,outputShapes:i},o);for(var d=0;d<e.length;d++)e[d].sourceLayer=this,e[d].nodeIndex=this.inboundNodes.length-1,e[d].tensorIndex=d},e.prototype.getConfig=function(){var t={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(t.batchInputShape=this.batchInputShape),null!=this.dtype&&(t.dtype=this.dtype),t},e.prototype.disposeWeights=function(){return this.weights.forEach((function(t){return t.dispose()})),this.weights.length},e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Layer '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){if(!this.built)throw new Error("Cannot dispose Layer "+this.name+" because it has not been built yet.");if(null===this._refCount)throw new Error("Cannot dispose Layer "+this.name+" because it has not been used yet.");this.assertNotDisposed();var t=0;return 0==--this._refCount&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}},e}(ff.Serializable);function Wm(t,e,n){if((null==e||null!=n&&n>0)&&(e=t.sourceLayer,n=t.nodeIndex),0===e.inboundNodes.length)return[t];var r=e.inboundNodes[n];if(0===r.inboundLayers.length)return r.inputTensors;for(var a=[],i=0;i<r.inboundLayers.length;i++)for(var o=0,s=Wm(r.inputTensors[i],r.inboundLayers[i],r.nodeIndices[i]);o<s.length;o++){var u=s[o];-1===a.indexOf(u)&&a.push(u)}return a}var Vm,Um=function(t){function e(e){var n=t.call(this,{dtype:e.dtype,name:null!=e.name?e.name:Sm("input").toString()})||this;if(null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),n.trainable=!1,n.built=!0,n.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new Lf("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r=e.batchInputShape;if(null==r){if(null==e.inputShape)throw new Lf("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Lf("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var a=e.dtype||"float32";n.batchInputShape=r,n.dtype=a,n.inputSpec=[{shape:r}];var i=new Mm(n.dtype,n.batchInputShape,n,[],{},n.name);return i.nodeIndex=0,i.tensorIndex=0,new Lm({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n}return Tf(e,t),e.prototype.apply=function(t,e){throw new Lf("Cannot pass any input to an InputLayer's apply() method. InputLayer name: "+this.name)},e.prototype.dispose=function(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}},e.prototype.getConfig=function(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}},e.className="InputLayer",e}(Pm);function jm(t){if(null==t.batchShape&&null==t.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=t.batchShape&&null!=t.shape)throw new Lf("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var e=t.batchShape;null!=t.shape&&null==e&&(e=[null].concat(t.shape));var n=t.dtype;return null==n&&(n="float32"),new Um({batchInputShape:e,name:t.name,dtype:n,sparse:t.sparse}).inboundNodes[0].outputTensors[0]}function Gm(t){return Of(this,void 0,void 0,(function(){var e,n,r,a,i,o,s,u;return _f(this,(function(l){switch(l.label){case 0:if(null==t)return[2];for(a in e=[],n=[],r=[],t)"number"!=typeof(i=t[a])&&(o=i,e.push(o.data()),n.push(a),r.push(o));return e.length>0?[4,Promise.all(e)]:[3,2];case 1:for(s=l.sent(),u=0;u<s.length;++u)t[n[u]]=s[u][0];Ze(r),l.label=2;case 2:return[2]}}))}))}function qm(t){if(null!=t)for(var e in t){var n=t[e];"number"!=typeof n&&n.dispose()}}ff.registerClass(Um),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}(Vm||(Vm={}));var Hm=function(){function t(){this.validationData=null}return t.prototype.setParams=function(t){this.params=t},t.prototype.onEpochBegin=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.onBatchBegin=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.onBatchEnd=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.onTrainBegin=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.onTrainEnd=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return[2]}))}))},t.prototype.setModel=function(t){},t}(),Km=function(){function t(t,e){void 0===e&&(e=10),null==t&&(t=[]),this.callbacks=t,this.queueLength=e}return t.prototype.append=function(t){this.callbacks.push(t)},t.prototype.setParams=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setParams(t)},t.prototype.setModel=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setModel(t)},t.prototype.onEpochBegin=function(t,e){return Of(this,void 0,void 0,(function(){var n,r;return _f(this,(function(a){switch(a.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onEpochBegin(t,e)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2]}}))}))},t.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n,r;return _f(this,(function(a){switch(a.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onEpochEnd(t,e)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2]}}))}))},t.prototype.onBatchBegin=function(t,e){return Of(this,void 0,void 0,(function(){var n,r;return _f(this,(function(a){switch(a.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onBatchBegin(t,e)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2]}}))}))},t.prototype.onBatchEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n,r;return _f(this,(function(a){switch(a.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onBatchEnd(t,e)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2]}}))}))},t.prototype.onTrainBegin=function(t){return Of(this,void 0,void 0,(function(){var e,n;return _f(this,(function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainBegin(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}}))}))},t.prototype.onTrainEnd=function(t){return Of(this,void 0,void 0,(function(){var e,n;return _f(this,(function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainEnd(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}}))}))},t}(),Xm=function(t){function e(){return t.call(this)||this}return Tf(e,t),e.prototype.onEpochBegin=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return this.seen=0,this.totals={},[2]}))}))},e.prototype.onBatchEnd=function(t,e){return Of(this,void 0,void 0,(function(){var t,n,r,a,i=this;return _f(this,(function(o){for(a in null==e&&(e={}),t=null==e.size?0:e.size,this.seen+=t,n=function(n){var a=e[n];if("number"==typeof a)r.totals.hasOwnProperty(n)||(r.totals[n]=0),r.totals[n]=r.totals[n]+a*t;else{var o=void 0;n in r.totals?o=r.totals[n]:r.totals[n]=0;var s=$e((function(){return Or(i.totals[n],Ia(a,t))}));r.totals[n]=s,null!=o&&o.dispose()}},r=this,e)n(a);return[2]}))}))},e.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){var t,n,r,a,i,o=this;return _f(this,(function(s){if(null!=e)for(t=function(t){if(null==n.totals[t])return"continue";"number"==typeof n.totals[t]?e[t]=n.totals[t]/n.seen:$e((function(){var n=Ia(_a(1,o.seen),o.totals[t]);e[t]=n,o.totals[t].dispose(),Qe(e[t])}))},n=this,r=0,a=this.params.metrics;r<a.length;r++)i=a[r],t(i);return[2]}))}))},e}(Hm),Ym=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.onTrainBegin=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return this.epoch=[],this.history={},[2]}))}))},e.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n;return _f(this,(function(r){for(n in null==e&&(e={}),this.epoch.push(t),e)null==this.history[n]&&(this.history[n]=[]),this.history[n].push(e[n]);return[2]}))}))},e.prototype.syncData=function(){return Of(this,void 0,void 0,(function(){var t,e,n,r,a,i,o,s,u;return _f(this,(function(l){switch(l.label){case 0:for(r in t=[],e=[],n=[],this.history)for(a=this.history[r],i=0;i<a.length;++i)"number"!=typeof a[i]&&(o=a[i],t.push(o.data()),e.push(r),n.push(i));return[4,Promise.all(t)];case 1:for(s=l.sent(),u=0;u<s.length;++u)this.history[e[u]][n[u]].dispose(),this.history[e[u]][n[u]]=s[u][0];return[2]}}))}))},e}(Hm),Jm=function(t){function e(e,n){var r=t.call(this)||this;if(r.currentEpoch=0,r.yieldEvery=n||"auto","auto"===r.yieldEvery&&(r.yieldEvery=125),"never"===r.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return pt.isNumber(r.yieldEvery)&&(r.maybeWait=function(t,e){var n,r=pt.now();return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var o=pt.now();return o-r<e?n:(r=o,n=t.apply(void 0,a))}}(r.maybeWait.bind(r),r.yieldEvery)),r.trainBegin=e.onTrainBegin,r.trainEnd=e.onTrainEnd,r.epochBegin=e.onEpochBegin,r.epochEnd=e.onEpochEnd,r.batchBegin=e.onBatchBegin,r.batchEnd=e.onBatchEnd,r.yield=e.onYield,r}return Tf(e,t),e.prototype.maybeWait=function(t,e,n){return Of(this,void 0,void 0,(function(){var r;return _f(this,(function(a){switch(a.label){case 0:return r=[],null==this.yield?[3,2]:[4,Gm(n)];case 1:a.sent(),r.push(this.yield(t,e,n)),a.label=2;case 2:return r.push(Ef()),[4,Promise.all(r)];case 3:return a.sent(),[2]}}))}))},e.prototype.onEpochBegin=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){switch(n.label){case 0:return this.currentEpoch=t,null==this.epochBegin?[3,3]:[4,Gm(e)];case 1:return n.sent(),[4,this.epochBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return n=[],null==this.epochEnd?[3,2]:[4,Gm(e)];case 1:r.sent(),n.push(this.epochEnd(t,e)),r.label=2;case 2:return"epoch"===this.yieldEvery&&n.push(Ef()),[4,Promise.all(n)];case 3:return r.sent(),[2]}}))}))},e.prototype.onBatchBegin=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,Gm(e)];case 1:return n.sent(),[4,this.batchBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onBatchEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return n=[],null==this.batchEnd?[3,2]:[4,Gm(e)];case 1:r.sent(),n.push(this.batchEnd(t,e)),r.label=2;case 2:return"batch"===this.yieldEvery?n.push(Ef()):pt.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,t,e)),[4,Promise.all(n)];case 3:return r.sent(),[2]}}))}))},e.prototype.onTrainBegin=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return null==this.trainBegin?[3,3]:[4,Gm(t)];case 1:return e.sent(),[4,this.trainBegin(t)];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},e.prototype.onTrainEnd=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(e){switch(e.label){case 0:return null==this.trainEnd?[3,3]:[4,Gm(t)];case 1:return e.sent(),[4,this.trainEnd(t)];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},e}(Hm);function $m(t,e){return null==t&&(t={}),t instanceof Hm?[t]:Array.isArray(t)&&t[0]instanceof Hm?t:Gf(t).map((function(t){return new Jm(t,e)}))}var Zm=function(){function t(){}return t.registerCallbackConstructor=function(e,n){pt.assert(e>=0&&Number.isInteger(e),(function(){return"Verbosity level is expected to be an integer >= 0, but got "+e})),t.checkForDuplicate(n),null==t.constructors[e]&&(t.constructors[e]=[]),t.constructors[e].push(n)},t.checkForDuplicate=function(e){for(var n in t.constructors)t.constructors[+n].forEach((function(t){if(t===e)throw new Lf("Duplicate callback constructor.")}))},t.clear=function(){t.constructors={}},t.createCallbacks=function(e){var n=[];for(var r in t.constructors){var a=+r;e>=a&&n.push.apply(n,t.constructors[a])}return n.map((function(t){return new t}))},t.constructors={},t}();function Qm(t,e,n,r,a,i,o,s,u){var l=new Ym,c=[new Xm].concat(Zm.createCallbacks(e));null!=t&&c.push.apply(c,t),c.push(l);var p=new Km(c);return p.setParams({epochs:n,initialEpoch:r,samples:a,steps:i,batchSize:o,verbose:e,doValidation:s,metrics:u}),{callbackList:p,history:l}}function tg(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),Jf(t,ff.SerializationMap.getMap().classNameMap,e,"layer",n)}function eg(t,e){return $e((function(){"float32"!==t.dtype&&(t=t.asType("float32"));var n=Tc(Kd(t),e,!0),r=Un(n.shape,Ff()),a=ha(xa(n,r));return _a(t,a)}))}function ng(t,e){return $e((function(){return Ic(Kd(Da(e,t)),-1)}))}function rg(t,e){return $e((function(){return Ic(zr(Da(e,t)),-1)}))}function ag(t,e){return $e((function(){var n=Da(t,e),r=Gr(zr(t),Ff(),Number.MAX_VALUE),a=zr(_a(n,r));return Ia(100,Ic(a,-1))}))}function ig(t,e,n){return void 0===n&&(n=!1),$e((function(){if(n)e=ni(e);else{var r=Tc(e,e.shape.length-1,!0);e=_a(e,r)}return e=Gr(e,Ff(),1-Ff()),ta(Tc(Ia(t.toFloat(),$r(e)),e.shape.length-1))}))}function og(t,e){return $e((function(){var n=Jr(function(t){var e=[Dd(t.shape)];return t.reshape(e)}(t)).toInt(),r=(e=Gr(e,Ff(),1-Ff())).shape;return ig(el(n,r[r.length-1]).reshape(r),e,!1)}))}function sg(t,e){return $e((function(){var n;return n=Gr(e,Ff(),1-Ff()),n=$r(_a(n,Da(1,n))),Ic(function(t,e){if(!pt.arraysEqual(t.shape,e.shape))throw new Lf("logits and labels must have the same shape, but got shapes "+JSON.stringify(t.shape)+" and "+JSON.stringify(e.shape));return $e((function(){var n=e.relu(),r=e.abs().neg();return n.sub(e.mul(t)).add(r.exp().log1p())}))}(t,n),-1)}))}function ug(t,e){return $e((function(){var n=eg(t,-1),r=eg(e,-1),a=Ia(n,r);return ta(Tc(a,-1))}))}var lg={meanSquaredError:ng,meanAbsoluteError:rg,meanAbsolutePercentageError:ag,meanSquaredLogarithmicError:function(t,e){return $e((function(){var n=Gr(e,Ff(),Number.MAX_VALUE),r=$r(Or(1,n)),a=Gr(t,Ff(),Number.MAX_VALUE),i=$r(Or(1,a));return Ic(Kd(Da(r,i)),-1)}))},squaredHinge:function(t,e){return $e((function(){var n=xa(0,Da(1,Ia(t,e)));return Ic(Kd(n),-1)}))},hinge:function(t,e){return $e((function(){var n=xa(0,Da(1,Ia(t,e)));return Ic(n,-1)}))},categoricalHinge:function(t,e){return $e((function(){var n=Tc(Ia(t,e),-1),r=kc(Ia(Da(1,t),e),-1);return xa(0,Or(1,Da(r,n)))}))},logcosh:function(t,e){return $e((function(){var n=Math.log(2),r=Da(e,t),a=Da(Or(r,pa(Ia(-2,r))),n);return Ic(a,-1)}))},categoricalCrossentropy:ig,sparseCategoricalCrossentropy:og,binaryCrossentropy:sg,kullbackLeiblerDivergence:function(t,e){return $e((function(){var n=Gr(t,Ff(),1),r=Gr(e,Ff(),1);return Tc(Ia(t,$r(_a(n,r))),-1)}))},poisson:function(t,e){return $e((function(){var n=$r(Or(Ff(),e));return Ic(Da(e,Ia(t,n)),-1)}))},cosineProximity:ug};function cg(t){if("string"==typeof t){if(t in lg)return lg[t];var e="Unknown loss "+t;throw t.toLowerCase().includes("softmaxcrossentropy")&&(e="Unknown loss "+t+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new Lf(e)}return t}function pg(t,e){return $e((function(){var n=Ia(.5,qn(e)),r=zd(Nl(e,n),t.dtype);return Ic(wl(t,r),-1)}))}function hg(t,e){return $e((function(){return zd(wl(Cc(t,-1),Cc(e,-1)),"float32")}))}function fg(t,e){return $e((function(){return qu(t.equal(1),e.equal(1)).sum().cast("float32")}))}function dg(t,e){return $e((function(){var n=fg(t,e),r=function(t,e){return $e((function(){return qu(t.equal(0),e.equal(1)).sum().cast("float32")}))}(t,e),a=n.add(r);return Yu(Nl(a,0),n.div(a),0).cast("float32")}))}function mg(t,e){return sg(t,e)}function gg(t,e){return t.rank===e.rank&&(t=t.squeeze([t.rank-1])),(e=e.argMax(-1)).dtype!==t.dtype&&(e=e.asType(t.dtype)),wl(t,e).asType("float32")}var vg=ig,yg=og,bg={binaryAccuracy:pg,categoricalAccuracy:hg,precision:dg,categoricalCrossentropy:vg,sparseCategoricalCrossentropy:yg,mse:ng,MSE:ng,mae:rg,MAE:rg,mape:ag,MAPE:ag,cosine:ug};function xg(t){if(Vf(null!==t,"Unknown LossOrMetricFn "+t),"string"==typeof t)return t;for(var e=void 0,n=0,r=Object.keys(lg);n<r.length;n++){var a=r[n];if(lg[a]===t){e=a;break}}if(void 0!==e)return e;for(var i=0,o=Object.keys(bg);i<o.length;i++)if(a=o[i],bg[a]===t){e=a;break}return void 0!==e?e:t.name}function wg(t,e,n){if(void 0===n&&(n=!1),null==t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype||!Cg(t))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){var r=JSON.stringify(t);r.length>1048576&&console.warn('User-defined metadata of model "'+e+'" is too large in size (length='+r.length+" when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.")}}function Cg(t){if(null===t)return!0;if("object"==typeof t){if(Object.getPrototypeOf(t)===Object.prototype){for(var e=0,n=Object.keys(t);e<n.length;e++){var r=n[e];if("string"!=typeof r)return!1;if(!Cg(t[r]))return!1}return!0}if(Array.isArray(t)){for(var a=0,i=t;a<i.length;a++)if(!Cg(i[a]))return!1;return!0}return!1}var o=typeof t;return"string"===o||"number"===o||"boolean"===o}function Ng(t,e,n){void 0===n&&(n=console.log);for(var r="",a=0;a<t.length;++a)a>0&&(r=r.slice(0,r.length-1)+" "),r=(r+=t[a]).slice(0,e[a]),r+=" ".repeat(e[a]-r.length);n(r)}function Sg(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}Ng([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function kg(t,e,n,r){var a;try{a=JSON.stringify(t.outputShape)}catch(t){a="multiple"}for(var i=[],o=0,s=t.inboundNodes;o<s.length;o++){var u=s[o];if(!(null!=n&&n.length>0&&-1===n.indexOf(u)))for(var l=0;l<u.inboundLayers.length;++l){var c=u.inboundLayers[l].name,p=u.nodeIndices[l],h=u.tensorIndices[l];i.push(c+"["+p+"]["+h+"]")}}var f=t.name,d=t.getClassName(),m=0===i.length?"":i[0];for(Ng([f+" ("+d+")",a,t.countParams().toString(),m],e,r),l=1;l<i.length;++l)Ng(["","","",i[l]],e,r)}function Ig(t,e,n){return("inboundNodes"===t||"outputLayers"===t||"inputLayers"===t)&&0===e&&"string"==typeof n}function Eg(t,e){if(null===t)return null;if("string"==typeof t)return Hf(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var n=[],r=t.length,a=0;a<r;++a){var i=t[a];Ig(e,a,i)?n.push(i):n.push(Eg(i,e))}return n}for(var o={},s=0,u=Object.keys(t);s<u.length;s++){var l=u[s],c=t[l];if("name"===l&&"string"==typeof c)o[l]=c;else{var p=Hf(l);o[p]=Eg(c,p)}}return o}function Ag(t,e){if(null==t)return null;if("string"==typeof t)return qf(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var n=[],r=t.length,a=0;a<r;++a){var i=t[a];Ig(e,a,i)?n.push(i):n.push(Ag(i,e))}return n}for(var o={},s=0,u=Object.keys(t);s<u.length;s++){var l=u[s],c=t[l];o[qf(l)]="name"!==l&&"className"!==l||"string"!=typeof c?Ag(c,l):c}return o}var Tg="1.7.4",Rg=function(){function t(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof t)for(var n in e.id2Value)this.id2Value[n]=e.id2Value[n],n in e.id2Mask&&(this.id2Mask[n]=e.id2Mask[n]);else{if(null==e)return;for(var r=0,a=e;r<a.length;r++){var i=a[r];this.add(i.key,i.value)}}}return t.prototype.add=function(t,e,n){if(null!=this.id2Value[t.id])throw new Lf("Duplicate key: name="+t.name+", id="+t.id);return this.id2Value[t.id]=function(t,e){if(null==t.dtype||t.dtype===e.dtype)return e;try{return nr(e,t.dtype)}catch(n){throw new Lf("The dtype of the feed ("+e.dtype+") can not be cast to the dtype of the key '"+t.name+"' ("+t.dtype+").")}}(t,e),this.name2Id[t.name]=t.id,null!=n&&(this.id2Mask[t.id]=n),this},t.prototype.addFeed=function(t){this.add(t.key,t.value)},t.prototype.hasKey=function(t){return null!=this.id2Value[t.id]},t.prototype.names=function(){return Object.keys(this.name2Id)},t.prototype.getValue=function(t){if(t instanceof Mm){if(null==this.id2Value[t.id])throw new Lf("Nonexistent key: "+t.name);return this.id2Value[t.id]}var e=this.name2Id[t];if(null==e)throw new Lf("Feed dict has no SymbolicTensor name: "+t);return this.id2Value[e]},t.prototype.getMask=function(t){if(t instanceof Mm){if(null==this.id2Value[t.id])throw new Lf("Nonexistent key: "+t.name);return this.id2Mask[t.id]}var e=this.name2Id[t];if(null==e)throw new Lf("Feed dict has no SymbolicTensor name: "+t);return this.id2Mask[e]},t.prototype.disposeMasks=function(){null!=this.id2Mask&&Ze(this.id2Mask)},t}(),Dg={},Og={};function _g(t,e,n,r){for(var a=null!=n&&n.training,i=Array.isArray(t),o=i?t:[t],s=o.map((function(t){return t.name})),u=[],l=e.names(),c=0,p=s;c<p.length;c++){var h=p[c];-1!==l.indexOf(h)?u.push(e.getValue(h)):u.push(null)}null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);var f,d,m=s.join(",")+"|"+e.names().join(",");if(null==Dg[m]){var g=function(t,e){pt.assert(null!=t&&t.length>0,(function(){return"Expected at least one fetch, got none"}));var n=[],r={};if(1===t.length){var a=Mg(t[0],e);n=a.sorted,r=a.recipientMap}else for(var i=new Set,o=0,s=t;o<s.length;o++){for(var u=Mg(s[o],e),l=u.sorted,c=u.recipientMap,p=0,h=l;p<h.length;p++){var f=h[p];i.has(f.name)||(n.push(f),i.add(f.name))}var d=function(t){null==r[t]&&(r[t]=new Set),c[t].forEach((function(e){return r[t].add(e)}))};for(var m in c)d(m)}return{sorted:n,recipientCounts:Fg(r)}}(o,e);f=g.sorted,d=g.recipientCounts,Dg[m]=f,Og[m]=d}f=Dg[m],d={},a||Object.assign(d,Og[m]);for(var v=new Rg(e),y=0;y<f.length;++y){if(null!=r){var b=Ye().numTensors;b>r.maxNumTensors&&(r.maxNumTensors=b),b<r.minNumTensors&&(r.minNumTensors=b)}var x=f[y],w=x.sourceLayer;if(!(w instanceof Um)){for(var C=[],N=[],S=[],k=!1,I=0,E=x.inputs;I<E.length;I++){var A=E[I],T=v.getValue(A),R=v.getMask(A);C.push(T),N.push(R),null!=R&&(k=!0),a||(d[A.name]--,0!==d[A.name]||e.hasKey(A)||-1!==s.indexOf(A.name)||T.isDisposed||!0===A.sourceLayer.stateful||S.push(T))}k&&((n=n||{}).mask=N[0]);var D=Gf(w.apply(C,n)),O=null;w.supportsMasking&&(O=w.computeMask(C,N));for(var _=zg(x),F=Array.isArray(_)?_:[_],M=0;M<F.length;++M){v.hasKey(F[M])||v.add(F[M],D[M],Array.isArray(O)?O[0]:O);var z=s.indexOf(F[M].name);-1!==z&&(u[z]=D[M])}a||Ze(S)}}return v.disposeMasks(),i?u:u[0]}function Fg(t){var e={};for(var n in t)e[n]=t[n].size;return e}function Mg(t,e){for(var n=new Set,r=[],a={},i=0,o=e.names();i<o.length;i++){var s=o[i];n.add(s)}var u=[],l=[];for(u.push(t);u.length>0;){var c=u[u.length-1];if(n.has(c.name))u.pop();else{var p=l[l.length-1]===u.length-1;if(0===c.inputs.length||p)u.pop(),r.push(c),n.add(c.name),p&&l.pop();else{l.push(u.length-1);for(var h=0,f=c.inputs;h<f.length;h++){var d=f[h];null==a[d.name]&&(a[d.name]=new Set),a[d.name].add(c.name),n.has(d.name)||u.push(d)}}}}return{sorted:r,recipientMap:a}}function zg(t){var e;if(1===t.sourceLayer.inboundNodes.length)e=t.sourceLayer.output;else{for(var n=null,r=0;r<t.sourceLayer.inboundNodes.length;++r)for(var a=0,i=t.sourceLayer.inboundNodes[r].outputTensors;a<i.length;a++)if(i[a].id===t.id){n=r;break}e=t.sourceLayer.getOutputAt(n)}return e}function Lg(t,e){return function(t,e,n){var r=e.length;if(null==t||Array.isArray(t)&&0===t.length)return e.map((function(t){return null}));if(1===r)return Array.isArray(t)&&1===t.length?t:"object"==typeof t&&e[0]in t?[t[e[0]]]:[t];if(Array.isArray(t)){if(t.length!==r)throw new Error("Provided "+n+" is an array of "+t.length+" element(s), but the model has "+r+" outputs. Make sure a set of weights is provided for each model output.");return t}if("object"==typeof t&&Object.keys(t).length>0&&"object"==typeof t[Object.keys(t)[0]]){var a=[];return e.forEach((function(e){e in t?a.push(t[e]):a.push(null)})),a}throw new Error("The model has multiple ("+r+") outputs, so "+n+" must be either an array with "+r+" elements or an object with "+e+" keys. Provided "+n+" not understood: "+JSON.stringify(t))}(t,e,"classWeight")}function Bg(t,e,n,r){return Of(this,void 0,void 0,(function(){var a,i,o,s,u;return _f(this,(function(l){switch(l.label){case 0:if(null!=e||null!=r)throw new Error("Support sampleWeight is not implemented yet");return null==n?[3,2]:(a=$e((function(){if(1===t.shape.length)return t.clone();if(2===t.shape.length){if(t.shape[1]>1)return t.argMax(1);if(1===t.shape[1])return t.reshape([t.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+t.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+t.rank+") during handling of class weights. The rank is expected to be 1 or 2.")})),s=(o=Array).from,[4,a.data()]);case 1:return i=s.apply(o,[l.sent()]),Ze(a),u=[],i.forEach((function(t){if(null==n[t])throw new Error("classWeight must contain all classes in the training data. The class "+t+" exists in the data but not in classWeight");u.push(n[t])})),[2,_n(u,"float32")];case 2:return[2,null]}}))}))}function Pg(t,e){return Ia(t,e)}function Wg(t,e){var n,r,a=e;n=a.xs,r=a.ys,pt.assert(null!=n&&null!=r,(function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+e}));var i=Vg("input",t.inputNames,n),o=Vg("output",t.outputNames,r),s=i[0].shape[0];pt.assert(i.length===t.inputs.length,(function(){return"LayersModel has "+t.inputs.length+" inputs, but the dataset provides "+i.length+" inputs. (Expected input keys: "+JSON.stringify(t.inputNames)+")"})),pt.assert(o.length===t.outputs.length,(function(){return"LayersModel has "+t.outputs.length+" outputs, but the dataset provides "+o.length+" outputs. (Expected output keys: "+JSON.stringify(t.outputNames)+")"}));for(var u=function(e){pt.assert(i[e].shape[0]===s,(function(){return"Batch size mismatch: input "+t.inputNames[e]+" has "+i[e].shape[0]+"; expected "+s+" based on input "+t.inputNames[0]+"."}))},l=0;l<i.length;l++)u(l);for(var c=function(e){pt.assert(o[e].shape[0]===s,(function(){return"Batch size mismatch: output "+t.outputNames[e]+" has "+o[e].shape[0]+"; expected "+s+" based on input "+t.inputNames[0]+"."}))},p=0;p<o.length;p++)c(p);return{xs:i,ys:o}}function Vg(t,e,n){if(n instanceof wt)return[n];if(Array.isArray(n))return pt.assert(n.length===e.length,(function(){return"Received an array of "+n.length+" Tensors, but expected "+e.length+" to match the "+t+" keys "+e+"."})),n;for(var r=[],a=0,i=e;a<i.length;a++){var o=i[a];if(null==n[o])throw new Lf("The feature data generated by the dataset lacks the required "+t+" key '"+o+"'.");r.push(n[o])}return r}function Ug(t,e,n){return Of(this,void 0,void 0,(function(){var r,a,i,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,S,k,I,E,A,T,R,D,O,_,F,M,z;return _f(this,(function(L){switch(L.label){case 0:if(r=null!=n.batchesPerEpoch,pt.assert(null!=t.optimizer,(function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."})),pt.assert(null!=n,(function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."})),pt.assert(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs})),pt.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+n.batchesPerEpoch})),pt.assert(null==n.validationSplit,(function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."})),t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,L.label=1;case 1:return L.trys.push([1,,26,27]),a=null!=n.validationData,i=void 0,o=void 0,a&&(jg(n.validationData)?pt.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches})):(s=function(t){if(3===t.length)throw new Bf("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(n.validationData),i=s.xs,o=s.ys)),u=t.makeTrainFunction(),l=t.getDedupedMetricsNames(),c=a?l.slice().concat(l.map((function(t){return"val_"+t}))):l.slice(),p=$m(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,f=Qm(p,h,n.epochs,null,null,function(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}(e,n),null,a,c),d=f.callbackList,m=f.history,d.setModel(t),t.history=m,[4,d.onTrainBegin()];case 2:return L.sent(),t.stopTraining_=!1,g=null==n.initialEpoch?0:n.initialEpoch,[4,e.iterator()];case 3:v=L.sent(),L.label=4;case 4:return g<n.epochs?(y={},[4,d.onEpochBegin(g)]):[3,23];case 5:return L.sent(),b=0,x=0,r?[3,7]:[4,e.iterator()];case 6:v=L.sent(),L.label=7;case 7:return!r||b<n.batchesPerEpoch?[4,v.next()]:[3,21];case 8:return w=L.sent(),r&&w.done?(console.warn("You provided `batchesPerEpoch` as "+n.batchesPerEpoch+", but your dataset iterator ran out of data after "+b+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,21]):null==w.value?[3,15]:(C=Wg(t,w.value),N=C.xs,S=C.ys,(k={}).batch=x,k.size=N[0].shape[0],[4,d.onBatchBegin(x,k)]);case 9:if(L.sent(),I=[],null==n.classWeight)return[3,13];E=Lg(n.classWeight,t.outputNames),z=0,L.label=10;case 10:return z<E.length?(T=(A=I).push,[4,Bg(S[z],null,E[z])]):[3,13];case 11:T.apply(A,[L.sent()]),L.label=12;case 12:return++z,[3,10];case 13:for(R=N.concat(S).concat(I),D=u(R),Ze(R),z=0;z<l.length;++z)O=l[z],_=D[z],k[O]=_,Qe(_);return[4,d.onBatchEnd(x,k)];case 14:L.sent(),qm(k),x++,b++,L.label=15;case 15:return(r?b>=n.batchesPerEpoch:w.done)?a?(F=void 0,jg(n.validationData)?(M=Gf,[4,t.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return F=M.apply(void 0,[L.sent()]),[3,18];case 17:F=Gf(t.evaluate(i,o,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0})),L.label=18;case 18:for(z=0;z<t.metricsNames.length;++z)y["val_"+t.metricsNames[z]]=F[z];L.label=19;case 19:return[3,21];case 20:return t.stopTraining_?[3,21]:[3,7];case 21:return[4,d.onEpochEnd(g,y)];case 22:return L.sent(),g++,t.stopTraining_?[3,23]:[3,4];case 23:return[4,d.onTrainEnd()];case 24:return L.sent(),[4,t.history.syncData()];case 25:return L.sent(),[2,t.history];case 26:return t.isTraining=!1,[7];case 27:return[2]}}))}))}function jg(t){return"function"==typeof t.iterator}function Gg(t,e,n){return Of(this,void 0,void 0,(function(){var r,a,i,o,s,u,l,c,p,h;return _f(this,(function(f){switch(f.label){case 0:if(r=null!=(n=n||{}).batches,a=t.testFunction,i=[],n.verbose>0)throw new Bf("Verbose mode is not implemented yet.");return pt.assert(!r||n.batches>0&&Number.isInteger(n.batches),(function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)})),function(t){return"function"==typeof t.next}(e)?(s=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:s=f.sent(),f.label=3;case 3:o=s,u=0,l=0,c=function(){var e;return _f(this,(function(s){switch(s.label){case 0:return[4,o.next()];case 1:return e=s.sent(),i=$e((function(){if(e.value){var n=Wg(t,e.value),r=n.xs,o=n.ys,s=r.concat(o),c=$e((function(){return a(s)}));if(Ze(s),0===l)for(var p=0;p<c.length;++p)i.push(On(0));var h=s[0].shape[0],f=function(t){var e=c[t],n=i[t];i[t]=$e((function(){return Or(i[t],Ia(h,e))})),l>0&&Ze(n)};for(p=0;p<c.length;++p)f(p);Ze(c),u+=h,++l}return i})),e.done?(r&&console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` batches (in this case, "+n.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2]}}))},f.label=4;case 4:return!r||l<n.batches?[5,c()]:[3,6];case 5:return"break"===f.sent()?[3,6]:[3,4];case 6:for(p=0;p<i.length;++p)h=i[p],i[p]=_a(i[p],u),Ze(h);return[2,jf(i)]}}))}))}function qg(t){pt.assert(t>0&&Number.isInteger(t),(function(){return"batchSize is required to be a positive integer, but got "+t}))}function Hg(t,e,n){return null==t?[null]:Array.isArray(t)?t.map((function(t){return Bd(t,e,n-e)})):Bd(t,e,n-e)}function Kg(t,e){return $e((function(){return null==t?null:Array.isArray(t)?t.map((function(t){return Kg(t,e)})):Hd(t,"int32"===e.dtype?e:e.toInt())}))}function Xg(t,e){for(var n=[],r=0,a=null;r<t;)(a=r+e)>=t&&(a=t),n.push([r,a]),r=a;return n}function Yg(t,e,n,r,a,i,o,s,u,l,c,p,h,f,d){return Of(this,void 0,void 0,(function(){var m,g,v,y,b,x,w,C;return _f(this,(function(N){switch(N.label){case 0:if(null==a&&(a=32),null==i&&(i=1),null==c&&(c=!0),null==h&&(h=0),m=!1,null!=u&&null!=l&&(m=!0),null!=d&&(m=!0,null==f))throw new Lf("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(g=t.checkNumSamples(n,a,f,"steps_per_epoch"))&&(v=Md(0,g)),null==o&&(o=1),y=Qm(s,o,i,h,g,f,a,m,p),b=y.callbackList,x=y.history,b.setModel(t),t.history=x,[4,b.onTrainBegin()];case 1:N.sent(),t.stopTraining_=!1,w=function(i){var o,s,p,h,d;return _f(this,(function(y){switch(y.label){case 0:return[4,b.onEpochBegin(i)];case 1:if(y.sent(),o={},null==f)return[3,2];throw new Bf("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new Bf("batch shuffling is not implemneted yet");c&&pt.shuffle(v),s=_n(v),p=Xg(g,a),h=function(i){var c;return _f(this,(function(h){switch(h.label){case 0:return c={},[4,b.onBatchBegin(i,c)];case 1:return h.sent(),$e((function(){var h=p[i][0],f=p[i][1],d=Bd(s,h,f-h);c.batch=i,c.size=f-h;for(var g=Kg(n,d),v=e(g),y=0;y<r.length;++y){var b=r[y],x=v[y];c[b]=x,Qe(x)}if(i===p.length-1&&m){var w=t.testLoop(u,l,a);for(y=0;y<r.length;++y)b=r[y],Qe(x=w[y]),o["val_"+b]=x}})),[4,b.onBatchEnd(i,c)];case 2:return h.sent(),qm(c),t.stopTraining_?[2,"break"]:[2]}}))},d=0,y.label=3;case 3:return d<p.length?[5,h(d)]:[3,6];case 4:if("break"===y.sent())return[3,6];y.label=5;case 5:return++d,[3,3];case 6:s.dispose(),y.label=7;case 7:return[4,b.onEpochEnd(i,o)];case 8:return y.sent(),t.stopTraining_?[2,"break"]:[2]}}))},C=h,N.label=2;case 2:return C<i?[5,w(C)]:[3,5];case 3:if("break"===N.sent())return[3,5];N.label=4;case 4:return++C,[3,2];case 5:return[4,b.onTrainEnd()];case 6:return N.sent(),[4,t.history.syncData()];case 7:return N.sent(),[2,t.history]}}))}))}function Jg(t,e,n,r){return void 0===r&&(r={}),Of(this,void 0,void 0,(function(){var a,i,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N;return _f(this,(function(S){switch(S.label){case 0:if(t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,S.label=1;case 1:return S.trys.push([1,,7,8]),qg(p=null==r.batchSize?32:r.batchSize),[4,t.standardizeUserData(e,n,r.sampleWeight,r.classWeight,!1,p)];case 2:if(h=S.sent(),a=h[0],i=h[1],c=h[2],f=!1,d=void 0,!(null!=r.validationData&&r.validationData.length>0))return[3,4];if(f=!0,2!==r.validationData.length)throw 3===r.validationData.length?new Bf("validationData including sample weights is not supported yet."):new Lf("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");return o=r.validationData[0],s=r.validationData[1],[4,t.standardizeUserData(o,s,null,null,!0,p)];case 3:return m=S.sent(),u=m[0],l=m[1],d=u.concat(l),[3,5];case 4:null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(f=!0,g=Math.floor(a[0].shape[0]*(1-r.validationSplit)),v=a[0].shape[0],u=Hg(a,g,v),a=Hg(a,0,g),l=Hg(i,g,v),i=Hg(i,0,g),d=u.concat(l)):null!=r.validationSteps&&(f=!0),S.label=5;case 5:return y=a.concat(i).concat(c),t.checkTrainableWeightsConsistency(),b=t.makeTrainFunction(),x=t.getDedupedMetricsNames(),w=void 0,C=void 0,f?(t.makeTestFunction(),w=t.testFunction,C=x.slice().concat(x.map((function(t){return"val_"+t})))):(w=null,d=[],C=x.slice()),N=$m(r.callbacks,r.yieldEvery),[4,Yg(t,b,y,x,p,r.epochs,r.verbose,N,w,d,r.shuffle,C,r.initialEpoch,null,null)];case 6:return[2,S.sent()];case 7:return t.isTraining=!1,Zg(a,e),Zg(i,n),Zg(u,o),Zg(l,s),null!=c&&Ze(c),[7];case 8:return[2]}}))}))}function $g(t){var e=[];t instanceof wt&&(t=[t]);for(var n=0;n<t.length;++n){var r=t[n];if(1===r.rank)e.push(Ld(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(r)}}return e}function Zg(t,e){if(null!=t){var n=[];if(e instanceof wt)n.push(e.id);else if(Array.isArray(e))e.forEach((function(t){return n.push(t.id)}));else if(null!=e)for(var r in e){var a=e[r];n.push(a.id)}var i=[];if(t instanceof wt)-1===n.indexOf(t.id)&&i.push(t);else if(Array.isArray(t))t.forEach((function(t){-1===n.indexOf(t.id)&&i.push(t)}));else if(null!=t)for(var o in t){var s=t[o];-1===n.indexOf(s.id)&&i.push(s)}i.forEach((function(t){t.isDisposed||t.dispose()}))}}function Qg(t){return Array.isArray(t)}function tv(t){return!function(t){return t instanceof wt}(t)&&!Qg(t)}function ev(t,e,n,r,a){if(void 0===r&&(r=!0),void 0===a&&(a=""),null==e||0===e.length){if(null!=t){var i=!1;if(Qg(t)&&t.length>0)i=!0;else if(tv(t)){for(var o in t)if(t.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new Lf("Error when checking model "+a+" expected no data, but got "+t)}return[]}if(null==t)return e.map((function(t){return null}));var s;if(tv(t)){t=t,s=[];for(var u=0,l=e;u<l.length;u++){var c=l[u];if(null==t[c])throw new Lf('No data provided for "'+c+'". Need data for each key in: '+e);s.push(t[c])}}else if(Qg(t)){if((t=t).length!==e.length)throw new Lf("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see "+e.length+" Tensor(s), but instead got the following list of Tensor(s): "+t);s=t}else{if(t=t,e.length>1)throw new Lf("The model "+a+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);s=[t]}if(s=$g(s),null!=n)for(var p=0;p<e.length;++p)if(null!=n[p]){var h=s[p];if(h.shape.length!==n[p].length)throw new Lf("Error when checking "+a+": expected "+e[p]+" to have "+n[p].length+" dimension(s). but got array with shape "+h.shape);for(var f=0;f<n[p].length;++f)if(0!==f||r){var d=h.shape[f],m=n[p][f];if(null!=m&&m>=0&&d!==m)throw new Lf("Error when checking "+a+": expected "+e[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function nv(t,e,n,r,a){var i;if(void 0===r&&(r=!0),void 0===a&&(a=""),Array.isArray(t)){if(t.length!==e.length)throw new Lf("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 "+e.length+" Tensor(s), but instead got "+t.length+" Tensors(s).");i=t}else{if(e.length>1)throw new Lf("The model expects "+e.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(t.shape)+".");i=[t]}if(null!=n)for(var o=0;o<e.length;++o)if(null!=n[o]){var s=i[o];if(s.shape.length!==n[o].length)throw new Lf("Error when checking "+a+": expected "+e[o]+" to have "+n[o].length+" dimension(s), but got array with shape "+JSON.stringify(s.shape));for(var u=0;u<n[o].length;++u)if(0!==u||r){var l=s.shape[u],c=n[o][u];if(null!=c&&c!==l)throw new Lf("Error when checking "+a+": expected "+e[o]+" to have shape "+JSON.stringify(n[o])+" but got array with shape "+JSON.stringify(s.shape)+".")}}}var rv=function(t){function e(e){var n=t.call(this,e)||this;return n.isTraining=!1,n}return Tf(e,t),e.prototype.summary=function(t,e,n){if(void 0===n&&(n=console.log),!this.built)throw new Lf("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(t,e,n,r){void 0===r&&(r=console.log);var a,i=function(t){var e=!0,n=[],r=[];for(var a in t.nodesByDepth)n.push(t.nodesByDepth[a]);for(var i=0,o=n;i<o.length;i++){var s=o[i];if(s.length>1||1===s.length&&s[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,s)}if(e)for(var u=0,l=t.layers;u<l.length;u++){for(var c=!1,p=0,h=l[u].inboundNodes;p<h.length;p++){var f=h[p];if(-1!==r.indexOf(f)){if(c){e=!1;break}c=!0}}if(!e)break}return e}(t),o=["Layer (type)","Output shape","Param #"];if(i?(e=e||65,n=n||[.45,.85,1]):(e=e||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map((function(t){return Math.floor(e*t)}))),!i)for(var s in o.push("Receives inputs"),a=[],t.nodesByDepth)a.push.apply(a,t.nodesByDepth[s]);r("_".repeat(e)),Ng(o,n,r),r("=".repeat(e));for(var u=t.layers,l=0;l<u.length;++l)i?Sg(u[l],n,r):kg(u[l],n,a,r),r((l===u.length-1?"=":"_").repeat(e));t.checkTrainableWeightsConsistency();var c=function(t){return null!=t.collectedTrainableWeights?Tm(t.collectedTrainableWeights):Tm(t.trainableWeights)}(t),p=Tm(t.nonTrainableWeights);r("Total params: "+(c+p)),r("Trainable params: "+c),r("Non-trainable params: "+p),r("_".repeat(e))}(this,t,e,n)},e.prototype.compile=function(t){var e=this;if(null==t.loss&&(t.loss=[]),this.loss=t.loss,"string"==typeof t.optimizer)this.optimizer_=function(t){var e={Adagrad:function(){return kf.adagrad(.01)},Adadelta:function(){return kf.adadelta(1,.95,Ff())},Adam:function(){return kf.adam(.001,.9,.999,Ff())},Adamax:function(){return kf.adamax(.002,.9,.999,Ff(),0)},RMSProp:function(){return kf.rmsprop(.001,.9,0,Ff())},SGD:function(){return kf.sgd(.01)}};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,t in e)return e[t]();throw new Lf("Unknown Optimizer "+t)}(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof gf))throw new Lf("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}var n=[];if(Array.isArray(t.loss)||"string"==typeof t.loss||"function"==typeof t.loss)if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new Lf("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+t.loss+".");var r=t.loss;n=r.map((function(t){return cg(t)}))}else{var a=cg(t.loss);this.outputs.forEach((function(t){n.push(a)}))}else{for(var i in t.loss=t.loss,t.loss)if(-1===this.outputNames.indexOf(i))throw new Lf('Unknown entry in loss dictionary: "'+i+'". Only expected the following keys: '+this.outputNames);for(var o=0,s=this.outputNames;o<s.length;o++){var u=s[o];null==t.loss[u]&&console.warn('Output "'+u+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+u+" during training"),n.push(cg(t.loss[u]))}}this.lossFunctions=n,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var l=0;l<this.outputs.length;++l){var c=this.internalOutputShapes[l],p=this.outputNames[l];this.feedOutputNames.push(p),this.feedOutputShapes.push(c),this.feedLossFns.push(this.lossFunctions[l])}var h=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],kd("loss",(function(){for(var t=0;t<e.outputs.length;++t)if(-1===h.indexOf(t)){var n=e.lossFunctions[t];e.outputs.length>1&&(e.metricsTensors.push([n,t]),e.metricsNames.push(e.outputNames[t]+"_loss"))}}));var f=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map((function(t){return[]}));var n;if("string"==typeof t||"function"==typeof t)n=[t];else{if(!Array.isArray(t)&&"object"!=typeof t)throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: "+t);n=t}if(Array.isArray(n))return e.map((function(t){return n}));for(var r=[],a=0,i=e;a<i.length;a++){var o=i[a],s=n.hasOwnProperty(o)?n[o]:[];Array.isArray(s)||(s=[s]),r.push(s)}return r}(t.metrics,this.outputNames);kd("metric",(function(){for(var t=function(t){if(-1!==h.indexOf(t))return"continue";!function(n){for(var r,a,i,o=function(n){if("string"==typeof n&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var o=e.internalOutputShapes[t];1===o[o.length-1]||e.lossFunctions[t]===sg?-1!==["accuracy","acc"].indexOf(n)?a=pg:-1!==["crossentropy","ce"].indexOf(n)&&(a=mg):e.lossFunctions[t]===og?-1!==["accuracy","acc"].indexOf(n)?a=gg:-1!==["crossentropy","ce"].indexOf(n)&&(a=yg):-1!==["accuracy","acc"].indexOf(n)?a=hg:-1!==["crossentropy","ce"].indexOf(n)&&(a=vg);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),i=a,r=""+s}else{var u=function(t){if("string"==typeof t&&t in bg)return bg[t];if("string"!=typeof t&&null!=t)return t;throw new Lf("Unknown metric "+t)}(n);i=u,r=""+xg(n)}var l;kd(r,(function(){l=i})),function(t,n,r){e.outputNames.length>1&&(n=e.outputNames[t]+"_"+n),e.metricsNames.push(n),e.metricsTensors.push([r,t])}(t,r,l)},s=0,u=n;s<u.length;s++)o(u[s])}(f[t])},n=0;n<e.outputs.length;++n)t(n)})),this.collectedTrainableWeights=this.trainableWeights},e.prototype.checkTrainableWeightsConsistency=function(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")},e.prototype.evaluate=function(t,e,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize;qg(r);var a=this.standardizeUserDataXY(t,e,!0,r);try{var i=a[0].concat(a[1]);this.makeTestFunction();var o=this.testFunction;return jf(this.testLoop(o,i,r,n.verbose,n.steps))}finally{Zg(a[0],t),Zg(a[1],e)}},e.prototype.evaluateDataset=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){return this.makeTestFunction(),[2,Gg(this,t,e)]}))}))},e.prototype.checkNumSamples=function(t,e,n,r){var a;if(void 0===r&&(r="steps"),null!=n){if(a=null,null!=e)throw new Lf("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+e)}else{if(null==t)throw new Lf("Either the input data should have a defined shape, or "+r+" shoud be specified.");a=Array.isArray(t)?t[0].shape[0]:t.shape[0]}return a},e.prototype.execute=function(t,e){if(Array.isArray(e)&&0===e.length)throw new Lf("`outputs` is an empty Array, which is not allowed.");var n=Array.isArray(e),r=n?e:[e],a=this.retrieveSymbolicTensors(r),i=new Rg;if(t instanceof wt&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new Lf("The number of inputs provided ("+t.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var o=0;o<this.inputs.length;++o)i.add(this.inputs[o],t[o])}else for(var s=0,u=this.inputs;s<u.length;s++){var l=u[s],c=t[l.name];if(null==c)throw new Lf("No value is provided for the model's input "+l.name);i.add(l,c)}var p=_g(a,i);return n?p:p[0]},e.prototype.retrieveSymbolicTensors=function(t){for(var e=Wf(null,t.length),n=t.length,r=0,a=this.layers;r<a.length;r++){for(var i=a[r],o=Array.isArray(i.output)?i.output:[i.output],s=o.map((function(t){return t.name})),u=0;u<t.length;++u){var l=s.indexOf(t[u]);if(-1!==l&&(e[u]=o[l],n--),0===n)break}if(0===n)break}if(n>0){var c=[];throw e.forEach((function(e,n){null==e&&c.push(t[n])})),new Lf("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return e},e.prototype.predictLoop=function(t,e,n){var r=this;return void 0===e&&(e=32),void 0===n&&(n=!1),$e((function(){var a=r.checkNumSamples(t);if(n)throw new Bf("Verbose predictLoop() is not implemented yet.");for(var i=Xg(a,e),o=r.outputs.map((function(t){return[]})),s=function(e){$e((function(){var n=i[e][0],a=i[e][1],o=Hg(t,n,a),s=[];if(Array.isArray(o))for(var u=0;u<o.length;++u)s.push({key:r.inputs[u],value:o[u]});else s.push({key:r.inputs[0],value:o});var l=new Rg(s);return _g(r.outputs,l)})).forEach((function(t,e){return o[e].push(t)}))},u=0;u<i.length;++u)s(u);return jf(o.map((function(t){return Kn(t,0)})))}))},e.prototype.predict=function(t,e){void 0===e&&(e={});var n=$g(t);nv(n,this.inputNames,this.feedInputShapes,!1);try{var r=null==e.batchSize?32:e.batchSize;return qg(r),this.predictLoop(n,r)}finally{Zg(n,t)}},e.prototype.predictOnBatch=function(t){nv(t,this.inputNames,this.feedInputShapes,!0);var e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)},e.prototype.standardizeUserDataXY=function(t,e,n,r){if(void 0===n&&(n=!0),null==this.optimizer_)throw new zf("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var a=[],i=0;i<this.feedOutputShapes.length;++i){var o=this.feedOutputShapes[i];this.feedLossFns[i]===og?a.push(o.slice(0,o.length-1).concat([1])):a.push(o)}if(function(t,e,n){var r=Zf(t.map((function(t){return t.shape[0]})));r.sort();var a=Zf(e.map((function(t){return t.shape[0]})));if(a.sort(),r.length>1)throw new Lf("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map((function(t){return t.shape}))));if(a.length>1)throw new Lf("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map((function(t){return t.shape}))));if(r.length>0&&a.length>0&&!pt.arraysEqual(r,a))throw new Lf("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+a[0]+" target sample(s).")}(t=ev(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=ev(e,this.feedOutputNames,a,!1,"target")),function(t,e,n){for(var r=[ng,sg,ig],a=0;a<t.length;++a){var i=t[a],o=e[a],s=n[a];if(null!=o){if(o===ig&&1===i.shape[i.shape.length-1])throw new Lf("You are passing a target array of shape "+i.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==r.indexOf(o))for(var u=i.shape.slice(1),l=s.slice(1),c=0;c<u.length;++c){var p=u[c],h=l[c];if(null!=h&&p!==h)throw new Lf("A target Tensor with shape "+i.shape+" was passed for an output of shape "+s+", while using a loss function that expects targets to have the same shape as the output.")}}}}(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&t[0].shape[0]%r!=0)throw new Lf("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+t[0].shape[0]+" sample(s).");return[t,e]},e.prototype.standardizeUserData=function(t,e,n,r,a,i){return void 0===a&&(a=!0),Of(this,void 0,void 0,(function(){var o,s,u,l,c,p,h,f;return _f(this,(function(d){switch(d.label){case 0:if(o=this.standardizeUserDataXY(t,e,a,i),s=o[0],u=o[1],null!=n)throw new Error("sample weight is not supported yet.");if(l=null,null==r)return[3,4];c=Lg(r,this.outputNames),l=[],p=0,d.label=1;case 1:return p<c.length?(f=(h=l).push,[4,Bg(u[p],null,c[p])]):[3,4];case 2:f.apply(h,[d.sent()]),d.label=3;case 3:return++p,[3,1];case 4:return[2,[s,u,l]]}}))}))},e.prototype.testLoop=function(t,e,n,r,a){var i=this;return void 0===r&&(r=0),$e((function(){var o=i.checkNumSamples(e,n,a,"steps"),s=[];if(r>0)throw new Bf("Verbose mode is not implemented yet.");if(null!=a)throw new Bf("steps mode in testLoop() is not implemented yet");for(var u=Xg(o,n),l=_n(Md(0,o)),c=0;c<u.length;++c){var p=u[c][0],h=u[c][1],f=Bd(l,p,h-p),d=Kg(e,f),m=t(d);if(0===c)for(var g=0;g<m.length;++g)s.push(On(0));for(g=0;g<m.length;++g){var v=m[g];s[g]=Or(s[g],Ia(h-p,v))}}for(g=0;g<s.length;++g)s[g]=_a(s[g],o);return s}))},e.prototype.getDedupedMetricsNames=function(){for(var t=this.metricsNames,e=[],n=0;n<t.length;++n){var r=t[n],a=r;Uf(t,r)>1&&(a+="_"+Uf(t.slice(0,n),r)),e.push(a)}return e},e.prototype.makeTrainFunction=function(){var t=this;return function(e){var n=[],r=e.slice(0,t.inputs.length),a=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),i=e.slice(t.inputs.length+t.outputs.length,t.inputs.length+2*t.outputs.length),o=[],s=t.collectedTrainableWeights.map((function(t){return t.read()}));return[t.optimizer_.minimize((function(){for(var e=[],s=0;s<t.inputs.length;++s)e.push({key:t.inputs[s],value:r[s]});var u,l=new Rg(e),c=_g(t.outputs,l,{training:!0});for(s=0;s<t.lossFunctions.length;++s){var p=(0,t.lossFunctions[s])(a[s],c[s]);null!=i[s]&&(p=Pg(p,i[s]));var h=Ic(p);n.push(h),u=0===s?p:Or(u,p)}for(s=0;s<t.metricsTensors.length;++s){var f=void 0;if(t.outputs.length>1&&s<t.outputs.length)f=n[s];else{var d=t.metricsTensors[s][0],m=t.metricsTensors[s][1];f=Ic(d(a[m],c[m]))}Qe(f),o.push(f)}return u=Ic(u),t.calculateLosses().forEach((function(t){u=Or(u,t)})),u}),!0,s)].concat(o)}},e.prototype.makeTestFunction=function(){var t=this;this.testFunction=function(e){return $e((function(){for(var n,r=[],a=e.slice(0,t.inputs.length),i=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),o=[],s=0;s<t.inputs.length;++s)o.push({key:t.inputs[s],value:a[s]});var u=new Rg(o),l=_g(t.outputs,u);for(s=0;s<t.lossFunctions.length;++s){var c=t.lossFunctions[s],p=Ic(c(i[s],l[s]));n=0===s?p:Or(n,p),r.push(n)}for(s=0;s<t.metricsTensors.length;++s){var h=t.metricsTensors[s][0],f=t.metricsTensors[s][1],d=Ic(h(i[f],l[f]));r.push(d)}return r}))}},e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),Of(this,void 0,void 0,(function(){return _f(this,(function(r){return[2,Jg(this,t,e,n)]}))}))},e.prototype.fitDataset=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){return[2,Ug(this,t,e)]}))}))},e.prototype.trainOnBatch=function(t,e){return Of(this,void 0,void 0,(function(){var n,r,a,i,o,s,u,l,c;return _f(this,(function(p){switch(p.label){case 0:return[4,this.standardizeUserData(t,e)];case 1:n=p.sent(),r=n[0],a=n[1],i=this.makeTrainFunction(),o=i(r.concat(a)),s=[],u=0,l=o,p.label=2;case 2:return u<l.length?[4,l[u].data()]:[3,5];case 3:c=p.sent(),s.push(c[0]),p.label=4;case 4:return u++,[3,2];case 5:return Ze(o),[2,jf(s)]}}))}))},e.prototype.getNamedWeights=function(t){for(var e=[],n=null!=t&&t.trainableOnly,r=n?this.trainableWeights:this.weights,a=this.getWeights(n),i=0;i<r.length;++i)n&&!r[i].trainable||e.push({name:r[i].originalName,tensor:a[i]});return e},Object.defineProperty(e.prototype,"stopTraining",{get:function(){return this.stopTraining_},set:function(t){this.stopTraining_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"optimizer",{get:function(){return this.optimizer_},set:function(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=t.prototype.dispose.call(this);if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var n=Ye().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=n-Ye().numTensors}return e},e.prototype.getLossIdentifiers=function(){var t;if("string"==typeof this.loss)t=qf(this.loss);else if(Array.isArray(this.loss)){for(var e=0,n=this.loss;e<n.length;e++)if("string"!=typeof n[e])throw new Error("Serialization of non-string loss is not supported.");t=this.loss.map((function(t){return qf(t)}))}else{var r=Object.keys(this.loss);t={};for(var a=this.loss,i=0,o=r;i<o.length;i++){var s=o[i];if("string"!=typeof a[s])throw new Error("Serialization of non-string loss is not supported.");t[s]=qf(a[s])}}return t},e.prototype.getMetricIdentifiers=function(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[qf(xg(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((function(t){return qf(xg(t))}));var t={};for(var e in this.metrics)t[e]=qf(xg(this.metrics[e]));return t},e.prototype.getTrainingConfig=function(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}},e.prototype.loadTrainingConfig=function(t){if(null!=t.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=t.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=t.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");var e,n,r=tg(Eg(t.optimizer_config));if("string"==typeof t.loss)e=Hf(t.loss);else if(Array.isArray(t.loss))e=t.loss.map((function(t){return Hf(t)}));else if(null!=t.loss)for(var a in e={},t.loss)e[a]=Hf(t.loss[a]);if(Array.isArray(t.metrics))n=t.metrics.map((function(t){return Hf(t)}));else if(null!=t.metrics)for(var a in n={},t.metrics)n[a]=Hf(t.metrics[a]);this.compile({loss:e,metrics:n,optimizer:r})},e.prototype.save=function(t,e){return Of(this,void 0,void 0,(function(){var n,r,a,i,o,s,u,l,c,p,h;return _f(this,(function(f){switch(f.label){case 0:if("string"==typeof t){if(0===(n=af.getSaveHandlers(t)).length)throw new Lf("Cannot find any save handlers for URL '"+t+"'");if(n.length>1)throw new Lf("Found more than one ("+n.length+") save handlers for URL '"+t+"'");t=n[0]}if(null==t.save)throw new Lf("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,af.encodeWeights(this.getNamedWeights(e))];case 1:return r=f.sent(),a=this.toJSON(null,!1),i={modelTopology:a,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v"+Tg,convertedBy:null},null!=e&&e.includeOptimizer&&null!=this.optimizer?(i.trainingConfig=this.getTrainingConfig(),o="optimizer",p=(c=af).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,p.apply(c,[f.sent(),o])];case 3:s=f.sent(),u=s.data,l=s.specs,(h=r.specs).push.apply(h,l),r.data=af.concatenateArrayBuffers([r.data,u]),f.label=4;case 4:return null!=this.userDefinedMetadata&&(wg(this.userDefinedMetadata,this.name,!0),i.userDefinedMetadata=this.userDefinedMetadata),i.weightData=r.data,i.weightSpecs=r.specs,[2,t.save(i)]}}))}))},e.prototype.setUserDefinedMetadata=function(t){wg(t,this.name),this.userDefinedMetadata=t},e.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},e.className="Model",e}(function(t){function e(n){var r=t.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var a=r.getClassName().toLowerCase();r.name=Sm(a)}if(r.supportsMasking=!1,r.trainable_=!0,Array.isArray(n.inputs)?r.inputs=n.inputs.slice():r.inputs=[n.inputs],Array.isArray(n.outputs)?r.outputs=n.outputs.slice():r.outputs=[n.outputs],Zf(r.inputs).length!==r.inputs.length)throw new Lf("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map((function(t){return t.name})));Zf(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map((function(t){return t.name}))),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[],r.internalContainerRefs=[];for(var i=0,o=r.outputs;i<o.length;i++){var s=(I=o[i]).sourceLayer,u=I.nodeIndex,l=I.tensorIndex;r.outputLayers.push(s),r.outputLayersNodeIndices.push(u),r.outputLayersTensorIndices.push(l)}for(var c=0,p=r.inputs;c<p.length;c++)s=(I=p[c]).sourceLayer,u=I.nodeIndex,l=I.tensorIndex,Vf(0===u,"input layer has >1 nodes"),Vf(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 h=0;h<r.inputLayers.length;h++){if(!((s=r.inputLayers[h])instanceof Um))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+n.inputs+". Input "+h+" (0-based) originates from layer type "+s.getClassName()+".");r.inputNames.push(s.name),r.feedInputShapes.push(s.batchInputShape),r.feedInputNames.push(s.name)}for(var f=0,d=r.outputLayers;f<d.length;f++)s=d[f],r.outputNames.push(s.name);r.internalInputShapes=r.inputs.map((function(t){return t.shape})),r.internalOutputShapes=r.outputs.map((function(t){return t.shape}));for(var m={},g={},v={},y={},b={},x=[],w=function(t,n,a,i,o,s){null!=i&&null!=o&&null!=s||(i=t.sourceLayer,o=t.nodeIndex,s=t.tensorIndex);var u=i.inboundNodes[o];if(-1!==a.indexOf(u))throw new zf("The tensor "+t.name+' at layer "'+i.name+'" is part of a cycle.');if(-1===n.indexOf(u)){r.containerNodes.add(e.nodeKey(i,o)),i.id in b||(b[i.id]=Object.keys(b).length),-1===a.indexOf(u)&&a.push(u);for(var l=u.inboundLayers.length,c=0;c<l;c++){var p=u.inputTensors[c],h=u.inboundLayers[c],f=u.nodeIndices[c],d=u.tensorIndices[c];w(p,n,a,h,f,d)}for(n.push(u);a.indexOf(u)>=0;)a.splice(a.indexOf(u),1);x.push(u)}},C=[],N=[],S=0,k=r.outputs;S<k.length;S++){var I=k[S];w(I,C,N)}for(var E=0,A=x.slice().reverse();E<A.length;E++){g[(J=A[E]).id]=J,J.id in m||(m[J.id]=0);var T=m[J.id],R=null==v[J.outboundLayer.id]?0:v[J.outboundLayer.id];for(T=Math.max(T,R),v[J.outboundLayer.id]=T,y[J.outboundLayer.id]=J.outboundLayer,m[J.id]=T,h=0;h<J.inboundLayers.length;h++){var D=J.inboundLayers[h],O=(u=J.nodeIndices[h],D.inboundNodes[u]),_=null==m[O.id]?0:m[O.id];m[O.id]=Math.max(T+1,_),g[O.id]=O}}var F={};for(var M in m)(T=m[M])in F||(F[T]=[]),F[T].push(g[M]);var z={};for(var L in v)(T=v[L])in z||(z[T]=[]),z[T].push(y[L]);var B=Object.keys(z).map((function(t){return parseInt(t,10)})).sort($f);r.layers=[];for(var P=0,W=B;P<W.length;P++){var V=z[T=W[P]];V.sort((function(t,e){var n=b[t.id],r=b[e.id];return n<r?-1:n>r?1:0}));for(var U=0,j=V;U<j.length;U++)(s=j[U])instanceof e&&r.internalContainerRefs.push(s),r.layers.push(s)}r.layersByDepth=z,B=Object.keys(F).map((function(t){return parseInt(t,10)})).sort($f);for(var G=r.inputs.slice(),q=[],H=0,K=B;H<K.length;H++)for(var X=0,Y=F[T=K[H]];X<Y.length;X++){var J;if(null!=(s=(J=Y[X]).outboundLayer)){for(var $=0,Z=J.inputTensors;$<Z.length;$++)if(I=Z[$],-1===G.indexOf(I))throw new zf("Graph disconnected: cannot obtain value for tensor "+I+' at layer "'+s.name+'". The following previous layers were accessed without issue: '+q);for(var Q=0,tt=J.outputTensors;Q<tt.length;Q++)I=tt[Q],G.push(I);q.push(s.name)}}r.nodesByDepth=F;for(var et=r.layers.map((function(t){return t.name})),nt=function(t){var e=et.filter((function(e){return e===t})).length;if(1!==e)throw new zf('The name "'+t+'" is used '+e+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(et))},rt=0,at=et;rt<at.length;rt++)nt(at[rt]);return r.outboundNodes=[],r.inboundNodes=[],new Lm({outboundLayer:r,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:r.inputs,outputTensors:r.outputs,inputMasks:r.inputs.map((function(t){return null})),outputMasks:r.outputs.map((function(t){return null})),inputShapes:r.inputs.map((function(t){return t.shape})),outputShapes:r.outputs.map((function(t){return t.shape}))}),r.built=!0,r._refCount=1,r}return Tf(e,t),e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){this.assertNotDisposed();var t={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(var e=0,n=this.layers;e<n.length;e++){var r=n[e];t.numDisposedVariables+=r.dispose().numDisposedVariables}for(var a=0,i=this.internalContainerRefs;a<i.length;a++){var o=i[a];t.numDisposedVariables+=o.dispose().numDisposedVariables}}return t.refCountAfterDispose=this._refCount,t},Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.layers.forEach((function(e){e._trainableWeights.forEach((function(e){return e.trainable=t}))})),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(this._trainableWeights.length>0)throw new Lf("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 t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t=t.concat(r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var a=[],i=0,o=this.layers;i<o.length;i++)r=o[i],a.push.apply(a,r.trainableWeights);return a.concat(t)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.loadWeights=function(t,e){void 0===e&&(e=!0);for(var n={},r=0,a=0,i=this.layers;a<i.length;a++)for(var o=0,s=i[a].weights;o<s.length;o++){var u=s[o];if(null!=n[u.originalName])throw new Lf("Duplicate weight name: "+u.originalName);n[u.originalName]=u,r++}var l=[];for(var c in t){if(null!=n[c])l.push([n[c],t[c]]);else if(e)throw new Lf("Provided weight data has no target variable: "+c);delete n[c]}if(e){var p=[];for(var h in n)p.push(h);if(p.length>0)throw new Lf(p.length+" of "+r+" weights are not set: "+p)}_m(l)},e.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers "+Tg,e.backend="TensorFlow.js",e},e.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=Ag(this.updatedConfig());return e?JSON.stringify(n):n},e.prototype.call=function(t,e){var n=this;return $e((function(){t=Gf(t);for(var r=new Rg,a=0;a<n.inputs.length;++a)r.add(n.inputs[a],t[a]);return _g(n.outputs,r,e)}))},e.prototype.computeMask=function(t,e){var n=this;return $e((function(){var r;return t=Gf(t),r=null==e?Wf(null,t.length):Gf(e),n.runInternalGraph(t,r)[1]}))},e.prototype.computeOutputShape=function(t){var e=Im(t);if(e.length!==this.inputLayers.length)throw new Lf("Invalid inputShape argument "+t+": model has "+this.inputLayers.length+" tensor inputs.");for(var n={},r=0;r<e.length;r++){var a=this.inputLayers[r],i=e[r];n[N=a.name+"_0_0"]=i}var o=Object.keys(this.nodesByDepth).map((function(t){return parseInt(t,10)})).sort($f);if(o.length>1)for(var s=0,u=o;s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){var h=p[c];if(a=h.outboundLayer,-1===this.inputLayers.map((function(t){return t.id})).indexOf(a.id)){for(var f=[],d=0;d<h.inboundLayers.length;d++){var m=h.inboundLayers[d],g=h.nodeIndices[d],v=h.tensorIndices[d],y=n[N=m.name+"_"+g+"_"+v];f.push(y)}var b=Im(a.computeOutputShape(jf(f))),x=a.inboundNodes.indexOf(h);for(d=0;d<b.length;d++)n[N=a.name+"_"+x+"_"+d]=b[d]}}var w=[],C=[];for(r=0;r<this.outputLayers.length;r++){a=this.outputLayers[r],x=this.outputLayersNodeIndices[r],v=this.outputLayersTensorIndices[r];var N=a.name+"_"+x+"_"+v;C.push(N)}for(r=0;r<C.length;r++){var S=C[r];Vf(S in n),w.push(n[S])}return jf(w)},e.prototype.runInternalGraph=function(t,e){null==e&&(e=Wf(null,t.length));for(var n={},r=0;r<this.inputs.length;++r){var a=this.inputs[r],i=t[r],o=e[r];n[a.id]=[i,o]}for(var s=0,u=Object.keys(this.nodesByDepth).map((function(t){return parseInt(t,10)})).sort($f);s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){for(var h=p[c],f=h.outboundLayer,d=h.inputTensors,m=h.outputTensors,g=new Array,v=0,y=d;v<y.length;v++)(a=y[v]).id in n&&g.push(n[a.id]);if(g.length===d.length){var b={},x=void 0,w=void 0,C=void 0,N=void 0;if(null!=h.callArgs&&(b=h.callArgs),1===g.length){var S=g[0],k=S[0],I=S[1];null==b.mask&&(b.mask=I),C=Gf(f.call(k,b)),N=Gf(f.computeMask(k,I)),x=[k],w=[I]}else x=g.map((function(t){return t[0]})),w=g.map((function(t){return t[1]})),null==b.mask&&(b.mask=w),C=Gf(f.call(x,b)),N=Gf(f.computeMask(x,w));if(f.activityRegularizer)throw new Bf("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<m.length;++r)a=m[r],i=C[r],o=N[r],n[a.id]=[i,o]}}for(var E=[],A=[],T=[],R=0,D=this.outputs;R<D.length;R++){Vf((a=D[R]).id in n,"Could not compute output "+a.name+" : "+a.id);var O=n[a.id],_=O[0];o=O[1],T.push(_.shape),E.push(_),A.push(o)}return[E,A,T]},e.prototype.buildNodeConversionMap=function(t){for(var n,r={},a=0,i=this.layers;a<i.length;a++){var o=i[a];n=o instanceof e?1:0;for(var s=0;s<o.inboundNodes.length;s++){var u=e.nodeKey(o,s);this.containerNodes.has(u)&&(r[u]=n,n+=1)}}return r},e.prototype.getLayer=function(t,e){if(null!=e){if(this.layers.length<=e)throw new Lf("Was asked to retrieve layer at index "+e+", but model only has "+this.layers.length+" layer(s).");return this.layers[e]}if(null==t)throw new Lf("Provide either a layer name or layer index");for(var n=0,r=this.layers;n<r.length;n++){var a=r[n];if(a.name===t)return a}throw new Lf("No such layer: "+t)},e.prototype.calculateLosses=function(){var t=this;return $e((function(){for(var n=[],r=0,a=t.layers;r<a.length;r++)for(var i=a[r],o=0;o<i.inboundNodes.length;++o){var s=e.nodeKey(i,o);t.containerNodes.has(s)&&n.push.apply(n,i.calculateLosses())}return n}))},e.prototype.getConfig=function(){for(var t={name:this.name},n=this.buildNodeConversionMap(this.layers),r=[],a=0,i=this.layers;a<i.length;a++){for(var o=(x=i[a]).getClassName(),s=x.getConfig(),u=[],l=0;l<x.inboundNodes.length;l++){var c=x.inboundNodes[l],p=e.nodeKey(x,l),h={};if(this.containerNodes.has(p)){if(c.callArgs)try{JSON.stringify(c.callArgs),h=c.callArgs}catch(t){console.warn("Layer "+x.name+" was passed non-serializable keyword arguments: "+c.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),h={}}if(c.inboundLayers.length>0){for(var f=[],d=0;d<c.inboundLayers.length;d++){var m=c.inboundLayers[d],g=c.nodeIndices[d],v=c.tensorIndices[d];null==(C=n[e.nodeKey(m,g)])&&(C=0),f.push([m.name,C,v,h])}u.push(f)}}}var y={};y.name=x.name,y.className=o,y.config=s,y.inboundNodes=u,r.push(y)}t.layers=r;var b=[];for(d=0;d<this.inputLayers.length;d++){var x=this.inputLayers[d];g=this.inputLayersNodeIndices[d],p=e.nodeKey(x,g),this.containerNodes.has(p)&&(null!==(C=n[p])&&void 0!==C||(C=0),v=this.inputLayersTensorIndices[d],b.push([x.name,C,v]))}t.inputLayers=b;var w=[];for(d=0;d<this.outputLayers.length;d++){var C;x=this.outputLayers[d],g=this.outputLayersNodeIndices[d],p=e.nodeKey(x,g),this.containerNodes.has(p)&&(null!==(C=n[p])&&void 0!==C||(C=0),v=this.outputLayersTensorIndices[d],w.push([x.name,C,v]))}return t.outputLayers=w,t},e.fromConfig=function(t,e,n,r){void 0===n&&(n={}),void 0===r&&(r=!1);var a={},i={};function o(t,e){t.name in i?i[t.name].push(e):i[t.name]=[e]}function s(t,e){for(var n,r=[],i=0,s=e;i<s.length;i++){var u=s[i],l=u[0],c=u[1],p=u[2];if(n=null==u[3]?{}:u[3],!(l in a))return void o(t,e);var h=a[l];if(h.inboundNodes.length<=c)return void o(t,e);var f=h.inboundNodes[c];r.push(f.outputTensors[p])}r.length>0&&t.apply(jf(r),n)}function u(t){var n=t.name,i=tg(t,null!=e.customObjects?e.customObjects:{});i.setFastWeightInitDuringBuild(r),a[n]=i,t.inboundNodes.forEach((function(t){if(!(t instanceof Array))throw new Lf("Corrupted configuration, expected array for nodeData: "+t);o(i,t)}))}for(var l=e.name,c=e.layers,p=0,h=c;p<h.length;p++)u(m=h[p]);for(;!Qf(i);)for(var f=0,d=c;f<d.length;f++){var m=d[f];if((T=a[m.name]).name in i){var g=i[T.name];delete i[T.name];for(var v=0,y=g;v<y.length;v++)s(T,y[v])}}for(var b=[],x=[],w=0,C=e.inputLayers;w<C.length;w++){var N=(m=C[w])[0],S=m[1],k=m[2];Vf(N in a);var I=(T=a[N]).inboundNodes[S].outputTensors;b.push(I[k])}for(var E=0,A=e.outputLayers;E<A.length;E++){var T;N=(m=A[E])[0],S=m[1],k=m[2],Vf(N in a),I=(T=a[N]).inboundNodes[S].outputTensors,x.push(I[k])}return new t({inputs:b,outputs:x,name:l})},Object.defineProperty(e.prototype,"stateful",{get:function(){if(this._stateful)throw new Lf("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(var t=0,e=this.layers;t<e.length;t++)if(e[t].stateful)return!0;return!1},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){var t=this;$e((function(){t.layers.forEach((function(t){t.stateful&&t.resetStates()}))}))},e}(Pm));function av(t,e,n){return Of(this,void 0,void 0,(function(){var r,a,i,o,s,u,l,c,p;return _f(this,(function(h){switch(h.label){case 0:if(null==n&&(n={}),null==t.load)throw new Lf("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,t.load()];case 1:if(r=h.sent(),null!=(a=r.modelTopology).model_config&&(a=a.model_config),i=null==n.strict||n.strict,o=null!=r.weightData&&null!=r.weightSpecs&&i,s=tg(Eg(a),e,o),null!=(u=r.trainingConfig)&&s.loadTrainingConfig(u),null!=r.userDefinedMetadata&&s.setUserDefinedMetadata(r.userDefinedMetadata),null==r.weightData)return[3,4];if(null==r.weightSpecs)throw new Lf("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return l=function(t,e){var n=af.decodeWeights(t,e),r={},a=[];return e.forEach((function(t){"optimizer"===t.group?a.push({name:t.name,tensor:n[t.name]}):r[t.name]=n[t.name]})),{modelWeights:r,optimizerWeights:a}}(r.weightData,r.weightSpecs),c=l.modelWeights,p=l.optimizerWeights,s.loadWeights(c,i),null!=s.optimizer&&p.length>0?[4,s.optimizer.setWeights(p)]:[3,3];case 2:h.sent(),h.label=3;case 3:Ze(c),Ze(p.map((function(t){return t.tensor}))),h.label=4;case 4:return[2,s]}}))}))}ff.registerClass(rv);var iv=function(t){function e(e){var n=t.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},n.trainable=!0,n.built=!1,n.name=null!=e.name?e.name:Sm("sequential_"),null!=e.layers)for(var r=0,a=e.layers;r<a.length;r++){var i=a[r];n.add(i)}return n}return Tf(e,t),e.prototype.checkShape=function(t){if(t.inboundNodes[0].outputTensors[0].shape.some((function(t){return t<0})))throw new Lf("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},e.prototype.add=function(t){var n,r=t instanceof e||t instanceof rv;if(r){if(1!==(n=t).outputs.length)throw new Lf("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Lf("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===t.inboundNodes.length){if(null==t.batchInputShape)throw new Lf("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var a=jm({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(a)}if(r)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==t.inboundNodes.length)throw new Lf("A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer "+t.name+" which has "+t.inboundNodes.length+" pre-existing inbound connections.");if(1!==t.inboundNodes[0].outputTensors.length)throw new Lf("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=Wm(this.outputs[0])}this.inboundNodes=[],new Lm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Wf(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((function(t){return t.shape})),outputShapes:this.outputs[0].shape})}else{var i=t.apply(this.outputs[0]);if(Array.isArray(i))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[i],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1},e.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}},e.prototype.call=function(t,e){return null==this.model&&this.build(),this.model.call(t,e)},e.prototype.build=function(t){if(Am(t),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new rv({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0},e.prototype.countParams=function(){return this.built||this.build(),t.prototype.countParams.call(this)},e.prototype.summary=function(e,n,r){void 0===r&&(r=console.log),this.built||this.build(),t.prototype.summary.call(this,e,n,r)},e.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},e.prototype.evaluate=function(t,e,n){if(void 0===n&&(n={}),!this.built)throw new zf("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)},e.prototype.evaluateDataset=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){if(!this.built)throw new zf("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(t,e)]}))}))},e.prototype.predict=function(t,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(t,e)},e.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},e.prototype.compile=function(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames},Object.defineProperty(e.prototype,"optimizer",{get:function(){return null==this.model?void 0:this.model.optimizer},set:function(t){this.model.optimizer=t},enumerable:!0,configurable:!0}),e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),Of(this,void 0,void 0,(function(){return _f(this,(function(r){if(!this.built)throw new zf("The model needs to be compiled before being used.");return[2,this.model.fit(t,e,n)]}))}))},e.prototype.fitDataset=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){if(!this.built)throw new zf("The model needs to be compiled before being used.");return[2,this.model.fitDataset(t,e)]}))}))},e.prototype.trainOnBatch=function(t,e){return Of(this,void 0,void 0,(function(){return _f(this,(function(n){return[2,this.model.trainOnBatch(t,e)]}))}))},e.fromConfig=function(t,n,r,a){var i;void 0===r&&(r={}),void 0===a&&(a=!1);var o={};if(n instanceof Array){if(null==n[0].className||"Merge"===n[0].className)throw new Lf("Legacy serialization format not supported yet.");i=n}else pt.assert(null!=n.layers,(function(){return"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."})),i=n.layers,delete n.layers,o=n;var s=new t(o);if(!(s instanceof e))throw new Bf("Sequential.fromConfig called on non-Sequential input: "+s);for(var u=0,l=i;u<l.length;u++){var c=tg(l[u],void 0,a);a&&c.setFastWeightInitDuringBuild(!0),s.add(c)}return s},Object.defineProperty(e.prototype,"stopTraining",{get:function(){if(null==this.model)throw new Lf("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining},set:function(t){if(null==this.model)throw new Lf("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e],a={};a.className=r.getClassName(),a.config=r.getConfig(),t.push(a)}return{name:this.name,layers:t}},e.className="Sequential",e}(rv);function ov(t){return new rv(t)}function sv(t){return new iv(t)}function uv(t,e){return null==e&&(e={}),function(t,e){return Of(this,void 0,void 0,(function(){var n;return _f(this,(function(r){if(null==e&&(e={}),"string"==typeof t){if(0===(n=af.getLoadHandlers(t,e.onProgress)).length)n.push(af.browserHTTPRequest(t,e));else if(n.length>1)throw new Lf("Found more than one ("+n.length+") load handlers for URL '"+t+"'");t=n[0]}return[2,av(t,void 0,e)]}))}))}(t,e)}function lv(t){return jm(t)}function cv(t,e){Zm.registerCallbackConstructor(t,e)}ff.registerClass(iv);var pv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.getConfig=function(){return{}},e}(ff.Serializable),hv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=1),function(t,e){if(void 0===e&&(e=1),1!==e)throw new Bf("Support for alpha values other than 1 ("+e+") is not implemented yet.");return Dc(t)}(t,e)},e.className="elu",e}(pv);ff.registerClass(hv);var fv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return zc(t)},e.className="selu",e}(pv);ff.registerClass(fv);var dv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return Fc(t)},e.className="relu",e}(pv);ff.registerClass(dv);var mv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return $e((function(){return Ca(6,Fc(t))}))},e.className="relu6",e}(pv);ff.registerClass(mv);var gv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return t},e.className="linear",e}(pv);ff.registerClass(gv);var vv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return aa(t)},e.className="sigmoid",e}(pv);ff.registerClass(vv);var yv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return function(t){return $e((function(){var e=Or(.5,Ia(.2,t));return Gr(e,0,1)}))}(t)},e.className="hardSigmoid",e}(pv);ff.registerClass(yv);var bv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return pa(t)},e.className="softplus",e}(pv);ff.registerClass(bv);var xv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return function(t){return $e((function(){return _a(t,zr(t).add(1))}))}(t)},e.className="softsign",e}(pv);ff.registerClass(xv);var wv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t){return ma(t)},e.className="tanh",e}(pv);ff.registerClass(wv);var Cv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),ni(t,e)},e.className="softmax",e}(pv);ff.registerClass(Cv);var Nv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),ri(t,e)},e.className="logSoftmax",e}(pv);function Sv(t){return t.getClassName()}function kv(t,e){return void 0===e&&(e={}),Jf(t,ff.SerializationMap.getMap().classNameMap,e,"activation")}function Iv(t){var e;return null==t?kv(e={className:"linear",config:{}}):"string"==typeof t?((e={}).className=t,e.config={},kv(e)):t instanceof pv?t:kv(t)}function Ev(t){if(null!=t&&"object"!=typeof t)throw new Error("Argument to L1L2 regularizer's constructor is expected to be an object, but received: "+t)}ff.registerClass(Nv);var Av=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e}(ff.Serializable),Tv=function(t){function e(e){var n=t.call(this)||this;return Ev(e),n.l1=null==e||null==e.l1?.01:e.l1,n.l2=null==e||null==e.l2?.01:e.l2,n.hasL1=0!==n.l1,n.hasL2=0!==n.l2,n}return Tf(e,t),e.prototype.apply=function(t){var e=this;return $e((function(){var n=Vn([1]);return e.hasL1&&(n=Or(n,Tc(Ia(e.l1,zr(t))))),e.hasL2&&(n=Or(n,Tc(Ia(e.l2,Kd(t))))),n.asScalar()}))},e.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},e.fromConfig=function(t,e){return new t({l1:e.l1,l2:e.l2})},e.className="L1L2",e}(Av);ff.registerClass(Tv);var Rv={l1l2:"L1L2"};function Dv(t){return Xf(t)}function Ov(t,e){return void 0===e&&(e={}),Jf(t,ff.SerializationMap.getMap().classNameMap,e,"regularizer")}function _v(t){return null==t?null:"string"==typeof t?Ov({className:t in Rv?Rv[t]:t,config:{}}):t instanceof Av?t:Ov(t)}var Fv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,null!=e&&(n.maxValue=e.maxValue),n}return Tf(e,t),e.prototype.call=function(t,e){t=Em(t);var n=Fc(t);return null!=this.maxValue&&(n=Gr(n,0,this.maxValue)),n},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={maxValue:this.maxValue},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ReLU",e}(Pm);ff.registerClass(Fv);var Mv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_ALPHA=.3,null==e&&(e={}),n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return Tf(e,t),e.prototype.call=function(t,e){var n=Em(t);return Oc(n,this.alpha)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LeakyReLU",e}(Pm);ff.registerClass(Mv);var zv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),n.supportsMasking=!0,n.alphaInitializer=bm(e.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=_v(e.alphaRegularizer),n.alphaConstraint=dd(e.alphaConstraint),null==e.sharedAxes)n.sharedAxes=null;else if(Array.isArray(e.sharedAxes))n.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Lf("Expected sharedAxes to be a number or an array of numbers, but got "+e.sharedAxes);n.sharedAxes=[e.sharedAxes]}return n}return Tf(e,t),e.prototype.build=function(t){var e=(t=Am(t)).slice(1);if(null!=this.sharedAxes)for(var n=0,r=this.sharedAxes;n<r.length;n++)e[(i=r[n])-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);var a={};if(null!=this.sharedAxes)for(var i=1;i<t.length;++i)a[i]=t[i];this.inputSpec=[new Fm({ndim:t.length,axes:a})],this.built=!0},e.prototype.call=function(t,e){return t=Em(t),_c(t,this.alpha.read())},e.prototype.getConfig=function(){var e={alphaInitializer:ym(this.alphaInitializer),alphaRegularizer:Dv(this.alphaRegularizer),alphaConstraint:hd(this.alphaConstraint),sharedAxes:this.sharedAxes},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="PReLU",e}(Pm);ff.registerClass(zv);var Lv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==n.DEFAULT_ALPHA)throw new Bf("Non-default alpha value ("+e.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return Tf(e,t),e.prototype.call=function(t,e){var n=Em(t);return Dc(n)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ELU",e}(Pm);ff.registerClass(Lv);var Bv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_THETA=1,null==e&&(e={}),n.theta=null==e.theta?n.DEFAULT_THETA:e.theta,n}return Tf(e,t),e.prototype.call=function(t,e){var n=Em(t);return n.mul(zd(n.greater(this.theta),"float32"))},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={theta:this.theta},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ThresholdedReLU",e}(Pm);ff.registerClass(Bv);var Pv=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_AXIS=1,null==e&&(e={}),n.softmax=(new Cv).apply,n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n}return Tf(e,t),e.prototype.call=function(t,e){var n=Em(t);return this.softmax(n,this.axis)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Softmax",e}(Pm);function Wv(t,e,n){if("number"==typeof t)return Wf(t,e);if(t.length!==e)throw new Lf("The "+n+" argument must be an integer or tuple of "+e+" integers. Received: "+t.length+" elements.");for(var r=0;r<e;++r){var a=t[r];if(!Rd(a))throw new Lf("The "+n+" argument must be an integer or tuple of "+e+" integers. Received: "+JSON.stringify(t)+" including a non-integer number "+a)}return t}function Vv(t,e,n,r,a){return void 0===a&&(a=1),null==t?t:(i="same"===n?t:t-(e+(e-1)*(a-1))+1,Math.floor((i+r-1)/r));var i}function Uv(t,e,n,r){if(null==t)return null;if("valid"===r)t=t*e+Fd([n-e,0]);else{if("same"!==r)throw new Lf("Unsupport padding mode: "+r+".");t*=e}return t}function jv(t,e){return $e((function(){return wd(e),"channelsFirst"===e?ai(t,[0,2,3,1]):t}))}function Gv(t,e){return $e((function(){return wd(e),"channelsFirst"===e?ai(t,[0,2,3,4,1]):t}))}function qv(t,e,n,r,a,i,o,s){return void 0===r&&(r=[1,1]),void 0===a&&(a="valid"),void 0===s&&(s=null),$e((function(){if(null==i&&(i="channelsLast"),wd(i),3!==t.rank&&4!==t.rank)throw new Lf("conv2dWithBiasActivation expects input to be of rank 3 or 4, but received "+t.rank+".");if(3!==e.rank&&4!==e.rank)throw new Lf("conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received "+t.rank+".");var u=jv(t,i);if("causal"===a)throw new Bf("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Lp.conv2d({x:u,filter:e,strides:r,pad:"same"===a?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:s}),"channelsFirst"===i&&(u=ai(u,[0,3,1,2])),u}))}ff.registerClass(Pv);var Hv=function(t){function e(n,r){var a=t.call(this,r)||this;if(a.bias=null,a.DEFAULT_KERNEL_INITIALIZER="glorotNormal",a.DEFAULT_BIAS_INITIALIZER="zeros",e.verifyArgs(r),a.rank=n,nd(a.rank,"rank"),1!==a.rank&&2!==a.rank&&3!==a.rank)throw new Bf("Convolution layer for rank other than 1, 2, or 3 ("+a.rank+") is not implemented yet.");if(a.kernelSize=Wv(r.kernelSize,n,"kernelSize"),a.strides=Wv(null==r.strides?1:r.strides,n,"strides"),a.padding=null==r.padding?"valid":r.padding,Cd(a.padding),a.dataFormat=null==r.dataFormat?"channelsLast":r.dataFormat,wd(a.dataFormat),a.activation=Iv(r.activation),a.useBias=null==r.useBias||r.useBias,a.biasInitializer=bm(r.biasInitializer||a.DEFAULT_BIAS_INITIALIZER),a.biasConstraint=dd(r.biasConstraint),a.biasRegularizer=_v(r.biasRegularizer),a.activityRegularizer=_v(r.activityRegularizer),a.dilationRate=Wv(null==r.dilationRate?1:r.dilationRate,n,"dilationRate"),1===a.rank&&Array.isArray(a.dilationRate)&&1!==a.dilationRate.length)throw new Lf("dilationRate must be a number or an array of a single number for 1D convolution, but received "+JSON.stringify(a.dilationRate));if(2===a.rank){if("number"==typeof a.dilationRate)a.dilationRate=[a.dilationRate,a.dilationRate];else if(2!==a.dilationRate.length)throw new Lf("dilationRate must be a number or array of two numbers for 2D convolution, but received "+JSON.stringify(a.dilationRate))}else if(3===a.rank)if("number"==typeof a.dilationRate)a.dilationRate=[a.dilationRate,a.dilationRate,a.dilationRate];else if(3!==a.dilationRate.length)throw new Lf("dilationRate must be a number or array of three numbers for 3D convolution, but received "+JSON.stringify(a.dilationRate));return a}return Tf(e,t),e.verifyArgs=function(t){if(Vf("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!ed(t.kernelSize,"number",1,3))throw new Lf("BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received "+JSON.stringify(t.kernelSize)+".")},e.prototype.getConfig=function(){var e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Sv(this.activation),useBias:this.useBias,biasInitializer:ym(this.biasInitializer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),biasConstraint:hd(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Pm),Kv=function(t){function e(n,r){var a=t.call(this,n,r)||this;return a.kernel=null,e.verifyArgs(r),a.filters=r.filters,nd(a.filters,"filters"),a.kernelInitializer=bm(r.kernelInitializer||a.DEFAULT_KERNEL_INITIALIZER),a.kernelConstraint=dd(r.kernelConstraint),a.kernelRegularizer=_v(r.kernelRegularizer),a}return Tf(e,t),e.prototype.build=function(t){var e;t=Am(t);var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new Lf("The channel dimension of the input should be defined. Found "+t[n]);var r=t[n],a=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:(e={},e[n]=r,e)}],this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){var e;t=Em(t);var r=null==n.bias?null:n.bias.read(),a=ad(n.activation.getClassName());if(null!=a&&2===n.rank)e=qv(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate,a);else{if(1===n.rank)e=function(t,e,n,r,a,i,o){return void 0===r&&(r=1),void 0===a&&(a="valid"),void 0===o&&(o=1),$e((function(){if(null==i&&(i="channelsLast"),wd(i),3!==t.shape.length)throw new Lf("The input of a conv1dWithBias operation should be 3, but is "+t.shape.length+" instead.");if(3!==e.shape.length)throw new Lf("The kernel for a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead");if(null!=n&&1!==n.shape.length)throw new Lf("The bias for a conv1dWithBias operation should be 1, but is "+e.shape.length+" instead");if("channelsFirst"===i&&(t=ai(t,[0,2,1])),"causal"===a)throw new Bf("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s=Vl(t,e,r,"same"===a?"same":"valid","NWC",o);return null!=n&&(s=Yd(s,n)),s}))}(t,n.kernel.read(),r,n.strides[0],n.padding,n.dataFormat,n.dilationRate[0]);else if(2===n.rank)e=qv(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate);else{if(3!==n.rank)throw new Bf("convolutions greater than 3D are not implemented yet.");e=function(t,e,n,r,a,i,o){return void 0===r&&(r=[1,1,1]),void 0===a&&(a="valid"),$e((function(){if(null==i&&(i="channelsLast"),wd(i),4!==t.rank&&5!==t.rank)throw new Lf("conv3dWithBias expects input to be of rank 4 or 5, but received "+t.rank+".");if(4!==e.rank&&5!==e.rank)throw new Lf("conv3dWithBias expects kernel to be of rank 4 or 5, but received "+t.rank+".");var s=Gv(t,i);if("causal"===a)throw new Bf("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return s=jl(s,e,r,"same"===a?"same":"valid","NDHWC",o),null!=n&&(s=Yd(s,n)),"channelsFirst"===i&&(s=ai(s,[0,4,1,2,3])),s}))}(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate)}null!=n.activation&&(e=n.activation.apply(e))}return e}))},e.prototype.computeOutputShape=function(t){t=Am(t);for(var e=[],n="channelsLast"===this.dataFormat?t.slice(1,t.length-1):t.slice(2),r=0;r<n.length;++r){var a=Vv(n[r],this.kernelSize[r],this.padding,this.strides[r],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[r]);e.push(a)}var i=[t[0]];return"channelsLast"===this.dataFormat?(i=i.concat(e)).push(this.filters):(i.push(this.filters),i=i.concat(e)),i},e.prototype.getConfig=function(){var e={filters:this.filters,kernelInitializer:ym(this.kernelInitializer),kernelRegularizer:Dv(this.kernelRegularizer),kernelConstraint:hd(this.kernelConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.verifyArgs=function(t){if(!("filters"in t)||"number"!=typeof t.filters||t.filters<1)throw new Lf("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},e}(Hv),Xv=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return Tf(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!ed(t.kernelSize,"number",1,2))throw new Lf("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(Kv);ff.registerClass(Xv);var Yv=function(t){function e(n){var r=t.call(this,3,n)||this;return e.verifyArgs(n),r}return Tf(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&(!Array.isArray(t.kernelSize)||1!==t.kernelSize.length&&3!==t.kernelSize.length))throw new Lf("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv3D",e}(Kv);ff.registerClass(Yv);var Jv=function(t){function e(e){var n=t.call(this,e)||this;if(n.inputSpec=[new Fm({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new Lf("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return Tf(e,t),e.prototype.build=function(t){var e;if(4!==(t=Am(t)).length)throw new Lf("Input should have rank 4; Received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new Lf("The channel dimension of the inputs should be defined. Found `None`.");var r=t[n],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 Fm({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){var e=Em(t);if(4!==e.shape.length)throw new Lf("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+e.shape.length);var r,a,i=e.shape,o=i[0];"channelsFirst"===n.dataFormat?(r=2,a=3):(r=1,a=2);var s=i[r],u=i[a],l=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],f=[o,Uv(s,p,l,n.padding),Uv(u,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(e=ai(e,[0,2,3,1]));var d=Jl(e,n.kernel.read(),f,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(d=ai(d,[0,3,1,2])),null!=n.bias&&(d=Yd(d,n.bias.read(),n.dataFormat)),null!=n.activation&&(d=n.activation.apply(d)),d}))},e.prototype.computeOutputShape=function(t){var e,n,r,a=(t=Am(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var i=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[e]=this.filters,a[n]=Uv(a[n],s,i,this.padding),a[r]=Uv(a[r],u,o,this.padding),a},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(Xv);ff.registerClass(Jv);var $v=function(t){function e(e){return t.call(this,2,e)||this}return Tf(e,t),e.className="SeparableConv2D",e}(function(t){function e(e,n){var r=t.call(this,e,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new Lf("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new Lf("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 Lf("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=bm(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=_v(n.depthwiseRegularizer),r.depthwiseConstraint=dd(n.depthwiseConstraint),r.pointwiseInitializer=bm(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=_v(n.pointwiseRegularizer),r.pointwiseConstraint=dd(n.pointwiseConstraint),r}return Tf(e,t),e.prototype.build=function(t){var e;if((t=Am(t)).length<this.rank+2)throw new Lf("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n]||t[n]<0)throw new Lf("The channel dimension of the inputs should be defined, but found "+JSON.stringify(t[n]));for(var r=t[n],a=this.kernelSize.concat([r,this.depthMultiplier]),i=[],o=0;o<this.rank;++o)i.push(1);i.push(r*this.depthMultiplier,this.filters),this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,!0,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.inputSpec=[new Fm({ndim:this.rank+2,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){var e;if(t=Em(t),1===n.rank)throw new Bf("1D separable convolution is not implemented yet.");return 2===n.rank&&("channelsFirst"===n.dataFormat&&(t=ai(t,[0,2,3,1])),e=Yl(t,n.depthwiseKernel.read(),n.pointwiseKernel.read(),n.strides,n.padding,n.dilationRate,"NHWC")),n.useBias&&(e=Yd(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),"channelsFirst"===n.dataFormat&&(e=ai(e,[0,3,1,2])),e}))},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=ym(this.depthwiseInitializer),e.pointwiseInitializer=ym(this.pointwiseInitializer),e.depthwiseRegularizer=Dv(this.depthwiseRegularizer),e.pointwiseRegularizer=Dv(this.pointwiseRegularizer),e.depthwiseConstraint=hd(this.depthwiseConstraint),e.pointwiseConstraint=hd(this.pointwiseConstraint),e},e.className="SeparableConv",e}(Kv));ff.registerClass($v);var Zv=function(t){function e(n){var r=t.call(this,1,n)||this;return e.verifyArgs(n),r.inputSpec=[{ndim:3}],r}return Tf(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.dataFormat,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!ed(t.kernelSize,"number",1,1))throw new Lf("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv1D",e}(Kv);ff.registerClass(Zv);var Qv=function(t){function e(e){var n=t.call(this,e)||this;return"number"==typeof e.cropping?n.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?n.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:n.cropping=e.cropping,n.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,n.inputSpec=[{ndim:4}],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return"channelsFirst"===this.dataFormat?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]},e.prototype.call=function(t,e){var n=this;return $e((function(){return t=Em(t),"channelsLast"===n.dataFormat?Wd(Wd(t,n.cropping[0][0],t.shape[1]-n.cropping[0][0]-n.cropping[0][1],2),n.cropping[1][0],t.shape[2]-n.cropping[1][1]-n.cropping[1][0],3):Wd(Wd(t,n.cropping[0][0],t.shape[2]-n.cropping[0][0]-n.cropping[0][1],3),n.cropping[1][0],t.shape[3]-n.cropping[1][1]-n.cropping[1][0],4)}))},e.prototype.getConfig=function(){var e={cropping:this.cropping,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Cropping2D",e}(Pm);ff.registerClass(Qv);var ty=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=null==e.size?n.DEFAULT_SIZE:e.size,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,n}return Tf(e,t),e.prototype.computeOutputShape=function(t){if("channelsFirst"===this.dataFormat){var e=null==t[2]?null:this.size[0]*t[2],n=null==t[3]?null:this.size[1]*t[3];return[t[0],t[1],e,n]}return e=null==t[1]?null:this.size[0]*t[1],n=null==t[2]?null:this.size[1]*t[2],[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return $e((function(){var e=Em(t),r=e.shape;if("channelsFirst"===n.dataFormat){e=ai(e,[0,2,3,1]);var a=n.size[0]*r[2],i=n.size[1]*r[3],o=e.resizeNearestNeighbor([a,i]);return ai(o,[0,3,1,2])}return a=n.size[0]*r[1],i=n.size[1]*r[2],e.resizeNearestNeighbor([a,i])}))},e.prototype.getConfig=function(){var e={size:this.size,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="UpSampling2D",e}(Pm);ff.registerClass(ty);var ey=function(t){function e(e){var n=t.call(this,2,e)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,n.depthwiseInitializer=bm(e.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=dd(e.depthwiseConstraint),n.depthwiseRegularizer=_v(e.depthwiseRegularizer),n}return Tf(e,t),e.prototype.build=function(t){if((t=Am(t)).length<4)throw new Lf("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(t)+".");var e="channelsFirst"===this.dataFormat?1:3;if(null==t[e]||t[e]<0)throw new Lf("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+t[e]+").");var n=t[e],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){var e=function(t,e,n,r,a,i){return void 0===n&&(n=[1,1]),void 0===r&&(r="valid"),$e((function(){null==a&&(a="channelsLast"),wd(a);var i=jv(t,a);if(4!==t.rank)throw new Lf("Input for depthwiseConv2d is required to be 4-D, but is instead "+t.rank+"-D");if(4!==e.rank)throw new Lf("depthwiseKernel is required to be 4-D, but is instead "+e.rank+"-D");return i=Hl(i,e,n,"same"===r?"same":"valid","NHWC",null),"channelsFirst"===a&&(i=ai(i,[0,3,1,2])),i}))}(t=Em(t),n.depthwiseKernel.read(),n.strides,n.padding,n.dataFormat);return n.useBias&&(e=Yd(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),e}))},e.prototype.computeOutputShape=function(t){t=Am(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,a=Vv(e,this.kernelSize[0],this.padding,this.strides[0]),i=Vv(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[t[0],r,a,i]:[t[0],a,i,r]},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=ym(this.depthwiseInitializer),e.depthwiseRegularizer=Dv(this.depthwiseRegularizer),e.depthwiseConstraint=hd(this.depthwiseRegularizer),e},e.className="DepthwiseConv2D",e}(Hv);ff.registerClass(ey);var ny=function(t){function e(e){var n=t.call(this,e)||this;return n.rate=Math.max(Math.min(e.rate,1),0),n.noiseShape=e.noiseShape,n.seed=e.seed,n.supportsMasking=!0,n}return Tf(e,t),e.prototype.getNoiseShape=function(t){if(null==this.noiseShape)return this.noiseShape;for(var e=t.shape,n=[],r=0;r<this.noiseShape.length;++r)n.push(null==this.noiseShape[r]?e[r]:this.noiseShape[r]);return n},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);if(0<n.rate&&n.rate<1){var a=null!=e.training&&e.training,i=n.getNoiseShape(r);return $d((function(){return Jd(r,n.rate,i,n.seed)}),(function(){return r}),a)}return t}))},e.prototype.getConfig=function(){var e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.dispose=function(){return t.prototype.dispose.call(this)},e.className="Dropout",e}(Pm);ff.registerClass(ny);var ry=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[{ndim:3}],n}return Tf(e,t),e.prototype.getNoiseShape=function(t){var e=t.shape;return[e[0],1,e[2]]},e.className="SpatialDropout1D",e}(ny);ff.registerClass(ry);var ay=function(t){function e(e){var n=t.call(this,e)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){var r=null;null!=e.batchSize&&(r=e.batchSize),n.batchInputShape=[r,e.inputDim]}return n.units=e.units,nd(n.units,"units"),n.activation=Iv(e.activation),null!=e.useBias&&(n.useBias=e.useBias),n.kernelInitializer=bm(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=bm(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=dd(e.kernelConstraint),n.biasConstraint=dd(e.biasConstraint),n.kernelRegularizer=_v(e.kernelRegularizer),n.biasRegularizer=_v(e.biasRegularizer),n.activityRegularizer=_v(e.activityRegularizer),n.supportsMasking=!0,n.inputSpec=[{minNDim:2}],n}return Tf(e,t),e.prototype.build=function(t){var e,n=(t=Am(t))[t.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[n,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(e={},e[-1]=n,e)}],this.built=!0},e.prototype.computeOutputShape=function(t){var e=(t=Am(t)).slice();return e[e.length-1]=this.units,e},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r,a=Em(t),i=ad(n.activation.getClassName());return null!=i?r=qd(a,n.kernel.read(),i,n.bias?n.bias.read():null):(r=qd(a,n.kernel.read()),null!=n.bias&&(r=Yd(r,n.bias.read())),null!=n.activation&&(r=n.activation.apply(r))),r}))},e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),biasInitializer:ym(this.biasInitializer),kernelRegularizer:Dv(this.kernelRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),biasConstraint:hd(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dense",e}(Pm);ff.registerClass(ay);var iy=function(t){function e(e){var n=this;return e=e||{},(n=t.call(this,e)||this).inputSpec=[{minNDim:3}],n.dataFormat=e.dataFormat,n}return Tf(e,t),e.prototype.computeOutputShape=function(t){for(var e=0,n=(t=Am(t)).slice(1);e<n.length;e++)if(null==n[e])throw new Lf('The shape of the input to "Flatten" is not fully defined (got '+t.slice(1)+'). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.');return[t[0],Dd(t,1)]},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);if("channelsFirst"===n.dataFormat&&r.rank>1){for(var a=[0],i=2;i<r.rank;++i)a.push(i);a.push(1),r=r.transpose(a)}return function(t){if(t.rank<=1)throw new Lf("batchFlatten requires a minimum rank of 2. Got rank: "+t.rank+".");var e=[t.shape[0],Dd(t.shape,1)];return t.reshape(e)}(r)}))},e.prototype.getConfig=function(){var e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);var n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Flatten",e}(Pm);ff.registerClass(iy);var oy=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.activation=Iv(e.activation),n}return Tf(e,t),e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);return n.activation.apply(r)}))},e.prototype.getConfig=function(){var e={activation:Sv(this.activation)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Activation",e}(Pm);ff.registerClass(oy);var sy=function(t){function e(e){var n=t.call(this,e)||this;return n.n=e.n,n.inputSpec=[{ndim:2}],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return[t[0],this.n,t[1]]},e.prototype.call=function(t,e){var n=this;return $e((function(){return function(t,e){return $e((function(){if(2!==t.shape.length)throw new Lf("repeat() expects a rank-2 tensor, but received a rank-"+t.shape.length+" tensor.");return jd(Ld(t,1),[1,e,1])}))}(t=Em(t),n.n)}))},e.prototype.getConfig=function(){var e={n:this.n},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="RepeatVector",e}(Pm);ff.registerClass(sy);var uy=function(t){function e(e){var n=t.call(this,e)||this;n.targetShape=e.targetShape;for(var r=0;r<n.targetShape.length;++r)n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);return n}return Tf(e,t),e.prototype.isUnknown=function(t){return t<0||null==t},e.prototype.fixUnknownDimension=function(t,e){for(var n="Total size of new array must be unchanged.",r=e.slice(),a=1,i=null,o=0;o<r.length;++o){var s=r[o];if(this.isUnknown(s)){if(null!==i)throw new Lf("Can only specifiy one unknown dimension.");i=o}else a*=s}var u=Dd(t);if(null!==i){if(0===a||u%a!=0)throw new Lf(n);r[i]=u/a}else if(u!==a)throw new Lf(n);return r},e.prototype.computeOutputShape=function(t){for(var e=!1,n=0;n<t.length;++n)if(this.isUnknown(t[n])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t),a=r.shape,i=a.slice(0,1).concat(n.fixUnknownDimension(a.slice(1),n.targetShape));return r.reshape(i)}))},e.prototype.getConfig=function(){var e={targetShape:this.targetShape},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Reshape",e}(Pm);ff.registerClass(uy);var ly=function(t){function e(e){var n=t.call(this,e)||this;if(null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error("Permute constructor requires `dims` to be an Array, but received "+e.dims+" instead.");var r=Md(1,e.dims.length+1);if(!pt.arraysEqual(e.dims.slice().sort(),r))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");return n.dims=e.dims,n.dimsIncludingBatch=[0].concat(n.dims),n.inputSpec=[new Fm({ndim:n.dims.length+1})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){var e=(t=Am(t)).slice();return this.dims.forEach((function(n,r){e[r+1]=t[n]})),e},e.prototype.call=function(t,e){return ai(Em(t),this.dimsIncludingBatch)},e.prototype.getConfig=function(){var e={dims:this.dims},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Permute",e}(Pm);ff.registerClass(ly);var cy=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,n.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0,n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={maskValue:this.maskValue};return Object.assign(n,e),n},e.prototype.computeMask=function(t,e){var n=Em(t);return wc(Dl(n,this.maskValue),-1)},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t),a=wc(Dl(r,n.maskValue),-1,!0);return r.mul(a.asType(r.dtype))}))},e.className="Masking",e}(Pm);ff.registerClass(cy);var py=function(t){function e(e){var n=t.call(this,e)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){var r=null;null!=e.batchSize&&(r=e.batchSize),null==e.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(Gf(e.inputLength))}return n.inputDim=e.inputDim,nd(n.inputDim,"inputDim"),n.outputDim=e.outputDim,nd(n.outputDim,"outputDim"),n.embeddingsInitializer=bm(e.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=_v(e.embeddingsRegularizer),n.activityRegularizer=_v(e.activityRegularizer),n.embeddingsConstraint=dd(e.embeddingsConstraint),n.maskZero=e.maskZero,n.supportsMasking=e.maskZero,n.inputLength=e.inputLength,n}return Tf(e,t),e.prototype.build=function(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0},e.prototype.warnOnIncompatibleInputShape=function(t){},e.prototype.computeMask=function(t,e){var n=this;return $e((function(){return n.maskZero?(t=Em(t),Dl(t,Hn(t))):null}))},e.prototype.computeOutputShape=function(t){if(t=Am(t),null==this.inputLength)return t.concat([this.outputDim]);var e=Gf(this.inputLength);if(e.length!==t.length-1)throw new Lf('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);for(var n=0,r=0;r<e.length;++r){var a=e[r],i=t[r+1];if(null!=a&&null!=i&&a!==i)throw new Lf('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);null==a&&(e[n]=i),n++}return[t[0]].concat(e,[this.outputDim])},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);return"int32"!==r.dtype&&(r=zd(r,"int32")),Hd(n.embeddings.read(),r.as1D()).reshape(Am(n.computeOutputShape(r.shape)))}))},e.prototype.getConfig=function(){var e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ym(this.embeddingsInitializer),embeddingsRegularizer:Dv(this.embeddingsRegularizer),activityRegularizer:Dv(this.activityRegularizer),embeddingsConstraint:hd(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Embedding",e}(Pm);ff.registerClass(py);var hy=function(t){function e(e){var n=t.call(this,e||{})||this;return n.supportsMasking=!0,n}return Tf(e,t),e.prototype.mergeFunction=function(t){throw new Bf},e.prototype.computeElementwiseOpOutputShape=function(t,e){if(null==t||null==e)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(0===e.length)return t;for(var n=t.slice(0,t.length-e.length),r=0;r<e.length;++r){var a=t[t.length-e.length+r],i=e[r];if(null==a||null==i||a<0||i<0)n.push(null);else if(1===a)n.push(i);else if(1===i)n.push(a);else{if(a!==i)throw new Lf("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(a)}}return n},e.prototype.build=function(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Am(t)]),(t=t).length<2)throw new Lf("A merge layer should be called on an Array of at least 2 inputs. Got "+t.length+" input(s).");for(var e=[],n=0,r=t;n<r.length;n++)null!=(o=r[n])&&null!==o[0]&&e.push(o[0]);if((e=Zf(e)).length>1)throw new Lf("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(t)+".");for(var a=null==t[0]?null:t[0].slice(1),i=1;i<t.length;++i){var o=null==t[i]?null:t[i].slice(1);a=this.computeElementwiseOpOutputShape(a,o)}var s=t.map((function(t){return t.length}));-1===t.indexOf(null)&&1===Zf(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){if(t=t,n.reshapeRequired){var e=[],r=t.map((function(t){return t.rank}));if(-1===r.indexOf(null)){for(var a=Fd(r),i=0,o=t;i<o.length;i++){for(var s=(h=o[i]).rank,u=0;u<a-s;++u)h=Ld(h,1);e.push(h)}return n.mergeFunction(e)}for(var l=!1,c=0,p=t;c<p.length;c++){var h;if(null==(s=(h=p[c]).rank)){var f=h.shape,d=f[0],m=f.slice(1).concat([d]),g=h.reshape([d].concat(Dd(f.slice(1))));g=(g=ai(g,[1,0])).reshape(m),e.push(g),l=!0}else if(s>1){var v=Md(1,s).concat([0]);e.push(ai(h,v)),l=!0}else e.push(h)}var y=n.mergeFunction(e),b=y.rank;if(l)if(null==b){var x=y.shape;m=[d=x[x.length-1]].concat(x.slice(0,x.length-1)),y=ai(y.reshape([-1,d]),[1,0]).reshape(m)}else b>1&&(v=[b-1].concat(Md(0,b-1)),y=ai(y,v));return y}return n.mergeFunction(t)}))},e.prototype.computeOutputShape=function(t){var e;e=null==(t=t)[0]?null:t[0].slice(1);for(var n=1;n<t.length;++n){var r=null==t[n]?null:t[n].slice(1);e=this.computeElementwiseOpOutputShape(e,r)}for(var a=[],i=0,o=t;i<o.length;i++)null!=(r=o[i])&&null!==r[0]&&a.push(r[0]);return 1===(a=Zf(a)).length?a.concat(e):[null].concat(e)},e.prototype.computeMask=function(t,e){return $e((function(){if(null==e)return null;if(!Array.isArray(e))throw new Lf("`mask` should be an Array");if(!Array.isArray(t))throw new Lf("`inputs` should be an Array");if(e.length!==t.length)throw new Lf("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+t.length+" vs "+e.length+")");if(e.every((function(t){return null==t})))return null;for(var n=(e=e.map((function(t){return null==t?t:ir(t,0)})))[0],r=1;r<e.length-1;++r)n=qu(n,e[r]);return n}))},e}(Pm),fy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.mergeFunction=function(t){return $e((function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=Or(e,t[n]);return e}))},e.className="Add",e}(hy);ff.registerClass(fy);var dy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.mergeFunction=function(t){return $e((function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=Ia(e,t[n]);return e}))},e.className="Multiply",e}(hy);ff.registerClass(dy);var my=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.mergeFunction=function(t){return $e((function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=Or(e,t[n]);return Ia(1/t.length,e)}))},e.className="Average",e}(hy);ff.registerClass(my);var gy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.mergeFunction=function(t){return $e((function(){for(var e=t[0],n=1;n<t.length;++n)e=xa(e,t[n]);return e}))},e.className="Maximum",e}(hy);ff.registerClass(gy);var vy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.mergeFunction=function(t){return $e((function(){for(var e=t[0],n=1;n<t.length;++n)e=Ca(e,t[n]);return e}))},e.className="Minimum",e}(hy);ff.registerClass(vy);var yy=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_AXIS=-1,null==e&&(e={}),n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n}return Tf(e,t),e.prototype.build=function(t){if(!Array.isArray(t)||!Array.isArray(t[0])||1===t.length)throw new Lf("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var e=!0,n=0,r=t=t;n<r.length;n++)if(null!=(c=r[n])){e=!1;break}if(!e){for(var a=[],i=0;i<t.length;++i){var o=t[i].slice();o.splice(this.axis,1);for(var s=!1,u=0,l=a;u<l.length;u++){var c=l[u];if(pt.arraysEqual(c,o)){s=!0;break}}s||a.push(o)}if(a.length>1)throw new Lf("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}},e.prototype.mergeFunction=function(t){var e=this;return $e((function(){return Vd(t,e.axis)}))},e.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Lf("A `Concatenate` layer should be called on a list of inputs.");for(var e=t,n=e[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,a=0,i=e.slice(1);a<i.length;a++){var o=i[a];if(null==n[r]||null==o[r]){n[r]=null;break}n[r]+=o[r]}return n},e.prototype.computeMask=function(t,e){var n=this;if(null==e)return null;if(!Array.isArray(e))throw new Lf("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new Lf("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new Lf("Mismatch in the length of mask ("+e.length+") and the legnth of inputs ("+t.length+")");return $e((function(){var r=!0;if(e.forEach((function(t){null==t||(r=!1)})),r)return null;for(var a=[],i=0;i<t.length;++i)null==e[i]?a.push(qn(t[i]).asType("bool")):e[i].rank<t[i].rank?a.push(ir(e[i],-1)):a.push(e[i]);var o=Kn(a,n.axis);return xc(o,-1,!1)}))},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Concatenate",e}(hy);function by(t,e){for(;t<0;)t+=e;return t}ff.registerClass(yy);var xy=function(t){function e(e){var n=t.call(this,e)||this;return n.axes=e.axes,n.normalize=null!=e.normalize&&e.normalize,n.supportsMasking=!0,n.reshapeRequired=!1,n}return Tf(e,t),e.prototype.build=function(t){pt.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),(function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."}));var e=t[0],n=t[1];if(e.length>3||n.length>3)throw new Bf("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);if(e[r[0]]!==n[r[1]])throw new Lf("Dimension incompatibility: "+e[r[0]]+" !== "+n[r[1]])},e.prototype.mergeFunction=function(t){if(2!==t.length)throw new Lf("A `Dot` layer must be called on exactly 2 inputs, but received "+t.length+" input(s).");var e,n=t[0],r=t[1];return e=Array.isArray(this.axes)?this.axes.map((function(e,n){return by(e,t[n].shape.length)})):[by(this.axes,n.shape.length),by(this.axes,r.shape.length)],this.normalize&&(n=eg(n,e[0]),r=eg(r,e[1])),function(t,e,n){if(t.shape.length>3||e.shape.length>3)throw new Bf("batchDot is not implemented for tensors of 4D or higher rank yet");if(pt.assert(t.shape.length>=2,(function(){return"batchDot requires the rank of x to be >= 2, but got "+t.shape.length})),pt.assert(t.shape.length>=2,(function(){return"batchDot requires the rank of y to be >= 2, but got "+e.shape.length})),"number"==typeof n&&(n=[n,n]),"complex64"===t.dtype||"complex64"===e.dtype)throw new Bf("batchDot is not implemented for complex64-type Tensors yet.");var r=t.shape.length,a=e.shape.length;null==n&&(n=[r-1,a-2]);var i=n;return $e((function(){var n,o;if(r>a){n=r-a;for(var s=[],u=0;u<n;++u)s.push(1);e=e.reshape(e.shape.concat(s))}else if(a>r){for(n=a-r,s=[],u=0;u<n;++u)s.push(1);t=t.reshape(t.shape.concat(s))}else n=0;if(2===t.shape.length&&2===e.shape.length)o=i[0]===i[1]?t.mulStrict(e).sum(i[0]):t.transpose([1,0]).mulStrict(e).sum(i[1]);else{var l=i[0]!==t.shape.length-1,c=i[1]===e.shape.length-1;o=t.matMul(e,l,c)}if(n>0){var p,h=[];for(u=p=r>a?r+a-3:r-1;u<p+n;++u)h.push(u);o=o.squeeze(h)}return 1===o.shape.length&&(o=o.expandDims(1)),o}))}(n,r,e)},e.prototype.interpretAxes=function(t,e){return Array.isArray(this.axes)?this.axes:[by(this.axes,t.length),by(this.axes,e.length)]},e.prototype.computeOutputShape=function(t){pt.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),(function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."}));var e=t[0].slice(),n=t[1].slice();if(e.length>3||n.length>3)throw new Bf("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);e.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var a=e.concat(n);return 1===a.length&&a.push(1),a},e.prototype.computeMask=function(t,e){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dot",e}(hy);ff.registerClass(xy);var wy=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.stddev=e.stddev,n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);return $d((function(){return Gd(r.shape,0,n.stddev).add(r)}),(function(){return r}),e.training||!1)}))},e.className="GaussianNoise",e}(Pm);ff.registerClass(wy);var Cy=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e);var r=Em(t);return n.rate>0&&n.rate<1?$d((function(){var t=Math.sqrt(n.rate/(1-n.rate));return r.mul(Gd(r.shape,1,t))}),(function(){return r}),e.training||!1):r}))},e.className="GaussianDropout",e}(Pm);ff.registerClass(Cy);var Ny=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n.noiseShape=e.noiseShape,n}return Tf(e,t),e.prototype._getNoiseShape=function(t){return this.noiseShape||Em(t).shape},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return $e((function(){if(n.rate<1&&n.rate>0){var r=n._getNoiseShape(t);return $d((function(){var e=Em(t),a=-1.7580993408473766,i=Sl(vl(r),n.rate);i=zd(i,"float32");var o=Math.pow((1-n.rate)*(1+n.rate*Math.pow(a,2)),-.5),s=-o*a*n.rate;return e.mul(i).add(i.add(-1).mul(a)).mul(o).add(s)}),(function(){return Em(t)}),e.training||!1)}return t}))},e.className="AlphaDropout",e}(Pm);function Sy(t,e,n,r,a,i){var o;if(void 0===i&&(i=.001),2===t.rank)o=zu(t,e,n,r,a,i);else if(3===t.rank)o=Pu(t,e,n,r,a,i);else{if(4!==t.rank)throw new Bf("batchNormalization is not implemented for array of rank "+t.rank+" yet");o=Uu(t,e,n,r,a,i)}return o}ff.registerClass(Ny);var ky=function(t){function e(e){var n=this;return null==e&&(e={}),(n=t.call(this,e)||this).supportsMasking=!0,n.axis=null==e.axis?-1:e.axis,n.momentum=null==e.momentum?.99:e.momentum,n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=bm(e.betaInitializer||"zeros"),n.gammaInitializer=bm(e.gammaInitializer||"ones"),n.movingMeanInitializer=bm(e.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=bm(e.movingVarianceInitializer||"ones"),n.betaConstraint=dd(e.betaConstraint),n.gammaConstraint=dd(e.gammaConstraint),n.betaRegularizer=_v(e.betaRegularizer),n.gammaRegularizer=_v(e.gammaRegularizer),n}return Tf(e,t),e.prototype.build=function(t){var e;t=Am(t);var n=this.axis>=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new Lf("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new Fm({ndim:t.length,axes:(e={},e[n]=r,e)})];var a=[r];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},e.prototype.call=function(t,e){var n=this;return $e((function(){var r=null!=e.training&&e.training,a=Em(t),i=a.shape,o=i.length,s=Md(0,o),u=n.axis>=0?n.axis:n.axis+o;s.splice(u,1);var l=Wf(1,o);l[u]=i[u];var c=s.slice();c.sort();var p=!pt.arraysEqual(c,Md(0,o).slice(0,o-1));if(!r)return function(){if(p){var t=n.movingMean.read().reshape(l),e=n.movingVariance.read().reshape(l),r=n.center?n.beta.read().reshape(l):null,i=n.scale?n.gamma.read().reshape(l):null;return Sy(a,t,e,r,i,n.epsilon)}return Sy(a,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(t,e,n,r,a){return void 0===a&&(a=.001),pt.arraysEqual(r.slice().sort(),Md(0,t.rank-1))?function(t,e,n,r,a){return void 0===a&&(a=.001),$e((function(){var i=Ac(t,r),o=i.mean,s=i.variance;return[Sy(t,o,s,n,e,a),o,s]}))}(t,e,n,r,a):function(t,e,n,r,a){return void 0===a&&(a=.001),$e((function(){for(var i=Ac(t,r),o=i.mean,s=i.variance,u=[],l=0,c=Md(0,t.rank);l<c.length;l++){var p=c[l];-1!==r.indexOf(p)?u.push(1):u.push(t.shape[p])}var h=o.reshape(u),f=s.reshape(u),d=null==e?null:e.reshape(u),m=null==n?null:n.reshape(u);return[Sy(t,h,f,m,d,a),o,s]}))}(t,e,n,r,a)}(a,n.gamma.read(),n.beta.read(),s,n.epsilon),f=h[0],d=h[1],m=h[2],g=function(t,e,n){$e((function(){var r=1-n,a=t.read(),i=a.sub(e).mul(r);t.write(a.sub(i))}))};return g(n.movingMean,d,n.momentum),g(n.movingVariance,m,n.momentum),f}))},e.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ym(this.betaInitializer),gammaInitializer:ym(this.gammaInitializer),movingMeanInitializer:ym(this.movingMeanInitializer),movingVarianceInitializer:ym(this.movingVarianceInitializer),betaRegularizer:Dv(this.betaRegularizer),gammaRegularizer:Dv(this.gammaRegularizer),betaConstraint:hd(this.betaConstraint),gammaConstraint:hd(this.gammaConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="BatchNormalization",e}(Pm);ff.registerClass(ky);var Iy=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).axis=null==e.axis?-1:e.axis,"number"==typeof n.axis){if(!Number.isInteger(n.axis))throw new Error("Expected axis to be an integer, but received "+n.axis)}else{if(!Array.isArray(n.axis))throw new Error("Expected axis to be an integer or an array of integers, but received "+JSON.stringify(n.axis));for(var r=0,a=n.axis;r<a.length;r++){var i=a[r];if(!Number.isInteger(i))throw new Error("Expected axis to be an array of integers, but received "+JSON.stringify(n.axis))}}return n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=bm(e.betaInitializer||"zeros"),n.gammaInitializer=bm(e.gammaInitializer||"ones"),n.betaRegularizer=_v(e.betaRegularizer),n.gammaRegularizer=_v(e.gammaRegularizer),n.supportsMasking=!0,n}return Tf(e,t),e.prototype.build=function(t){var e=(t=Am(t)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(var n=0;n<this.axis.length;++n)this.axis[n]<0&&(this.axis[n]+=e);for(var r=0,a=this.axis;r<a.length;r++){var i=a[r];if(i<0||i>=e)throw new Error("Invalid axis: "+i)}if(this.axis.length!==Zf(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var o=this.axis.map((function(e){return t[e]}));this.scale?this.gamma=this.addWeight("gamma",o,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",o,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0},e.prototype.call=function(t,e){var n=this,r=Em(t),a=r.shape,i=a.length;return $e((function(){for(var t=Ac(r,n.axis,!0),e=t.mean,o=t.variance,s=Wf(1,i),u=0,l=n.axis;u<l.length;u++){var c=l[u];s[c]=a[c]}for(var p=function(t){return null!=t&&t.shape.length!==i&&n.axis!==[i-1]?t.reshape(s):t},h=p(n.gamma.read()),f=p(n.beta.read()),d=[],m=[],g=0;g<i;++g)-1!==n.axis.indexOf(g)?(d.push(a[g]),m.push(1)):(d.push(1),m.push(a[g]));return e=e.tile(d),o=o.tile(d),h=h.tile(m),f=f.tile(m),Sy(r,e,o,f,h,n.epsilon)}))},e.prototype.getConfig=function(){var e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ym(this.betaInitializer),gammaInitializer:ym(this.gammaInitializer),betaRegularizer:Dv(this.betaRegularizer),gammaRegularizer:Dv(this.gammaRegularizer)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LayerNormalization",e}(Pm);ff.registerClass(Iy);var Ey=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)n.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Lf("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+e.padding.length+" array.");var r=void 0,a=void 0;if("number"==typeof e.padding[0])r=[e.padding[0],e.padding[0]],a=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Lf("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+e.padding[0].length+" array.");if(r=e.padding[0],2!==e.padding[1].length)throw new Lf("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+e.padding[1].length+" array.");a=e.padding[1]}n.padding=[r,a]}return n.inputSpec=[new Fm({ndim:4})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){var e,n;return t=Am(t),"channelsFirst"===this.dataFormat?(e=null!=t[2]&&t[2]>=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])},e.prototype.call=function(t,e){var n=this;return $e((function(){return function(t,e,n){return $e((function(){if(4!==t.rank)throw new Lf("temporalPadding expects input tensor to be 4-D, but received a "+t.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new Lf("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 Lf("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],nl(t,r)}))}(Em(t),n.padding,n.dataFormat)}))},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ZeroPadding2D",e}(Pm);function Ay(t,e,n,r,a,i){return $e((function(){var o;wd(a),Nd(i),Cd(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==i&&(i="max"),t=jv(t,a);var s="same"===r?"same":"valid";return o="max"===i?uc(t,e,n,s):lc(t,e,n,s),"channelsFirst"===a&&(o=ai(o,[0,3,1,2])),o}))}function Ty(t,e,n,r,a,i){return $e((function(){var o;wd(a),Nd(i),Cd(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==i&&(i="max"),t=Gv(t,a);var s="same"===r?"same":"valid";return o="max"===i?pc(t,e,n,s):hc(t,e,n,s),"channelsFirst"===a&&(o=ai(o,[0,4,1,2,3])),o}))}ff.registerClass(Ey);var Ry=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=2),n=t.call(this,e)||this,"number"==typeof e.poolSize)n.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Lf("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));n.poolSize=e.poolSize}if(nd(n.poolSize,"poolSize"),null==e.strides)n.strides=n.poolSize;else if("number"==typeof e.strides)n.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Lf("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));n.strides=e.strides}return nd(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,Cd(n.padding),n.inputSpec=[new Fm({ndim:3})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){var e=Vv((t=Am(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},e.prototype.call=function(t,e){var n=this;return $e((function(){n.invokeCallHook(t,e),t=Ld(Em(t),2);var r=n.poolingFunction(Em(t),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return ur(r,[2])}))},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Pm),Dy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ay(t,e,n,r,a,"max")},e.className="MaxPooling1D",e}(Ry);ff.registerClass(Dy);var Oy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ay(t,e,n,r,a,"avg")},e.className="AveragePooling1D",e}(Ry);ff.registerClass(Oy);var _y=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Lf("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides];return nd(n.poolSize,"poolSize"),nd(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wd(n.dataFormat),Cd(n.padding),n.inputSpec=[new Fm({ndim:4})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){t=Am(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=Vv(e,this.poolSize[0],this.padding,this.strides[0]),n=Vv(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return $e((function(){return n.invokeCallHook(t,e),n.poolingFunction(Em(t),n.poolSize,n.strides,n.padding,n.dataFormat)}))},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Pm),Fy=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ay(t,e,n,r,a,"max")},e.className="MaxPooling2D",e}(_y);ff.registerClass(Fy);var My=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ay(t,e,n,r,a,"avg")},e.className="AveragePooling2D",e}(_y);ff.registerClass(My);var zy=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Lf("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides,e.strides];return nd(n.poolSize,"poolSize"),nd(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wd(n.dataFormat),Cd(n.padding),n.inputSpec=[new Fm({ndim:5})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){t=Am(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[4]:t[3];return e=Vv(e,this.poolSize[0],this.padding,this.strides[0]),n=Vv(n,this.poolSize[1],this.padding,this.strides[1]),r=Vv(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n,r]:[t[0],e,n,r,t[4]]},e.prototype.call=function(t,e){var n=this;return $e((function(){return n.invokeCallHook(t,e),n.poolingFunction(Em(t),n.poolSize,n.strides,n.padding,n.dataFormat)}))},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Pm),Ly=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ty(t,e,n,r,a,"max")},e.className="MaxPooling3D",e}(zy);ff.registerClass(Ly);var By=function(t){function e(e){return t.call(this,e)||this}return Tf(e,t),e.prototype.poolingFunction=function(t,e,n,r,a){return wd(a),Cd(r),Ty(t,e,n,r,a,"avg")},e.className="AveragePooling3D",e}(zy);ff.registerClass(By);var Py=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new Fm({ndim:3})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new Bf},e}(Pm),Wy=function(t){function e(e){return t.call(this,e||{})||this}return Tf(e,t),e.prototype.call=function(t,e){return $e((function(){var e=Em(t);return Ic(e,1)}))},e.className="GlobalAveragePooling1D",e}(Py);ff.registerClass(Wy);var Vy=function(t){function e(e){return t.call(this,e||{})||this}return Tf(e,t),e.prototype.call=function(t,e){return $e((function(){var e=Em(t);return kc(e,1)}))},e.className="GlobalMaxPooling1D",e}(Py);ff.registerClass(Vy);var Uy=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wd(n.dataFormat),n.inputSpec=[new Fm({ndim:4})],n}return Tf(e,t),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(t,e){throw new Bf},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Pm),jy=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.call=function(t,e){var n=this;return $e((function(){var e=Em(t);return"channelsLast"===n.dataFormat?Ic(e,[1,2]):Ic(e,[2,3])}))},e.className="GlobalAveragePooling2D",e}(Uy);ff.registerClass(jy);var Gy=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.call=function(t,e){var n=this;return $e((function(){var e=Em(t);return"channelsLast"===n.dataFormat?kc(e,[1,2]):kc(e,[2,3])}))},e.className="GlobalMaxPooling2D",e}(Uy);function qy(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new Lf("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=t.slice(t.length-r,t.length),t=t.slice(0,t.length-r)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function a(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=a(e),constants:n=a(n)}}function Hy(t,e,n,r,a,i,o,s){return void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===s&&(s=!1),$e((function(){var u=e.shape.length;if(u<3)throw new Lf("Input should be at least 3D, but is "+u+"D.");var l=[1,0].concat(Md(2,u));if(e=ai(e,l),null!=i)throw new Bf("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=a.asType("bool").asType("float32")).rank===u-1&&(a=ir(a,-1)),a=ai(a,l)),r&&(e=ec(e,0),null!=a&&(a=ec(a,0)));var c,p,h=[],f=n,d=e.shape[0],m=cr(e);null!=a&&(p=cr(a));for(var g,v=function(e){var n=m[e],r=$e((function(){return t(n,f)}));if(null==a)c=r[0],f=r[1];else{var i=$e((function(){var t=p[e],n=qn(t).sub(t);return{output:r[0].mul(t).addStrict(f[0].mul(n)),newStates:f.map((function(e,a){return r[1][a].mul(t).addStrict(e.mul(n))}))}}));c=i.output,f=i.newStates}s&&h.push(c)},y=0;y<d;++y)v(y);return s&&(g=lr(h,1)),[c,g,f]}))}ff.registerClass(Gy);var Ky=function(t){function e(e){var n,r=t.call(this,e)||this;if(null==e.cell)throw new Lf("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(e.cell)?new eb({cells:e.cell}):e.cell).stateSize)throw new Lf("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=e.returnSequences&&e.returnSequences,r.returnState=null!=e.returnState&&e.returnState,r.goBackwards=null!=e.goBackwards&&e.goBackwards,r._stateful=null!=e.stateful&&e.stateful,r.unroll=null!=e.unroll&&e.unroll,r.supportsMasking=!0,r.inputSpec=[new Fm({ndim:3})],r.stateSpec=null,r.states_=null,r.numConstants=null,r.keptStates=[],r}return Tf(e,t),e.prototype.getStates=function(){return null==this.states_?Md(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((function(t){return null})):this.states_},e.prototype.setStates=function(t){this.states_=t},e.prototype.computeOutputShape=function(t){km(t)&&(t=t[0]),t=t;var e=this.cell.stateSize;Array.isArray(e)||(e=[e]);var n,r=e[0];if(n=this.returnSequences?[t[0],t[1],r]:[t[0],r],this.returnState){for(var a=[],i=0,o=e;i<o.length;i++){var s=o[i];a.push([t[0],s])}return[n].concat(a)}return n},e.prototype.computeMask=function(t,e){var n=this;return $e((function(){Array.isArray(e)&&(e=e[0]);var t=n.returnSequences?e:null;if(n.returnState){var r=n.states.map((function(t){return null}));return[t].concat(r)}return t}))},Object.defineProperty(e.prototype,"states",{get:function(){if(null==this.states_){for(var t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[],n=0;n<t;++n)e.push(null);return e}return this.states_},set:function(t){this.states_=t},enumerable:!0,configurable:!0}),e.prototype.build=function(t){if(null!=this.numConstants)throw new Bf("Constants support is not implemented in RNN yet.");km(t)&&(t=t[0]),t=t;var e=this.stateful?t[0]:null,n=t[t.length-1];this.inputSpec[0]=new Fm({shape:[e,null,n]});var r,a=[t[0]].concat(t.slice(2));if(this.cell.build(a),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!pt.arraysEqual(this.stateSpec.map((function(t){return t.shape[t.shape.length-1]})),r))throw new Lf("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize)}else this.stateSpec=r.map((function(t){return new Fm({shape:[null,t]})}));this.stateful&&this.resetStates()},e.prototype.resetStates=function(t,e){var n=this;void 0===e&&(e=!1),$e((function(){if(!n.stateful)throw new Mf("Cannot call resetStates() on an RNN Layer that is not stateful.");var r=n.inputSpec[0].shape[0];if(null==r)throw new Lf("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==n.states_)Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map((function(t){return Vn([r,t])})):n.states_=[Vn([r,n.cell.stateSize])];else if(null==t)Ze(n.states_),null!=n.keptStates&&(Ze(n.keptStates),n.keptStates=[]),Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map((function(t){return Vn([r,t])})):n.states_[0]=Vn([r,n.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==n.states_.length)throw new Lf("Layer "+n.name+" expects "+n.states_.length+" state(s), but it received "+t.length+" state value(s). Input received: "+t);!0===e?n.keptStates.push(n.states_.slice()):Ze(n.states_);for(var a=0;a<n.states_.length;++a){var i=t[a],o=Array.isArray(n.cell.stateSize)?n.cell.stateSize[a]:n.cell.stateSize,s=[r,o];if(!pt.arraysEqual(i.shape,s))throw new Lf("State "+a+" is incompatible with layer "+n.name+": expected shape="+s+", received shape="+i.shape);n.states_[a]=i}}n.states_=n.states_.map((function(t){return Qe(t.clone())}))}))},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,a=null==n?null:n.constants;null==n&&(n={});var i=qy(e,r,a,this.numConstants);e=i.inputs,r=i.initialState,a=i.constants;var o=[],s=[];if(null!=r){n.initialState=r,o=o.concat(r),this.stateSpec=[];for(var u=0,l=r;u<l.length;u++){var c=l[u];this.stateSpec.push(new Fm({shape:c.shape}))}s=s.concat(this.stateSpec)}if(null!=a&&(n.constants=a,o=o.concat(a),this.numConstants=a.length),o[0]instanceof Mm){var p=[e].concat(o),h=this.inputSpec.concat(s),f=this.inputSpec;this.inputSpec=h;var d=t.prototype.apply.call(this,p,n);return this.inputSpec=f,d}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return $e((function(){var r=null==e?null:e.mask,a=null==e?null:e.training,i=null==e?null:e.initialState;t=Em(t),null==i&&(i=n.stateful?n.states_:n.getInitialState(t));var o=Array.isArray(n.cell.stateSize)?n.cell.stateSize.length:1;if(i.length!==o)throw new Lf("RNN Layer has "+o+" state(s) but was passed "+i.length+" initial state(s).");n.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s={training:a},u=Hy((function(t,e){var r=n.cell.call([t].concat(e),s);return[r[0],r.slice(1)]}),t,i,n.goBackwards,r,null,n.unroll,n.returnSequences),l=u[0],c=u[1],p=u[2];n.stateful&&n.resetStates(p,a);var h=n.returnSequences?c:l;return n.returnState?[h].concat(p):h}))},e.prototype.getInitialState=function(t){var e=this;return $e((function(){var n=Vn(t.shape);return n=Ld(n=Tc(n,[1,2])),Array.isArray(e.cell.stateSize)?e.cell.stateSize.map((function(t){return t>1?jd(n,[1,t]):n})):e.cell.stateSize>1?[jd(n,[1,e.cell.stateSize])]:[n]}))},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);var n=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:n};var r=t.prototype.getConfig.call(this);return Object.assign(e,r),e},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=tg(e.cell,n);return new t(Object.assign(e,{cell:r}))},e.className="RNN",e}(Pm);ff.registerClass(Ky);var Xy=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e}(Pm),Yy=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,nd(n.units,"units"),n.activation=Iv(null==e.activation?n.DEFAULT_ACTIVATION:e.activation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=bm(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=bm(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=bm(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=_v(e.kernelRegularizer),n.recurrentRegularizer=_v(e.recurrentRegularizer),n.biasRegularizer=_v(e.biasRegularizer),n.kernelConstraint=dd(e.kernelConstraint),n.recurrentConstraint=dd(e.recurrentConstraint),n.biasConstraint=dd(e.biasConstraint),n.dropout=_d([1,Fd([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=_d([1,Fd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Tf(e,t),e.prototype.build=function(t){t=Am(t),this.kernel=this.addWeight("kernel",[t[t.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},e.prototype.call=function(t,e){var n=this;return $e((function(){if(2!==(t=t).length)throw new Lf("SimpleRNNCell expects 2 input Tensors, got "+t.length+".");var r=t[1];t=t[0];var a,i=null!=e.training&&e.training;0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=nb((function(){return qn(t)}),n.dropout,i)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=nb((function(){return qn(r)}),n.recurrentDropout,i));var o=n.dropoutMask,s=n.recurrentDropoutMask;a=qd(null!=o?Ia(t,o):t,n.kernel.read()),null!=n.bias&&(a=Yd(a,n.bias.read())),null!=s&&(r=Ia(r,s));var u=Or(a,qd(r,n.recurrentKernel.read()));return null!=n.activation&&(u=n.activation.apply(u)),[u,u]}))},e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="SimpleRNNCell",e}(Xy);ff.registerClass(Yy);var Jy=function(t){function e(e){return e.cell=new Yy(e),t.call(this,e)||this}return Tf(e,t),e.prototype.call=function(e,n){var r=this;return $e((function(){null!=r.cell.dropoutMask&&(Ze(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Ze(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:a,training:i,initialState:o})}))},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return new t(e)},e.className="SimpleRNN",e}(Ky);ff.registerClass(Jy);var $y=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,nd(n.units,"units"),n.activation=Iv(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=Iv(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=bm(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=bm(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=bm(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=_v(e.kernelRegularizer),n.recurrentRegularizer=_v(e.recurrentRegularizer),n.biasRegularizer=_v(e.biasRegularizer),n.kernelConstraint=dd(e.kernelConstraint),n.recurrentConstraint=dd(e.recurrentConstraint),n.biasConstraint=dd(e.biasConstraint),n.dropout=_d([1,Fd([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=_d([1,Fd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Tf(e,t),e.prototype.build=function(t){var e=(t=Am(t))[t.length-1];this.kernel=this.addWeight("kernel",[e,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){if(2!==(t=t).length)throw new Lf("GRUCell expects 2 input Tensors (inputs, h, c), got "+t.length+".");var r=null!=e.training&&e.training,a=t[1];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=nb((function(){return qn(t)}),n.dropout,r,3)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=nb((function(){return qn(a)}),n.recurrentDropout,r,3));var i,o,s,u=n.dropoutMask,l=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=Ia(t,u[0]));var c=qd(t,n.kernel.read());n.useBias&&(c=Yd(c,n.bias.read())),0<n.recurrentDropout&&n.recurrentDropout<1&&(a=Ia(a,l[0]));var p=n.recurrentKernel.read(),h=Zn(p,[2*n.units,n.units],p.rank-1),f=h[0],d=h[1],m=qd(a,f),g=Zn(c,3,c.rank-1),v=g[0],y=g[1],b=g[2],x=Zn(m,2,m.rank-1),w=x[0],C=x[1];i=n.recurrentActivation.apply(Or(v,w)),o=n.recurrentActivation.apply(Or(y,C));var N=qd(Ia(o,a),d);s=n.activation.apply(Or(b,N));var S=Or(Ia(i,a),Ia(Or(1,ta(i)),s));return[S,S]}))},e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),recurrentActivation:Sv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="GRUCell",e}(Xy);ff.registerClass($y);var Zy=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new $y(e),t.call(this,e)||this}return Tf(e,t),e.prototype.call=function(e,n){var r=this;return $e((function(){null!=r.cell.dropoutMask&&(Ze(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Ze(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:a,training:i,initialState:o})}))},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),recurrentActivation:Sv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="GRU",e}(Ky);ff.registerClass(Zy);var Qy=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,nd(n.units,"units"),n.activation=Iv(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=Iv(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=bm(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=bm(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=bm(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=e.unitForgetBias,n.kernelRegularizer=_v(e.kernelRegularizer),n.recurrentRegularizer=_v(e.recurrentRegularizer),n.biasRegularizer=_v(e.biasRegularizer),n.kernelConstraint=dd(e.kernelConstraint),n.recurrentConstraint=dd(e.recurrentConstraint),n.biasConstraint=dd(e.biasConstraint),n.dropout=_d([1,Fd([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=_d([1,Fd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=[n.units,n.units],n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Tf(e,t),e.prototype.build=function(t){var e,n,r=(t=Am(t))[t.length-1];if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var a=this.biasInitializer,i=this.units;n=new((e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Tf(e,t),e.prototype.apply=function(t,e){var n=a.apply([i]),r=(new nm).apply([i]),o=a.apply([2*i]);return Ud(Ud(n,r),o)},e}(tm)).className="CustomInit",e)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},e.prototype.call=function(t,e){var n=this;return $e((function(){var r=null!=e.training&&e.training;if(3!==(t=t).length)throw new Lf("LSTMCell expects 3 input Tensors (inputs, h, c), got "+t.length+".");var a=t[1],i=t[2];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=nb((function(){return qn(t)}),n.dropout,r,4)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=nb((function(){return qn(a)}),n.recurrentDropout,r,4));var o,s,u,l,c=n.dropoutMask,p=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=Ia(t,c[0]));var h=qd(t,n.kernel.read());0<n.recurrentDropout&&n.recurrentDropout<1&&(a=Ia(a,p[0])),h=Or(h,qd(a,n.recurrentKernel.read())),n.useBias&&(h=Yd(h,n.bias.read()));var f=Zn(h,4,h.rank-1),d=f[0],m=f[1],g=f[2],v=f[3];o=n.recurrentActivation.apply(d),s=n.recurrentActivation.apply(m),u=Or(Ia(s,i),Ia(o,n.activation.apply(g))),l=n.recurrentActivation.apply(v);var y=Ia(l,n.activation.apply(u));return[y,y,u]}))},e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),recurrentActivation:Sv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LSTMCell",e}(Xy);ff.registerClass(Qy);var tb=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Qy(e),t.call(this,e)||this}return Tf(e,t),e.prototype.call=function(e,n){var r=this;return $e((function(){null!=r.cell.dropoutMask&&(Ze(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Ze(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:a,training:i,initialState:o})}))},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Sv(this.activation),recurrentActivation:Sv(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ym(this.kernelInitializer),recurrentInitializer:ym(this.recurrentInitializer),biasInitializer:ym(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Dv(this.kernelRegularizer),recurrentRegularizer:Dv(this.recurrentRegularizer),biasRegularizer:Dv(this.biasRegularizer),activityRegularizer:Dv(this.activityRegularizer),kernelConstraint:hd(this.kernelConstraint),recurrentConstraint:hd(this.recurrentConstraint),biasConstraint:hd(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="LSTM",e}(Ky);ff.registerClass(tb);var eb=function(t){function e(e){var n=t.call(this,e)||this;return n.cells=e.cells,n}return Tf(e,t),Object.defineProperty(e.prototype,"stateSize",{get:function(){for(var t=[],e=0,n=this.cells.slice().reverse();e<n.length;e++){var r=n[e];Array.isArray(r.stateSize)?t.push.apply(t,r.stateSize):t.push(r.stateSize)}return t},enumerable:!0,configurable:!0}),e.prototype.call=function(t,e){var n=this;return $e((function(){for(var r=(t=t).slice(1),a=[],i=0,o=n.cells.slice().reverse();i<o.length;i++){var s=o[i];Array.isArray(s.stateSize)?a.push(r.splice(0,s.stateSize.length)):a.push(r.splice(0,1))}a.reverse();for(var u,l=[],c=0;c<n.cells.length;++c)s=n.cells[c],r=a[c],u=0===c?[t[0]].concat(r):[u[0]].concat(r),u=s.call(u,e),l.push(u.slice(1));r=[];for(var p=0,h=l.slice().reverse();p<h.length;p++){var f=h[p];r.push.apply(r,f)}return[u[0]].concat(r)}))},e.prototype.build=function(t){var e;km(t)&&(t=t[0]),t=t,this.cells.forEach((function(n,r){kd("RNNCell_"+r,(function(){n.build(t),e=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,t=[t[0],e]}))})),this.built=!0},e.prototype.getConfig=function(){for(var e=[],n=0,r=this.cells;n<r.length;n++){var a=r[n];e.push({className:a.getClassName(),config:a.getConfig()})}var i={cells:e},o=t.prototype.getConfig.call(this);return Object.assign(i,o),i},e.fromConfig=function(t,e,n){void 0===n&&(n={});for(var r=[],a=0,i=e.cells;a<i.length;a++){var o=i[a];r.push(tg(o,n))}return new t({cells:r})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(!this.trainable)return[];for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var a=[],i=0,o=this.cells;i<o.length;i++)r=o[i],a.push.apply(a,r.trainableWeights);return a.concat(t)}return t},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.weights)}return Om(t)},e.prototype.setWeights=function(t){for(var e=[],n=0,r=this.cells;n<r.length;n++)for(var a=r[n],i=a.weights.length,o=t.splice(i),s=0;s<a.weights.length;++s)e.push([a.weights[s],o[s]]);_m(e)},e.className="StackedRNNCells",e}(Xy);function nb(t,e,n,r){function a(){return Jd(t(),e)}if(void 0===n&&(n=null),void 0===r&&(r=1),r>1){for(var i=[],o=0;o<r;o++)i.push($d(a,t,n));return i.map((function(t){return Qe(t.clone())}))}return Qe($d(a,t,n).clone())}ff.registerClass(eb);var rb=function(t){function e(e){var n=t.call(this,e)||this;return n.layer=e.layer,n}return Tf(e,t),e.prototype.build=function(t){this.built=!0},Object.defineProperty(e.prototype,"trainable",{get:function(){return null!=this.layer&&this.layer.trainable},set:function(t){null!=this.layer&&(this.layer.trainable=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.layer.getWeights()},e.prototype.setWeights=function(t){this.layer.setWeights(t)},e.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=tg(e.layer,n);delete e.layer;var a={layer:r};return Object.assign(a,e),new t(a)},e}(Pm),ab=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n}return Tf(e,t),e.prototype.build=function(e){if((e=Am(e)).length<3)throw new Lf("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var n=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),t.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(t){var e=[(t=Am(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},e.prototype.call=function(t,e){var n=this;return $e((function(){return Hy((function(t,r){return[Em(n.layer.call(t,e)),[]]}),t=Em(t),[],!1,null,null,!1,!0)[1]}))},e.className="TimeDistributed",e}(rb);ff.registerClass(ab);var ib=function(t){function e(e){var n=t.call(this,e)||this,r=e.layer.getConfig(),a={};a.className=e.layer.getClassName(),a.config=r,n.forwardLayer=tg(a),r.goBackwards=!0!==r.goBackwards;var i={};if(i.className=e.layer.getClassName(),i.config=r,n.backwardLayer=tg(i),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,function(t){td(bd,"BidirectionalMergeMode",t)}(n.mergeMode),e.weights)throw new Bf("weights support is not implemented for Bidirectional layer yet.");return n._stateful=e.layer.stateful,n.returnSequences=e.layer.returnSequences,n.returnState=e.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=e.layer.inputSpec,n.numConstants=null,n}return Tf(e,t),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(t){var e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))},e.prototype.computeOutputShape=function(t){var e,n,r,a=this.forwardLayer.computeOutputShape(t);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(r=a.slice(1),e=a[0]):e=a[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[e].concat(r).concat(r.slice()):jf(n)},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,a=null==n?null:n.constants;null==n&&(n={});var i=qy(e,r,a,this.numConstants);if(e=i.inputs,r=i.initialState,a=i.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==a)return t.prototype.apply.call(this,e,n);var o=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new Lf("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(t){return new Fm({shape:t.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 Bf("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof Mm,p=0,h=o;p<h.length;p++)if(h[p]instanceof Mm!==c)throw new Lf("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){var f=[e].concat(o),d=this.inputSpec.concat(s),m=this.inputSpec;this.inputSpec=d;var g=t.prototype.apply.call(this,f,n);return this.inputSpec=m,g}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return $e((function(){var r,a,i,o,s=e.initialState;if(null==s)r=n.forwardLayer.call(t,e),a=n.backwardLayer.call(t,e);else{var u=s.slice(0,s.length/2),l=s.slice(s.length/2);r=n.forwardLayer.call(t,Object.assign(e,{initialState:u})),a=n.backwardLayer.call(t,Object.assign(e,{initialState:l}))}return n.returnState&&(Array.isArray(r)&&(i=r.slice(1).concat(a.slice(1))),r=r[0],a=a[0]),n.returnSequences&&(a=ec(a,1)),"concat"===n.mergeMode?o=Vd([r,a]):"sum"===n.mergeMode?o=Or(r,a):"ave"===n.mergeMode?o=Ia(.5,Or(r,a)):"mul"===n.mergeMode?o=Ia(r,a):null==n.mergeMode&&(o=[r,a]),n.returnState?null==n.mergeMode?o.concat(i):[o].concat(i):o}))},e.prototype.resetStates=function(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},e.prototype.build=function(t){var e=this;kd(this.forwardLayer.name,(function(){e.forwardLayer.build(t)})),kd(this.backwardLayer.name,(function(){e.backwardLayer.build(t)})),this.built=!0},e.prototype.computeMask=function(t,e){var n;if(Array.isArray(e)&&(e=e[0]),n=this.returnSequences?null==this.mergeMode?[e,e]:e:null==this.mergeMode?[null,null]:null,this.returnState){var r=this.forwardLayer.states.map((function(t){return null}));return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}return n},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={mergeMode:this.mergeMode},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.fromConfig=function(t,e){var n=tg(e.layer);if(delete e.layer,null!=e.numConstants)throw new Bf("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=e;return r.layer=n,new t(r)},e.className="Bidirectional",e}(rb);function ob(t){return new Oy(t)}function sb(t){return new My(t)}function ub(t){return new By(t)}function lb(t){return new Vy(t)}function cb(t){return new Gy(t)}function pb(t){return new Dy(t)}function hb(t){return new Fy(t)}ff.registerClass(ib);var fb=lb,db=cb,mb=pb,gb=hb,vb=Object.freeze({inputLayer:function(t){return new Um(t)},elu:function(t){return new Lv(t)},reLU:function(t){return new Fv(t)},leakyReLU:function(t){return new Mv(t)},prelu:function(t){return new zv(t)},softmax:function(t){return new Pv(t)},thresholdedReLU:function(t){return new Bv(t)},conv1d:function(t){return new Zv(t)},conv2d:function(t){return new Xv(t)},conv2dTranspose:function(t){return new Jv(t)},conv3d:function(t){return new Yv(t)},separableConv2d:function(t){return new $v(t)},cropping2D:function(t){return new Qv(t)},upSampling2d:function(t){return new ty(t)},depthwiseConv2d:function(t){return new ey(t)},activation:function(t){return new oy(t)},dense:function(t){return new ay(t)},dropout:function(t){return new ny(t)},spatialDropout1d:function(t){return new ry(t)},flatten:function(t){return new iy(t)},repeatVector:function(t){return new sy(t)},reshape:function(t){return new uy(t)},permute:function(t){return new ly(t)},embedding:function(t){return new py(t)},add:function(t){return new fy(t)},average:function(t){return new my(t)},concatenate:function(t){return new yy(t)},maximum:function(t){return new gy(t)},minimum:function(t){return new vy(t)},multiply:function(t){return new dy(t)},dot:function(t){return new xy(t)},batchNormalization:function(t){return new ky(t)},layerNormalization:function(t){return new Iy(t)},zeroPadding2d:function(t){return new Ey(t)},averagePooling1d:ob,avgPool1d:function(t){return ob(t)},avgPooling1d:function(t){return ob(t)},averagePooling2d:sb,avgPool2d:function(t){return sb(t)},avgPooling2d:function(t){return sb(t)},averagePooling3d:ub,avgPool3d:function(t){return ub(t)},avgPooling3d:function(t){return ub(t)},globalAveragePooling1d:function(t){return new Wy(t)},globalAveragePooling2d:function(t){return new jy(t)},globalMaxPooling1d:lb,globalMaxPooling2d:cb,maxPooling1d:pb,maxPooling2d:hb,maxPooling3d:function(t){return new Ly(t)},gru:function(t){return new Zy(t)},gruCell:function(t){return new $y(t)},lstm:function(t){return new tb(t)},lstmCell:function(t){return new Qy(t)},simpleRNN:function(t){return new Jy(t)},simpleRNNCell:function(t){return new Yy(t)},rnn:function(t){return new Ky(t)},stackedRNNCells:function(t){return new eb(t)},bidirectional:function(t){return new ib(t)},timeDistributed:function(t){return new ab(t)},globalMaxPool1d:fb,globalMaxPool2d:db,maxPool1d:mb,maxPool2d:gb,Layer:Pm,RNN:Ky,RNNCell:Xy,input:lv,gaussianNoise:function(t){return new wy(t)},gaussianDropout:function(t){return new Cy(t)},alphaDropout:function(t){return new Ny(t)},masking:function(t){return new cy(t)}}),yb=Object.freeze({binaryAccuracy:function(t,e){return pg(t,e)},binaryCrossentropy:function(t,e){return mg(t,e)},sparseCategoricalAccuracy:function(t,e){return gg(t,e)},categoricalAccuracy:function(t,e){return hg(t,e)},categoricalCrossentropy:function(t,e){return vg(t,e)},precision:function(t,e){return dg(t,e)},recall:function(t,e){return function(t,e){return $e((function(){var n=fg(t,e),r=function(t,e){return $e((function(){return qu(t.equal(1),e.equal(0)).sum().cast("float32")}))}(t,e),a=n.add(r);return Yu(Nl(a,0),n.div(a),0).cast("float32")}))}(t,e)},cosineProximity:function(t,e){return ug(t,e)},meanAbsoluteError:function(t,e){return rg(t,e)},meanAbsolutePercentageError:function(t,e){return ag(t,e)},MAPE:function(t,e){return ag(t,e)},mape:function(t,e){return ag(t,e)},meanSquaredError:function(t,e){return ng(t,e)},MSE:function(t,e){return ng(t,e)},mse:function(t,e){return ng(t,e)}}),bb=Object.freeze({modelFromJSON:function(t,e){return Of(this,void 0,void 0,(function(){var n,r,a,i,o,s,u,l;return _f(this,(function(c){switch(c.label){case 0:return"modelTopology"in t||(t={modelTopology:t}),null!=(n=(t=t).modelTopology).model_config&&(n=n.model_config),r=Eg(n),a=tg(r,e),null==t.weightsManifest?[3,2]:[4,af.loadWeights(t.weightsManifest,t.pathPrefix,a.weights.map((function(t){return t.originalName})))];case 1:for(i=c.sent(),o={},s=0,u=a.weights;s<u.length;s++)l=u[s],o[l.originalName]=i[l.originalName];a.loadWeights(o),Ze(i),c.label=2;case 2:return[2,a]}}))}))}}),xb=Object.freeze({l1l2:function(t){return new Tv(t)},l1:function(t){return function(t){return Ev(t),new Tv({l1:null!=t?t.l1:null,l2:0})}(t)},l2:function(t){return function(t){return Ev(t),new Tv({l2:null!=t?t.l2:null,l1:0})}(t)}}),wb=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.model=null,e}return Tf(e,t),e.prototype.setModel=function(t){if(!(t instanceof rv))throw new Error("model must be a LayersModel, not some other Container");this.model=t},e}(Hm);function Cb(t,e){return t<e}function Nb(t,e){return t>e}var Sb,kb,Ib=function(t){function e(e){var n=t.call(this)||this;if(null==e&&(e={}),e.restoreBestWeights)throw new Bf("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor=e.monitor||"val_loss",n.minDelta=Math.abs(e.minDelta||0),n.patience=e.patience||0,n.verbose=e.verbose||0,n.mode=e.mode||"auto",n.baseline=e.baseline,-1===["auto","min","max"].indexOf(n.mode)&&(console.warn("EarlyStopping mode '"+n.mode+"' is invalid. Falling back to mode 'auto'."),n.mode="auto"),"min"===n.mode?n.monitorFunc=Cb:"max"===n.mode||-1!==n.monitor.indexOf("acc")?n.monitorFunc=Nb:n.monitorFunc=Cb,n.monitorFunc===Cb&&(n.minDelta*=-1),n}return Tf(e,t),e.prototype.onTrainBegin=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Cb?1/0:-1/0,[2]}))}))},e.prototype.onEpochEnd=function(t,e){return Of(this,void 0,void 0,(function(){var n;return _f(this,(function(r){switch(r.label){case 0:return[4,Gm(e)];case 1:return r.sent(),null==(n=this.getMonitorValue(e))||(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=t,this.model.stopTraining=!0))),[2]}}))}))},e.prototype.onTrainEnd=function(t){return Of(this,void 0,void 0,(function(){return _f(this,(function(t){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]}))}))},e.prototype.getMonitorValue=function(t){null==t&&(t={});var e=t[this.monitor];return null==e&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(t)),e},e}(wb),Eb={earlyStopping:function(t){return new Ib(t)}},Ab=function(){return(Ab=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t}).apply(this,arguments)};function Tb(t,e,n,r){return new(n||(n=Promise))((function(a,i){function o(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(o,s)}u((r=r.apply(t,e||[])).next())}))}function Rb(t,e){var n,r,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=e.call(t,o)}catch(t){i=[6,t],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}!function(t){t[t.DT_INVALID=0]="DT_INVALID",t[t.DT_FLOAT=1]="DT_FLOAT",t[t.DT_DOUBLE=2]="DT_DOUBLE",t[t.DT_INT32=3]="DT_INT32",t[t.DT_UINT8=4]="DT_UINT8",t[t.DT_INT16=5]="DT_INT16",t[t.DT_INT8=6]="DT_INT8",t[t.DT_STRING=7]="DT_STRING",t[t.DT_COMPLEX64=8]="DT_COMPLEX64",t[t.DT_INT64=9]="DT_INT64",t[t.DT_BOOL=10]="DT_BOOL",t[t.DT_QINT8=11]="DT_QINT8",t[t.DT_QUINT8=12]="DT_QUINT8",t[t.DT_QINT32=13]="DT_QINT32",t[t.DT_BFLOAT16=14]="DT_BFLOAT16",t[t.DT_FLOAT_REF=101]="DT_FLOAT_REF",t[t.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",t[t.DT_INT32_REF=103]="DT_INT32_REF",t[t.DT_UINT8_REF=104]="DT_UINT8_REF",t[t.DT_INT16_REF=105]="DT_INT16_REF",t[t.DT_INT8_REF=106]="DT_INT8_REF",t[t.DT_STRING_REF=107]="DT_STRING_REF",t[t.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",t[t.DT_INT64_REF=109]="DT_INT64_REF",t[t.DT_BOOL_REF=110]="DT_BOOL_REF",t[t.DT_QINT8_REF=111]="DT_QINT8_REF",t[t.DT_QUINT8_REF=112]="DT_QUINT8_REF",t[t.DT_QINT32_REF=113]="DT_QINT32_REF",t[t.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(Sb||(Sb={})),function(t){!function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(t.CheckpointFormatVersion||(t.CheckpointFormatVersion={}))}(kb||(kb={}));var Db={};function Ob(t,e){var n={tfOpName:t,category:"custom",inputs:[],attrs:[],customExecutor:e};Db[t]=n}function _b(t){return Db[t]}function Fb(t){delete Db[t]}function Mb(t,e,n,r){var a=e.inputParams[t];if(a&&void 0!==a.inputIndexStart){var i=a.inputIndexStart,o=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?i+1:a.inputIndexEnd;if("tensor"===a.type)return zb(e.inputNames[a.inputIndexStart],n,r);if("tensors"===a.type)return e.inputNames.slice(i,o).map((function(t){return zb(t,n,r)}));var s=Array.prototype.slice.call(zb(e.inputNames.slice(i)[0],n,r).dataSync());return"number"===a.type?s[0]:s}var u=e.attrParams[t];return u&&u.value}function zb(t,e,n){var r=Pb(t),a=r[0],i=r[1],o=n.currentContextIds.find((function(t){return!!e[Bb(a,t)]}));return void 0!==o?e[Bb(a,o)][i]:void 0}function Lb(t,e){var n=Pb(t),r=n[0],a=n[1];return[Bb(r,e&&e.currentContextId),a]}function Bb(t,e){return e?t+"-"+e:t}function Pb(t){var e=t.lastIndexOf(":");return-1===e?[t,0]:[t.substring(0,e),Number(t.substring(e+1))]}function Wb(t,e){for(var n=[],r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}var Vb=Object.freeze({json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),Ub=Object.freeze({json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),jb=Object.freeze({json:[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"}]}]}),Gb=Object.freeze({json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]}]}),qb=Object.freeze({json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]}),Hb=Object.freeze({json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),Kb=Object.freeze({json:[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}]}),Xb=Object.freeze({json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),Yb=Object.freeze({json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}]}),Jb=Object.freeze({json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),$b=Object.freeze({json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),Zb=Object.freeze({json:[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),Qb=Object.freeze({json:[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]}]}),tx=Object.freeze({json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),ex=Object.freeze({json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),nx=Object.freeze({json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]}]}),rx=function(){function t(){var t=[Vb,Ub,jb,Gb,qb,Hb,Kb,Jb,Yb,Xb,$b,Zb,Qb,tx,ex,nx],e=[].concat.apply([],t.map((function(t){return t.json})));this.opMappers=e.reduce((function(t,e){return t[e.tfOpName]=e,t}),{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.transformGraph=function(t,e){var n=this;void 0===e&&(e={});var r=[],a=[],i=t.node.reduce((function(t,e){return t[e.name]=n.mapNode(e),e.op.startsWith("Placeholder")&&r.push(t[e.name]),"Const"===e.op&&a.push(t[e.name]),t}),{}),o=[],s=[],u={},l={};null!=e&&(u=this.mapSignatureEntries(e.inputs),l=this.mapSignatureEntries(e.outputs));var c=Object.keys(i);return c.forEach((function(t){var e=i[t];e.inputNames.forEach((function(t){var n=Lb(t)[0];e.inputs.push(i[n]),i[n].children.push(e)}))})),0===Object.keys(l).length?c.forEach((function(t){var e=i[t];0===e.children.length&&s.push(e)})):Object.keys(l).forEach((function(t){var e=Lb(t)[0],n=i[e];null!=n&&(n.signatureKey=l[t],s.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((function(t){var e=Lb(t)[0],n=i[e];n&&(n.signatureKey=u[t],o.push(n))})):o=r,{nodes:i,inputs:o,outputs:s,weights:a,placeholders:r,signature:e}},t.prototype.mapSignatureEntries=function(t){return Object.keys(t||{}).reduce((function(e,n){return e[t[n].name]=n,e}),{})},t.prototype.mapNode=function(t){var e=_b(t.op)||this.opMappers[t.op]||{};null==t.attr&&(t.attr={});var n={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map((function(t){return t.startsWith("^")?t.substr(1):t})),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return null!=e.inputs&&(n.inputParams=e.inputs.reduce((function(t,e){return t[e.name]={type:e.type,inputIndexStart:e.start,inputIndexEnd:e.end},t}),{})),null!=e.attrs&&(n.attrParams=e.attrs.reduce((function(e,n){var r=n.type,a=void 0;switch(n.type){case"string":void 0===(a=ix(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=ix(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":void 0===(a=dx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=dx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":void 0===(a=sx(t.attr,n.tfName,n.defaultValue||0))&&n.tfDeprecatedName&&(a=sx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":void 0===(a=fx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=fx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":void 0===(a=ox(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=ox(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":void 0===(a=gx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=gx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":void 0===(a=hx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=hx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":void 0===(a=mx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=mx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":void 0===(a=lx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=lx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":void 0===(a=cx(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(a=cx(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+n.type+" for op: "+t.op)}return e[n.name]={value:a,type:r},e}),{})),n},t}();function ax(t,e){var n=Array.isArray(t)?String.fromCharCode.apply(null,t):function(t){var e=c().global;if(void 0!==e.atob)return e.atob(t);if("undefined"!=typeof Buffer)return new Buffer(t,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(t);return e?n:n.toLowerCase()}function ix(t,e,n,r){void 0===r&&(r=!1);var a=t[e];return null!=a?ax(a.s,r):n}function ox(t,e,n){var r=t[e];return r?r.b:n}function sx(t,e,n){var r=t[e]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof a?a:parseInt(a,10)}function ux(t){switch("string"==typeof t&&(t=Sb[t]),t){case Sb.DT_FLOAT:return"float32";case Sb.DT_INT32:case Sb.DT_INT64:case Sb.DT_INT8:case Sb.DT_UINT8:return"int32";case Sb.DT_BOOL:return"bool";case Sb.DT_DOUBLE:return"float32";case Sb.DT_STRING:return"string";default:return null}}function lx(t,e,n){var r=t[e];return r&&r.type?ux(r.type):n}function cx(t,e,n){var r=t[e];return r&&r.list&&r.list.type?r.list.type.map((function(t){return ux(t)})):n}function px(t){if(!t.unknownRank)return null!=t.dim?t.dim.map((function(t){return"number"==typeof t.size?t.size:parseInt(t.size,10)})):[]}function hx(t,e,n){var r=t[e];return r&&r.shape?px(r.shape):n}function fx(t,e,n){var r=t[e];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((function(t){return"number"==typeof t?t:parseInt(t,10)})):n}function dx(t,e,n,r){void 0===r&&(r=!1);var a=t[e];return a&&a.list&&a.list.s?a.list.s.map((function(t){return ax(t,r)})):n}function mx(t,e,n){var r=t[e];return r&&r.list&&r.list.shape?r.list.shape.map((function(t){return px(t)})):n}function gx(t,e,n){var r=t[e];return r&&r.list&&r.list.b?r.list.b:n}var vx=function(){function t(t,e,n){var r=this;this.node=t,this.tensorMap=e,this.context=n,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map((function(t){return r.getInput(t)})),null!=t.rawAttrs&&(this.attrs=Object.keys(t.rawAttrs).reduce((function(t,e){return t[e]=r.getAttr(e),t}),{}))}return t.prototype.getInput=function(t){return zb(t,this.tensorMap,this.context)},t.prototype.getAttr=function(t,e){var n=this.node.rawAttrs[t];if(null!=n.tensor)return zb(t,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return sx(this.node.rawAttrs,t,e);if(null!=n.s)return ix(this.node.rawAttrs,t,e);if(null!=n.b)return ox(this.node.rawAttrs,t,e);if(null!=n.shape)return hx(this.node.rawAttrs,t,e);if(null!=n.type)return lx(this.node.rawAttrs,t,e);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return fx(this.node.rawAttrs,t,e);if(null!=n.list.s)return dx(this.node.rawAttrs,t,e);if(null!=n.list.shape)return mx(this.node.rawAttrs,t,e);if(null!=n.list.b)return gx(this.node.rawAttrs,t,e);if(null!=n.list.type)return cx(this.node.rawAttrs,t,e)}return e},t}(),yx=function(){function t(e,n,r,a,i,o,s){this.name=e,this.dtype=n,this.maxSize=r,this.elementShape=a,this.identicalElementShapes=i,this.dynamicSize=o,this.clearAfterRead=s,this.tensors=[],this.closed_=!1,this.id=t.nextId++}return Object.defineProperty(t.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),t.prototype.clearAndClose=function(){this.tensors.forEach((function(t){return t.tensor.dispose()})),this.tensors=[],this.closed_=!0},t.prototype.size=function(){return this.tensors.length},t.prototype.read=function(t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||t>=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map((function(t){return e.read(t)}))},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach((function(t,r){return n.write(t,e[r])}))},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n<this.size();n++)t.push(n)}if(0===t.length)return Rn([],[0].concat(this.elementShape));var r=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),lr(r,0)},t.prototype.concat=function(t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+t);if(0===this.size())return Rn([],[0].concat(this.elementShape));for(var e=[],n=0;n<this.size();n++)e.push(n);var r=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),Kn(r,0)},t.prototype.scatter=function(t,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(t.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+e.shape[0]);var n=Math.max.apply(Math,t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error("Max index must be < array size ("+n+" vs. "+this.maxSize+")");this.writeMany(t,cr(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,a=t.map((function(t){return r+=t}));if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var i=0===r?0:e.size/r,o=[];$e((function(){e=e.reshape([1,r,i]);for(var s=0;s<t.length;++s){var u=[0,0===s?0:a[s-1],0],l=[1,t[s],i];o[s]=dc(e,u,l).reshape(n.elementShape)}return o}));for(var s=[],u=0;u<t.length;u++)s[u]=u;this.writeMany(s,o)},t.prototype.assertShapesMatchAllowUndefinedSize=function(t,e,n){void 0===n&&(n=""),pt.assert(this.shapesEqualAllowUndefinedSize(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))},t.prototype.shapesEqualAllowUndefinedSize=function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(-1!==t[n]&&-1!==e[n]&&t[n]!==e[n])return!1;return!0},t.nextId=0,t}();function bx(t,e,n){var r=function(t,e,n){switch(t.category){case"arithmetic":return $e((function(){return function(t,e,n){switch(t.op){case"BiasAdd":case"AddV2":case"Add":return[Or(Mb("a",t,e,n),Mb("b",t,e,n))];case"AddN":return[Eu(Mb("tensors",t,e,n))];case"FloorMod":case"Mod":return[Sa(Mb("a",t,e,n),Mb("b",t,e,n))];case"Mul":return[Ia(Mb("a",t,e,n),Mb("b",t,e,n))];case"RealDiv":case"Div":return[_a(Mb("a",t,e,n),Mb("b",t,e,n))];case"DivNoNan":return[$u(Mb("a",t,e,n),Mb("b",t,e,n))];case"FloorDiv":return[ba(Mb("a",t,e,n),Mb("b",t,e,n))];case"Sub":return[Da(Mb("a",t,e,n),Mb("b",t,e,n))];case"Minimum":return[Ca(Mb("a",t,e,n),Mb("b",t,e,n))];case"Maximum":return[xa(Mb("a",t,e,n),Mb("b",t,e,n))];case"Pow":return[Aa(Mb("a",t,e,n),Mb("b",t,e,n))];case"SquaredDifference":return[bl(Mb("a",t,e,n),Mb("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"basic_math":return $e((function(){return function(t,e,n){switch(t.op){case"Abs":case"ComplexAbs":return[zr(Mb("x",t,e,n))];case"Acos":return[Lr(Mb("x",t,e,n))];case"Acosh":return[Br(Mb("x",t,e,n))];case"Asin":return[Pr(Mb("x",t,e,n))];case"Asinh":return[Wr(Mb("x",t,e,n))];case"Atan":return[Vr(Mb("x",t,e,n))];case"Atan2":return[va(Mb("x",t,e,n),Mb("y",t,e,n))];case"Atanh":return[Ur(Mb("x",t,e,n))];case"Ceil":return[jr(Mb("x",t,e,n))];case"Complex":return[En(Mb("real",t,e,n),Mb("imag",t,e,n))];case"Cos":return[qr(Mb("x",t,e,n))];case"Cosh":return[Hr(Mb("x",t,e,n))];case"Elu":return[Dc(Mb("x",t,e,n))];case"Erf":return[Kr(Mb("x",t,e,n))];case"Exp":return[Xr(Mb("x",t,e,n))];case"Expm1":return[Yr(Mb("x",t,e,n))];case"Floor":return[Jr(Mb("x",t,e,n))];case"Log":return[$r(Mb("x",t,e,n))];case"Log1p":return[Zr(Mb("x",t,e,n))];case"Imag":return[Tn(Mb("x",t,e,n))];case"Neg":return[ta(Mb("x",t,e,n))];case"Reciprocal":return[ea(Mb("x",t,e,n))];case"Real":return[An(Mb("x",t,e,n))];case"Relu":return[Fc(Mb("x",t,e,n))];case"Round":return[na(Mb("x",t,e,n))];case"Selu":return[zc(Mb("x",t,e,n))];case"Sigmoid":return[aa(Mb("x",t,e,n))];case"Sin":return[la(Mb("x",t,e,n))];case"Sign":return[ia(Mb("x",t,e,n))];case"Sinh":return[ca(Mb("x",t,e,n))];case"Softplus":return[pa(Mb("x",t,e,n))];case"Sqrt":return[ha(Mb("x",t,e,n))];case"Square":return[yl(Mb("x",t,e,n))];case"Tanh":return[ma(Mb("x",t,e,n))];case"Tan":return[da(Mb("x",t,e,n))];case"Relu6":case"ClipByValue":return[Gr(Mb("x",t,e,n),Mb("clipValueMin",t,e,n),Mb("clipValueMax",t,e,n))];case"Rsqrt":return[ra(zb(t.inputNames[0],e,n))];case"Prod":return[Rc(Mb("x",t,e,n),Mb("axes",t,e,n))];case"LeakyRelu":return[Oc(Mb("x",t,e,n),Mb("alpha",t,e,n))];case"Prelu":return[_c(Mb("x",t,e,n),Mb("alpha",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"control":return function(t,e,n){return Tb(void 0,void 0,void 0,(function(){var r,a,i,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,S,k,I,E,A,T,R,D,O,_,F,M,z;return Rb(this,(function(L){switch(L.label){case 0:switch(t.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[Mb("pred",t,e,n).clone()]];case 2:return r=Mb("pred",t,e,n),a=Mb("data",t,e,n),[4,r.data()];case 3:return[2,L.sent()[0]?[void 0,a.clone()]:[a.clone(),void 0]];case 4:return[2,(i=t.inputNames.find((function(t){return void 0!==zb(t,e,n)})))?[zb(i,e,n).clone()]:void 0];case 5:return o=Mb("frameName",t,e,n),s=Mb("tensor",t,e,n),n.enterFrame(o),[2,[s.clone()]];case 6:return u=Mb("tensor",t,e,n),n.exitFrame(),[2,[u.clone()]];case 7:return l=Mb("tensor",t,e,n),n.nextIteration(),[2,[l.clone()]];case 8:return c=Mb("size",t,e,n),p=Mb("dtype",t,e,n),h=Mb("elementShape",t,e,n),f=Mb("dynamicSize",t,e,n),d=Mb("clearAfterRead",t,e,n),m=Mb("identicalElementShapes",t,e,n),g=Mb("name",t,e,n),v=new yx(g,p,c,h,m,f,d),n.addTensorArray(v),[2,[On(v.id),On(1)]];case 9:return y=Mb("tensorArrayId",t,e,n),b=Mb("index",t,e,n),x=Mb("tensor",t,e,n),n.getTensorArray(y).write(b,x),[2,[On(1)]];case 10:return w=Mb("tensorArrayId",t,e,n),C=Mb("index",t,e,n),[2,[n.getTensorArray(w).read(C)]];case 11:return N=Mb("tensorArrayId",t,e,n),S=Mb("indices",t,e,n),k=Mb("dtype",t,e,n),[2,[n.getTensorArray(N).gather(S,k)]];case 12:return I=Mb("tensorArrayId",t,e,n),E=Mb("indices",t,e,n),A=Mb("tensor",t,e,n),n.getTensorArray(I).scatter(E,A),[2,[On(1)]];case 13:return T=Mb("tensorArrayId",t,e,n),R=n.getTensorArray(T),D=Mb("dtype",t,e,n),[2,[R.concat(D)]];case 14:return O=Mb("tensorArrayId",t,e,n),_=Mb("tensor",t,e,n),F=Mb("lengths",t,e,n),n.getTensorArray(O).split(F,_),[2,[On(1)]];case 15:return M=Mb("tensorArrayId",t,e,n),[2,[On(n.getTensorArray(M).size(),"int32")]];case 16:return z=Mb("tensorArrayId",t,e,n),n.getTensorArray(z).clearAndClose(),[2,[On(0)]];case 17:throw TypeError("Node type "+t.op+" is not implemented")}}))}))}(t,e,n);case"convolution":return $e((function(){return function(t,e,n){switch(t.op){case"Conv1D":var r=Mb("stride",t,e,n),a=Mb("pad",t,e,n),i=Mb("dataFormat",t,e,n).toUpperCase(),o=Mb("dilation",t,e,n);return[Vl(Mb("x",t,e,n),Mb("filter",t,e,n),r,a,i,o)];case"Conv2D":r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),i=Mb("dataFormat",t,e,n).toUpperCase();var s=Mb("dilations",t,e,n);return[Ul(Mb("x",t,e,n),Mb("filter",t,e,n),[r[1],r[2]],a,i,[s[1],s[2]])];case"_FusedConv2D":case"FusedDepthwiseConv2dNative":var u=Mb("fusedOps",t,e,n),l=u[0],c=u[1],p="biasadd"===l,h="prelu"===c,f="fusedbatchnorm"===l,d=Mb("numArgs",t,e,n);if(p){if(h&&2!==d)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!h&&1!==d)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(f)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),i=Mb("dataFormat",t,e,n).toUpperCase(),s=Mb("dilations",t,e,n);var m=Mb("args",t,e,n),g=m[0],v=m[1];return[("_FusedConv2D"===t.op?Lp.conv2d:Lp.depthwiseConv2d)({x:Mb("x",t,e,n),filter:Mb("filter",t,e,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[s[1],s[2]],bias:g,activation:c,preluActivationWeights:v})];case"Conv2DBackpropInput":case"Conv2dTranspose":var y=Mb("outputShape",t,e,n);return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),[Jl(Mb("x",t,e,n),Mb("filter",t,e,n),y,[r[1],r[2]],a)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),s=Mb("dilations",t,e,n),i=Mb("dataFormat",t,e,n).toUpperCase(),[Hl(Mb("input",t,e,n),Mb("filter",t,e,n),[r[1],r[2]],a,i,[s[1],s[2]])];case"Conv3D":return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),i=Mb("dataFormat",t,e,n).toUpperCase(),s=Mb("dilations",t,e,n),[jl(Mb("x",t,e,n),Mb("filter",t,e,n),[r[1],r[2],r[3]],a,i,[s[1],s[2],s[3]])];case"AvgPool":r=Mb("strides",t,e,n),a=Mb("pad",t,e,n);var b=Mb("kernelSize",t,e,n);return[lc(Mb("x",t,e,n),[b[1],b[2]],[r[1],r[2]],a)];case"MaxPool":return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),b=Mb("kernelSize",t,e,n),[uc(Mb("x",t,e,n),[b[1],b[2]],[r[1],r[2]],a)];case"MaxPoolWithArgmax":r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),b=Mb("kernelSize",t,e,n);var x=Mb("includeBatchInIndex",t,e,n),w=fc(Mb("x",t,e,n),[b[1],b[2]],[r[1],r[2]],a,x);return[w.result,w.indexes];case"AvgPool3D":return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),b=Mb("kernelSize",t,e,n),[hc(Mb("x",t,e,n),[b[1],b[2],b[3]],[r[1],r[2],r[3]],a)];case"MaxPool3D":return r=Mb("strides",t,e,n),a=Mb("pad",t,e,n),b=Mb("kernelSize",t,e,n),[pc(Mb("x",t,e,n),[b[1],b[2],b[3]],[r[1],r[2],r[3]],a)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"creation":return $e((function(){return function(t,e,n){switch(t.op){case"Fill":var r=Mb("shape",t,e,n),a=Mb("dtype",t,e,n);return[Un(r,Mb("value",t,e,n),a)];case"LinSpace":var i=Mb("start",t,e,n);return[jn(i,Mb("stop",t,e,n),Mb("num",t,e,n))];case"Multinomial":var o=Mb("logits",t,e,n),s=Mb("numSamples",t,e,n),u=Mb("seed",t,e,n);return[tl(o,s,u)];case"OneHot":var l=Mb("indices",t,e,n),c=Mb("depth",t,e,n),p=Mb("onValue",t,e,n),h=Mb("offValue",t,e,n);return[el(l,c,p,h)];case"Ones":return[Wn(Mb("shape",t,e,n),Mb("dtype",t,e,n))];case"OnesLike":return[qn(Mb("x",t,e,n))];case"RandomUniform":return[vl(Mb("shape",t,e,n),Mb("minval",t,e,n),Mb("maxval",t,e,n),Mb("dtype",t,e,n))];case"Range":return[Gn(i=Mb("start",t,e,n),Mb("stop",t,e,n),Mb("step",t,e,n),Mb("dtype",t,e,n))];case"TruncatedNormal":r=Mb("shape",t,e,n);var f=Mb("mean",t,e,n),d=Mb("stdDev",t,e,n);return u=Mb("seed",t,e,n),[xl(r,f,d,Mb("dtype",t,e,n),u)];case"Zeros":return[Vn(Mb("shape",t,e,n),Mb("dtype",t,e,n))];case"ZerosLike":return[Hn(Mb("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"dynamic":return function(t,e,n){return Tb(void 0,void 0,void 0,(function(){var r,a,i,o,s,u,l,c;return Rb(this,(function(p){switch(p.label){case 0:switch(t.op){case"NonMaxSuppressionV5":case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,5];case"ListDiff":return[3,7]}return[3,8];case 1:return r=Mb("boxes",t,e,n),a=Mb("scores",t,e,n),i=Mb("maxOutputSize",t,e,n),o=Mb("iouThreshold",t,e,n),s=Mb("scoreThreshold",t,e,n),"NonMaxSuppressionV5"!==t.op?[3,3]:(u=Mb("softNmsSigma",t,e,n),[4,Tp.nonMaxSuppressionWithScoreAsync(r,a,i,o,s,u)]);case 2:return[2,[(c=p.sent()).selectedIndices,c.selectedScores]];case 3:return[4,Tp.nonMaxSuppressionAsync(r,a,i,o,s)];case 4:return[2,[p.sent()]];case 5:return l=Mb("condition",t,e,n).asType("bool"),[4,Ju(l)];case 6:return c=[p.sent()],l.dispose(),[2,c];case 7:return[2,pr(Mb("x",t,e,n),Mb("y",t,e,n))];case 8:throw TypeError("Node type "+t.op+" is not implemented")}}))}))}(t,e,n);case"evaluation":return $e((function(){return function(t,e,n){switch(t.op){case"TopKV2":var r=Mb("x",t,e,n),a=Mb("k",t,e,n),i=Mb("sorted",t,e,n),o=jc(r,a,i);return[o.values,o.indices];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"image":return $e((function(){return function(t,e,n){switch(t.op){case"ResizeBilinear":var r=Mb("images",t,e,n),a=Mb("size",t,e,n),i=Mb("alignCorners",t,e,n);return[Tp.resizeBilinear(r,[a[0],a[1]],i)];case"ResizeNearestNeighbor":return r=Mb("images",t,e,n),a=Mb("size",t,e,n),i=Mb("alignCorners",t,e,n),[Tp.resizeNearestNeighbor(r,[a[0],a[1]],i)];case"CropAndResize":var o=Mb("image",t,e,n),s=Mb("boxes",t,e,n),u=Mb("boxInd",t,e,n),l=Mb("cropSize",t,e,n),c=Mb("method",t,e,n),p=Mb("extrapolationValue",t,e,n);return[Tp.cropAndResize(o,s,u,l,c,p)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"graph":return $e((function(){return function(t,e,n){switch(t.op){case"Const":return e[t.name];case"PlaceholderWithDefault":var r=Mb("default",t,e,n);return[zb(t.name,e,n)||r];case"Placeholder":return[zb(t.name,e,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[Mb("x",t,e,n).clone()];case"IdentityN":return Mb("x",t,e,n).map((function(t){return t.clone()}));case"Snapshot":return[Mb("x",t,e,n).clone()];case"Shape":return[_n(Mb("x",t,e,n).shape,"int32")];case"ShapeN":return Mb("x",t,e,n).map((function(t){return _n(t.shape)}));case"Size":return[On(Mb("x",t,e,n).size,"int32")];case"Rank":return[On(Mb("x",t,e,n).rank,"int32")];case"NoOp":return[On(1)];case"Print":var a=Mb("x",t,e,n),i=Mb("data",t,e,n),o=Mb("message",t,e,n),s=Mb("summarize",t,e,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(var u=0;u<i.length;u++)console.log(Array.prototype.slice.call(i[u].dataSync()).slice(0,s));return[a];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"logical":return $e((function(){return function(t,e,n){switch(t.op){case"Equal":return[wl(Mb("a",t,e,n),Mb("b",t,e,n))];case"NotEqual":return[Dl(Mb("a",t,e,n),Mb("b",t,e,n))];case"Greater":return[Nl(Mb("a",t,e,n),Mb("b",t,e,n))];case"GreaterEqual":return[Sl(Mb("a",t,e,n),Mb("b",t,e,n))];case"Less":return[El(Mb("a",t,e,n),Mb("b",t,e,n))];case"LessEqual":return[Al(Mb("a",t,e,n),Mb("b",t,e,n))];case"LogicalAnd":return[qu(Mb("a",t,e,n),Mb("b",t,e,n))];case"LogicalNot":return[Hu(Mb("a",t,e,n))];case"LogicalOr":return[Ku(Mb("a",t,e,n),Mb("b",t,e,n))];case"Select":case"SelectV2":return[Yu(Mb("condition",t,e,n),Mb("a",t,e,n),Mb("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"matrices":return $e((function(){return function(t,e,n){switch(t.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Zl(Mb("a",t,e,n),Mb("b",t,e,n),Mb("transposeA",t,e,n),Mb("transposeB",t,e,n))];case"Transpose":return[ai(Mb("x",t,e,n),Mb("perm",t,e,n))];case"_FusedMatMul":var r=Mb("fusedOps",t,e,n),a=r[0],i=r[1],o="biasadd"===a,s="prelu"===i,u=Mb("numArgs",t,e,n);if(o){if(s&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!s&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}var l=Mb("args",t,e,n),c=l[0],p=l[1];return[Lp.matMul({a:Mb("a",t,e,n),b:Mb("b",t,e,n),transposeA:Mb("transposeA",t,e,n),transposeB:Mb("transposeB",t,e,n),bias:c,activation:i,preluActivationWeights:p})];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"normalization":return $e((function(){return function(t,e,n){switch(t.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[_u(Mb("x",t,e,n),Mb("mean",t,e,n),Mb("variance",t,e,n),Mb("offset",t,e,n),Mb("scale",t,e,n),Mb("epsilon",t,e,n))];case"LRN":return[Lc(Mb("x",t,e,n),Mb("radius",t,e,n),Mb("bias",t,e,n),Mb("alpha",t,e,n),Mb("beta",t,e,n))];case"Softmax":return[ni(Mb("x",t,e,n))];case"LogSoftmax":return[ri(Mb("x",t,e,n))];case"SparseToDense":return[Jc(Mb("sparseIndices",t,e,n),Mb("outputShape",t,e,n),Mb("sparseValues",t,e,n),Mb("defaultValue",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"reduction":return $e((function(){return function(t,e,n){switch(t.op){case"Max":var r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n);return[kc(Mb("x",t,e,n),r,a)];case"Mean":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[Ic(Mb("x",t,e,n),r,a)];case"Min":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[Ec(Mb("x",t,e,n),r,a)];case"Sum":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[Tc(Mb("x",t,e,n),r,a)];case"All":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[xc(Mb("x",t,e,n),r,a)];case"Any":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[wc(Mb("x",t,e,n),r,a)];case"ArgMax":return r=Mb("axis",t,e,n),[Cc(Mb("x",t,e,n),r)];case"ArgMin":return r=Mb("axis",t,e,n),[Nc(Mb("x",t,e,n),r)];case"Prod":return r=Mb("axis",t,e,n),a=Mb("keepDims",t,e,n),[Rc(Mb("x",t,e,n),r,a)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"slice_join":return $e((function(){return function(t,e,n){switch(t.op){case"ConcatV2":case"Concat":var r=Mb("n",t,e,n),a=Mb("axis",t,e,n),i=Mb("tensors",t,e,n);return i=i.slice(0,r),[Kn(i,a)];case"GatherV2":case"Gather":a=Mb("axis",t,e,n);var o=Mb("x",t,e,n),s=Mb("indices",t,e,n);return[Ml(o,s.asType("int32"),a)];case"ReverseV2":case"Reverse":return a=Mb("axis",t,e,n),o=Mb("x",t,e,n),[ec(o,a)];case"Slice":var u=Mb("begin",t,e,n),l=Mb("size",t,e,n);return[dc(Mb("x",t,e,n),u,l)];case"StridedSlice":u=Mb("begin",t,e,n);var c=Mb("end",t,e,n),p=Mb("strides",t,e,n),h=Mb("beginMask",t,e,n),f=Mb("endMask",t,e,n),d=Mb("ellipsisMask",t,e,n),m=Mb("newAxisMask",t,e,n),g=Mb("shrinkAxisMask",t,e,n),v=Mb("x",t,e,n);if(1===u.length&&v.shape.length>1)for(var y=1;y<v.shape.length;y++)u.push(0),c.push(v.shape[y]),p.push(p[0]);return[Uc(v,u,c,p,h,f,d,m,g)];case"Pack":return $e((function(){var r=Mb("axis",t,e,n),a=Mb("tensors",t,e,n),i=a[0].shape,o=a[0].squeeze().shape,s=a.map((function(t){var e=pt.arraysEqual(t.shape,i);if(!e&&!pt.arraysEqual(t.squeeze().shape,o))throw new Error("the input tensors shape does not match");return e?t:t.reshape(i)}));return[lr(s,r)]}));case"Unpack":return $e((function(){var r=Mb("axis",t,e,n),a=Mb("tensor",t,e,n);return cr(a,r)}));case"Tile":var b=Mb("reps",t,e,n);return[Zu(Mb("x",t,e,n),b)];case"Split":case"SplitV":a=Mb("axis",t,e,n);var x=Mb("numOrSizeSplits",t,e,n);return Zn(Mb("x",t,e,n),x,a);case"ScatterNd":s=Mb("indices",t,e,n);var w=Mb("values",t,e,n),C=Mb("shape",t,e,n);return[Gc(s,w,C)];case"GatherNd":var N=Mb("x",t,e,n);return s=Mb("indices",t,e,n),[$c(N,s)];case"SparseToDense":s=Mb("sparseIndices",t,e,n),C=Mb("outputShape",t,e,n);var S=Mb("sparseValues",t,e,n),k=Mb("defaultValue",t,e,n);return[Jc(s,S,C,S.dtype===k.dtype?k:k.asType(S.dtype))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"spectral":return $e((function(){return function(t,e,n){switch(t.op){case"FFT":return[qc(Mb("x",t,e,n))];case"IFFT":return[Hc(Mb("x",t,e,n))];case"RFFT":return[Kc(Mb("x",t,e,n))];case"IRFFT":return[Xc(Mb("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"transformation":return $e((function(){return function(t,e,n){switch(t.op){case"Cast":return[nr(Mb("x",t,e,n),Mb("dtype",t,e,n))];case"ExpandDims":var r=Mb("axis",t,e,n);return[ir(Mb("x",t,e,n),r)];case"Squeeze":return r=Mb("axis",t,e,n),[ur(Mb("x",t,e,n),r)];case"Reshape":return[or(Mb("x",t,e,n),Mb("shape",t,e,n))];case"PadV2":case"Pad":return[nl(Mb("x",t,e,n),Wb(Mb("padding",t,e,n),2),Mb("constantValue",t,e,n))];case"SpaceToBatchND":var a=Mb("blockShape",t,e,n),i=Wb(Mb("paddings",t,e,n),2);return[sr(Mb("x",t,e,n),a,i)];case"BatchToSpaceND":a=Mb("blockShape",t,e,n);var o=Wb(Mb("crops",t,e,n),2);return[er(Mb("x",t,e,n),a,o)];case"DepthToSpace":var s=Mb("blockSize",t,e,n),u=Mb("dataFormat",t,e,n).toUpperCase();return[ar(Mb("x",t,e,n),s,u)];default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n)}));case"custom":var r=_b(t.op);if(r&&r.customExecutor)return r.customExecutor(new vx(t,e,n));throw TypeError("Custom op "+t.op+" is not registered.");default:throw TypeError("Unknown op '"+t.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()")}}(t,e,n);return r instanceof Promise?r.then((function(t){return[].concat(t)})):[].concat(r)}var xx=function(){function t(t,e){this.weightMap=t,this.tensorArrayMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return t.prototype.newFrame=function(t,e){return{id:t,frameName:e,iterationId:0}},Object.defineProperty(t.prototype,"currentContext",{get:function(){return this.contexts},set:function(t){this.contexts!==t&&(this.contexts=t,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),t.prototype.generateCurrentContextIds=function(){for(var t=[],e=0;e<this.contexts.length-1;e++){var n=this.contexts.slice(0,this.contexts.length-e);t.push(this.contextIdforContexts(n))}t.push(""),this._currentContextIds=t},t.prototype.contextIdforContexts=function(t){return t?t.map((function(t){return 0===t.id&&0===t.iterationId?"":t.frameName+"-"+t.iterationId})).join("/"):""},t.prototype.enterFrame=function(t){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,t)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},t.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}();function wx(t,e,n){for(var r=new Set,a=[],i=null,o=null,s=new Set,u=Object.keys(t).map((function(t){return Pb(t)[0]})),l=e.slice();l.length>0;){var c=l.pop();(Sx(c)||kx(c))&&null==i&&(o=(i=c).children.map((function(t){return t.name})).filter((function(t){return r.has(t)}))),r.add(c.name),null==n[c.name]&&-1===u.indexOf(c.name)&&(0!==c.inputs.length?c.inputs.forEach((function(t){s.has(t.name)||(s.add(t.name),l.push(t))})):a.push(c.name))}return{inputs:t,outputs:e,usedNodes:r,missingInputs:a,dynamicNode:i,syncInputs:o}}var Cx=["Switch","Merge","Enter","Exit","NextIteration"],Nx=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function Sx(t){return Cx.indexOf(t.op)>=0}function kx(t){return Nx.indexOf(t.op)>=0}var Ix=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._outputs=t.outputs,this._inputs=t.inputs,this._signature=t.signature}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map((function(e){return t[e].map((function(t){return t.id}))}));this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this._inputs.map((function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map((function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this._inputs.map((function(t){return t.signatureKey||t.name}))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this._outputs.map((function(t){return t.signatureKey||t.name}))},enumerable:!0,configurable:!0}),t.prototype.getCompilationKey=function(t,e){var n=t.map((function(t){return t.name})).sort(),r=e.map((function(t){return t.name})).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},t.prototype.compile=function(t,e){var n=wx(t,e,this.weightMap),r=n.missingInputs,a=n.dynamicNode,i=n.syncInputs;if(null!=a)throw new Error("This execution contains the node '"+a.name+"', which has the dynamic op '"+a.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+i+"]");if(r.length>0){var o=e.map((function(t){return t.name})),s=Object.keys(t);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+s+"]. Missing the following inputs: ["+r+"]")}return function(t,e,n){var r=n.usedNodes,a=n.inputs,i=[];Object.keys(a).map((function(t){return Pb(t)[0]})).map((function(e){return t.nodes[e]})).forEach((function(t){r.has(t.name)&&i.push(t)})),t.weights.forEach((function(t){r.has(t.name)&&i.push(t)}));for(var o=new Set,s=[];i.length>0;){var u=i.pop();o.add(u.name),e[u.name]||s.push(u),u.children.forEach((function(t){!o.has(t.name)&&r.has(t.name)&&t.inputs.every((function(t){return o.has(t.name)}))&&i.push(t)}))}return s}(this.graph,this.weightMap,n)},t.prototype.execute=function(t,e){var n=this;t=this.mapInputs(t);var r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e);var a=r.map((function(t){return n.graph.nodes[Pb(t)[0]]})),i=e.map((function(t){return n.graph.nodes[Pb(t)[0]]})),o=this.getCompilationKey(a,i),s=this.compiledMap.get(o);null==s&&(s=this.compile(t,i),this.compiledMap.set(o,s));var u={};return $e((function(){var r=new xx(n._weightMap,u),a=Ab({},n.weightMap);Object.keys(t).forEach((function(e){var n=Pb(e),r=n[0],i=[];i[n[1]]=t[e],a[r]=i}));for(var i=n.getFrozenTensorIds(a),o={},l=0;l<s.length;l++){var c=s[l];if(!a[c.name]){var p=bx(c,a,r);if(p instanceof Promise)throw new Error("The execution of the op '"+c.op+"' returned a promise. Please use model.executeAsync() instead.");a[c.name]=p,n.checkTensorForDisposal(c.name,c,a,r,i,e,o)}}return e.map((function(t){return zb(t,a,r)}))}))},t.prototype.getFrozenTensorIds=function(t){var e=[].concat.apply([],Object.keys(t).map((function(e){return t[e]})).map((function(t){return t.map((function(t){return t.id}))})));return new Set(e)},t.prototype.checkTensorForDisposal=function(t,e,n,r,a,i,o){"control"!==e.category&&-1===i.indexOf(t)&&(n[t].forEach((function(t){null!=t&&(o[t.id]=(o[t.id]||0)+e.children.length)})),e.inputs.forEach((function(t){if("control"!==t.category){var e=function(t,e,n){return e[Bb(t,n.currentContextId)]}(t.name,n,r);null!=e&&e.forEach((function(t){if(t&&!a.has(t.id)){var e=o[t.id];1===e?(t.dispose(),delete o[t.id]):null!=e&&o[t.id]--}}))}})))},t.prototype.executeAsync=function(t,e){return Tb(this,void 0,void 0,(function(){var n,r,a,i,o,s,u=this;return Rb(this,(function(l){switch(l.label){case 0:return t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e),n={},r=new xx(this._weightMap,n),[4,this.executeWithControlFlow(t,r,e)];case 1:return a=l.sent(),i=e.map((function(t){return zb(t,a,r)})),o=new Set(i.map((function(t){return t.id}))),s=new Set(Object.keys(t).map((function(e){return t[e].id}))),Object.keys(a).forEach((function(t){a[t].forEach((function(t){!t||t.isDisposed||o.has(t.id)||s.has(t.id)||-1!==u.weightIds.indexOf(t.id)||t.dispose()}))})),[2,i]}}))}))},t.prototype.executeWithControlFlow=function(t,e,n){return Tb(this,void 0,void 0,(function(){var r,a,i,o,s,u,l,c,p,h,f,d,m,g,v,y,b=this;return Rb(this,(function(x){switch(x.label){case 0:r=Object.keys(t),a=r.map((function(t){return b.graph.nodes[Pb(t)[0]]})),i=n.map((function(t){return b.graph.nodes[Pb(t)[0]]})),o=wx(t,i,this.weightMap),s=o.usedNodes,u=o.missingInputs,l=o.dynamicNode,c=o.syncInputs,p=a.concat(this.graph.weights).map((function(t){return{node:t,contexts:e.currentContext}})),h=Ab({},this.weightMap),Object.keys(t).forEach((function(e){var n=Pb(e),r=n[0],a=[];a[n[1]]=t[e],h[r]=a})),f={},d=this.getFrozenTensorIds(h),m={},x.label=1;case 1:return p.length>0?(g=this.processStack(a,p,e,h,m,d,n,f,s),[4,Promise.all(g)]):[3,3];case 2:return x.sent(),[3,1];case 3:if(null==l&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(v=i.filter((function(t){return!Sx(t)&&!zb(t.name,h,e)})).map((function(t){return t.name}))).length>0)throw y="",null!=l&&(y="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+c+"]"),new Error("Cannot compute the outputs ["+v+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+u+"]. "+y);return[2,h]}}))}))},t.prototype.processStack=function(t,e,n,r,a,i,o,s,u){for(var l=this,c=[],p=function(){var p=e.pop();n.currentContext=p.contexts;var f="";if("Enter"===p.node.op&&Mb("isConstant",p.node,r,n)&&(f=Lb(p.node.name,n)[0]),-1===t.indexOf(p.node)){var d=bx(p.node,r,n);f||(f=Lb(p.node.name,n)[0]);var m=n.currentContext;d instanceof Promise?c.push(d.then((function(t){return r[f]=t,n.currentContext=m,l.checkTensorForDisposal(f,p.node,r,n,i,o,s),l.processChildNodes(p.node,e,n,r,a,u),t}))):(r[f]=d,h.checkTensorForDisposal(f,p.node,r,n,i,o,s),h.processChildNodes(p.node,e,n,r,a,u))}else h.processChildNodes(p.node,e,n,r,a,u)},h=this;e.length>0;)p();return c},t.prototype.processChildNodes=function(t,e,n,r,a,i){t.children.forEach((function(t){var o=Lb(t.name,n)[0];!a[o]&&i.has(t.name)&&("Merge"===t.op?t.inputNames.some((function(t){return!!zb(t,r,n)}))&&(a[o]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every((function(t){return!!zb(t,r,n)}))&&(a[o]=!0,e.push({contexts:n.currentContext,node:t})))}))},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach((function(e){return t.weightMap[e].forEach((function(t){return t.dispose()}))}))},t.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach((function(n){var r=t[n],a=Pb(n)[0],i=e.graph.nodes[a];if(i.attrParams.shape&&i.attrParams.shape.value){var o=i.attrParams.shape.value,s=o.length===r.shape.length&&r.shape.every((function(t,e){return-1===o[e]||o[e]===t}));pt.assert(s,(function(){return"The shape of dict['"+i.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+r.shape+"]"}))}i.attrParams.dtype&&i.attrParams.dtype.value&&pt.assert(r.dtype===i.attrParams.dtype.value,(function(){return"The dtype of dict['"+i.name+"'] provided in model.execute(dict) must be "+i.attrParams.dtype.value+", but was "+r.dtype}))}))},t.prototype.mapInputs=function(t){var e={};for(var n in t)null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[n]?e[this._signature.inputs[n].name]=t[n]:e[n]=t[n];return e},t.prototype.checkInputs=function(t){var e=this,n=Object.keys(t).filter((function(t){var n=Pb(t)[0];return null==e.graph.nodes[n]}));if(n.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+n+"] that are not part of graph")},t.prototype.mapOutputs=function(t){var e=this;return t.map((function(t){return null!=e._signature&&null!=e._signature.outputs&&null!=e._signature.outputs[t]?e._signature.outputs[t].name:t}),{})},t.prototype.checkOutputs=function(t){var e=this;t.forEach((function(t){var n=Pb(t)[0];if(!e.graph.nodes[n])throw new Error("The output '"+t+"' is not found in the graph")}))},t}(),Ex=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=af.browserHTTPRequest(t,this.loadOptions);else{var e=af.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(af.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return Tb(this,void 0,void 0,(function(){var t,e,n,r;return Rb(this,(function(a){switch(a.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return t=this,[4,this.handler.load()];case 1:return t.artifacts=a.sent(),e=this.artifacts.modelTopology,n={},null!=this.artifacts.userDefinedMetadata&&(n=this.artifacts.userDefinedMetadata.signature),this.version=e.versions.producer+"."+e.versions.minConsumer,r=af.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs),this.executor=new Ix(rx.Instance.transformGraph(e,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),[2,!0]}}))}))},t.prototype.save=function(t,e){return Tb(this,void 0,void 0,(function(){var e;return Rb(this,(function(n){if("string"==typeof t){if(0===(e=af.getSaveHandlers(t)).length)throw new Error("Cannot find any save handlers for URL '"+t+"'");if(e.length>1)throw new Error("Found more than one ("+e.length+") save handlers for URL '"+t+"'");t=e[0]}if(null==t.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[2,t.save(this.artifacts)]}))}))},t.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},t.prototype.normalizeInputs=function(t){if(!(t instanceof wt||Array.isArray(t)))return t;if((t=Array.isArray(t)?t:[t]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce((function(e,n,r){return e[n]=t[r],e}),{})},t.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},t.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var n=this.executor.execute(t,e);return n.length>1?n:n[0]},t.prototype.executeAsync=function(t,e){return Tb(this,void 0,void 0,(function(){var n;return Rb(this,(function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return[2,(n=r.sent()).length>1?n:n[0]]}}))}))},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce((function(e,n){return e[n]=[t[n]],e}),{})},t.prototype.dispose=function(){this.executor.dispose()},t}();function Ax(t,e){return void 0===e&&(e={}),Tb(this,void 0,void 0,(function(){var n;return Rb(this,(function(r){switch(r.label){case 0:if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==e&&(e={}),e.fromTFHub&&null==t.load&&(t.endsWith("/")||(t+="/"),t+="model.json?tfjs-format=file"),[4,(n=new Ex(t,e)).load()];case 1:return r.sent(),[2,n]}}))}))}var Tx="1.7.4",Rx=function(t,e){return(Rx=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function Dx(t,e){function n(){this.constructor=t}Rx(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function Ox(t,e,n,r){return new(n||(n=Promise))((function(a,i){function o(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(o,s)}u((r=r.apply(t,e||[])).next())}))}function _x(t,e){var n,r,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=e.call(t,o)}catch(t){i=[6,t],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function Fx(t,e){return t(e={exports:{}},e.exports),e.exports}"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self&&self;var Mx=Fx((function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.alea=a}(0,t)})),zx=Fx((function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function a(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.xor128=a}(0,t)})),Lx=Fx((function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function a(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.xorwow=a}(0,t)})),Bx=Fx((function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,a=e.i;return t=r[a],n=(t^=t>>>7)^t<<24,n^=(t=r[a+1&7])^t>>>10,n^=(t=r[a+3&7])^t>>>3,n^=(t=r[a+4&7])^t<<7,t=r[a+7&7],n^=(t^=t<<13)^t<<9,r[a]=n,e.i=a+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.xorshift7=a}(0,t)})),Px=Fx((function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,a=e.X,i=e.i;return e.w=r=r+1640531527|0,n=a[i+34&127],t=a[i=i+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=a[i]=n^t,e.i=i,n+(r^r>>>16)|0},function(t,e){var n,r,a,i,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),a=0,i=-32;i<u;++i)e&&(r^=e.charCodeAt((i+32)%e.length)),0===i&&(o=r),r^=r<<10,r^=r>>>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&(e&&e.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;t.w=o,t.X=s,t.i=a}(e,t)}(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.xor4096=a}(0,t)})),Wx=Fx((function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function a(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,a=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^a,e.a=a-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}e&&e.exports?e.exports=a:this.tychei=a}(0,t)})),Vx=Fx((function(t){!function(e,r){var a,i=this,o=256,s="random",u=r.pow(o,6),l=r.pow(2,52),c=2*l,p=255;function h(t,n,h){var g=[],v=d(function t(e,n){var r,a=[],i=typeof e;if(n&&"object"==i)for(r in e)try{a.push(t(e[r],n-1))}catch(t){}return a.length?a:"string"==i?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return a&&(t=a.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,m(e)]}}():t,3),g),y=new function(t){var e,n=t.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);a<o;)s[a]=a++;for(a=0;a<o;a++)s[a]=s[i=p&i+t[a%n]+(e=s[a])],s[i]=e;(r.g=function(t){for(var e,n=0,a=r.i,i=r.j,s=r.S;t--;)e=s[a=p&a+1],n=n*o+s[p&(s[a]=s[i=p&i+e])+(s[i]=e)];return r.i=a,r.j=i,n})(o)}(g),b=function(){for(var t=y.g(6),e=u,n=0;t<l;)t=(t+n)*o,e*=o,n=y.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,d(m(y.S),e),(n.pass||h||function(t,e,n,a){return a&&(a.S&&f(a,y),t.state=function(){return f(y,{})}),n?(r[s]=t,e):t})(b,v,"global"in n?n.global:this==r,n.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",a=0;a<r.length;)e[p&a]=p&(n^=19*e[p&a])+r.charCodeAt(a++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(r["seed"+s]=h,d(r.random(),e),t.exports){t.exports=h;try{a=n(906)}catch(t){}}}([],Math)}));Vx.alea=Mx,Vx.xor128=zx,Vx.xorwow=Lx,Vx.xorshift7=Bx,Vx.xor4096=Px,Vx.tychei=Wx;var Ux=Vx.alea;function jx(t,e,n,r){if(void 0===n&&(n=new Map),void 0===r&&(r=new Set),null==t)return null;if(r.has(t))throw new Error("Circular references are not supported.");if(n.has(t))return n.get(t);var a=e(t);if(a.recurse&&null!==a.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse){if(Xx(t)){var i=Array.isArray(t)?[]:{};for(var o in r.add(t),t){var s=jx(t[o],e,n,r);i[o]=s}return r.delete(t),i}throw new Error("Can't recurse into non-iterable type: "+t)}return n.set(t,a.value),a.value}function Gx(t,e){return void 0===e&&(e=Hx),qx(t,e)}function qx(t,e,n){void 0===n&&(n=new Set);var r=t[0];if(n.has(r))throw new Error("Circular references are not supported.");var a=e(t);if(a.recurse&&null!==a.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse){if(Xx(r)){var i=Array.isArray(r)?[]:{};n.add(r);var o=function(r){var a=qx(t.map((function(t){return t[r]})),e,n);i[r]=a};for(var s in r)o(s);return n.delete(r),i}throw new Error("Can't recurse into non-iterable type: "+r)}return a.value}function Hx(t){return null===t?null:Xx(t[0])?{value:null,recurse:!0}:{value:t,recurse:!1}}function Kx(t,e){return Ox(this,void 0,void 0,(function(){var n,r,a,i,o,s;return _x(this,(function(u){switch(u.label){case 0:n=new Map,jx(t,e,n),r=0,a=Array.from(n.keys()),u.label=1;case 1:return r<a.length?(i=a[r],(o=n.get(i))instanceof Promise?[4,o]:[3,3]):[3,4];case 2:s=u.sent(),n.set(i,s),u.label=3;case 3:return r++,[3,1];case 4:return[2,jx(t,e,n)]}}))}))}function Xx(t){return null!=t&&!ArrayBuffer.isView(t)&&(Array.isArray(t)||"object"==typeof t&&!(t instanceof wt))}function Yx(t){return function(t,e){return jx(t,e)}(t,Jx)}function Jx(t){return t instanceof wt?{value:t.clone(),recurse:!1}:Xx(t)?{value:null,recurse:!0}:{value:t,recurse:!1}}var $x=function(){function t(t){if(this.capacity=t,this.begin=0,this.end=0,null==t)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(t<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(t),this.doubledCapacity=2*t}return t.prototype.wrap=function(t){for(;t<0;)t+=this.doubledCapacity;return t%this.doubledCapacity},t.prototype.get=function(t){if(t<0)throw new RangeError("Can't get item at a negative index.");return this.data[t%this.capacity]},t.prototype.set=function(t,e){if(t<0)throw new RangeError("Can't set item at a negative index.");this.data[t%this.capacity]=e},t.prototype.length=function(){var t=this.end-this.begin;return t<0&&(t=this.doubledCapacity+t),t},t.prototype.isFull=function(){return this.length()===this.capacity},t.prototype.isEmpty=function(){return 0===this.length()},t.prototype.push=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,t),this.end=this.wrap(this.end+1)},t.prototype.pushAll=function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e];this.push(r)}},t.prototype.pop=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);var t=this.get(this.end);return this.set(this.end,void 0),t},t.prototype.unshift=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,t)},t.prototype.shift=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var t=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),t},t.prototype.shuffleExcise=function(t){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var e=this.wrap(this.begin+t),n=this.get(e);return this.set(e,this.pop()),n},t}(),Zx=function(t){function e(){return t.call(this,e.INITIAL_CAPACITY)||this}return Dx(e,t),e.prototype.isFull=function(){return!1},e.prototype.push=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.push.call(this,e)},e.prototype.unshift=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.unshift.call(this,e)},e.prototype.expand=function(){for(var t=2*this.capacity,e=new Array(t),n=this.length(),r=0;r<n;r++)e[r]=this.get(this.wrap(this.begin+r));this.data=e,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n},e.INITIAL_CAPACITY=32,e}($x);function Qx(t){return new iw(t)}function tw(t){return new ow(t)}function ew(t,e){return new vw(t,e)}function nw(t,e){return void 0===e&&(e=rw.FAIL),new yw(t,e)}var rw,aw=function(){function t(){}return t.prototype.toArray=function(){return Ox(this,void 0,void 0,(function(){var t,e;return _x(this,(function(n){switch(n.label){case 0:return t=[],[4,this.next()];case 1:e=n.sent(),n.label=2;case 2:return e.done?[3,4]:(t.push(e.value),[4,this.next()]);case 3:return e=n.sent(),[3,2];case 4:return[2,t]}}))}))},t.prototype.toArrayForTest=function(){return Ox(this,void 0,void 0,(function(){var t,e,n;return _x(this,(function(r){switch(r.label){case 0:return t=this.prefetch(100),e=[],[4,t.next()];case 1:n=r.sent(),r.label=2;case 2:return n.done?[3,4]:(e.push(n.value),[4,t.next()]);case 3:return n=r.sent(),[3,2];case 4:return[2,e]}}))}))},t.prototype.resolveFully=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){switch(e.label){case 0:return[4,this.next()];case 1:t=e.sent(),e.label=2;case 2:return t.done?[3,4]:[4,this.next()];case 3:return t=e.sent(),[3,2];case 4:return[2]}}))}))},t.prototype.resolveWhile=function(t){return Ox(this,void 0,void 0,(function(){var e,n;return _x(this,(function(r){switch(r.label){case 0:return[4,this.next()];case 1:e=r.sent(),n=t(e.value),r.label=2;case 2:return e.done||!n?[3,4]:[4,this.next()];case 3:return e=r.sent(),n=t(e.value),[3,2];case 4:return[2]}}))}))},t.prototype.handleErrors=function(t){return new fw(this,t)},t.prototype.filter=function(t){return new pw(this,t)},t.prototype.map=function(t){return new hw(this,t)},t.prototype.mapAsync=function(t){return new dw(this,t)},t.prototype.serialMapAsync=function(t){return new dw(this,t).serial()},t.prototype.flatmap=function(t){return new gw(this,t)},t.prototype.forEachAsync=function(t){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){return[2,this.map(t).resolveFully()]}))}))},t.prototype.serialForEach=function(t){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){return[2,this.serialMapAsync(t).resolveWhile((function(t){return!0===t}))]}))}))},t.prototype.rowMajorBatch=function(t,e){return void 0===e&&(e=!0),new cw(this,t,e)},t.prototype.columnMajorBatch=function(t,e,n){return void 0===e&&(e=!0),void 0===n&&(n=Hx),this.rowMajorBatch(t,e).map((function(t){return Gx(t,n)}))},t.prototype.concatenate=function(t,e){return new vw(Qx([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new lw(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new uw(this,t)},t.prototype.prefetch=function(t){return new bw(this,t)},t.prototype.shuffle=function(t,e){return new xw(this,t,e)},t.prototype.serial=function(){return new sw(this)},t}(),iw=function(t){function e(e){var n=t.call(this)||this;return n.items=e,n.trav=0,n}return Dx(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],this.trav++,[2,{value:Yx(t),done:!1}])}))}))},e}(aw),ow=function(t){function e(e){var n=t.call(this)||this;return n.nextFn=e,n}return Dx(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){try{return[2,this.nextFn()]}catch(t){throw t.message="Error thrown while iterating through a dataset: "+t.message,t}return[2]}))}))},e}(aw),sw=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.lastRead=Promise.resolve({value:null,done:!1}),n}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return[2,this.upstream.next()]}))}))},e}(aw),uw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){switch(e.label){case 0:return this.count++<this.maxCount?[4,this.upstream.next()]:[3,2];case 1:return(t=e.sent()).done?[2,t]:(Ze(t.value),[3,0]);case 2:return[2,this.upstream.next()]}}))}))},e}(aw),lw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Take"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]}))}))},e}(aw),cw=function(t){function e(e,n,r){void 0===r&&(r=!0);var a=t.call(this)||this;return a.upstream=e,a.batchSize=n,a.enableSmallLastBatch=r,a.lastRead=Promise.resolve({value:null,done:!1}),a}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){var t,e;return _x(this,(function(n){switch(n.label){case 0:t=[],n.label=1;case 1:return t.length<this.batchSize?[4,this.upstream.next()]:[3,3];case 2:return(e=n.sent()).done?this.enableSmallLastBatch&&t.length>0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return[2,{value:t,done:!1}]}}))}))},e}(aw),pw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.predicate=n,r.lastRead=Promise.resolve({value:null,done:!1}),r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(t=e.sent()).done||this.predicate(t.value)?[2,t]:(Ze(t.value),[3,0]);case 2:return[2]}}))}))},e}(aw),hw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a,i,o;return _x(this,(function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,{value:null,done:!0}];for(e=Mt.getTensorsInContainer(t.value),n=this.transform(t.value),r=Mt.getTensorsInContainer(n),a=0,i=e;a<i.length;a++)o=i[a],Mt.isTensorInList(o,r)||o.dispose();return[2,{value:n,done:!1}]}}))}))},e}(aw),fw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.handler=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){switch(e.label){case 0:e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,e.sent()];case 3:return t=e.sent(),this.handler(t)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}}))}))},e}(aw),dw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a,i,o;return _x(this,(function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:return(t=s.sent()).done?[2,{value:null,done:!0}]:(e=Mt.getTensorsInContainer(t.value),[4,this.transform(t.value)]);case 2:for(n=s.sent(),r=Mt.getTensorsInContainer(n),a=0,i=e;a<i.length;a++)o=i[a],Mt.isTensorInList(o,r)||o.dispose();return[2,{value:n,done:!1}]}}))}))},e}(aw),mw=function(t){function e(){var e=t.call(this)||this;return e.outputQueue=new Zx,e.lastRead=Promise.resolve({value:null,done:!1}),e}return Dx(e,t),e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:return 0!==this.outputQueue.length()?[3,2]:[4,this.pump()];case 1:return t.sent()?[3,0]:[2,{value:null,done:!0}];case 2:return[2,{value:this.outputQueue.shift(),done:!1}]}}))}))},e}(aw),gw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},e.prototype.pump=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a,i,o;return _x(this,(function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,!1];for(e=Mt.getTensorsInContainer(t.value),n=this.transform(t.value),r=Mt.getTensorsInContainer(n),this.outputQueue.pushAll(n),a=0,i=e;a<i.length;a++)o=i[a],Mt.isTensorInList(o,r)||o.dispose();return[2,!0]}}))}))},e}(mw),vw=function(t){function e(e,n){var r=t.call(this)||this;return r.baseErrorHandler=n,r.lastRead=null,r.iterator=null,r.moreIterators=e,r}return Dx(e,t),e.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]}))}))},e.prototype.readFromChain=function(t){return Ox(this,void 0,void 0,(function(){var e,n;return _x(this,(function(r){switch(r.label){case 0:return[4,t];case 1:return r.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=r.sent()).done)return[2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),r.label=3;case 3:return[4,this.iterator.next()];case 4:return(n=r.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,n]}}))}))},e}(aw);!function(t){t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST"}(rw||(rw={}));var yw=function(t){function e(e,n){void 0===n&&(n=rw.FAIL);var r=t.call(this)||this;return r.iterators=e,r.mismatchMode=n,r.count=0,r.currentPromise=null,r}return Dx(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return Ox(this,void 0,void 0,(function(){function e(t){return t instanceof aw?{value:t.next().then((function(t){return n++,t.done&&r++,t.value})),recurse:!1}:{value:null,recurse:!0}}var n,r,a;return _x(this,(function(i){switch(i.label){case 0:return[4,t];case 1:return i.sent(),n=0,r=0,[4,Kx(this.iterators,e)];case 2:if(a=i.sent(),n===r)return[2,{value:null,done:!0}];if(r>0)switch(this.mismatchMode){case rw.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case rw.SHORTEST:return[2,{value:null,done:!0}];case rw.LONGEST:}return this.count++,[2,{value:a,done:!1}]}}))}))},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]}))}))},e}(aw),bw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.bufferSize=n,r.buffer=new $x(n),r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},e.prototype.refill=function(){for(;!this.buffer.isFull();){var t=this.upstream.next();this.buffer.push(t)}},e.prototype.next=function(){return this.refill(),this.buffer.shift()},e}(aw),xw=function(t){function e(e,n,r){var a=t.call(this,e,n)||this;return a.upstream=e,a.windowSize=n,a.upstreamExhausted=!1,a.random=Ux(r||pt.now().toString()),a.lastRead=Promise.resolve({value:null,done:!1}),a}return Dx(e,t),e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t=this;return _x(this,(function(e){return this.lastRead=this.lastRead.then((function(){return t.serialNext()})),[2,this.lastRead]}))}))},e.prototype.randomInt=function(t){return Math.floor(this.random()*t)},e.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},e.prototype.serialNext=function(){return Ox(this,void 0,void 0,(function(){var t,e;return _x(this,(function(n){switch(n.label){case 0:this.upstreamExhausted||this.refill(),n.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return(e=n.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return[2,{value:null,done:!0}]}}))}))},e}(bw),ww=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var n=this;void 0===e&&(e=!0);var r=this;return pt.assert(t>0,(function(){return"batchSize needs to be positive, but it is\n "+t})),Cw((function(){return Ox(n,void 0,void 0,(function(){return _x(this,(function(n){switch(n.label){case 0:return[4,r.iterator()];case 1:return[2,n.sent().columnMajorBatch(t,e,kw)]}}))}))}),this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){var e,r;return _x(this,(function(a){switch(a.label){case 0:return[4,n.iterator()];case 1:return r=(e=a.sent()).concatenate,[4,t.iterator()];case 2:return[2,r.apply(e,[a.sent()])]}}))}))}),this.size===1/0||t.size===1/0?1/0:null!=this.size&&null!=t.size?this.size+t.size:null)},t.prototype.filter=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().filter((function(e){return $e((function(){return t(e)}))}))]}}))}))}),this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}}))}))},t.prototype.forEach=function(t){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){return He("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]}))}))},t.prototype.map=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().map((function(e){return $e((function(){return t(e)}))}))]}}))}))}),this.size)},t.prototype.mapAsync=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().mapAsync(t)]}}))}))}),this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().prefetch(t)]}}))}))}),this.size)},t.prototype.repeat=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){var e=this;return _x(this,(function(r){return[2,ew(tw((function(){return Ox(e,void 0,void 0,(function(){var t;return _x(this,(function(e){switch(e.label){case 0:return t={},[4,n.iterator()];case 1:return[2,(t.value=e.sent(),t.done=!1,t)]}}))}))})).take(t))]}))}))}),null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().skip(t)]}}))}))}),null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.size<t||void 0===t||t<0)?0:null)},t.prototype.shuffle=function(t,e,n){var r=this;if(void 0===n&&(n=!0),null==t||t<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError("`Dataset.shuffle()` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size ("+this.size+" elements)");var a=this,i=Ux(e||pt.now().toString());return Cw((function(){return Ox(r,void 0,void 0,(function(){var e;return _x(this,(function(r){switch(r.label){case 0:return e=i.int32(),n&&(e+=i.int32()),[4,a.iterator()];case 1:return[2,r.sent().shuffle(t,e.toString())]}}))}))}),this.size)},t.prototype.take=function(t){var e=this,n=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().take(t)]}}))}))}),null!=this.size&&this.size>t?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArray()]}}))}))},t.prototype.toArrayForTest=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArrayForTest()]}}))}))},t.MAX_BUFFER_SIZE=1e4,t}();function Cw(t,e){return void 0===e&&(e=null),new(function(n){function r(){var t=null!==n&&n.apply(this,arguments)||this;return t.size=e,t}return Dx(r,n),r.prototype.iterator=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){return[2,t()]}))}))},r}(ww))}function Nw(t){var e=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(e){return[2,Qx(t)]}))}))}),t.length)}function Sw(t){var e,n=this;if(!Xx(t))throw new Error("The argument to zip() must be an object or array.");if(Array.isArray(t))for(var r=0;r<t.length;r++)e=null==e?t[r].size:Math.min(e,t[r].size);else if(t instanceof Object)for(var a in t)e=null==e?t[a].size:Math.min(e,t[a].size);return Cw((function(){return Ox(n,void 0,void 0,(function(){return _x(this,(function(e){switch(e.label){case 0:return[4,Kx(t,(function(t){if(t instanceof ww)return{value:t.iterator(),recurse:!1};if(Xx(t))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")}))];case 1:return[2,nw(e.sent(),rw.SHORTEST)]}}))}))}),e)}function kw(t){return null===t?null:function(t){return null==t||function(t){return null===t||"object"!=typeof t&&"function"!=typeof t}(t)||Array.isArray(t)||"object"==typeof t&&t instanceof wt||pt.isTypedArray(t)}(t[0])?{value:Iw(t),recurse:!1}:{value:null,recurse:!0}}function Iw(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof wt?lr(t):Rn(t)}var Ew=function(t){function e(e){var n=t.call(this)||this;return n.input=e,n}return Dx(e,t),e.prototype.iterator=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:return[4,this.input.iterator()];case 1:return[2,t.sent().decodeUTF8().split("\n").map((function(t){return t.endsWith("\r")&&(t=t.slice(0,-1)),t}))]}}))}))},e}(ww),Aw='"',Tw=Symbol("out"),Rw=Symbol("field"),Dw=Symbol("quote"),Ow=Symbol("quoteafterquote"),_w=Symbol("quoteinquote"),Fw=function(t){function e(e,n){var r=t.call(this)||this;return r.input=e,r.hasHeader=!0,r.fullColumnNames=null,r.columnNamesValidated=!1,r.columnConfigs=null,r.configuredColumnsOnly=!1,r.delimiter=",",r.delimWhitespace=!1,r.base=new Ew(e),n||(n={}),r.hasHeader=!1!==n.hasHeader,r.fullColumnNames=n.columnNames,r.columnConfigs=n.columnConfigs,r.configuredColumnsOnly=n.configuredColumnsOnly,n.delimWhitespace?(pt.assert(null==n.delimiter,(function(){return"Delimiter should not be provided when delimWhitespace is true."})),r.delimWhitespace=!0,r.delimiter=" "):r.delimiter=n.delimiter?n.delimiter:",",r}return Dx(e,t),e.prototype.columnNames=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:t.sent(),t.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}}))}))},e.prototype.setColumnNames=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a,i,o=this;return _x(this,(function(s){switch(s.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(t=s.sent(),!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&t&&pt.assert(t.length===this.fullColumnNames.length,(function(){return"The length of provided columnNames ("+o.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."})),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce((function(t,e){return t[e]=t[e]+1||1,t}),{}),n=Object.keys(e).filter((function(t){return e[t]>1})),pt.assert(0===n.length,(function(){return"Duplicate column names found: "+n.toString()})),this.columnConfigs)for(r=0,a=Object.keys(this.columnConfigs);r<a.length;r++)if(i=a[r],-1===this.fullColumnNames.indexOf(i))throw new Error('The key "'+i+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2]}}))}))},e.prototype.maybeReadHeaderLine=function(){return Ox(this,void 0,void 0,(function(){var t,e;return _x(this,(function(n){switch(n.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return[4,n.sent().next()];case 2:if((t=n.sent()).done)throw new Error("No data was found for CSV parsing.");return e=t.value,[2,this.parseRow(e,!1)];case 3:return[2,null]}}))}))},e.prototype.iterator=function(){return Ox(this,void 0,void 0,(function(){var t,e=this;return _x(this,(function(n){switch(n.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:n.sent(),n.label=2;case 2:return[4,this.base.iterator()];case 3:return t=n.sent(),this.hasHeader&&(t=t.skip(1)),[2,t.map((function(t){return e.makeDataElement(t)}))]}}))}))},e.prototype.makeDataElement=function(t){for(var e=this.parseRow(t),n={},r={},a=0;a<this.fullColumnNames.length;a++){var i=this.fullColumnNames[a],o=this.columnConfigs?this.columnConfigs[i]:null;if(!this.configuredColumnsOnly||o){var s=e[a],u=null;if(""===s)if(o&&void 0!==o.default)u=o.default;else{if(o&&(o.required||o.isLabel))throw new Error("Required column "+i+" is empty in this line: "+t);u=void 0}else{var l=Number(s);if(isNaN(l))u=o&&"bool"===o.dtype?this.getBoolean(s):s;else if(o&&o.dtype)switch(o.dtype){case"float32":u=l;break;case"int32":u=Math.floor(l);break;case"bool":u=this.getBoolean(s);break;default:u=l}else u=l}o&&o.isLabel?r[i]=u:n[i]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}},e.prototype.getBoolean=function(t){return"1"===t||"true"===t.toLowerCase()?1:0},e.prototype.parseRow=function(t,e){void 0===e&&(e=!0);for(var n=[],r=0,a=t.length,i=Tw,o=0;o<a;o++)switch(i){case Tw:switch(t.charAt(o)){case Aw:r=o+1,i=Dw;break;case this.delimiter:if(r=o+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),i=Tw;break;default:i=Rw,r=o}break;case Rw:switch(t.charAt(o)){case this.delimiter:n.push(t.substring(r,o)),i=Tw,r=o+1}break;case Dw:switch(t.charAt(o)){case Aw:i=Ow}break;case Ow:switch(t.charAt(o)){case this.delimiter:n.push(t.substring(r,o-1)),i=Tw,r=o+1;break;case Aw:i=Dw;break;default:i=_w}break;case _w:switch(t.charAt(o)){case Aw:i=Dw}}if(i===Ow?n.push(t.substring(r,a-1)):n.push(t.substring(r)),e&&n.length!==this.fullColumnNames.length)throw new Error("Invalid row in csv file. Should have "+this.fullColumnNames.length+" elements in a row, but got "+n);return n},e}(ww),Mw=function(t){function e(e){var n=t.call(this)||this;n.microphoneConfig=e,n.isClosed=!1,n.fftSize=e.fftSize||1024;var r=Math.log2(n.fftSize);if(n.fftSize<0||r<4||r>14||!Number.isInteger(r))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+n.fftSize);if(n.numFrames=e.numFramesPerSpectrogram||43,n.sampleRateHz=e.sampleRateHz,n.columnTruncateLength=e.columnTruncateLength||n.fftSize,n.audioTrackConstraints=e.audioTrackConstraints,n.smoothingTimeConstant=e.smoothingTimeConstant||0,n.includeSpectrogram=!1!==e.includeSpectrogram,n.includeWaveform=!0===e.includeWaveform,!n.includeSpectrogram&&!n.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return n}return Dx(e,t),e.prototype.summary=function(){return"microphone"},e.create=function(t){return void 0===t&&(t={}),Ox(this,void 0,void 0,(function(){var n;return _x(this,(function(r){switch(r.label){case 0:if(c().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return[4,(n=new e(t)).start()];case 1:return r.sent(),[2,n]}}))}))},e.prototype.start=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r;return _x(this,(function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),t=this,[4,navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})];case 1:return t.stream=a.sent(),[3,3];case 2:throw e=a.sent(),new Error("Error thrown while initializing video stream: "+e.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(n=window.AudioContext||window.webkitAudioContext,this.audioContext=new n,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate)}else this.sampleRateHz=this.audioContext.sampleRate;return r=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,r.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}}))}))},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a;return _x(this,(function(i){switch(i.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return n=i.sent(),this.includeSpectrogram&&(r=this.flattenQueue(n.freqDataQueue),t=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(a=this.flattenQueue(n.timeDataQueue),e=this.getTensorFromAudioDataArray(a,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:t,waveform:e},done:!1}]}}))}))},e.prototype.capture=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}}))}))},e.prototype.getAudioData=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r=this;return _x(this,(function(a){return t=[],e=[],n=0,[2,new Promise((function(a){var i=setInterval((function(){r.includeSpectrogram&&(r.analyser.getFloatFrequencyData(r.freqData),r.freqData[0]===-1/0&&a({freqDataQueue:t,timeDataQueue:e}),t.push(r.freqData.slice(0,r.columnTruncateLength))),r.includeWaveform&&(r.analyser.getFloatTimeDomainData(r.timeData),e.push(r.timeData.slice())),++n===r.numFrames&&(clearInterval(i),a({freqDataQueue:t,timeDataQueue:e}))}),r.fftSize/r.sampleRateHz*1e3)}))]}))}))},e.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},e.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},e.prototype.getSampleRate=function(){return this.sampleRateHz},e.prototype.flattenQueue=function(t){var e=t[0].length,n=new Float32Array(t.length*e);return t.forEach((function(t,r){return n.set(t,r*e)})),n},e.prototype.getTensorFromAudioDataArray=function(t,e){var n=new Float32Array(pt.sizeFromShape(e));return n.set(t,n.length-t.length),Rn(n,e)},e}(aw),zw=function(t){function e(e,n){var r=t.call(this)||this;if(r.webcamVideoElement=e,r.webcamConfig=n,r.isClosed=!0,r.resize=!1,r.needToResize())if(r.resize=!0,r.cropSize=[r.webcamConfig.resizeHeight,r.webcamConfig.resizeWidth],r.cropBoxInd=_n([0],"int32"),r.webcamConfig.centerCrop){var a=1*r.webcamConfig.resizeWidth/r.webcamVideoElement.width,i=1*r.webcamConfig.resizeHeight/r.webcamVideoElement.height,o=(1-a)/2,s=(1-i)/2,u=o+a,l=i+s;r.cropBox=Fn([s,o,l,u],[1,4])}else r.cropBox=Fn([0,0,1,1],[1,4]);return r}return Dx(e,t),e.prototype.summary=function(){return"webcam"},e.create=function(t,n){return void 0===n&&(n={}),Ox(this,void 0,void 0,(function(){var r;return _x(this,(function(a){switch(a.label){case 0:if(c().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!n.resizeWidth||!n.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=n.resizeWidth,t.height=n.resizeHeight}return[4,(r=new e(t,n)).start()];case 1:return a.sent(),[2,r]}}))}))},e.prototype.start=function(){return Ox(this,void 0,void 0,(function(){var t,e,n=this;return _x(this,(function(r){switch(r.label){case 0:this.webcamConfig.facingMode&&pt.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(function(){return"Invalid webcam facing mode: "+n.webcamConfig.facingMode+". Please provide 'user' or 'environment'"})),r.label=1;case 1:return r.trys.push([1,3,,4]),t=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return t.stream=r.sent(),[3,4];case 3:throw(e=r.sent()).message="Error thrown while initializing video stream: "+e.message,e;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise((function(t){n.webcamVideoElement.onloadedmetadata=function(){t()}}))]}}))}))},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){if(this.isClosed)return[2,{value:null,done:!0}];try{t=lf.fromPixels(this.webcamVideoElement)}catch(t){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(t))}if(!this.resize)return[2,{value:t,done:!1}];try{return[2,{value:this.cropAndResizeFrame(t),done:!1}]}catch(t){throw new Error("Error thrown cropping the video: "+t.message)}finally{t.dispose()}return[2]}))}))},e.prototype.needToResize=function(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)},e.prototype.cropAndResizeFrame=function(t){var e=this;return $e((function(){var n,r=t.toFloat().expandDims(0),a=(n=Tp.cropAndResize(r,e.cropBox,e.cropBoxInd,e.cropSize,"bilinear")).shape;return n.reshape(a.slice(1))}))},e.prototype.capture=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}}))}))},e.prototype.stop=function(){this.stream.getTracks().forEach((function(t){return t.stop()}));try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0},e.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},e}(aw),Lw=function(){},Bw=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Dx(e,t),e.prototype.split=function(t){return new Pw(this,t)},e}(aw),Pw=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.impl=new Ww(e,n),r}return Dx(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return[2,this.impl.next()]}))}))},e}(Bw),Ww=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.separator=n,r.carryover="",r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return Ox(this,void 0,void 0,(function(){var t,e,n,r,a;return _x(this,(function(i){switch(i.label){case 0:return[4,this.upstream.next()];case 1:if((t=i.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],n=0,r=e.slice(0,-1);n<r.length;n++)a=r[n],this.outputQueue.push(a);return this.carryover=e[e.length-1],[2,!0]}}))}))},e}(mw),Vw=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Dx(e,t),e.prototype.decodeUTF8=function(){return new Uw(this)},e}(aw),Uw=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.impl=new jw(e),n}return Dx(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return[2,this.impl.next()]}))}))},e}(Bw),jw=function(t){function e(e){var r=t.call(this)||this;if(r.upstream=e,c().get("IS_BROWSER"))r.decoder=new TextDecoder("utf-8");else{var a=n(589).StringDecoder;r.decoder=new a("utf8")}return r}return Dx(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},e.prototype.pump=function(){return Ox(this,void 0,void 0,(function(){var t,e,n;return _x(this,(function(r){switch(r.label){case 0:return[4,this.upstream.next()];case 1:return(t=r.sent()).done?[2,!1]:(e=t.value,n=c().get("IS_BROWSER")?this.decoder.decode(e,{stream:!0}):this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(n),[2,!0])}}))}))},e}(mw),Gw=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.file=e,r.options=n,pt.assert(e instanceof Uint8Array||!!c().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."})),r.offset=n.offset||0,r.chunkSize=n.chunkSize||1048576,r}return Dx(e,t),e.prototype.summary=function(){return"FileChunks "+this.file},e.prototype.next=function(){return Ox(this,void 0,void 0,(function(){var t,e,n=this;return _x(this,(function(r){switch(r.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise((function(t,e){var r=n.offset+n.chunkSize;if(n.file instanceof Uint8Array)t(new Uint8Array(n.file.slice(n.offset,r)));else{var a=new FileReader;a.onload=function(n){var r=a.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(r)},a.onabort=function(t){return e(new Error("Aborted"))},a.onerror=function(t){return e(new Error(t.type))};var i=n.file.slice(n.offset,r);a.readAsArrayBuffer(i)}n.offset=r})),e={},[4,t]);case 1:return[2,(e.value=r.sent(),e.done=!1,e)]}}))}))},e}(Vw);function qw(t,e){return void 0===e&&(e={}),Ox(this,void 0,void 0,(function(){var n,r,a,i,o;return _x(this,(function(s){switch(s.label){case 0:return"string"==typeof t?n=t:(n=t.url,r=Hw(t)),[4,pt.fetch(n,r)];case 1:return(a=s.sent()).ok?(o=Uint8Array.bind,[4,a.arrayBuffer()]):[3,3];case 2:return i=new(o.apply(Uint8Array,[void 0,s.sent()])),[2,new Gw(i,e)];case 3:throw new Error(a.statusText)}}))}))}var Hw=function(t){return{method:t.method,headers:t.headers,body:t.body,mode:t.mode,credentials:t.credentials,cache:t.cache,redirect:t.redirect,referrer:t.referrer,integrity:t.integrity}};function Kw(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var Xw=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.input=e,r.options=n,r}return Dx(e,t),e.prototype.iterator=function(){return Ox(this,void 0,void 0,(function(){var t;return _x(this,(function(e){return Kw(this.input)&&c().get("IS_NODE")&&(t=n(993),this.input=t.readFileSync(this.input.substr(7))),[2,new Gw(this.input,this.options)]}))}))},e}(Lw),Yw=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.url=e,r.fileOptions=n,r}return Dx(e,t),e.prototype.iterator=function(){return Ox(this,void 0,void 0,(function(){return _x(this,(function(t){return Kw(this.url)?[2,new Xw(this.url,this.fileOptions).iterator()]:[2,qw(this.url,this.fileOptions)]}))}))},e}(Lw);function Jw(t,e){return void 0===e&&(e={}),new Fw(new Yw(t),e)}function $w(t){var e=this,n=tw(t);return Cw((function(){return Ox(e,void 0,void 0,(function(){return _x(this,(function(t){return[2,n]}))}))}))}function Zw(t){var e=this;return Cw((function(){return Ox(e,void 0,void 0,(function(){var e;return _x(this,(function(n){switch(n.label){case 0:return[4,t()];case 1:return e=n.sent(),[2,tw((function(){return e.next()}))]}}))}))}))}function Qw(t,e){return Ox(this,void 0,void 0,(function(){return _x(this,(function(n){return[2,zw.create(t,e)]}))}))}function tC(t){return Ox(this,void 0,void 0,(function(){return _x(this,(function(e){return[2,Mw.create(t)]}))}))}var eC="1.7.4",nC={"tfjs-core":df,"tfjs-data":eC,"tfjs-layers":Tg,"tfjs-converter":Tx,tfjs:"1.7.4"}},499:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BATCH_SIZE=32,e.EPOCHS=1e3,e.MIN_NN_SIZE=16,e.MAX_NN_SIZE=1024,e.DEFAULT_DENSE_LAYERS={nnSizeFactor:2,activation:"relu"},e.LEARNING_RATE=.005,e.TRAIN_VAL_RATIO=.25},171:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),r=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.min=e.min(),this.max=e.max()}return n(t,[{key:"transform",value:function(t){return t.sub(this.min).div(this.max.sub(this.min))}},{key:"inverseTransform",value:function(t){return t.mul(this.max.sub(this.min)).add(this.min)}}]),t}();e.default=r},420:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(n(714)),i=n(499),o=function(){function t(e){if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),void 0===e)throw new Error("Config must be present");this.layers=e.layers||i.DEFAULT_DENSE_LAYERS,this.batchSize=e.batchSize||i.BATCH_SIZE,this.epochs=e.epochs||i.EPOCHS,this.learningRate=e.learningRate||i.LEARNING_RATE,this.xNormalizer=e.xNormalizer,this.yNormalizer=e.yNormalizer,this.encoder=e.encoder,this.callbacks=e.callbacks||a.callbacks.earlyStopping({monitor:"val_loss",patience:20,restore_best_weights:!0})}return r(t,[{key:"buildModelAndTrain",value:function(t,e,n,r){return this.model=this.buildModel(t.shape[1]),this.model.fit(t,e,{batchSize:this.batchSize,epochs:this.epochs,validationData:[n,r],callbacks:this.callbacks}).then((function(t){return t.history}))}},{key:"buildModel",value:function(t){if(!t)throw new Error("InputShape missing");var e=a.sequential(),n=Math.min(i.MAX_NN_SIZE,Math.max(Math.round(this.layers.nnSizeFactor*t),i.MIN_NN_SIZE));e.add(a.layers.dense({inputShape:t,units:n,activation:this.layers.activation,kernelInitializer:"randomNormal"})),e.add(a.layers.dense({units:n,activation:this.layers.activation})),e.add(a.layers.dense({units:1,activation:"linear"}));var r={optimizer:a.train.adam(this.learningRate),loss:"meanSquaredError"};return e.compile(r),e}},{key:"predict",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!("model"in this))throw new Error("Can not make prediction without model");var n=e?t:this.encoder.encode(t),r=this.xNormalizer.transform(a.tensor(n)),i=this.model.predict(r),o=this.yNormalizer.inverseTransform(i);return o.dataSync()}}]),t}();e.default=o},909:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=n(46),i=function(){function t(e,n,r){var i=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.averages=n.map((function(t){return t===a.dataTypes.CATEGORICAL?{}:null})),this.yMean=function(t){return t.reduce((function(t,e){return t+e}),0)/t.length},this.types=n,e.map((function(t,e){i.checkInput(t),t.map((function(t,o){n[o]===a.dataTypes.CATEGORICAL&&(t in i.averages[o]?(i.averages[o][t].count+=1,i.averages[o][t].sum+=r[e]):i.averages[o][t]={count:1,sum:r[e]})}))}))}return r(t,[{key:"checkInput",value:function(t){if(t.length!==this.types.length)throw new Error("Input size error")}},{key:"encode",value:function(t){var e=this;return t.map((function(t){return e.checkInput(t),t.map((function(t,n){return e.types[n]===a.dataTypes.CATEGORICAL?t in e.averages[n]?e.averages[n][t].sum/e.averages[n][t].count:e.yMean:t}))}))}}]),t}();e.default=i},568:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.splitTrainValidation=function(t,e,n){var r=[],a=[],i=[],o=[],s=1;if(t.length!=e.length)throw new Error("Sizes of input arguments do not match"+t.length+" and "+e.length);return t.map((function(t,u){var l=1e4*Math.sin(s++);(l-=Math.floor(l))<n?(i.push(t),o.push(e[u])):(r.push(t),a.push(e[u]))})),0==a.length&&(r.push(t[0]),a.push(e[0])),0==o.length&&(i.push(t[0]),o.push(e[0])),{xTrain:r,yTrain:a,xVal:i,yVal:o}}},46:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.dataTypes={MEASURE:"measure",CATEGORICAL:"categorical"}},330:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createRegressionModel=function(t){if(t.data&&t.types){var e=t.data.y,n=new a.default(t.data.x,t.types,e),s=n.encode(t.data.x),u=r.tensor(s),l=new i.default(u),h=new i.default(r.tensor(e)),f={xNormalizer:l,yNormalizer:h,encoder:n};f.batchSize=t.batchSize||!1,f.epochs=t.epochs||!1,f.layers=t.layers||!1;var d=p(s,e,l,h,u),m=d.xNormTrain,g=d.yNormTrain,v=d.xNormVal,y=d.yNormVal,b=d.xNorm,x=new o.default(f);return x.buildModelAndTrain(m,g,v,y).then((function(t){var n=c(x,b,h,e);return{model:x,mse:n.mse,r2:n.r2,mae:n.mae,history:t}}))}},e.trainPretrainedModel=function(t,e,n){if(!t)throw new Error("model does not exist");var a=void 0,i=void 0,o=void 0;n?(a=n.batchSize||t.batchSize,i=n.epochs||t.epochs,o=n.callbacks||t.callbacks):(a=t.batchSize,i=t.epochs,o=t.callbacks);var s=t.encoder.encode(e.x),u=r.tensor(s),l=p(s,e.y,t.xNormalizer,t.yNormalizer,u),h=l.xNormTrain,f=l.yNormTrain,d=l.xNormVal,m=l.yNormVal,g=l.xNorm,v={batchSize:a,epochs:i,validationData:[d,m],callbacks:o};return t.model.fit(h,f,v).then((function(n){var r=c(t,g,t.yNormalizer,e.y);return{model:t,mse:r.mse,r2:r.r2,mae:r.mae,history:n.history}}))};var r=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}(n(714)),a=l(n(909)),i=l(n(171)),o=l(n(420)),s=n(568),u=n(499);function l(t){return t&&t.__esModule?t:{default:t}}function c(t,e,n,a){var i=r.tensor(a),o=r.moments(i).variance.dataSync()[0],s=t.model.predict(e),u=n.inverseTransform(s).flatten(),l=r.metrics.meanSquaredError(i,u).dataSync()[0];return{mae:r.metrics.meanAbsoluteError(i,u).dataSync()[0],mse:l,r2:1-l/o}}function p(t,e,n,a,i){var o=(0,s.splitTrainValidation)(t,e,u.TRAIN_VAL_RATIO),l=o.xTrain,c=o.yTrain,p=o.xVal,h=o.yVal,f=r.tensor(l),d=r.tensor(c),m=r.tensor(p),g=r.tensor(h);return{xNormTrain:n.transform(f),yNormTrain:a.transform(d),xNormVal:n.transform(m),yNormVal:a.transform(g),xNorm:n.transform(i)}}},244:(t,e,n)=>{"use strict";var r,a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=n(330);void 0===(r=function(){return function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return a(t,[{key:"createModel",value:function(t){return(0,i.createRegressionModel)(t).then((function(t){return t}))}},{key:"continueTraining",value:function(t,e,n){return(0,i.trainPretrainedModel)(t,e,n).then((function(t){return t}))}}]),t}()}.apply(e,[]))||(t.exports=r)},906:()=>{},993:()=>{},352:()=>{},589:()=>{},758:()=>{}},e={};function n(r){if(e[r])return e[r].exports;var a=e[r]={exports:{}};return t[r](a,a.exports,n),a.exports}return n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n(244)})()}));
- //# sourceMappingURL=whatIfService.min.js.map
|